code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def classifer_metrics(label, pred):
"""
computes f1, precision and recall on the entity class
"""
prediction = np.argmax(pred, axis=1)
label = label.astype(int)
pred_is_entity = prediction != not_entity_index
label_is_entity = label != not_entity_index
corr_pred = (prediction == label)... | computes f1, precision and recall on the entity class |
def GetParentFileEntry(self):
"""Retrieves the parent file entry.
Returns:
CPIOFileEntry: parent file entry or None if not available.
"""
location = getattr(self.path_spec, 'location', None)
if location is None:
return None
parent_location = self._file_system.DirnamePath(location)
... | Retrieves the parent file entry.
Returns:
CPIOFileEntry: parent file entry or None if not available. |
def _make_serverproxy_handler(name, command, environment, timeout, absolute_url, port):
"""
Create a SuperviseAndProxyHandler subclass with given parameters
"""
# FIXME: Set 'name' properly
class _Proxy(SuperviseAndProxyHandler):
def __init__(self, *args, **kwargs):
super().__ini... | Create a SuperviseAndProxyHandler subclass with given parameters |
def add_arguments(cls, parser):
"""Add arguments to the parser for collection in app.args.
Args:
parser:
`argparse.ArgumentParser`. Parser.
Arguments added here are server on
self.args.
"""
parser.add_argument(
'-c... | Add arguments to the parser for collection in app.args.
Args:
parser:
`argparse.ArgumentParser`. Parser.
Arguments added here are server on
self.args. |
def findFilesWithPattern(
self, fileName, searchPattern, fillFindData, dokanFileInfo
):
"""Find files in a certain path that match the search pattern.
:param fileName: path to search
:type fileName: ctypes.c_wchar_p
:param searchPattern: pattern to search for
:type s... | Find files in a certain path that match the search pattern.
:param fileName: path to search
:type fileName: ctypes.c_wchar_p
:param searchPattern: pattern to search for
:type searchPattern: ctypes.c_wchar_p
:param fillFindData: function pointer for populating search results
... |
def load(filename, format=None, **kwargs):
'''
load(filename) yields the data contained in the file referenced by the given filename in a
neuropythy or neuropythy-friendly format.
load(filename, format) specifies that the given format should be used; this should be the name
of the importer (thou... | load(filename) yields the data contained in the file referenced by the given filename in a
neuropythy or neuropythy-friendly format.
load(filename, format) specifies that the given format should be used; this should be the name
of the importer (though a file extension that is recognized also will work).... |
def unsubscribe_from_trades(self, pair, **kwargs):
"""Unsubscribe to the passed pair's trades channel.
:param pair: str, Symbol pair to request data for
:param kwargs:
:return:
"""
identifier = ('trades', pair)
self._unsubscribe('trades', identifier, symbol=pair,... | Unsubscribe to the passed pair's trades channel.
:param pair: str, Symbol pair to request data for
:param kwargs:
:return: |
def main(gamepad=None):
"""Vibrate the gamepad."""
if not gamepad:
gamepad = inputs.devices.gamepads[0]
# Vibrate left
gamepad.set_vibration(1, 0, 1000)
time.sleep(2)
# Vibrate right
gamepad.set_vibration(0, 1, 1000)
time.sleep(2)
# Vibrate Both
gamepad.set_vibration(... | Vibrate the gamepad. |
def _get_resources_to_iterate(self, sam_template, macro_resolver):
"""
Returns a list of resources to iterate, order them based on the following order:
1. AWS::Serverless::Function - because API Events need to modify the corresponding Serverless::Api resource.
2. AWS::Serverless... | Returns a list of resources to iterate, order them based on the following order:
1. AWS::Serverless::Function - because API Events need to modify the corresponding Serverless::Api resource.
2. AWS::Serverless::Api
3. Anything else
This is necessary because a Function resour... |
def find_stoichiometrically_balanced_cycles(model):
u"""
Find metabolic reactions in stoichiometrically balanced cycles (SBCs).
Identify forward and reverse cycles by closing all exchanges and using FVA.
Parameters
----------
model : cobra.Model
The metabolic model under investigation.... | u"""
Find metabolic reactions in stoichiometrically balanced cycles (SBCs).
Identify forward and reverse cycles by closing all exchanges and using FVA.
Parameters
----------
model : cobra.Model
The metabolic model under investigation.
Notes
-----
"SBCs are artifacts of metabol... |
def coerce(value1, value2, default=None):
"""Exclude NoSet objec
.. code-block::
>>> coerce(NoSet, 'value')
'value'
"""
if value1 is not NoSet:
return value1
elif value2 is not NoSet:
return value2
else:
return default | Exclude NoSet objec
.. code-block::
>>> coerce(NoSet, 'value')
'value' |
def minimize_algorithm_1dim_golden(function, a, b, c, tolerance=DOUBLE_TOL):
'''
Given a function f, and given a bracketing triplet of abscissas ax, bx, cx
(such that bx is between ax and cx, and f(bx) is less than both f(ax) and f(cx)),
this routine performs a golden section search for the minimum, iso... | Given a function f, and given a bracketing triplet of abscissas ax, bx, cx
(such that bx is between ax and cx, and f(bx) is less than both f(ax) and f(cx)),
this routine performs a golden section search for the minimum, isolating it to
a fractional precision of about tol. The abscissa of the minimum is retu... |
def create_cluster(
self,
parent,
cluster_id,
cluster,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a cluster within an instance.
Example:
>>>... | Creates a cluster within an instance.
Example:
>>> from google.cloud import bigtable_admin_v2
>>>
>>> client = bigtable_admin_v2.BigtableInstanceAdminClient()
>>>
>>> parent = client.instance_path('[PROJECT]', '[INSTANCE]')
>>>
... |
def repr(self, changed_widgets=None):
"""Represents the widget as HTML format, packs all the attributes, children and so on.
Args:
client (App): Client instance.
changed_widgets (dict): A dictionary containing a collection of widgets that have to be updated.
The ... | Represents the widget as HTML format, packs all the attributes, children and so on.
Args:
client (App): Client instance.
changed_widgets (dict): A dictionary containing a collection of widgets that have to be updated.
The Widget that have to be updated is the key, and th... |
def _pypsa_load_timeseries(network, timesteps, mode=None):
"""
Time series in PyPSA compatible format for load instances
Parameters
----------
network : Network
The eDisGo grid topology model overall container
timesteps : array_like
Timesteps is an array-like object with entries... | Time series in PyPSA compatible format for load instances
Parameters
----------
network : Network
The eDisGo grid topology model overall container
timesteps : array_like
Timesteps is an array-like object with entries of type
:pandas:`pandas.Timestamp<timestamp>` specifying which... |
def _as_document(self, dataset):
""" Converts dataset to document indexed by to FTS index.
Args:
dataset (orm.Dataset): dataset to convert.
Returns:
dict with structure matches to BaseDatasetIndex._schema.
"""
assert isinstance(dataset, Dataset)
... | Converts dataset to document indexed by to FTS index.
Args:
dataset (orm.Dataset): dataset to convert.
Returns:
dict with structure matches to BaseDatasetIndex._schema. |
def _JMS_to_Bern_I(C, qq):
"""From JMS to BernI basis (= traditional SUSY basis in this case)
for $\Delta F=2$ operators.
`qq` should be 'sb', 'db', 'ds' or 'cu'"""
if qq in ['sb', 'db', 'ds']:
dd = 'dd'
ij = tuple(dflav[q] for q in qq)
elif qq == 'cu':
dd = 'uu'
ij =... | From JMS to BernI basis (= traditional SUSY basis in this case)
for $\Delta F=2$ operators.
`qq` should be 'sb', 'db', 'ds' or 'cu |
def import_item(name):
"""Import and return bar given the string foo.bar."""
package = '.'.join(name.split('.')[0:-1])
obj = name.split('.')[-1]
# Note: the original code for this was the following. We've left it
# visible for now in case the new implementation shows any problems down
# th... | Import and return bar given the string foo.bar. |
def _create_vm(self, vm_config):
"""
Attempt to create or update VM instance based on vm_parameters config.
"""
try:
vm_setup = self.compute.virtual_machines.create_or_update(
self.running_instance_id, self.running_instance_id,
vm_config
... | Attempt to create or update VM instance based on vm_parameters config. |
def get_savepath(self, url, savepath=None):
"""
Evaluates the savepath with the help of the given url.
:param str url: url to evaluate the savepath with
:return str: the evaluated savepath for the given url
"""
timestamp = int(time.time())
if not savepath:
... | Evaluates the savepath with the help of the given url.
:param str url: url to evaluate the savepath with
:return str: the evaluated savepath for the given url |
def p_preprocessor_line_line_file(p):
""" preproc_line : _LINE INTEGER STRING
"""
p.lexer.lineno = int(p[2]) + p.lexer.lineno - p.lineno(3) - 1
gl.FILENAME = p[3] | preproc_line : _LINE INTEGER STRING |
def build(self, tag, add_latest_tag=False, add_tags=None, raise_on_error=True, **kwargs):
"""
Overrides the superclass `build()` and filters the output. Messages are deferred to `push_log`, whereas the
final message is checked for a success message. If the latter is found, only the new image id ... | Overrides the superclass `build()` and filters the output. Messages are deferred to `push_log`, whereas the
final message is checked for a success message. If the latter is found, only the new image id is returned.
:param tag: Tag of the new image to be built. Unlike in the superclass, this is obligato... |
def bs(s: int) -> str:
"""Converts an int to its bits representation as a string of 0's and 1's.
"""
return str(s) if s <= 1 else bs(s >> 1) + str(s & 1) | Converts an int to its bits representation as a string of 0's and 1's. |
def _add_consequences(self, variant_obj):
"""Add the consequences found in all transcripts
Args:
variant_obj (puzzle.models.Variant)
"""
consequences = set()
for transcript in variant_obj.transcripts:
for consequence in transcript.consequence.split('&'):... | Add the consequences found in all transcripts
Args:
variant_obj (puzzle.models.Variant) |
def write_slide_list(self, logname, slides):
""" Write list of slides to logfile """
# Write slides.txt with list of slides
with open('%s/%s' % (self.cache, logname), 'w') as logfile:
for slide in slides:
heading = slide['heading']['text']
filename = s... | Write list of slides to logfile |
def prop_to_size(vals, mi=0.0, ma=5.0, power=0.5, log=False):
"""
Converts an array of property values (e.g. a metric or score) to values
that are more useful for marker sizes, line widths, or other visual
sizes. The new sizes are computed as:
y = mi + (ma -mi)(\frac{x_i - min(x){max(x) - min(x... | Converts an array of property values (e.g. a metric or score) to values
that are more useful for marker sizes, line widths, or other visual
sizes. The new sizes are computed as:
y = mi + (ma -mi)(\frac{x_i - min(x){max(x) - min(x)})^{power}
If ``log=True``, the natural logarithm of the property va... |
def disassociate_environment_option_pool(self, environment_option_id):
"""Remove a relationship of optionpool with Environment.
:param id_option_pool: Identifier of the Option Pool. Integer value and greater than zero.
:param id_environment: Identifier of the Environment Pool. Integer value and... | Remove a relationship of optionpool with Environment.
:param id_option_pool: Identifier of the Option Pool. Integer value and greater than zero.
:param id_environment: Identifier of the Environment Pool. Integer value and greater than zero.
:return: { 'id': < environment_option_id> }
... |
def total_stored(self, wanted, slots=None):
"""
Calculates the total number of items of that type
in the current window or given slot range.
Args:
wanted: function(Slot) or Slot or itemID or (itemID, metadata)
"""
if slots is None:
slots = self.wi... | Calculates the total number of items of that type
in the current window or given slot range.
Args:
wanted: function(Slot) or Slot or itemID or (itemID, metadata) |
def draw_box(self, box):
"""Draw a white box on the image.
Parameters
----------
:obj:`autolab_core.Box`
A 2D box to draw in the image.
Returns
-------
:obj:`ColorImage`
A new image that is the same as the current one, but with
... | Draw a white box on the image.
Parameters
----------
:obj:`autolab_core.Box`
A 2D box to draw in the image.
Returns
-------
:obj:`ColorImage`
A new image that is the same as the current one, but with
the white box drawn in. |
def kip_cont(self, ifig=110, modstart=0, modstop=-1,t0_model=0,
outfile='out.png', xlims=None, ylims=None,
xres=1000, yres=1000, ixaxis='model_number',
mix_zones=20, burn_zones=20, plot_radius=False,
engenPlus=True, engenMinus=False,
l... | This function creates a Kippenhahn plot with energy flux using
contours.
This plot uses mixing_regions and burning_regions written to
your history.data or star.log. Set both variables in the
log_columns.list file to 20 as a start.
The output log file should then contain columns... |
def reply_audio(
self,
audio: str,
quote: bool = None,
caption: str = "",
parse_mode: str = "",
duration: int = 0,
performer: str = None,
title: str = None,
thumb: str = None,
disable_notification: bool = None,
reply_to_message_id: ... | Bound method *reply_audio* of :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
.. code-block:: python
client.send_audio(
chat_id=message.chat.id,
audio=audio
)
Example:
.. code-block:: python
messag... |
def fetch_sel(self, ipmicmd, clear=False):
"""Fetch SEL entries
Return an iterable of SEL entries. If clearing is requested,
the fetch and clear will be done as an atomic operation, assuring
no entries are dropped.
:param ipmicmd: The Command object to use to interrogate
:param clear:... | Fetch SEL entries
Return an iterable of SEL entries. If clearing is requested,
the fetch and clear will be done as an atomic operation, assuring
no entries are dropped.
:param ipmicmd: The Command object to use to interrogate
:param clear: Whether to clear the entries upon retrieval. |
def watchlist_movies(self, **kwargs):
"""
Get the list of movies on an account watchlist.
Args:
page: (optional) Minimum 1, maximum 1000.
sort_by: (optional) 'created_at.asc' | 'created_at.desc'
language: (optional) ISO 639-1 code.
Returns:
... | Get the list of movies on an account watchlist.
Args:
page: (optional) Minimum 1, maximum 1000.
sort_by: (optional) 'created_at.asc' | 'created_at.desc'
language: (optional) ISO 639-1 code.
Returns:
A dict respresentation of the JSON returned from the AP... |
def _fix_set_options(cls, options):
"""Alter the set options from None/strings to sets in place."""
optional_set_options = ('ignore', 'select')
mandatory_set_options = ('add_ignore', 'add_select')
def _get_set(value_str):
"""Split `value_str` by the delimiter `,` and return ... | Alter the set options from None/strings to sets in place. |
def _get_api_sig(args):
"""Flickr API need a hash string which made using post arguments
:param args: Arguments of the flickr request
:type args: list of sets
:return: api_sig, ex: ('api_sig', 'abcdefg')
:rtype: tuple
"""
tmp_sig = api_secret
for i in args:
tmp_sig = tmp_sig + i... | Flickr API need a hash string which made using post arguments
:param args: Arguments of the flickr request
:type args: list of sets
:return: api_sig, ex: ('api_sig', 'abcdefg')
:rtype: tuple |
def render_particles(self):
"""
Render visible particles at each strip position, by modifying
the strip's color list.
"""
for strip_pos in range(self._start, self._end + 1):
blended = COLORS.black
# Render visible emitters
if self.has_e_color... | Render visible particles at each strip position, by modifying
the strip's color list. |
def populate_with_defaults():
'''Create user admin and grant him all permission
If the admin user already exists the function will simply return
'''
logging.getLogger(__name__).debug("Populating with default users")
if not User.select().where(User.name == 'admin').exists():
admin = User.cre... | Create user admin and grant him all permission
If the admin user already exists the function will simply return |
async def _base_request(self, url, content_type, response_type, data):
"""Send a generic authenticated POST request.
Args:
url (str): URL of request.
content_type (str): Request content type.
response_type (str): The desired response format. Valid options
... | Send a generic authenticated POST request.
Args:
url (str): URL of request.
content_type (str): Request content type.
response_type (str): The desired response format. Valid options
are: 'json' (JSON), 'protojson' (pblite), and 'proto' (binary
... |
def _set_igmpPIM(self, v, load=False):
"""
Setter method for igmpPIM, mapped from YANG variable /interface_vlan/vlan/ip/igmpPIM (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_igmpPIM is considered as a private
method. Backends looking to populate this va... | Setter method for igmpPIM, mapped from YANG variable /interface_vlan/vlan/ip/igmpPIM (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_igmpPIM is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_ig... |
def from_csv(cls, path, header=0, sep=',', index_col=0, parse_dates=True,
encoding=None, tupleize_cols=None,
infer_datetime_format=False):
"""
Read CSV file.
.. deprecated:: 0.21.0
Use :func:`read_csv` instead.
It is preferable to use the m... | Read CSV file.
.. deprecated:: 0.21.0
Use :func:`read_csv` instead.
It is preferable to use the more powerful :func:`read_csv`
for most general purposes, but ``from_csv`` makes for an easy
roundtrip to and from a file (the exact counterpart of
``to_csv``), especiall... |
def format_cli(self, value):
"""
Build a single parameter argument.
:return: list of CLI strings -- not escaped. If the parameter should not be expressed, returns None.
:rtype: list[str]|None
"""
if value is None or (self.type == 'flag' and not value):
return... | Build a single parameter argument.
:return: list of CLI strings -- not escaped. If the parameter should not be expressed, returns None.
:rtype: list[str]|None |
def import_staging(self, source, staging_start=None, as_qual=False,
test_filename=None, test_rater=None):
"""Action: import an external sleep staging file.
Parameters
----------
source : str
Name of program where staging was exported. One of 'alice',
... | Action: import an external sleep staging file.
Parameters
----------
source : str
Name of program where staging was exported. One of 'alice',
'compumedics', 'domino', 'remlogic', 'sandman'.
staging_start : datetime, optional
Absolute time when staging... |
def monitor(options={}):
"""Starts syncing with W&B if you're in Jupyter. Displays your W&B charts live in a Jupyter notebook.
It's currently a context manager for legacy reasons.
"""
try:
from IPython.display import display
except ImportError:
def display(stuff): return None
c... | Starts syncing with W&B if you're in Jupyter. Displays your W&B charts live in a Jupyter notebook.
It's currently a context manager for legacy reasons. |
def check_stripe_api_version(app_configs=None, **kwargs):
"""Check the user has configured API version correctly."""
from . import settings as djstripe_settings
messages = []
default_version = djstripe_settings.DEFAULT_STRIPE_API_VERSION
version = djstripe_settings.get_stripe_api_version()
if not validate_strip... | Check the user has configured API version correctly. |
def started(self, component):
"""Sets up the application after startup."""
self.log("Running.")
self.log("Started event origin: ", component, lvl=verbose)
populate_user_events()
from hfos.events.system import AuthorizedEvents
self.log(len(AuthorizedEvents), "authorized ... | Sets up the application after startup. |
def evict(self):
"""Evict all caches related to these operations."""
logging.debug('Evicting cache for %r', self.cache_key)
_clear_version_cache(self.cache_key)
# Cause the cache key to be refreshed next time any operation is
# run to make sure we don't act on old cached data.
... | Evict all caches related to these operations. |
def _get_encoder_method(stream_type):
"""A function to get the python type to device cloud type converter function.
:param stream_type: The streams data type
:return: A function that when called with the python object will return the serializable
type for sending to the cloud. If there is no function f... | A function to get the python type to device cloud type converter function.
:param stream_type: The streams data type
:return: A function that when called with the python object will return the serializable
type for sending to the cloud. If there is no function for the given type, or the `stream_type`
i... |
def switch(self, gen_mode:bool=None):
"Put the model in generator mode if `gen_mode`, in critic mode otherwise."
self.gen_mode = (not self.gen_mode) if gen_mode is None else gen_mode | Put the model in generator mode if `gen_mode`, in critic mode otherwise. |
def run_agent(device_type):
"""Run a simple GPG-agent server."""
p = argparse.ArgumentParser()
p.add_argument('--homedir', default=os.environ.get('GNUPGHOME'))
p.add_argument('-v', '--verbose', default=0, action='count')
p.add_argument('--server', default=False, action='store_true',
... | Run a simple GPG-agent server. |
def dot1x_enable(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
dot1x = ET.SubElement(config, "dot1x", xmlns="urn:brocade.com:mgmt:brocade-dot1x")
enable = ET.SubElement(dot1x, "enable")
callback = kwargs.pop('callback', self._callback)
... | Auto Generated Code |
def site_pages(self, site_id, brozzled=None):
'''
Args:
site_id (str or int):
brozzled (bool): if true, results include only pages that have
been brozzled at least once; if false, only pages that have
not been brozzled; and if None (the default), a... | Args:
site_id (str or int):
brozzled (bool): if true, results include only pages that have
been brozzled at least once; if false, only pages that have
not been brozzled; and if None (the default), all pages
Returns:
iterator of brozzler.Page |
def get_c_extension(support_legacy=False, system_zstd=False, name='zstd',
warnings_as_errors=False, root=None):
"""Obtain a distutils.extension.Extension for the C extension.
``support_legacy`` controls whether to compile in legacy zstd format support.
``system_zstd`` controls whether ... | Obtain a distutils.extension.Extension for the C extension.
``support_legacy`` controls whether to compile in legacy zstd format support.
``system_zstd`` controls whether to compile against the system zstd library.
For this to work, the system zstd library and headers must match what
python-zstandard ... |
def from_like_context(ctx, param, value):
"""Return the value for an option from the context if the option
or `--all` is given, else return None."""
if ctx.obj and ctx.obj.get("like") and (value == "like" or ctx.obj.get("all_like")):
return ctx.obj["like"][param.name]
else:
return None | Return the value for an option from the context if the option
or `--all` is given, else return None. |
def open(self, path: str, mode: str='r') -> IO:
"""Open an IO-like object for `path`.
.. note::
Mode *must* be either 'r' or 'w', as the underlying objects
do not understand the full range of modes.
:param path: The path to open.
:param mode: The mode of the fi... | Open an IO-like object for `path`.
.. note::
Mode *must* be either 'r' or 'w', as the underlying objects
do not understand the full range of modes.
:param path: The path to open.
:param mode: The mode of the file being opened, either 'r' or 'w'. |
def find(pattern, path='.', exclude=None, recursive=True):
"""Find files that match *pattern* in *path*"""
import fnmatch
import os
if recursive:
for root, dirnames, filenames in os.walk(path):
for pat in _to_list(pattern):
for filename in fnmatch.filter(filenames, p... | Find files that match *pattern* in *path* |
def solidity_resolve_address(hex_code, library_symbol, library_address):
""" Change the bytecode to use the given library address.
Args:
hex_code (bin): The bytecode encoded in hexadecimal.
library_name (str): The library that will be resolved.
library_address (str): The address of the ... | Change the bytecode to use the given library address.
Args:
hex_code (bin): The bytecode encoded in hexadecimal.
library_name (str): The library that will be resolved.
library_address (str): The address of the library.
Returns:
bin: The bytecode encoded in hexadecimal with the ... |
def _prm_extract_missing_flags(data_dict, flags_dict):
"""Extracts storage flags for data in `data_dict`
if they were not specified in `flags_dict`.
See :const:`~pypet.storageservice.HDF5StorageService.TYPE_FLAG_MAPPING`
for how to store different types of data per default.
"""... | Extracts storage flags for data in `data_dict`
if they were not specified in `flags_dict`.
See :const:`~pypet.storageservice.HDF5StorageService.TYPE_FLAG_MAPPING`
for how to store different types of data per default. |
def new(self, verbose=False):
"""
Destroys the current session and creates a new, empty one.
:param wid: Window ID
:param verbose: print more
"""
response=api(url=self.__url+"/new", verbose=verbose)
return response | Destroys the current session and creates a new, empty one.
:param wid: Window ID
:param verbose: print more |
def auth_data(self):
'''
Gather and create the authorization data sets
We're looking at several constructs here.
Standard eauth: allow jsmith to auth via pam, and execute any command
on server web1
external_auth:
pam:
jsmith:
- web1:
... | Gather and create the authorization data sets
We're looking at several constructs here.
Standard eauth: allow jsmith to auth via pam, and execute any command
on server web1
external_auth:
pam:
jsmith:
- web1:
- .*
Django eaut... |
def init_widget(self):
""" Initialize the underlying widget.
"""
super(AndroidTimePicker, self).init_widget()
d = self.declaration
w = self.widget
self.set_hour(d.hour)
self.set_minute(d.minute)
self.set_hour_mode(d.hour_mode)
w.setOnTimeChangedL... | Initialize the underlying widget. |
def tx(self):
"""
Return a ``<c:tx>`` oxml element for this series, containing the
series name.
"""
xml = self._tx_tmpl.format(**{
'wksht_ref': self._series.name_ref,
'series_name': self.name,
'nsdecls': ' %s' % nsdecls('c'),
})
... | Return a ``<c:tx>`` oxml element for this series, containing the
series name. |
def plot_carpet(img, atlaslabels, detrend=True, nskip=0, size=(950, 800),
subplot=None, title=None, output_file=None, legend=False,
lut=None, tr=None):
"""
Plot an image representation of voxel intensities across time also know
as the "carpet plot" or "Power plot". See Jonath... | Plot an image representation of voxel intensities across time also know
as the "carpet plot" or "Power plot". See Jonathan Power Neuroimage
2017 Jul 1; 154:150-158.
Parameters
----------
img : Niimg-like object
See http://nilearn.github.io/manipulating_images/input_output.html
... |
def enable_servicegroup_host_checks(self, servicegroup):
"""Enable host checks for a servicegroup
Format of the line that triggers function call::
ENABLE_SERVICEGROUP_HOST_CHECKS;<servicegroup_name>
:param servicegroup: servicegroup to enable
:type servicegroup: alignak.objects... | Enable host checks for a servicegroup
Format of the line that triggers function call::
ENABLE_SERVICEGROUP_HOST_CHECKS;<servicegroup_name>
:param servicegroup: servicegroup to enable
:type servicegroup: alignak.objects.servicegroup.Servicegroup
:return: None |
def send_command(self, *args, **kwargs):
"""
If the ASA is in multi-context mode, then the base_prompt needs to be
updated after each context change.
"""
if len(args) >= 1:
command_string = args[0]
else:
command_string = kwargs["command_string"]
... | If the ASA is in multi-context mode, then the base_prompt needs to be
updated after each context change. |
def block_layer(inputs,
filters,
block_fn,
blocks,
strides,
is_training,
name,
data_format="channels_first",
use_td=False,
targeting_rate=None,
keep_prob=None):... | Creates one layer of blocks for the ResNet model.
Args:
inputs: `Tensor` of size `[batch, channels, height, width]`.
filters: `int` number of filters for the first convolution of the layer.
block_fn: `function` for the block to use within the model
blocks: `int` number of blocks contained in the laye... |
def merge_images(images, axis='t'):
""" Concatenate `images` in the direction determined in `axis`.
Parameters
----------
images: list of str or img-like object.
See NeuroImage constructor docstring.
axis: str
't' : concatenate images in time
'x' : concatenate images in the x d... | Concatenate `images` in the direction determined in `axis`.
Parameters
----------
images: list of str or img-like object.
See NeuroImage constructor docstring.
axis: str
't' : concatenate images in time
'x' : concatenate images in the x direction
'y' : concatenate images in t... |
def intervals_union(S):
"""Union of intervals
:param S: list of pairs (low, high) defining intervals [low, high)
:returns: ordered list of disjoint intervals with the same union as S
:complexity: O(n log n)
"""
E = [(low, -1) for (low, high) in S]
E += [(high, +1) for (low, high) in S]
... | Union of intervals
:param S: list of pairs (low, high) defining intervals [low, high)
:returns: ordered list of disjoint intervals with the same union as S
:complexity: O(n log n) |
def _entropy(labels):
"""Calculates the entropy for a labeling.
Parameters
----------
labels : list-like
List of labels.
Returns
-------
entropy : float
Entropy of the labeling.
.. note:: Based on sklearn.metrics.cluster.entropy
"""
if len(labels) == 0:
... | Calculates the entropy for a labeling.
Parameters
----------
labels : list-like
List of labels.
Returns
-------
entropy : float
Entropy of the labeling.
.. note:: Based on sklearn.metrics.cluster.entropy |
def build_query(self):
'''
Using the three graphs derived from self._diff_graph(), build a sparql update query in the format:
PREFIX foo: <http://foo.com>
PREFIX bar: <http://bar.com>
DELETE {...}
INSERT {...}
WHERE {...}
Args:
None: uses variables from self
Returns:
(str) sparql update que... | Using the three graphs derived from self._diff_graph(), build a sparql update query in the format:
PREFIX foo: <http://foo.com>
PREFIX bar: <http://bar.com>
DELETE {...}
INSERT {...}
WHERE {...}
Args:
None: uses variables from self
Returns:
(str) sparql update query as string |
def stamp_allowing_unusual_version_table(
config: Config,
revision: str,
sql: bool = False,
tag: str = None,
version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE) -> None:
"""
Stamps the Alembic version table with the given revision; don't run any
migrations.
This ... | Stamps the Alembic version table with the given revision; don't run any
migrations.
This function is a clone of ``alembic.command.stamp()``, but allowing
``version_table`` to change. See
http://alembic.zzzcomputing.com/en/latest/api/commands.html#alembic.command.stamp |
def show_raslog_output_show_all_raslog_raslog_entries_message(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_raslog = ET.Element("show_raslog")
config = show_raslog
output = ET.SubElement(show_raslog, "output")
show_all_raslog = ET.... | Auto Generated Code |
def get_query_builder(self, *args, **kwargs):
"""
Return the query builder class instance that should be used to
build the query which is passed to the search engine backend.
"""
query_builder = self.get_query_builder_class()
return query_builder(*args, **kwargs) | Return the query builder class instance that should be used to
build the query which is passed to the search engine backend. |
def eplotter(task, data): # CRYSTAL, VASP, EXCITING
'''
eplotter is like bdplotter but less complicated
'''
results, color, fdata = [], None, []
if task == 'optstory':
color = '#CC0000'
clickable = True
for n, i in enumerate(data):
fdata.append([n, i[4]])
... | eplotter is like bdplotter but less complicated |
def create_dataset_synchronous(self, file_url, dataset_type='image', token=None, url=API_CREATE_DATASET):
""" Creates a dataset so you can train models from it
:param file_url: string, url to an accessible zip file containing the necessary image files
and folder structure indicating the ... | Creates a dataset so you can train models from it
:param file_url: string, url to an accessible zip file containing the necessary image files
and folder structure indicating the labels to train. See docs online.
:param dataset_type: string, one of the dataset types, available options... |
def run(self):
"""Use directly check() api from pydocstyle."""
if self.exclude_from_doctest:
for pattern in self.exclude_from_doctest:
if fnmatch.fnmatch(self.filename, pattern):
return
checked_codes = pep257.conventions.pep257 | {'D998', 'D999'}
for error in self._check_source(... | Use directly check() api from pydocstyle. |
def plot_cand(candsfile, candloc=[], candnum=-1, threshold=0, savefile=True, returndata=False, outname='', newplot=True, returnstate=False, **kwargs):
""" Reproduce detection of a single candidate for plotting or inspection.
candsfile can be merge or single-scan cands pkl file. Difference defined by presence o... | Reproduce detection of a single candidate for plotting or inspection.
candsfile can be merge or single-scan cands pkl file. Difference defined by presence of scan in d['featureind'].
candloc reproduces candidate at given location (scan, segment, integration, dmind, dtind, beamnum).
candnum selects one to r... |
def lookup(self, token):
"""
Return key version if found, None otherwise
Lookup should look like this:
pattern:
<key>,<env>/<service>
example:
ami-id,staging/core
"""
# get search key and env/service from token
try:
key, envservice = token.split(",")
except Valu... | Return key version if found, None otherwise
Lookup should look like this:
pattern:
<key>,<env>/<service>
example:
ami-id,staging/core |
def xml_to_bytes(element, pretty_print=False):
"""Wrapper for etree.tostring, that takes care of unsupported pretty_print
option and prepends an encoding header."""
if use_lxml:
xml = etree.tostring(
element, encoding="UTF-8", xml_declaration=True, pretty_print=pretty_print
)
... | Wrapper for etree.tostring, that takes care of unsupported pretty_print
option and prepends an encoding header. |
def recatalog_analyses_due_date(portal):
"""Recatalog the index and metadata field 'getDueDate'
"""
logger.info("Updating Analyses getDueDate")
# No need to update those analyses that are verified or published. Only
# those that are under work
catalog = api.get_tool(CATALOG_ANALYSIS_LISTING)
... | Recatalog the index and metadata field 'getDueDate' |
def _fetch_system_by_machine_id(self):
'''
Get a system by machine ID
Returns
dict system exists in inventory
False system does not exist in inventory
None error connection or parsing response
'''
machine_id = generate_machine_id()
... | Get a system by machine ID
Returns
dict system exists in inventory
False system does not exist in inventory
None error connection or parsing response |
def set_etag(self, etag, weak=False):
"""Set the etag, and override the old one if there was one."""
self.headers["ETag"] = quote_etag(etag, weak) | Set the etag, and override the old one if there was one. |
def write(self, font, feaFile, compiler=None):
"""Write features and class definitions for this font to a feaLib
FeatureFile object.
Returns True if feature file was modified, False if no new features
were generated.
"""
self.setContext(font, feaFile, compiler=compiler)
... | Write features and class definitions for this font to a feaLib
FeatureFile object.
Returns True if feature file was modified, False if no new features
were generated. |
def html(self, text=TEXT):
""" Generate an HTML file from the report data. """
self.logger.debug("Generating the HTML report{}..."
.format(["", " (text only)"][text]))
html = []
for piece in self._pieces:
if isinstance(piece, string_types):
... | Generate an HTML file from the report data. |
def remove_all(self, other):
"""Remove all of the elems from other.
Raises a ValueError if the multiplicity of any elem in other is greater
than in self.
"""
if not self.is_superset(other):
raise ValueError('Passed collection is not a subset of this bag')
self.discard_all(other) | Remove all of the elems from other.
Raises a ValueError if the multiplicity of any elem in other is greater
than in self. |
def install(name=None, refresh=False, pkgs=None, version=None, test=False, **kwargs):
'''
Install the named package using the IPS pkg command.
Accepts full or partial FMRI.
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
... | Install the named package using the IPS pkg command.
Accepts full or partial FMRI.
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
Multiple Package Installation Options:
pkgs
A list... |
def update_with_slice(self,flag):
'''
update object with a given time slice flag
:parameter (boolean array) flag: a flag for indexing data along the ''time'' dimension
'''
N=flag.sum()
#Get object attributes to update
varSize ... | update object with a given time slice flag
:parameter (boolean array) flag: a flag for indexing data along the ''time'' dimension |
def load_ipython_extension(ip):
"""Load the extension in IPython."""
global _loaded
if not _loaded:
plugin = StoreMagic(shell=ip, config=ip.config)
ip.plugin_manager.register_plugin('storemagic', plugin)
_loaded = True | Load the extension in IPython. |
def create(cls, name, value):
""" Create a new ssh key."""
sshkey_params = {
'name': name,
'value': value,
}
result = cls.call('hosting.ssh.create', sshkey_params)
return result | Create a new ssh key. |
def validate_proof(self, proof, target_hash, merkle_root):
"""
Takes a proof array, a target hash value, and a merkle root
Checks the validity of the proof and return true or false
:param proof:
:param target_hash:
:param merkle_root:
:return:
"""
... | Takes a proof array, a target hash value, and a merkle root
Checks the validity of the proof and return true or false
:param proof:
:param target_hash:
:param merkle_root:
:return: |
def post_fork(self, payload_handler, io_loop):
'''
After forking we need to create all of the local sockets to listen to the
router
payload_handler: function to call with your payloads
'''
self.payload_handler = payload_handler
self.io_loop = io_loop
self... | After forking we need to create all of the local sockets to listen to the
router
payload_handler: function to call with your payloads |
def filter_vectors(self, input_list):
"""
Returns subset of specified input list.
"""
unique_dict = {}
for v in input_list:
unique_dict[v[1]] = v
return list(unique_dict.values()) | Returns subset of specified input list. |
def delete(self, table, where=None):
"""Delete existing rows from a table."""
if where:
where_key, where_val = where
query = "DELETE FROM {0} WHERE {1}='{2}'".format(wrap(table), where_key, where_val)
else:
query = 'DELETE FROM {0}'.format(wrap(table))
... | Delete existing rows from a table. |
def create_namespaced_daemon_set(self, namespace, body, **kwargs):
"""
create a DaemonSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_namespaced_daemon_set(namespace, body, async... | create a DaemonSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_namespaced_daemon_set(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:pa... |
def write(self, pin, value):
""" Set the pin state.
Make sure you put the pin in output mode first.
:param pin: The label for the pin to write to. (Ex. A0)
:param value: Boolean representing the new state
"""
port, pin = self.pin_to_port(pin)
portname = 'A'
... | Set the pin state.
Make sure you put the pin in output mode first.
:param pin: The label for the pin to write to. (Ex. A0)
:param value: Boolean representing the new state |
def namespace_present(name, **kwargs):
'''
Ensures that the named namespace is present.
name
The name of the namespace.
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
namespace = __salt__['kubernetes.show_namespace'](name, **kw... | Ensures that the named namespace is present.
name
The name of the namespace. |
def WaitUntilComplete(self,poll_freq=2,timeout=None):
"""Poll until all request objects have completed.
If status is 'notStarted' or 'executing' continue polling.
If status is 'succeeded' then success
Else log as error
poll_freq option is in seconds
Returns an Int the number of unsuccessful requests. Th... | Poll until all request objects have completed.
If status is 'notStarted' or 'executing' continue polling.
If status is 'succeeded' then success
Else log as error
poll_freq option is in seconds
Returns an Int the number of unsuccessful requests. This behavior is subject to change.
>>> clc.v2.Server(alia... |
def _value_format(self, value, serie):
"""
Format value for dual value display.
"""
if self.box_mode == "extremes":
return (
'Min: %s\nQ1 : %s\nQ2 : %s\nQ3 : %s\nMax: %s' %
tuple(map(self._y_format, serie.points[1:6]))
)
eli... | Format value for dual value display. |
def find_helping_materials(project_id, **kwargs):
"""Return a list of matched helping materials for a given project ID.
:param project_id: PYBOSSA Project ID
:type project_id: integer
:param kwargs: PYBOSSA HelpingMaterial members
:type info: dict
:rtype: list
:returns: A list of helping ma... | Return a list of matched helping materials for a given project ID.
:param project_id: PYBOSSA Project ID
:type project_id: integer
:param kwargs: PYBOSSA HelpingMaterial members
:type info: dict
:rtype: list
:returns: A list of helping materials that match the kwargs |
def build_job_configs(self, args):
"""Hook to build job configurations
"""
job_configs = {}
components = Component.build_from_yamlfile(args['comp'])
datafile = args['data']
if datafile is None or datafile == 'None':
return job_configs
NAME_FACTORY.upd... | Hook to build job configurations |
def detect(byte_string):
"""
Detect if a byte string seems to contain a PEM-encoded block
:param byte_string:
A byte string to look through
:return:
A boolean, indicating if a PEM-encoded block is contained in the byte
string
"""
if not isinstance(byte_string, byte_cls... | Detect if a byte string seems to contain a PEM-encoded block
:param byte_string:
A byte string to look through
:return:
A boolean, indicating if a PEM-encoded block is contained in the byte
string |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.