code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def authDomainUser(self, realmname, username, password, environ):
"""Returns True if this username/password pair is valid for the realm,
False otherwise. Used for basic authentication."""
try:
apikey = self.user_manager.get_user_api_key(username, create=None)
return apike... | Returns True if this username/password pair is valid for the realm,
False otherwise. Used for basic authentication. |
def _networking(self):
"""
Configures the IOL bridge in uBridge.
"""
bridge_name = "IOL-BRIDGE-{}".format(self.application_id + 512)
try:
# delete any previous bridge if it exists
yield from self._ubridge_send("iol_bridge delete {name}".format(name=bridge... | Configures the IOL bridge in uBridge. |
def dissoc(m, *args, **kw):
'''
dissoc(m, k1, k2...) yields a map equivalent to m without the arguments k1, k2, etc. If m is a
mutable pythin dictionary, this is equivalent to using del m[k] for k in [k1, k2...] then
returning m itself. If m is a persistent map, this is equivalent to calling m = m.d... | dissoc(m, k1, k2...) yields a map equivalent to m without the arguments k1, k2, etc. If m is a
mutable pythin dictionary, this is equivalent to using del m[k] for k in [k1, k2...] then
returning m itself. If m is a persistent map, this is equivalent to calling m = m.discard(k)
for all the keys then re... |
def _get_annotation_entries_from_data(self, graph: BELGraph, data: EdgeData) -> Optional[List[NamespaceEntry]]:
"""Get the annotation entries from an edge data dictionary."""
annotations_dict = data.get(ANNOTATIONS)
if annotations_dict is not None:
return [
entry
... | Get the annotation entries from an edge data dictionary. |
def _draw(self):
"""
Call the drawing API for the main menu widget with the current known
terminal size and the terminal.
"""
self._window.draw(self._width, self._height, self.terminal) | Call the drawing API for the main menu widget with the current known
terminal size and the terminal. |
def resize(widthWindow, heightWindow):
"""Setup 3D projection for window"""
glViewport(0, 0, widthWindow, heightWindow)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(70, 1.0*widthWindow/heightWindow, 0.001, 10000.0)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity() | Setup 3D projection for window |
def main():
"""
Example application that sends an email when an alarm event is
detected.
"""
try:
# Retrieve the first USB device
device = AlarmDecoder(SerialDevice(interface=SERIAL_DEVICE))
# Set up an event handler and open the device
device.on_alarm += handle_alar... | Example application that sends an email when an alarm event is
detected. |
def addLogicalInterfaceToThingType(self, thingTypeId, logicalInterfaceId, schemaId = None, name = None):
"""
Adds a logical interface to a thing type.
Parameters:
- thingTypeId (string) - the thing type
- logicalInterfaceId (string) - the id returned by the platform on cr... | Adds a logical interface to a thing type.
Parameters:
- thingTypeId (string) - the thing type
- logicalInterfaceId (string) - the id returned by the platform on creation of the logical interface
Throws APIException on failure. |
def system_monitor_compact_flash_threshold_marginal_threshold(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
system_monitor = ET.SubElement(config, "system-monitor", xmlns="urn:brocade.com:mgmt:brocade-system-monitor")
compact_flash = ET.SubElement(syst... | Auto Generated Code |
def load(fnames, tag=None, sat_id=None):
"""Load Kp index files
Parameters
------------
fnames : (pandas.Series)
Series of filenames
tag : (str or NoneType)
tag or None (default=None)
sat_id : (str or NoneType)
satellite id or None (default=None)
Returns
-------... | Load Kp index files
Parameters
------------
fnames : (pandas.Series)
Series of filenames
tag : (str or NoneType)
tag or None (default=None)
sat_id : (str or NoneType)
satellite id or None (default=None)
Returns
---------
data : (pandas.DataFrame)
Object ... |
def has_add_permission(self):
"""
Returns a boolean if the current user has permission to add another object of the same
type which is being viewed/edited.
"""
has_permission = False
if self.user is not None:
# We don't check for the object level permission -... | Returns a boolean if the current user has permission to add another object of the same
type which is being viewed/edited. |
def process(self):
"""!
@brief Performs clustering process in line with rules of BANG clustering algorithm.
@return (bang) Returns itself (BANG instance).
@see get_clusters()
@see get_noise()
@see get_directory()
@see get_dendrogram()
"""
... | !
@brief Performs clustering process in line with rules of BANG clustering algorithm.
@return (bang) Returns itself (BANG instance).
@see get_clusters()
@see get_noise()
@see get_directory()
@see get_dendrogram() |
def _at_warn(self, calculator, rule, scope, block):
"""
Implements @warn
"""
value = calculator.calculate(block.argument)
log.warn(repr(value)) | Implements @warn |
def parameters_changed(self):
"""Update the gradients of parameters for warping function
This method is called when having new values of parameters for warping function, kernels
and other parameters in a normal GP
"""
# using the warped X to update
self.X = self.transfor... | Update the gradients of parameters for warping function
This method is called when having new values of parameters for warping function, kernels
and other parameters in a normal GP |
def end_log_task(task, logger=logging, level='info'):
"""
Ends a log task
Args:
task (str): name of the log task to end
logger (logging.Logger): logger to use
level (str): log level to use
Returns:
None
"""
getattr(logger, level)(END_TASK_TRIGGER_MSG % task) | Ends a log task
Args:
task (str): name of the log task to end
logger (logging.Logger): logger to use
level (str): log level to use
Returns:
None |
def get_body(pyfunction):
"""Return unindented function body"""
# FIXME scope = pyfunction.get_scope()
pymodule = pyfunction.get_module()
start, end = get_body_region(pyfunction)
return fix_indentation(pymodule.source_code[start:end], 0) | Return unindented function body |
def save_json(filename, obj, normalize=True):
'''
save_json(filename, obj) writes the given object to the given filename (or stream) in a
normalized JSON format.
The optional argument normalize (default True) may be set to False to prevent the object from
being run through neuropythy's normalize ... | save_json(filename, obj) writes the given object to the given filename (or stream) in a
normalized JSON format.
The optional argument normalize (default True) may be set to False to prevent the object from
being run through neuropythy's normalize system. |
def distance_correlation_af_inv_sqr(x, y):
"""
Square of the affinely invariant distance correlation.
Computes the estimator for the square of the affinely invariant distance
correlation between two random vectors.
.. warning:: The return value of this function is undefined when the
... | Square of the affinely invariant distance correlation.
Computes the estimator for the square of the affinely invariant distance
correlation between two random vectors.
.. warning:: The return value of this function is undefined when the
covariance matrix of :math:`x` or :math:`y` is singu... |
def __create_grid_eight_connections(self):
"""!
@brief Creates network with connections that make up eight grid structure.
@details Each oscillator may be connected with eight neighbors in line with grid structure: right, right-upper, upper, upper-left, left, left-lower, lower, lower-right.
... | !
@brief Creates network with connections that make up eight grid structure.
@details Each oscillator may be connected with eight neighbors in line with grid structure: right, right-upper, upper, upper-left, left, left-lower, lower, lower-right. |
def guide(i):
"""
Input: {}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
}
"""
url=cfg['ck_web_wiki']
out('Opening web page '+url+' ...')
i... | Input: {}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
} |
def enable_disable_on_bot_select_deselect(self):
"""
Disables the botconfig groupbox and minus buttons when no bot is selected
:return:
"""
if not self.blue_listwidget.selectedItems() and not self.orange_listwidget.selectedItems():
self.bot_config_groupbox.setDisabled... | Disables the botconfig groupbox and minus buttons when no bot is selected
:return: |
def access_token(self) -> str:
"""
The access token stored within the requested token.
"""
if self._token_expires_at < time.time() + self._REFRESH_THRESHOLD:
self.request_token()
return self._token["access_token"] | The access token stored within the requested token. |
def to_vcf(self, path, rename=None, number=None, description=None,
fill=None, write_header=True):
r"""Write to a variant call format (VCF) file.
Parameters
----------
path : string
File path.
rename : dict, optional
Rename these columns in ... | r"""Write to a variant call format (VCF) file.
Parameters
----------
path : string
File path.
rename : dict, optional
Rename these columns in the VCF.
number : dict, optional
Override the number specified in INFO headers.
description :... |
def chown(self, path, user, group, recursive=False):
"""
Change file/dir owner
:param path: path of file/dir
:param user: user name
:param group: group name
:param recursive: apply chown recursively
:return:
"""
args = {
'path': path,
... | Change file/dir owner
:param path: path of file/dir
:param user: user name
:param group: group name
:param recursive: apply chown recursively
:return: |
def imported_classifiers(p: ecore.EPackage):
"""Determines which classifiers have to be imported into given module."""
classes = {c for c in p.eClassifiers if isinstance(c, ecore.EClass)}
supertypes = itertools.chain(*(c.eAllSuperTypes() for c in classes))
imported = {c for c in superty... | Determines which classifiers have to be imported into given module. |
def encode_int(cls, obj):
"""Verify the object is an int, and ASCII-encode it.
:param int obj: An integer to be encoded.
:raises: :class:`TypeError` if `obj` is not an integer.
:return: A binary representation of the int `obj` suitable to pass as the `payload` to
send_exit().
"""
i... | Verify the object is an int, and ASCII-encode it.
:param int obj: An integer to be encoded.
:raises: :class:`TypeError` if `obj` is not an integer.
:return: A binary representation of the int `obj` suitable to pass as the `payload` to
send_exit(). |
def AgregarTambero(self, cuit, iibb=None, **kwargs):
"Agrego los datos del productor a la liq."
tambero = {'cuit': cuit, 'iibb': iibb}
self.solicitud['tambero'] = tambero
return True | Agrego los datos del productor a la liq. |
def sections(self):
""" Returns a list of all media sections in this library. Library sections may be any of
:class:`~plexapi.library.MovieSection`, :class:`~plexapi.library.ShowSection`,
:class:`~plexapi.library.MusicSection`, :class:`~plexapi.library.PhotoSection`.
"""
... | Returns a list of all media sections in this library. Library sections may be any of
:class:`~plexapi.library.MovieSection`, :class:`~plexapi.library.ShowSection`,
:class:`~plexapi.library.MusicSection`, :class:`~plexapi.library.PhotoSection`. |
def _check_span_id(self, span_id):
"""Check the format of the span_id to ensure it is 16-character hex
value representing a 64-bit number. If span_id is invalid, logs a
warning message and returns None
:type span_id: str
:param span_id: Identifier for the span, unique within a s... | Check the format of the span_id to ensure it is 16-character hex
value representing a 64-bit number. If span_id is invalid, logs a
warning message and returns None
:type span_id: str
:param span_id: Identifier for the span, unique within a span.
:rtype: str
:returns: Sp... |
def xhtml_to_html(xhtml):
"""Convert all tags in an XHTML tree to HTML by removing their
XHTML namespace.
"""
try:
xhtml = xhtml.getroot()
except AttributeError:
pass
prefix = "{%s}" % XHTML_NAMESPACE
prefix_len = len(prefix)
for el in xhtml.iter(prefix + "*"):
el... | Convert all tags in an XHTML tree to HTML by removing their
XHTML namespace. |
def push_not_registered_user_data_task(data):
"""
Async: push_not_registered_user_data_task.apply_async(args=[data], countdown=100)
"""
lock_id = "%s-push-not-registered-user-data-task-%s" % (settings.ENV_PREFIX, data["email"])
acquire_lock = lambda: cache.add(lock_id, "true", LOCK_EXPIRE) # noqa: ... | Async: push_not_registered_user_data_task.apply_async(args=[data], countdown=100) |
def get_options(argv=None):
"""
Convert options into commands
return commands, message
"""
parser = argparse.ArgumentParser(usage="spyder [options] files")
parser.add_argument('--new-instance', action='store_true', default=False,
help="Run a new instance of Spyder, even if ... | Convert options into commands
return commands, message |
def dirty(self):
'''The set of instances in this :class:`Session` which have
been modified.'''
return frozenset(chain(*tuple((sm.dirty for sm
in itervalues(self._models))))) | The set of instances in this :class:`Session` which have
been modified. |
def init_build_dir(self):
"""
Clear out the build directory and create a new one.
"""
# Destroy the build directory, if it exists
logger.debug("Initializing %s" % self.build_dir)
if self.verbosity > 1:
self.stdout.write("Initializing build directory")
... | Clear out the build directory and create a new one. |
def next_sample(self):
"""Helper function for reading in next sample."""
if self._allow_read is False:
raise StopIteration
if self.seq is not None:
if self.cur < self.num_image:
idx = self.seq[self.cur]
else:
if self.last_batch_... | Helper function for reading in next sample. |
def show_details(self):
"""
extended print details of happiness parameters
"""
res = str(self)
res += '\nDETAILS\n'
for f in self.factors:
res += str(f)
return res | extended print details of happiness parameters |
def bundle_models(models):
"""Create a bundle of selected `models`. """
custom_models = _get_custom_models(models)
if custom_models is None:
return None
key = calc_cache_key(custom_models)
bundle = _bundle_cache.get(key, None)
if bundle is None:
try:
_bundle_cache[ke... | Create a bundle of selected `models`. |
def _delete_text_ngrams(self, text_id):
"""Deletes all n-grams associated with `text_id` from the data
store.
:param text_id: database ID of text
:type text_id: `int`
"""
with self._conn:
self._conn.execute(constants.DELETE_TEXT_NGRAMS_SQL, [text_id])
... | Deletes all n-grams associated with `text_id` from the data
store.
:param text_id: database ID of text
:type text_id: `int` |
def get_assessment_offered_bank_assignment_session(self, proxy):
"""Gets the session for assigning offered assessments to bank mappings.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.assessment.AssessmentOfferedBankAssignmentSession)
- an ``AssessmentOfferedBankAssignm... | Gets the session for assigning offered assessments to bank mappings.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.assessment.AssessmentOfferedBankAssignmentSession)
- an ``AssessmentOfferedBankAssignmentSession``
raise: NullArgument - ``proxy`` is ``null``
ra... |
def buildDPList(self):
"""Builds list of data products."""
updated = False
dps = []
itemlist = self.getItemDPList()
# first remove all items marked for removal, in case their names clash with new or renamed items
for item, dp in itemlist:
item._policy = item._... | Builds list of data products. |
def tag_dssp_data(assembly, loop_assignments=(' ', 'B', 'S', 'T')):
"""Adds output data from DSSP to an Assembly.
A dictionary will be added to the `tags` dictionary of each
residue called `dssp_data`, which contains the secondary
structure definition, solvent accessibility phi and psi values
from ... | Adds output data from DSSP to an Assembly.
A dictionary will be added to the `tags` dictionary of each
residue called `dssp_data`, which contains the secondary
structure definition, solvent accessibility phi and psi values
from DSSP. A list of regions of continuous secondary assignments
will also b... |
def get_shelveset(self, shelveset_id, request_data=None):
"""GetShelveset.
Get a single deep shelveset.
:param str shelveset_id: Shelveset's unique ID
:param :class:`<TfvcShelvesetRequestData> <azure.devops.v5_0.tfvc.models.TfvcShelvesetRequestData>` request_data: includeDetails, include... | GetShelveset.
Get a single deep shelveset.
:param str shelveset_id: Shelveset's unique ID
:param :class:`<TfvcShelvesetRequestData> <azure.devops.v5_0.tfvc.models.TfvcShelvesetRequestData>` request_data: includeDetails, includeWorkItems, maxChangeCount, and maxCommentLength
:rtype: :clas... |
def release_save(lock):
"""Release a lock and return its state."""
if hasattr(lock, '_release_save'):
return lock._release_save()
elif hasattr(lock, 'release'):
lock.release()
else:
raise TypeError('expecting Lock/RLock') | Release a lock and return its state. |
def getecho(self):
'''This returns the terminal echo mode. This returns True if echo is
on or False if echo is off. Child applications that are expecting you
to enter a password often set ECHO False. See waitnoecho().
Not supported on platforms where ``isatty()`` returns False. '''
... | This returns the terminal echo mode. This returns True if echo is
on or False if echo is off. Child applications that are expecting you
to enter a password often set ECHO False. See waitnoecho().
Not supported on platforms where ``isatty()`` returns False. |
def not_right(self, num):
"""
WITH SLICES BEING FLAT, WE NEED A SIMPLE WAY TO SLICE FROM THE LEFT [:-num:]
"""
if not self.list:
self._build_list()
if num == None:
return self.list[:-1:]
if num <= 0:
return []
return self.list... | WITH SLICES BEING FLAT, WE NEED A SIMPLE WAY TO SLICE FROM THE LEFT [:-num:] |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# extracting dictionary of coefficients specific to required
#... | See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values. |
def _check_and_replace_parser_args(parser, section, option, rename_func, make_dirs=True):
""" Searches for parser settings that define filenames.
If such settings are found, they are renamed according to the wildcard
rules. Moreover, it is also tried to create the corresponding folders.
... | Searches for parser settings that define filenames.
If such settings are found, they are renamed according to the wildcard
rules. Moreover, it is also tried to create the corresponding folders.
:param parser: A config parser
:param section: A config section
:param option: The ... |
def user_post_delete_handler(sender, **kwargs):
"""Sends a metric to InfluxDB when a User object is deleted."""
total = get_user_model().objects.all().count()
data = [{
'measurement': 'django_auth_user_delete',
'tags': {'host': settings.INFLUXDB_TAGS_HOST, },
'fields': {'value': 1, }... | Sends a metric to InfluxDB when a User object is deleted. |
def to_string(self, verbose=0):
"""String representation."""
rows = [[it + 1] + list(map(str, (self[k][it] for k in self.keys())))
for it in range(self.num_iterations)]
return tabulate(rows, headers=["Iter"] + list(self.keys())) | String representation. |
def select(self, filter_by=None):
"""
Parameters
----------
filter_by: callable, default None
Callable must take one argument (a record of queryset), and return True to keep record, or False to skip it.
Example : .select(lambda x: x.name == "my_name").
... | Parameters
----------
filter_by: callable, default None
Callable must take one argument (a record of queryset), and return True to keep record, or False to skip it.
Example : .select(lambda x: x.name == "my_name").
If None, records are not filtered.
Returns
... |
def getCol(self, x):
"""return the x-th column, starting at 0"""
return [self.getCell(x, i) for i in self.__size_range] | return the x-th column, starting at 0 |
def has_member(self, device_object):
"""Return bool whether group has a device as a member.
Args:
device_object (Computer or MobileDevice). Membership is
determined by ID, as names can be shared amongst devices.
"""
if device_object.tag == "computer":
... | Return bool whether group has a device as a member.
Args:
device_object (Computer or MobileDevice). Membership is
determined by ID, as names can be shared amongst devices. |
def search(self, resource, resource_class, search_filter=None, dmql_query=None, limit=9999999, offset=0,
optional_parameters=None, auto_offset=True, query_type='DMQL2', standard_names=0,
response_format='COMPACT-DECODED'):
"""
Preform a search on the RETS board
:par... | Preform a search on the RETS board
:param resource: The resource that contains the class to search
:param resource_class: The class to search
:param search_filter: The query as a dict
:param dmql_query: The query in dmql format
:param limit: Limit search values count
:par... |
def clear_dir(self):
"""Clear the output directory of all output files."""
for snapshot in output_utils.get_filenames(self.output_dir):
if snapshot.endswith('.pkl'):
os.remove(snapshot) | Clear the output directory of all output files. |
def imag(self):
"""Imaginary part"""
if hasattr(self.val, 'imag'):
return self.val.imag
else:
# SymPy
return self.val.as_real_imag()[1] | Imaginary part |
def make_class(clsname, func, attrs):
"""Turn a funcs list element into a class object."""
clsdict = {"__set__": create_setter(func, attrs)}
if len(attrs) > 0:
clsdict["__init__"] = create_init(attrs)
clsobj = type(str(clsname), (Descriptor, ), clsdict)
clsobj.__doc__ = docstrings.get(clsnam... | Turn a funcs list element into a class object. |
def get_site_pattern(agent):
"""Construct a dictionary of Monomer site states from an Agent.
This crates the mapping to the associated PySB monomer from an
INDRA Agent object."""
if not isinstance(agent, ist.Agent):
return {}
pattern = {}
# Handle bound conditions
for bc in agent.bo... | Construct a dictionary of Monomer site states from an Agent.
This crates the mapping to the associated PySB monomer from an
INDRA Agent object. |
def resolve_image(input, resolvers=None, fmt='png', width=300, height=300, frame=False, crop=None, bgcolor=None,
atomcolor=None, hcolor=None, bondcolor=None, framecolor=None, symbolfontsize=11, linewidth=2,
hsymbol='special', csymbol='special', stereolabels=False, stereowedges=True, ... | Resolve input to a 2D image depiction.
:param string input: Chemical identifier to resolve
:param list(string) resolvers: (Optional) Ordered list of resolvers to use
:param string fmt: (Optional) gif or png image format (default png)
:param int width: (Optional) Image width in pixels (default 300)
... |
def do_set_device(self, args):
"""Set the PLM OS device.
Device defaults to /dev/ttyUSB0
Usage:
set_device device
Arguments:
device: Required - INSTEON PLM device
"""
params = args.split()
device = None
try:
device = ... | Set the PLM OS device.
Device defaults to /dev/ttyUSB0
Usage:
set_device device
Arguments:
device: Required - INSTEON PLM device |
def _pfp__snapshot(self, recurse=True):
"""Save off the current value of the field
"""
super(Array, self)._pfp__snapshot(recurse=recurse)
self.snapshot_raw_data = self.raw_data
if recurse:
for item in self.items:
item._pfp__snapshot(recurse=recurse) | Save off the current value of the field |
def load_scatter_table(self, fn):
"""Load the scattering lookup tables.
Load the scattering lookup tables saved with save_scatter_table.
Args:
fn: The name of the scattering table file.
"""
data = pickle.load(file(fn))
if ("version" not ... | Load the scattering lookup tables.
Load the scattering lookup tables saved with save_scatter_table.
Args:
fn: The name of the scattering table file. |
def record_start(self, call_params):
"""REST RecordStart helper
"""
path = '/' + self.api_version + '/RecordStart/'
method = 'POST'
return self.request(path, method, call_params) | REST RecordStart helper |
def enable_signals(self):
'''
e.g signal_dict = {signal_path:signal_receiver_path_list, ....}
:return:
'''
signal_dict = self.settings[self.signal_key] or {}
for i in signal_dict.keys():
sig_module, signal_class = self.import_class_from_path(i)
for... | e.g signal_dict = {signal_path:signal_receiver_path_list, ....}
:return: |
def sampleV(self,R,z,n=1,**kwargs):
"""
NAME:
sampleV
PURPOSE:
sample a radial, azimuthal, and vertical velocity at R,z
INPUT:
R - Galactocentric distance (can be Quantity)
z - height (can be Quantity)
n= number of distances t... | NAME:
sampleV
PURPOSE:
sample a radial, azimuthal, and vertical velocity at R,z
INPUT:
R - Galactocentric distance (can be Quantity)
z - height (can be Quantity)
n= number of distances to sample
OUTPUT:
list of samples
... |
def get_zonecode():
'''
Get current timezone (i.e. PST, MDT, etc)
Returns:
str: An abbreviated timezone code
CLI Example:
.. code-block:: bash
salt '*' timezone.get_zonecode
'''
tz_object = pytz.timezone(get_zone())
loc_time = tz_object.localize(datetime.utcnow())
... | Get current timezone (i.e. PST, MDT, etc)
Returns:
str: An abbreviated timezone code
CLI Example:
.. code-block:: bash
salt '*' timezone.get_zonecode |
def value(self, observation, input_actions=None):
""" Calculate value for given state """
action, value = self(observation, input_actions)
return value | Calculate value for given state |
def plot_drawdown_underwater(returns, ax=None, **kwargs):
"""
Plots how far underwaterr returns are over time, or plots current
drawdown vs. date.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full... | Plots how far underwaterr returns are over time, or plots current
drawdown vs. date.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
ax : matplotlib.Axes, optional
Axes upon whic... |
def compute_venn3_areas(diagram_areas, normalize_to=1.0, _minimal_area=1e-6):
'''
The list of venn areas is given as 7 values, corresponding to venn diagram areas in the following order:
(Abc, aBc, ABc, abC, AbC, aBC, ABC)
(i.e. last element corresponds to the size of intersection A&B&C).
The retur... | The list of venn areas is given as 7 values, corresponding to venn diagram areas in the following order:
(Abc, aBc, ABc, abC, AbC, aBC, ABC)
(i.e. last element corresponds to the size of intersection A&B&C).
The return value is a list of areas (A_a, A_b, A_c, A_ab, A_bc, A_ac, A_abc),
such that the tot... |
def _parseMzml(self):
""" #TODO: docstring """
#TODO: this is already pretty nested, reduce that eg by using a function
# processRunNode
for event, element, elementTag in self:
if elementTag == 'mzML':
metadataNode = ETREE.Element(self.elementTag,
... | #TODO: docstring |
def resolution(file_, resolution_string):
"""
A filter to return the URL for the provided resolution of the thumbnail.
"""
if sorl_settings.THUMBNAIL_DUMMY:
dummy_source = sorl_settings.THUMBNAIL_DUMMY_SOURCE
source = dummy_source.replace('%(width)s', '(?P<width>[0-9]+)')
source ... | A filter to return the URL for the provided resolution of the thumbnail. |
def _compare_keys(element1, element2, key, compare_func, *args):
"""
Compares a specific key between two elements of a basis set
If the key exists in one element but not the other, False is returned.
If the key exists in neither element, True is returned.
Parameters
----------
element1 : ... | Compares a specific key between two elements of a basis set
If the key exists in one element but not the other, False is returned.
If the key exists in neither element, True is returned.
Parameters
----------
element1 : dict
Basis info for an element
element2 : dict
Basis info... |
def validate_sample_frame(sample_frame):
"""Makes sure that `sample_frame` has the columns we expect.
:param DataFrame sample_frame: A sample data frame.
:return: True (or raises an exception)
:raises TypeError: if sample_frame is not a pandas DataFrame
:raises ValueError: if columns are missing or... | Makes sure that `sample_frame` has the columns we expect.
:param DataFrame sample_frame: A sample data frame.
:return: True (or raises an exception)
:raises TypeError: if sample_frame is not a pandas DataFrame
:raises ValueError: if columns are missing or the wrong type |
def run(self):
"""
the main loop
"""
try:
master_process = BackgroundProcess.objects.filter(pk=self.process_id).first()
if master_process:
master_process.last_update = now()
master_process.message = 'init child processes'
... | the main loop |
def request_token(self):
""" Gets OAuth request token """
client = OAuth1(
client_key=self._server_cache[self.client.server].key,
client_secret=self._server_cache[self.client.server].secret,
callback_uri=self.callback,
)
request = {"auth": client}
... | Gets OAuth request token |
def update_result(result):
"""Update a result for a given result ID.
:param result: PYBOSSA result
"""
try:
result_id = result.id
result = _forbidden_attributes(result)
res = _pybossa_req('put', 'result', result_id, payload=result.data)
if res.get('id'):
ret... | Update a result for a given result ID.
:param result: PYBOSSA result |
def pause_point(self,
msg='SHUTIT PAUSE POINT',
shutit_pexpect_child=None,
print_input=True,
level=1,
resize=True,
color='32',
default_msg=None,
interact=False,
wait=-... | Inserts a pause in the build session, which allows the user to try
things out before continuing. Ignored if we are not in an interactive
mode, or the interactive level is less than the passed-in one.
Designed to help debug the build, or drop to on failure so the
situation can be debugged.
@param msg: ... |
def Network_getCertificate(self, origin):
"""
Function path: Network.getCertificate
Domain: Network
Method name: getCertificate
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'origin' (type: string) -> Origin to get certificate for.
Returns:
'table... | Function path: Network.getCertificate
Domain: Network
Method name: getCertificate
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'origin' (type: string) -> Origin to get certificate for.
Returns:
'tableNames' (type: array) -> No description
Descr... |
def lock(self, key, ttl=0):
"""Lock and retrieve a key-value entry in Couchbase.
:param key: A string which is the key to lock.
:param ttl: a TTL for which the lock should be valid.
While the lock is active, attempts to access the key (via
other :meth:`lock`, :meth:`ups... | Lock and retrieve a key-value entry in Couchbase.
:param key: A string which is the key to lock.
:param ttl: a TTL for which the lock should be valid.
While the lock is active, attempts to access the key (via
other :meth:`lock`, :meth:`upsert` or other mutation calls)
... |
def mark_all_read(user):
"""
Mark all message instances for a user as read.
:param user: user instance for the recipient
"""
BackendClass = stored_messages_settings.STORAGE_BACKEND
backend = BackendClass()
backend.inbox_purge(user) | Mark all message instances for a user as read.
:param user: user instance for the recipient |
def n_tanks(Q_plant, sed_inputs=sed_dict):
"""Return the number of sedimentation tanks required for a given flow rate.
Parameters
----------
Q_plant : float
Total plant flow rate
sed_inputs : dict
A dictionary of all of the constant inputs needed for sedimentation tank
calcul... | Return the number of sedimentation tanks required for a given flow rate.
Parameters
----------
Q_plant : float
Total plant flow rate
sed_inputs : dict
A dictionary of all of the constant inputs needed for sedimentation tank
calculations can be found in sed.yaml
Returns
--... |
def validate_key(self, key):
"""
Validate the provided reset key.
Returns:
The validated key.
Raises:
serializers.ValidationError:
If the provided key does not exist.
"""
if not models.PasswordResetToken.valid_tokens.filter(key=ke... | Validate the provided reset key.
Returns:
The validated key.
Raises:
serializers.ValidationError:
If the provided key does not exist. |
def rank_targets(sample_frame, ref_targets, ref_sample):
"""Uses the geNorm algorithm to determine the most stably expressed
genes from amongst ref_targets in your sample.
See Vandesompele et al.'s 2002 Genome Biology paper for information about
the algorithm: http://dx.doi.org/10.1186/gb-2002-3-7-rese... | Uses the geNorm algorithm to determine the most stably expressed
genes from amongst ref_targets in your sample.
See Vandesompele et al.'s 2002 Genome Biology paper for information about
the algorithm: http://dx.doi.org/10.1186/gb-2002-3-7-research0034
:param DataFrame sample_frame: A sample data frame... |
def superuser_required(view_func=None, redirect_field_name=REDIRECT_FIELD_NAME,
login_url='admin:login'):
"""
Decorator for views that checks that the user is logged in and is a superuser
member, redirecting to the login page if necessary.
"""
actual_decorator = user_passes_te... | Decorator for views that checks that the user is logged in and is a superuser
member, redirecting to the login page if necessary. |
def from_transform(cls, matrix):
r"""
:param matrix: 4x4 3d affine transform matrix
:type matrix: :class:`FreeCAD.Matrix`
:return: a unit, zero offset coordinate system transformed by the given matrix
:rtype: :class:`CoordSystem`
Individual rotation & translation matrici... | r"""
:param matrix: 4x4 3d affine transform matrix
:type matrix: :class:`FreeCAD.Matrix`
:return: a unit, zero offset coordinate system transformed by the given matrix
:rtype: :class:`CoordSystem`
Individual rotation & translation matricies are:
.. math::
R... |
def map_batch_parallel(input_list, batch_size, item_mapper=None, batch_mapper=None, flatten=True, n_jobs=-1, **kwargs):
"""
Split the data into batches and process each batch in its own thread.
Args:
input_list: An input object that has a list-like interface (indexing and slicing).
item_map... | Split the data into batches and process each batch in its own thread.
Args:
input_list: An input object that has a list-like interface (indexing and slicing).
item_mapper: (optional) A function to apply to each item in the batch.
batch_mapper: (optional) A function to apply to each batch. E... |
def procces_filters(all_needs, current_needlist):
"""
Filters all needs with given configuration
:param current_needlist: needlist object, which stores all filters
:param all_needs: List of all needs inside document
:return: list of needs, which passed the filters
"""
if current_needlist[... | Filters all needs with given configuration
:param current_needlist: needlist object, which stores all filters
:param all_needs: List of all needs inside document
:return: list of needs, which passed the filters |
def compare_datetimes(d1, d2):
""" Compares two datetimes safely, whether they are timezone-naive or timezone-aware.
If either datetime is naive it is converted to an aware datetime assuming UTC.
Args:
d1: first datetime.
d2: second datetime.
Returns:
-1 if d1 < d2, 0 if they are the same, or +1 ... | Compares two datetimes safely, whether they are timezone-naive or timezone-aware.
If either datetime is naive it is converted to an aware datetime assuming UTC.
Args:
d1: first datetime.
d2: second datetime.
Returns:
-1 if d1 < d2, 0 if they are the same, or +1 is d1 > d2. |
def dt_second(x):
"""Extracts the second out of a datetime samples.
:returns: an expression containing the second extracted from a datetime column.
Example:
>>> import vaex
>>> import numpy as np
>>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:34:22'], dtype=... | Extracts the second out of a datetime samples.
:returns: an expression containing the second extracted from a datetime column.
Example:
>>> import vaex
>>> import numpy as np
>>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:34:22'], dtype=np.datetime64)
>>> df... |
def correct_dihedral(self, construction_table,
use_lookup=None):
"""Reindexe the dihedral defining atom if linear reference is used.
Uses :meth:`~Cartesian.check_dihedral` to obtain the problematic
indices.
Args:
construction_table (pd.DataFrame):
... | Reindexe the dihedral defining atom if linear reference is used.
Uses :meth:`~Cartesian.check_dihedral` to obtain the problematic
indices.
Args:
construction_table (pd.DataFrame):
use_lookup (bool): Use a lookup variable for
:meth:`~chemcoord.Cartesian.g... |
def clear_data(self, request):
"""
Clear all OAuth related data from the session store.
"""
for key in request.session.keys():
if key.startswith(constants.SESSION_KEY):
del request.session[key] | Clear all OAuth related data from the session store. |
def trunk(self, unique=True):
"""Get the trunk of the tree starting at this root."""
# uniqueness is not correct in `trunk` yet
unique = False
res = []
if self.children:
if self.name is not None:
res.append(self)
for child in self.children:... | Get the trunk of the tree starting at this root. |
def site_config_dir(self):
"""Return ``site_config_dir``."""
directory = appdirs.site_config_dir(self.appname, self.appauthor,
version=self.version, multipath=self.multipath)
if self.create:
self._ensure_directory_exists(directory)
return director... | Return ``site_config_dir``. |
def startup_config_path(self):
"""
:returns: Path of the startup config
"""
return os.path.join(self._working_directory, "configs", "i{}_startup-config.cfg".format(self._dynamips_id)) | :returns: Path of the startup config |
def head(bucket, path='', key=None, keyid=None, service_url=None,
verify_ssl=None, kms_keyid=None, location=None, role_arn=None,
path_style=None, https_enable=None):
'''
Return the metadata for a bucket, or an object in a bucket.
CLI Examples:
.. code-block:: bash
salt mymin... | Return the metadata for a bucket, or an object in a bucket.
CLI Examples:
.. code-block:: bash
salt myminion s3.head mybucket
salt myminion s3.head mybucket myfile.png |
def isWOSFile(infile, checkedLines = 3):
"""Determines if _infile_ is the path to a WOS file. A file is considerd to be a WOS file if it has the correct encoding (`utf-8` with a BOM) and within the first _checkedLines_ a line starts with `"VR 1.0"`.
# Parameters
_infile_ : `str`
> The path to the tar... | Determines if _infile_ is the path to a WOS file. A file is considerd to be a WOS file if it has the correct encoding (`utf-8` with a BOM) and within the first _checkedLines_ a line starts with `"VR 1.0"`.
# Parameters
_infile_ : `str`
> The path to the targets file
_checkedLines_ : `optional [int]`... |
def _get_tap_file_path(self, test_case):
"""Get the TAP output file path for the test case."""
sanitized_test_case = test_case.translate(self._sanitized_table)
tap_file = sanitized_test_case + ".tap"
if self.outdir:
return os.path.join(self.outdir, tap_file)
return ta... | Get the TAP output file path for the test case. |
def publish(self, message):
"""Publish a single message.
Add the given message to this object; this will cause it to be
published once the batch either has enough messages or a sufficient
period of time has elapsed.
This method is called by :meth:`~.PublisherClient.publish`.
... | Publish a single message.
Add the given message to this object; this will cause it to be
published once the batch either has enough messages or a sufficient
period of time has elapsed.
This method is called by :meth:`~.PublisherClient.publish`.
Args:
message (~.pub... |
def manage(self, namespace, unknown):
"""Execute the manage command for django
:param namespace: namespace containing args with django manage.py arguments
:type namespace: Namespace
:param unknown: list of unknown arguments that get passed to the manage.py command
:type unknown:... | Execute the manage command for django
:param namespace: namespace containing args with django manage.py arguments
:type namespace: Namespace
:param unknown: list of unknown arguments that get passed to the manage.py command
:type unknown: list
:returns: None
:rtype: None... |
def create_link(id_link, post_data):
'''
Add record in link.
'''
if MLink.get_by_uid(id_link):
return False
try:
the_order = int(post_data['order'])
except:
the_order = 999
TabLink.create(name=post_data['name'],
... | Add record in link. |
def DefaultSelector():
""" This function serves as a first call for DefaultSelector to
detect if the select module is being monkey-patched incorrectly
by eventlet, greenlet, and preserve proper behavior. """
global _DEFAULT_SELECTOR
if _DEFAULT_SELECTOR is None:
if platform.python_implementa... | This function serves as a first call for DefaultSelector to
detect if the select module is being monkey-patched incorrectly
by eventlet, greenlet, and preserve proper behavior. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.