code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def JT(self):
r'''Joule Thomson coefficient of the chemical at its
current phase and temperature, in units of [K/Pa].
.. math::
\mu_{JT} = \left(\frac{\partial T}{\partial P}\right)_H = \frac{1}{C_p}
\left[T \left(\frac{\partial V}{\partial T}\right)_P - V\right]
... | r'''Joule Thomson coefficient of the chemical at its
current phase and temperature, in units of [K/Pa].
.. math::
\mu_{JT} = \left(\frac{\partial T}{\partial P}\right)_H = \frac{1}{C_p}
\left[T \left(\frac{\partial V}{\partial T}\right)_P - V\right]
= \frac{V}{C_p}\l... | Below is the the instruction that describes the task:
### Input:
r'''Joule Thomson coefficient of the chemical at its
current phase and temperature, in units of [K/Pa].
.. math::
\mu_{JT} = \left(\frac{\partial T}{\partial P}\right)_H = \frac{1}{C_p}
\left[T \left(\frac{\par... |
def remove_actor(self, actor, reset_camera=False):
"""
Removes an actor from the Renderer.
Parameters
----------
actor : vtk.vtkActor
Actor that has previously added to the Renderer.
reset_camera : bool, optional
Resets camera so all actors can b... | Removes an actor from the Renderer.
Parameters
----------
actor : vtk.vtkActor
Actor that has previously added to the Renderer.
reset_camera : bool, optional
Resets camera so all actors can be seen.
Returns
-------
success : bool
... | Below is the the instruction that describes the task:
### Input:
Removes an actor from the Renderer.
Parameters
----------
actor : vtk.vtkActor
Actor that has previously added to the Renderer.
reset_camera : bool, optional
Resets camera so all actors can be ... |
def step_context(self):
"""
Access the step_context
:returns: twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextList
:rtype: twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextList
"""
... | Access the step_context
:returns: twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextList
:rtype: twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextList | Below is the the instruction that describes the task:
### Input:
Access the step_context
:returns: twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextList
:rtype: twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepCont... |
def image(self):
"""
Returns a json-schema document that represents a single image entity.
"""
uri = "/%s/image" % self.uri_base
resp, resp_body = self.api.method_get(uri)
return resp_body | Returns a json-schema document that represents a single image entity. | Below is the the instruction that describes the task:
### Input:
Returns a json-schema document that represents a single image entity.
### Response:
def image(self):
"""
Returns a json-schema document that represents a single image entity.
"""
uri = "/%s/image" % self.uri_base
... |
def get_seeds(self, threshold):
""" Returns a list of seed points for isosurface extraction
given a threshold value
@ In, threshold, float, the isovalue for which we want to
identify seed points for isosurface extraction
"""
seeds = []
for e1, e2 i... | Returns a list of seed points for isosurface extraction
given a threshold value
@ In, threshold, float, the isovalue for which we want to
identify seed points for isosurface extraction | Below is the the instruction that describes the task:
### Input:
Returns a list of seed points for isosurface extraction
given a threshold value
@ In, threshold, float, the isovalue for which we want to
identify seed points for isosurface extraction
### Response:
def get_see... |
def list_findings(
self,
parent,
filter_=None,
order_by=None,
read_time=None,
field_mask=None,
page_size=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""... | Lists an organization or source's findings.
To list across all sources provide a ``-`` as the source id. Example:
/v1beta1/organizations/123/sources/-/findings
Example:
>>> from google.cloud import securitycenter_v1beta1
>>>
>>> client = securitycenter_v1bet... | Below is the the instruction that describes the task:
### Input:
Lists an organization or source's findings.
To list across all sources provide a ``-`` as the source id. Example:
/v1beta1/organizations/123/sources/-/findings
Example:
>>> from google.cloud import securitycenter_... |
def names(self):
"""The list of column names (List[str])."""
if not self._ex._cache.names_valid():
self._ex._cache.flush()
self._frame(fill_cache=True)
return list(self._ex._cache.names) | The list of column names (List[str]). | Below is the the instruction that describes the task:
### Input:
The list of column names (List[str]).
### Response:
def names(self):
"""The list of column names (List[str])."""
if not self._ex._cache.names_valid():
self._ex._cache.flush()
self._frame(fill_cache=True)
... |
def __regpoly_coords(self, x0, y0, x1, y1, sides, start, extent):
"""Create the coordinates of the regular polygon specified"""
coords = []
if extent == 0:
return coords
xm = (x0 + x1) / 2.
ym = (y0 + y1) / 2.
rx = xm - x0
ry = ym - y0
n = s... | Create the coordinates of the regular polygon specified | Below is the the instruction that describes the task:
### Input:
Create the coordinates of the regular polygon specified
### Response:
def __regpoly_coords(self, x0, y0, x1, y1, sides, start, extent):
"""Create the coordinates of the regular polygon specified"""
coords = []
if extent == 0:... |
def groupby_dict(dictionary, key):
''' Group dict of dicts by key.
'''
return dict((k, list(g)) for k, g in itertools.groupby(sorted(dictionary.keys(), key=lambda name: dictionary[name][key]), key=lambda name: dictionary[name][key])) | Group dict of dicts by key. | Below is the the instruction that describes the task:
### Input:
Group dict of dicts by key.
### Response:
def groupby_dict(dictionary, key):
''' Group dict of dicts by key.
'''
return dict((k, list(g)) for k, g in itertools.groupby(sorted(dictionary.keys(), key=lambda name: dictionary[name][key]), ... |
def from_meta(cls, meta: "DocstringMeta") -> T.Any:
"""Copy DocstringMeta from another instance."""
return cls(args=meta.args, description=meta.description) | Copy DocstringMeta from another instance. | Below is the the instruction that describes the task:
### Input:
Copy DocstringMeta from another instance.
### Response:
def from_meta(cls, meta: "DocstringMeta") -> T.Any:
"""Copy DocstringMeta from another instance."""
return cls(args=meta.args, description=meta.description) |
def random_terms(self):
'''Return dict of all and only random effects in model.'''
return {k: v for (k, v) in self.terms.items() if v.random} | Return dict of all and only random effects in model. | Below is the the instruction that describes the task:
### Input:
Return dict of all and only random effects in model.
### Response:
def random_terms(self):
'''Return dict of all and only random effects in model.'''
return {k: v for (k, v) in self.terms.items() if v.random} |
def passphrase_file(passphrase=None):
"""Read passphrase from a file. This should only ever be
used by our built in integration tests. At this time,
during normal operation, only pinentry is supported for
entry of passwords."""
cmd = []
pass_file = None
if not passphrase and 'CRYPTORITO_PASS... | Read passphrase from a file. This should only ever be
used by our built in integration tests. At this time,
during normal operation, only pinentry is supported for
entry of passwords. | Below is the the instruction that describes the task:
### Input:
Read passphrase from a file. This should only ever be
used by our built in integration tests. At this time,
during normal operation, only pinentry is supported for
entry of passwords.
### Response:
def passphrase_file(passphrase=None):
... |
def any_filepath_field(field, **kwargs):
"""
Lookup for nearest existing file
"""
def get_some_file(path):
subdirs, files = [], []
for entry in os.listdir(path):
entry_path = os.path.join(path, entry)
if os.path.isdir(entry_path):
subdir... | Lookup for nearest existing file | Below is the the instruction that describes the task:
### Input:
Lookup for nearest existing file
### Response:
def any_filepath_field(field, **kwargs):
"""
Lookup for nearest existing file
"""
def get_some_file(path):
subdirs, files = [], []
for entry in os.listdir(path):
... |
def plot_assets(calc_id=-1, site_model=False):
"""
Plot the sites and the assets
"""
# NB: matplotlib is imported inside since it is a costly import
import matplotlib.pyplot as p
from openquake.hmtk.plotting.patch import PolygonPatch
dstore = util.read(calc_id)
try:
region = dsto... | Plot the sites and the assets | Below is the the instruction that describes the task:
### Input:
Plot the sites and the assets
### Response:
def plot_assets(calc_id=-1, site_model=False):
"""
Plot the sites and the assets
"""
# NB: matplotlib is imported inside since it is a costly import
import matplotlib.pyplot as p
fro... |
def load(prefix, epoch, load_optimizer_states=False, **kwargs):
"""Creates a model from previously saved checkpoint.
Parameters
----------
prefix : str
path prefix of saved model files. You should have
"prefix-symbol.json", "prefix-xxxx.params", and
o... | Creates a model from previously saved checkpoint.
Parameters
----------
prefix : str
path prefix of saved model files. You should have
"prefix-symbol.json", "prefix-xxxx.params", and
optionally "prefix-xxxx.states", where xxxx is the
epoch number.... | Below is the the instruction that describes the task:
### Input:
Creates a model from previously saved checkpoint.
Parameters
----------
prefix : str
path prefix of saved model files. You should have
"prefix-symbol.json", "prefix-xxxx.params", and
optiona... |
def main(argv=sys.argv):
# type: (List[str]) -> int
"""Parse and check the command line arguments."""
parser = optparse.OptionParser(
usage="""\
usage: %prog [options] -o <output_path> <module_path> [exclude_pattern, ...]
Look recursively in <module_path> for Python modules and packages and create
... | Parse and check the command line arguments. | Below is the the instruction that describes the task:
### Input:
Parse and check the command line arguments.
### Response:
def main(argv=sys.argv):
# type: (List[str]) -> int
"""Parse and check the command line arguments."""
parser = optparse.OptionParser(
usage="""\
usage: %prog [options] -o <... |
def snip_string_middle(string, max_len=20, snip_string='...'):
"""
>>> snip_string_middle('this is long', 8)
'th...ong'
>>> snip_string_middle('this is long', 12)
'this is long'
>>> snip_string_middle('this is long', 8, '~')
'thi~long'
"""
#warn('use snip_string() instead', Dep... | >>> snip_string_middle('this is long', 8)
'th...ong'
>>> snip_string_middle('this is long', 12)
'this is long'
>>> snip_string_middle('this is long', 8, '~')
'thi~long' | Below is the the instruction that describes the task:
### Input:
>>> snip_string_middle('this is long', 8)
'th...ong'
>>> snip_string_middle('this is long', 12)
'this is long'
>>> snip_string_middle('this is long', 8, '~')
'thi~long'
### Response:
def snip_string_middle(string, max_len=20, snip... |
def transfer_call(self, call_params):
"""REST Transfer Live Call Helper
"""
path = '/' + self.api_version + '/TransferCall/'
method = 'POST'
return self.request(path, method, call_params) | REST Transfer Live Call Helper | Below is the the instruction that describes the task:
### Input:
REST Transfer Live Call Helper
### Response:
def transfer_call(self, call_params):
"""REST Transfer Live Call Helper
"""
path = '/' + self.api_version + '/TransferCall/'
method = 'POST'
return self.request(path... |
def checkBim(fileName, minNumber, chromosome):
"""Checks the BIM file for chrN markers.
:param fileName:
:param minNumber:
:param chromosome:
:type fileName: str
:type minNumber: int
:type chromosome: str
:returns: ``True`` if there are at least ``minNumber`` markers on
... | Checks the BIM file for chrN markers.
:param fileName:
:param minNumber:
:param chromosome:
:type fileName: str
:type minNumber: int
:type chromosome: str
:returns: ``True`` if there are at least ``minNumber`` markers on
chromosome ``chromosome``, ``False`` otherwise. | Below is the the instruction that describes the task:
### Input:
Checks the BIM file for chrN markers.
:param fileName:
:param minNumber:
:param chromosome:
:type fileName: str
:type minNumber: int
:type chromosome: str
:returns: ``True`` if there are at least ``minNumber`` markers on... |
def _get_request_body_bytes_only(param_name, param_value):
'''Validates the request body passed in and converts it to bytes
if our policy allows it.'''
if param_value is None:
return b''
if isinstance(param_value, bytes):
return param_value
raise TypeError(_ERROR_VALUE_SHOULD_BE_BY... | Validates the request body passed in and converts it to bytes
if our policy allows it. | Below is the the instruction that describes the task:
### Input:
Validates the request body passed in and converts it to bytes
if our policy allows it.
### Response:
def _get_request_body_bytes_only(param_name, param_value):
'''Validates the request body passed in and converts it to bytes
if our policy... |
def calculate2d(self, force=True):
"""
recalculate 2d coordinates. currently rings can be calculated badly.
:param force: ignore existing coordinates of atoms
"""
for ml in (self.__reagents, self.__reactants, self.__products):
for m in ml:
m.calculate... | recalculate 2d coordinates. currently rings can be calculated badly.
:param force: ignore existing coordinates of atoms | Below is the the instruction that describes the task:
### Input:
recalculate 2d coordinates. currently rings can be calculated badly.
:param force: ignore existing coordinates of atoms
### Response:
def calculate2d(self, force=True):
"""
recalculate 2d coordinates. currently rings can be c... |
def assignPrivilege(self, rolename, privilege="ACCESS"):
"""
Administrative access to ArcGIS Server is modeled as three broad
tiers of privileges:
ADMINISTER - A role that possesses this privilege has
unrestricted administrative access to ArcGIS
... | Administrative access to ArcGIS Server is modeled as three broad
tiers of privileges:
ADMINISTER - A role that possesses this privilege has
unrestricted administrative access to ArcGIS
Server.
PUBLISH - A role with PUBLISH pri... | Below is the the instruction that describes the task:
### Input:
Administrative access to ArcGIS Server is modeled as three broad
tiers of privileges:
ADMINISTER - A role that possesses this privilege has
unrestricted administrative access to ArcGIS
... |
def ecdsa_sign(private_key, data, hash_algorithm):
"""
Generates an ECDSA signature in pure Python (thus slow)
:param private_key:
The PrivateKey to generate the signature with
:param data:
A byte string of the data the signature is for
:param hash_algorithm:
A unicode str... | Generates an ECDSA signature in pure Python (thus slow)
:param private_key:
The PrivateKey to generate the signature with
:param data:
A byte string of the data the signature is for
:param hash_algorithm:
A unicode string of "sha1", "sha256", "sha384" or "sha512"
:raises:
... | Below is the the instruction that describes the task:
### Input:
Generates an ECDSA signature in pure Python (thus slow)
:param private_key:
The PrivateKey to generate the signature with
:param data:
A byte string of the data the signature is for
:param hash_algorithm:
A unico... |
def delete_local_docker_cache(docker_tag):
"""
Delete the local docker cache for the entire docker image chain
:param docker_tag: Docker tag
:return: None
"""
history_cmd = ['docker', 'history', '-q', docker_tag]
try:
image_ids_b = subprocess.check_output(history_cmd)
image_... | Delete the local docker cache for the entire docker image chain
:param docker_tag: Docker tag
:return: None | Below is the the instruction that describes the task:
### Input:
Delete the local docker cache for the entire docker image chain
:param docker_tag: Docker tag
:return: None
### Response:
def delete_local_docker_cache(docker_tag):
"""
Delete the local docker cache for the entire docker image chain
... |
def increment_name(name: str, start_marker: str = " (",
end_marker: str = ")") -> str:
"""
Increment the name where the incremental part is given by parameters.
Parameters
----------
name : str, nbformat.notebooknode.NotebookNode
Name
start_marker : str
The ma... | Increment the name where the incremental part is given by parameters.
Parameters
----------
name : str, nbformat.notebooknode.NotebookNode
Name
start_marker : str
The marker used before the incremental
end_marker : str
The marker after the incrementa
Returns
-------... | Below is the the instruction that describes the task:
### Input:
Increment the name where the incremental part is given by parameters.
Parameters
----------
name : str, nbformat.notebooknode.NotebookNode
Name
start_marker : str
The marker used before the incremental
end_marker :... |
def derive_key(mode, version, salt, key,
private_key, dh, auth_secret,
keyid, keylabel="P-256"):
"""Derive the encryption key
:param mode: operational mode (encrypt or decrypt)
:type mode: enumerate('encrypt', 'decrypt)
:param salt: encryption salt value
:type salt: st... | Derive the encryption key
:param mode: operational mode (encrypt or decrypt)
:type mode: enumerate('encrypt', 'decrypt)
:param salt: encryption salt value
:type salt: str
:param key: raw key
:type key: str
:param private_key: DH private key
:type key: object
:param dh: Diffie Helman... | Below is the the instruction that describes the task:
### Input:
Derive the encryption key
:param mode: operational mode (encrypt or decrypt)
:type mode: enumerate('encrypt', 'decrypt)
:param salt: encryption salt value
:type salt: str
:param key: raw key
:type key: str
:param private_k... |
def plan(description, stack_action, context,
tail=None, reverse=False):
"""A simple helper that builds a graph based plan from a set of stacks.
Args:
description (str): a description of the plan.
action (func): a function to call for each stack.
context (:class:`stacker.context... | A simple helper that builds a graph based plan from a set of stacks.
Args:
description (str): a description of the plan.
action (func): a function to call for each stack.
context (:class:`stacker.context.Context`): a
:class:`stacker.context.Context` to build the plan from.
... | Below is the the instruction that describes the task:
### Input:
A simple helper that builds a graph based plan from a set of stacks.
Args:
description (str): a description of the plan.
action (func): a function to call for each stack.
context (:class:`stacker.context.Context`): a
... |
def dump_dh_parameters(dh_parameters, encoding='pem'):
"""
Serializes an asn1crypto.algos.DHParameters object into a byte string
:param dh_parameters:
An asn1crypto.algos.DHParameters object
:param encoding:
A unicode string of "pem" or "der"
:return:
A byte string of the ... | Serializes an asn1crypto.algos.DHParameters object into a byte string
:param dh_parameters:
An asn1crypto.algos.DHParameters object
:param encoding:
A unicode string of "pem" or "der"
:return:
A byte string of the encoded DH parameters | Below is the the instruction that describes the task:
### Input:
Serializes an asn1crypto.algos.DHParameters object into a byte string
:param dh_parameters:
An asn1crypto.algos.DHParameters object
:param encoding:
A unicode string of "pem" or "der"
:return:
A byte string of th... |
def prepare_env(cls):
"""Prepares current environment and returns Python binary name.
This adds some virtualenv friendliness so that we try use uwsgi from it.
:rtype: str|unicode
"""
os.environ['PATH'] = cls.get_env_path()
return os.path.basename(Finder.python()) | Prepares current environment and returns Python binary name.
This adds some virtualenv friendliness so that we try use uwsgi from it.
:rtype: str|unicode | Below is the the instruction that describes the task:
### Input:
Prepares current environment and returns Python binary name.
This adds some virtualenv friendliness so that we try use uwsgi from it.
:rtype: str|unicode
### Response:
def prepare_env(cls):
"""Prepares current environment an... |
def iso2time(text):
"""
As for http2time, but parses the ISO 8601 formats:
1994-02-03 14:15:29 -0100 -- ISO 8601 format
1994-02-03 14:15:29 -- zone is optional
1994-02-03 -- only date
1994-02-03T14:15:29 -- Use T as separator
19940203T141529Z ... | As for http2time, but parses the ISO 8601 formats:
1994-02-03 14:15:29 -0100 -- ISO 8601 format
1994-02-03 14:15:29 -- zone is optional
1994-02-03 -- only date
1994-02-03T14:15:29 -- Use T as separator
19940203T141529Z -- ISO 8601 compact format
... | Below is the the instruction that describes the task:
### Input:
As for http2time, but parses the ISO 8601 formats:
1994-02-03 14:15:29 -0100 -- ISO 8601 format
1994-02-03 14:15:29 -- zone is optional
1994-02-03 -- only date
1994-02-03T14:15:29 -- Use T as sep... |
def save_token(token, request, *args, **kwargs):
"""Token persistence.
:param token: A dictionary with the token data.
:param request: The request instance.
:returns: A :class:`invenio_oauth2server.models.Token` instance.
"""
# Exclude the personal access tokens which doesn't expire.
user =... | Token persistence.
:param token: A dictionary with the token data.
:param request: The request instance.
:returns: A :class:`invenio_oauth2server.models.Token` instance. | Below is the the instruction that describes the task:
### Input:
Token persistence.
:param token: A dictionary with the token data.
:param request: The request instance.
:returns: A :class:`invenio_oauth2server.models.Token` instance.
### Response:
def save_token(token, request, *args, **kwargs):
... |
def InitFromFlowLogEntry(self, fle):
"""Init from FlowLogEntry rdfvalue."""
# TODO(user): putting this stub value for backwards compatibility.
# Remove as soon as AFF4 is gone.
self.flow_name = "GenericHunt"
self.client_id = fle.client_id
self.flow_id = fle.flow_id
self.timestamp = fle.tim... | Init from FlowLogEntry rdfvalue. | Below is the the instruction that describes the task:
### Input:
Init from FlowLogEntry rdfvalue.
### Response:
def InitFromFlowLogEntry(self, fle):
"""Init from FlowLogEntry rdfvalue."""
# TODO(user): putting this stub value for backwards compatibility.
# Remove as soon as AFF4 is gone.
self.flow... |
def get_uids(self, project=None):
"""Return a list of UIDs
project -- the Project to filter for
"""
self._update()
if not project or project.endswith('all_projects'):
return [self._gen_uid(task['uuid']) for project in self._tasks for task in self._tasks[project].valu... | Return a list of UIDs
project -- the Project to filter for | Below is the the instruction that describes the task:
### Input:
Return a list of UIDs
project -- the Project to filter for
### Response:
def get_uids(self, project=None):
"""Return a list of UIDs
project -- the Project to filter for
"""
self._update()
if not projec... |
def validate_allowed_to_pay(self):
''' Passes cleanly if we're allowed to pay, otherwise raise
a ValidationError. '''
self._refresh()
if not self.invoice.is_unpaid:
raise ValidationError("You can only pay for unpaid invoices.")
if not self.invoice.cart:
... | Passes cleanly if we're allowed to pay, otherwise raise
a ValidationError. | Below is the the instruction that describes the task:
### Input:
Passes cleanly if we're allowed to pay, otherwise raise
a ValidationError.
### Response:
def validate_allowed_to_pay(self):
''' Passes cleanly if we're allowed to pay, otherwise raise
a ValidationError. '''
self._refr... |
def source(self, source):
"""When the source gets updated, update the select widget"""
if isinstance(source, list):
# if source is a list, get first item or None
source = source[0] if len(source) > 0 else None
self._source = source | When the source gets updated, update the select widget | Below is the the instruction that describes the task:
### Input:
When the source gets updated, update the select widget
### Response:
def source(self, source):
"""When the source gets updated, update the select widget"""
if isinstance(source, list):
# if source is a list, get first item... |
def get_closest(word, possibilities, cutoff=0.6, fallback_to_first=True):
"""Returns closest match or just first from possibilities."""
possibilities = list(possibilities)
try:
return difflib_get_close_matches(word, possibilities, 1, cutoff)[0]
except IndexError:
if fallback_to_first:
... | Returns closest match or just first from possibilities. | Below is the the instruction that describes the task:
### Input:
Returns closest match or just first from possibilities.
### Response:
def get_closest(word, possibilities, cutoff=0.6, fallback_to_first=True):
"""Returns closest match or just first from possibilities."""
possibilities = list(possibilities)
... |
def more_than_one_index(s, brackets=2):
'''
Search for two sets of [] []
@param s: string to search
'''
start = 0
brackets_num = 0
while start != -1 and brackets_num < brackets:
start = s.find("[", start)
if start == -1:
break
start = s.find("]"... | Search for two sets of [] []
@param s: string to search | Below is the the instruction that describes the task:
### Input:
Search for two sets of [] []
@param s: string to search
### Response:
def more_than_one_index(s, brackets=2):
'''
Search for two sets of [] []
@param s: string to search
'''
start = 0
brackets_num = 0
while sta... |
def reverse_dict(self):
"""reverse dictionary"""
self.reserve_paint = dict(zip(self.paint.values(), self.paint.keys())) | reverse dictionary | Below is the the instruction that describes the task:
### Input:
reverse dictionary
### Response:
def reverse_dict(self):
"""reverse dictionary"""
self.reserve_paint = dict(zip(self.paint.values(), self.paint.keys())) |
def d_from_format(self, attr):
""" Find out the local name of an attribute
:param attr: An Attribute dictionary
:return: The local attribute name or "" if no mapping could be made
"""
if attr["name_format"]:
if self.name_format == attr["name_format"]:
... | Find out the local name of an attribute
:param attr: An Attribute dictionary
:return: The local attribute name or "" if no mapping could be made | Below is the the instruction that describes the task:
### Input:
Find out the local name of an attribute
:param attr: An Attribute dictionary
:return: The local attribute name or "" if no mapping could be made
### Response:
def d_from_format(self, attr):
""" Find out the local name of an a... |
def store_populate_failed(cls, resource: str, session: Optional[Session] = None) -> 'Action':
"""Store a "populate failed" event.
:param resource: The normalized name of the resource to store
Example:
>>> from bio2bel.models import Action
>>> Action.store_populate_failed('hgnc... | Store a "populate failed" event.
:param resource: The normalized name of the resource to store
Example:
>>> from bio2bel.models import Action
>>> Action.store_populate_failed('hgnc') | Below is the the instruction that describes the task:
### Input:
Store a "populate failed" event.
:param resource: The normalized name of the resource to store
Example:
>>> from bio2bel.models import Action
>>> Action.store_populate_failed('hgnc')
### Response:
def store_populate... |
def event_type(self, event_type):
"""
Sets the event_type of this DeviceEventData.
Event code
:param event_type: The event_type of this DeviceEventData.
:type: str
"""
if event_type is not None and len(event_type) > 100:
raise ValueError("Invalid valu... | Sets the event_type of this DeviceEventData.
Event code
:param event_type: The event_type of this DeviceEventData.
:type: str | Below is the the instruction that describes the task:
### Input:
Sets the event_type of this DeviceEventData.
Event code
:param event_type: The event_type of this DeviceEventData.
:type: str
### Response:
def event_type(self, event_type):
"""
Sets the event_type of this Dev... |
def apply_unitary(unitary_value: Any,
args: ApplyUnitaryArgs,
default: TDefault = RaiseTypeErrorIfNotProvided
) -> Union[np.ndarray, TDefault]:
"""High performance left-multiplication of a unitary effect onto a tensor.
If `unitary_value` defines an `_apply_... | High performance left-multiplication of a unitary effect onto a tensor.
If `unitary_value` defines an `_apply_unitary_` method, that method will be
used to apply `unitary_value`'s unitary effect to the target tensor.
Otherwise, if `unitary_value` defines a `_unitary_` method, its unitary
matrix will be... | Below is the the instruction that describes the task:
### Input:
High performance left-multiplication of a unitary effect onto a tensor.
If `unitary_value` defines an `_apply_unitary_` method, that method will be
used to apply `unitary_value`'s unitary effect to the target tensor.
Otherwise, if `unitar... |
def _convenienceMatchR(self, role, attr, match):
"""Method used by role based convenience functions to find a match"""
kwargs = {}
# If the user supplied some text to search for,
# supply that in the kwargs
if match:
kwargs[attr] = match
return self.findAllR(A... | Method used by role based convenience functions to find a match | Below is the the instruction that describes the task:
### Input:
Method used by role based convenience functions to find a match
### Response:
def _convenienceMatchR(self, role, attr, match):
"""Method used by role based convenience functions to find a match"""
kwargs = {}
# If the user sup... |
def attach_internet_gateway(self, internet_gateway_id, vpc_id):
"""
Attach an internet gateway to a specific VPC.
:type internet_gateway_id: str
:param internet_gateway_id: The ID of the internet gateway to delete.
:type vpc_id: str
:param vpc_id: The ID of the VPC to a... | Attach an internet gateway to a specific VPC.
:type internet_gateway_id: str
:param internet_gateway_id: The ID of the internet gateway to delete.
:type vpc_id: str
:param vpc_id: The ID of the VPC to attach to.
:rtype: Bool
:return: True if successful | Below is the the instruction that describes the task:
### Input:
Attach an internet gateway to a specific VPC.
:type internet_gateway_id: str
:param internet_gateway_id: The ID of the internet gateway to delete.
:type vpc_id: str
:param vpc_id: The ID of the VPC to attach to.
... |
def sqlwhere(criteria=None):
"""Generates SQL where clause. Returns (sql, values).
Criteria is a dictionary of {field: value}.
>>> sqlwhere()
('', [])
>>> sqlwhere({'id': 5})
('id=%s', [5])
>>> sqlwhere({'id': 3, 'name': 'toto'})
('id=%s and name=%s', [3, 'toto'])
>>> sqlwhere({'id'... | Generates SQL where clause. Returns (sql, values).
Criteria is a dictionary of {field: value}.
>>> sqlwhere()
('', [])
>>> sqlwhere({'id': 5})
('id=%s', [5])
>>> sqlwhere({'id': 3, 'name': 'toto'})
('id=%s and name=%s', [3, 'toto'])
>>> sqlwhere({'id': 3, 'name': 'toto', 'createdon': '2... | Below is the the instruction that describes the task:
### Input:
Generates SQL where clause. Returns (sql, values).
Criteria is a dictionary of {field: value}.
>>> sqlwhere()
('', [])
>>> sqlwhere({'id': 5})
('id=%s', [5])
>>> sqlwhere({'id': 3, 'name': 'toto'})
('id=%s and name=%s', [3... |
def overlap(a, b):
"""Check if two ranges overlap.
Parameters
----------
a : range
The first range.
b : range
The second range.
Returns
-------
overlaps : bool
Do these ranges overlap.
Notes
-----
This function does not support ranges with step != ... | Check if two ranges overlap.
Parameters
----------
a : range
The first range.
b : range
The second range.
Returns
-------
overlaps : bool
Do these ranges overlap.
Notes
-----
This function does not support ranges with step != 1. | Below is the the instruction that describes the task:
### Input:
Check if two ranges overlap.
Parameters
----------
a : range
The first range.
b : range
The second range.
Returns
-------
overlaps : bool
Do these ranges overlap.
Notes
-----
This fun... |
def from_id(cls, id):
"""
This decodes an ID to a public key and verifies the checksum byte. ID
structure in miniLock is the base58 encoded form of the public key
appended with a single-byte digest from blake2s of the public key, as a
simple check-sum.
"""
decoded... | This decodes an ID to a public key and verifies the checksum byte. ID
structure in miniLock is the base58 encoded form of the public key
appended with a single-byte digest from blake2s of the public key, as a
simple check-sum. | Below is the the instruction that describes the task:
### Input:
This decodes an ID to a public key and verifies the checksum byte. ID
structure in miniLock is the base58 encoded form of the public key
appended with a single-byte digest from blake2s of the public key, as a
simple check-sum.
... |
def Jacobi(self,*args,**kwargs):
"""
NAME:
Jacobi
PURPOSE:
calculate the Jacobi integral of the motion
INPUT:
t - (optional) time at which to get the radius
OmegaP= pattern speed of rotating frame (scalar)
pot= potential instance or ... | NAME:
Jacobi
PURPOSE:
calculate the Jacobi integral of the motion
INPUT:
t - (optional) time at which to get the radius
OmegaP= pattern speed of rotating frame (scalar)
pot= potential instance or list of such instances
OUTPUT:
Jac... | Below is the the instruction that describes the task:
### Input:
NAME:
Jacobi
PURPOSE:
calculate the Jacobi integral of the motion
INPUT:
t - (optional) time at which to get the radius
OmegaP= pattern speed of rotating frame (scalar)
pot= potent... |
def _thresholdNonLinearity(self, input, threshold, thresholdType=None):
"""
Non linearity function, to transform the activations during training and
encoding.
:param input: (array) Activations
:param threshold: (array) Thresholds
:param thresholdType: (string) 'soft', 'absoluteH... | Non linearity function, to transform the activations during training and
encoding.
:param input: (array) Activations
:param threshold: (array) Thresholds
:param thresholdType: (string) 'soft', 'absoluteHard' or 'relativeHard' | Below is the the instruction that describes the task:
### Input:
Non linearity function, to transform the activations during training and
encoding.
:param input: (array) Activations
:param threshold: (array) Thresholds
:param thresholdType: (string) 'soft', 'absoluteHard' or 'relati... |
def clean_global_runtime_state(reset_subsystem=False):
"""Resets the global runtime state of a pants runtime for cleaner forking.
:param bool reset_subsystem: Whether or not to clean Subsystem global state.
"""
if reset_subsystem:
# Reset subsystem state.
Subsystem.reset()
# Reset Goals and Tasks.
... | Resets the global runtime state of a pants runtime for cleaner forking.
:param bool reset_subsystem: Whether or not to clean Subsystem global state. | Below is the the instruction that describes the task:
### Input:
Resets the global runtime state of a pants runtime for cleaner forking.
:param bool reset_subsystem: Whether or not to clean Subsystem global state.
### Response:
def clean_global_runtime_state(reset_subsystem=False):
"""Resets the global runtim... |
def __validate_pattern(self, pattern):
"""!
@brief Validates pattern.
@details Throws exception if length of pattern is not equal to size of the network or if it consists feature with value that are not equal to [-1; 1].
@param[in] pattern (list): Pattern for recognition represe... | !
@brief Validates pattern.
@details Throws exception if length of pattern is not equal to size of the network or if it consists feature with value that are not equal to [-1; 1].
@param[in] pattern (list): Pattern for recognition represented by list of features that are equal to [-1; 1]... | Below is the the instruction that describes the task:
### Input:
!
@brief Validates pattern.
@details Throws exception if length of pattern is not equal to size of the network or if it consists feature with value that are not equal to [-1; 1].
@param[in] pattern (list): Pattern for ... |
def grab_project_data(prj):
"""
From the given Project, grab Sample-independent data.
There are some aspects of a Project of which it's beneficial for a Sample
to be aware, particularly for post-hoc analysis. Since Sample objects
within a Project are mutually independent, though, each doesn't need ... | From the given Project, grab Sample-independent data.
There are some aspects of a Project of which it's beneficial for a Sample
to be aware, particularly for post-hoc analysis. Since Sample objects
within a Project are mutually independent, though, each doesn't need to
know about any of the others. A P... | Below is the the instruction that describes the task:
### Input:
From the given Project, grab Sample-independent data.
There are some aspects of a Project of which it's beneficial for a Sample
to be aware, particularly for post-hoc analysis. Since Sample objects
within a Project are mutually independen... |
def __view_add_actions(self):
"""
Sets the View actions.
"""
self.__view.addAction(self.__container.engine.actions_manager.register_action(
"Actions|Umbra|Components|factory.script_editor|Search In Files|Replace All",
slot=self.__view_replace_all_action__triggere... | Sets the View actions. | Below is the the instruction that describes the task:
### Input:
Sets the View actions.
### Response:
def __view_add_actions(self):
"""
Sets the View actions.
"""
self.__view.addAction(self.__container.engine.actions_manager.register_action(
"Actions|Umbra|Components|fa... |
def get_suitable_vis_classes(obj):
"""Retuns a list of Vis classes that can handle obj."""
ret = []
for class_ in classes_vis():
if isinstance(obj, class_.input_classes):
ret.append(class_)
return ret | Retuns a list of Vis classes that can handle obj. | Below is the the instruction that describes the task:
### Input:
Retuns a list of Vis classes that can handle obj.
### Response:
def get_suitable_vis_classes(obj):
"""Retuns a list of Vis classes that can handle obj."""
ret = []
for class_ in classes_vis():
if isinstance(obj, class_.input_clas... |
def find_day_by_weekday_offset(year, month, weekday, offset):
"""Get the day number based on a date and offset
:param year: date year
:type year: int
:param month: date month
:type month: int
:param weekday: date week day
:type weekday: int
:param offset: offset (-1 is last, 1 is first ... | Get the day number based on a date and offset
:param year: date year
:type year: int
:param month: date month
:type month: int
:param weekday: date week day
:type weekday: int
:param offset: offset (-1 is last, 1 is first etc)
:type offset: int
:return: day number in the month
:... | Below is the the instruction that describes the task:
### Input:
Get the day number based on a date and offset
:param year: date year
:type year: int
:param month: date month
:type month: int
:param weekday: date week day
:type weekday: int
:param offset: offset (-1 is last, 1 is first ... |
def get_per_identity_records(self, events: Iterable, data_processor: DataProcessor
) -> Generator[Tuple[str, TimeAndRecord], None, None]:
"""
Uses the given iteratable events and the data processor convert the event into a list of
Records along with its identity ... | Uses the given iteratable events and the data processor convert the event into a list of
Records along with its identity and time.
:param events: iteratable events.
:param data_processor: DataProcessor to process each event in events.
:return: yields Tuple[Identity, TimeAndRecord] for al... | Below is the the instruction that describes the task:
### Input:
Uses the given iteratable events and the data processor convert the event into a list of
Records along with its identity and time.
:param events: iteratable events.
:param data_processor: DataProcessor to process each event in ... |
def get_card_list(self, openid, card_id=None):
"""
用于获取用户卡包里的,属于该appid下的卡券。
"""
card_data = {
'openid': openid
}
if card_id:
card_data['card_id'] = card_id
return self._post(
'card/user/getcardlist',
data=card_data
... | 用于获取用户卡包里的,属于该appid下的卡券。 | Below is the the instruction that describes the task:
### Input:
用于获取用户卡包里的,属于该appid下的卡券。
### Response:
def get_card_list(self, openid, card_id=None):
"""
用于获取用户卡包里的,属于该appid下的卡券。
"""
card_data = {
'openid': openid
}
if card_id:
card_data['car... |
def write(self):
"""This actually runs the qvality program from PATH."""
outfn = self.create_outfilepath(self.fn, self.outsuffix)
command = ['qvality']
command.extend(self.qvalityoptions)
command.extend([self.scores['target']['fn'], self.scores['decoy']['fn'],
... | This actually runs the qvality program from PATH. | Below is the the instruction that describes the task:
### Input:
This actually runs the qvality program from PATH.
### Response:
def write(self):
"""This actually runs the qvality program from PATH."""
outfn = self.create_outfilepath(self.fn, self.outsuffix)
command = ['qvality']
co... |
def cleanup_files(self):
"""Clean up files, remove builds."""
logger.debug('Cleaning up...')
with indent_log():
for req in self.reqs_to_cleanup:
req.remove_temporary_source()
if self._pip_has_created_build_dir():
logger.debug('Removing tem... | Clean up files, remove builds. | Below is the the instruction that describes the task:
### Input:
Clean up files, remove builds.
### Response:
def cleanup_files(self):
"""Clean up files, remove builds."""
logger.debug('Cleaning up...')
with indent_log():
for req in self.reqs_to_cleanup:
req.remo... |
def load_buffer_one_to_five(self, out_buffer):
"""
Loads first program buffer (0x93) with everything but
first three bytes and checksum
"""
struct.pack_into(b"< 2B", out_buffer, 3, self._program_type, len(self._prog_steps))
offset = 5
for ind, step in enumerate(se... | Loads first program buffer (0x93) with everything but
first three bytes and checksum | Below is the the instruction that describes the task:
### Input:
Loads first program buffer (0x93) with everything but
first three bytes and checksum
### Response:
def load_buffer_one_to_five(self, out_buffer):
"""
Loads first program buffer (0x93) with everything but
first three by... |
def _make_header(self, token_type=None, signing_algorithm=None):
"""
Make a JWT header
"""
if not token_type:
token_type = self.token_type
if not signing_algorithm:
signing_algorithm = self.signing_algorithm
header = {'typ': token_type, 'alg': si... | Make a JWT header | Below is the the instruction that describes the task:
### Input:
Make a JWT header
### Response:
def _make_header(self, token_type=None, signing_algorithm=None):
"""
Make a JWT header
"""
if not token_type:
token_type = self.token_type
if not signing_algorithm:
... |
def add_root_family(self, family_id):
"""Adds a root family.
arg: family_id (osid.id.Id): the ``Id`` of a family
raise: AlreadyExists - ``family_id`` is already in hierarchy
raise: NotFound - ``family_id`` not found
raise: NullArgument - ``family_id`` is ``null``
r... | Adds a root family.
arg: family_id (osid.id.Id): the ``Id`` of a family
raise: AlreadyExists - ``family_id`` is already in hierarchy
raise: NotFound - ``family_id`` not found
raise: NullArgument - ``family_id`` is ``null``
raise: OperationFailed - unable to complete reque... | Below is the the instruction that describes the task:
### Input:
Adds a root family.
arg: family_id (osid.id.Id): the ``Id`` of a family
raise: AlreadyExists - ``family_id`` is already in hierarchy
raise: NotFound - ``family_id`` not found
raise: NullArgument - ``family_id`` i... |
def create_or_login(resp):
"""This is called when login with OpenID succeeded and it's not
necessary to figure out if this is the users's first login or not.
This function has to redirect otherwise the user will be presented
with a terrible URL which we certainly don't want.
"""
session['openid'... | This is called when login with OpenID succeeded and it's not
necessary to figure out if this is the users's first login or not.
This function has to redirect otherwise the user will be presented
with a terrible URL which we certainly don't want. | Below is the the instruction that describes the task:
### Input:
This is called when login with OpenID succeeded and it's not
necessary to figure out if this is the users's first login or not.
This function has to redirect otherwise the user will be presented
with a terrible URL which we certainly don't... |
def create_event(self, **kwargs): # noqa: E501
"""Create a specific event # noqa: E501
The following fields are readonly and will be ignored when passed in the request: <code>id</code>, <code>isEphemeral</code>, <code>isUserEvent</code>, <code>runningState</code>, <code>canDelete</code>, <code>canClo... | Create a specific event # noqa: E501
The following fields are readonly and will be ignored when passed in the request: <code>id</code>, <code>isEphemeral</code>, <code>isUserEvent</code>, <code>runningState</code>, <code>canDelete</code>, <code>canClose</code>, <code>creatorType</code>, <code>createdAt</code>... | Below is the the instruction that describes the task:
### Input:
Create a specific event # noqa: E501
The following fields are readonly and will be ignored when passed in the request: <code>id</code>, <code>isEphemeral</code>, <code>isUserEvent</code>, <code>runningState</code>, <code>canDelete</code>, <c... |
def get_newest_possible_languagetool_version():
"""Return newest compatible version.
>>> version = get_newest_possible_languagetool_version()
>>> version in [JAVA_6_COMPATIBLE_VERSION, LATEST_VERSION]
True
"""
java_path = find_executable('java')
if not java_path:
# Just ignore this... | Return newest compatible version.
>>> version = get_newest_possible_languagetool_version()
>>> version in [JAVA_6_COMPATIBLE_VERSION, LATEST_VERSION]
True | Below is the the instruction that describes the task:
### Input:
Return newest compatible version.
>>> version = get_newest_possible_languagetool_version()
>>> version in [JAVA_6_COMPATIBLE_VERSION, LATEST_VERSION]
True
### Response:
def get_newest_possible_languagetool_version():
"""Return newest... |
def _multicall(hook_impls, caller_kwargs, firstresult=False):
"""Execute a call into multiple python functions/methods and return the
result(s).
``caller_kwargs`` comes from _HookCaller.__call__().
"""
__tracebackhide__ = True
results = []
excinfo = None
try: # run impl and wrapper set... | Execute a call into multiple python functions/methods and return the
result(s).
``caller_kwargs`` comes from _HookCaller.__call__(). | Below is the the instruction that describes the task:
### Input:
Execute a call into multiple python functions/methods and return the
result(s).
``caller_kwargs`` comes from _HookCaller.__call__().
### Response:
def _multicall(hook_impls, caller_kwargs, firstresult=False):
"""Execute a call into multi... |
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.
"""
sites.vs30 = 700 * np.ones(len(sites.vs30))
mean, stddevs = ... | See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values. | Below is the the instruction that describes the task:
### Input:
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
### Response:
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :m... |
def validate_input_file(input_filepath):
'''Input file validation function. Checks that file exists and can be
processed by SoX.
Parameters
----------
input_filepath : str
The input filepath.
'''
if not os.path.exists(input_filepath):
raise IOError(
"input_filep... | Input file validation function. Checks that file exists and can be
processed by SoX.
Parameters
----------
input_filepath : str
The input filepath. | Below is the the instruction that describes the task:
### Input:
Input file validation function. Checks that file exists and can be
processed by SoX.
Parameters
----------
input_filepath : str
The input filepath.
### Response:
def validate_input_file(input_filepath):
'''Input file vali... |
def preprocess_na(sent, label_type):
"""Preprocess Na sentences
Args:
sent: A sentence
label_type: The type of label provided
"""
if label_type == "phonemes_and_tones":
phonemes = True
tones = True
tgm = True
elif label_type == "phonemes_and_tones_no_tgm":
... | Preprocess Na sentences
Args:
sent: A sentence
label_type: The type of label provided | Below is the the instruction that describes the task:
### Input:
Preprocess Na sentences
Args:
sent: A sentence
label_type: The type of label provided
### Response:
def preprocess_na(sent, label_type):
"""Preprocess Na sentences
Args:
sent: A sentence
label_type: The t... |
def data_item_live(self, data_item):
""" Return a context manager to put the data item in a 'live state'. """
class LiveContextManager:
def __init__(self, manager, object):
self.__manager = manager
self.__object = object
def __enter__(self):
... | Return a context manager to put the data item in a 'live state'. | Below is the the instruction that describes the task:
### Input:
Return a context manager to put the data item in a 'live state'.
### Response:
def data_item_live(self, data_item):
""" Return a context manager to put the data item in a 'live state'. """
class LiveContextManager:
def __i... |
def _apply_BCs(self):
r"""
Applies all the boundary conditions that have been specified, by
adding values to the *A* and *b* matrices.
"""
if 'pore.bc_rate' in self.keys():
# Update b
ind = np.isfinite(self['pore.bc_rate'])
self.b[ind] = self['... | r"""
Applies all the boundary conditions that have been specified, by
adding values to the *A* and *b* matrices. | Below is the the instruction that describes the task:
### Input:
r"""
Applies all the boundary conditions that have been specified, by
adding values to the *A* and *b* matrices.
### Response:
def _apply_BCs(self):
r"""
Applies all the boundary conditions that have been specified, by... |
def listing(callback=None, path=None, method=Method.GET, resource=None, tags=None, summary="List resources",
middleware=None, default_limit=50, max_limit=None, use_wrapper=True):
# type: (Callable, Path, Methods, Resource, Tags, str, List[Any], int, int) -> Operation
"""
Decorator to configure a... | Decorator to configure an operation that returns a list of resources. | Below is the the instruction that describes the task:
### Input:
Decorator to configure an operation that returns a list of resources.
### Response:
def listing(callback=None, path=None, method=Method.GET, resource=None, tags=None, summary="List resources",
middleware=None, default_limit=50, max_limit=... |
def plot_importance(booster, ax=None, height=0.2,
xlim=None, ylim=None, title='Feature importance',
xlabel='F score', ylabel='Features',
importance_type='weight', max_num_features=None,
grid=True, show_values=True, **kwargs):
"""Plot im... | Plot importance based on fitted trees.
Parameters
----------
booster : Booster, XGBModel or dict
Booster or XGBModel instance, or dict taken by Booster.get_fscore()
ax : matplotlib Axes, default None
Target axes instance. If None, new figure and axes will be created.
grid : bool, Tu... | Below is the the instruction that describes the task:
### Input:
Plot importance based on fitted trees.
Parameters
----------
booster : Booster, XGBModel or dict
Booster or XGBModel instance, or dict taken by Booster.get_fscore()
ax : matplotlib Axes, default None
Target axes instan... |
def tidy_eggs_list(eggs_list):
"""Tidy the given eggs list
"""
tmp = []
for line in eggs_list:
line = line.lstrip().rstrip()
line = line.replace('\'', '')
line = line.replace(',', '')
if line.endswith('site-packages'):
continue
tmp.append(line)
ret... | Tidy the given eggs list | Below is the the instruction that describes the task:
### Input:
Tidy the given eggs list
### Response:
def tidy_eggs_list(eggs_list):
"""Tidy the given eggs list
"""
tmp = []
for line in eggs_list:
line = line.lstrip().rstrip()
line = line.replace('\'', '')
line = line.repl... |
def submit(self, timestamp):
"""Internal instance method to submit this task for running immediately.
Does not handle any iteration, end-date, etc., processing."""
Channel(RUN_TASK_CHANNEL).send({'id':self.pk, 'ts': timestamp.timestamp()}) | Internal instance method to submit this task for running immediately.
Does not handle any iteration, end-date, etc., processing. | Below is the the instruction that describes the task:
### Input:
Internal instance method to submit this task for running immediately.
Does not handle any iteration, end-date, etc., processing.
### Response:
def submit(self, timestamp):
"""Internal instance method to submit this task for running im... |
def t_FRACTION(self, t):
r'(\d+)(\.\d+)'
t.endlexpos = t.lexpos + len(t.value)
return t | r'(\d+)(\.\d+) | Below is the the instruction that describes the task:
### Input:
r'(\d+)(\.\d+)
### Response:
def t_FRACTION(self, t):
r'(\d+)(\.\d+)'
t.endlexpos = t.lexpos + len(t.value)
return t |
def convert_namespaces_ast(
ast,
api_url: str = None,
namespace_targets: Mapping[str, List[str]] = None,
canonicalize: bool = False,
decanonicalize: bool = False,
):
"""Recursively convert namespaces of BEL Entities in BEL AST using API endpoint
Canonicalization and decanonicalization is de... | Recursively convert namespaces of BEL Entities in BEL AST using API endpoint
Canonicalization and decanonicalization is determined by endpoint used and namespace_targets.
Args:
ast (BEL): BEL AST
api_url (str): endpoint url with a placeholder for the term_id (either /terms/<term_id>/canonicali... | Below is the the instruction that describes the task:
### Input:
Recursively convert namespaces of BEL Entities in BEL AST using API endpoint
Canonicalization and decanonicalization is determined by endpoint used and namespace_targets.
Args:
ast (BEL): BEL AST
api_url (str): endpoint url w... |
def template_runner(client, parser, args):
"""Executes template related operations"""
if args.builtin_list:
aomi.template.builtin_list()
elif args.builtin_info:
aomi.template.builtin_info(args.builtin_info)
elif args.template and args.destination and args.vault_paths:
aomi.render... | Executes template related operations | Below is the the instruction that describes the task:
### Input:
Executes template related operations
### Response:
def template_runner(client, parser, args):
"""Executes template related operations"""
if args.builtin_list:
aomi.template.builtin_list()
elif args.builtin_info:
aomi.templ... |
def clone(cls, repo_url, dest, binary='git'):
"""Clone the repo at repo_url into dest.
:param string binary: The path to the git binary to use, 'git' by default.
:returns: an instance of this class representing the cloned repo.
:rtype: Git
"""
cmd = [binary, 'clone', repo_url, dest]
process... | Clone the repo at repo_url into dest.
:param string binary: The path to the git binary to use, 'git' by default.
:returns: an instance of this class representing the cloned repo.
:rtype: Git | Below is the the instruction that describes the task:
### Input:
Clone the repo at repo_url into dest.
:param string binary: The path to the git binary to use, 'git' by default.
:returns: an instance of this class representing the cloned repo.
:rtype: Git
### Response:
def clone(cls, repo_url, dest, b... |
def get_rsa_key(self, client_key, request):
"""Retrieves a previously stored client provided RSA key."""
if not request.client:
request.client = self._clientgetter(client_key=client_key)
if hasattr(request.client, 'rsa_key'):
return request.client.rsa_key
return N... | Retrieves a previously stored client provided RSA key. | Below is the the instruction that describes the task:
### Input:
Retrieves a previously stored client provided RSA key.
### Response:
def get_rsa_key(self, client_key, request):
"""Retrieves a previously stored client provided RSA key."""
if not request.client:
request.client = self._cl... |
def find_nested_meta_first(d, prop_name, version):
"""Returns obj. for badgerfish and val for hbf. Appropriate for nested literals"""
if _is_badgerfish_version(version):
return find_nested_meta_first_bf(d, prop_name)
p = '^' + prop_name
return d.get(p) | Returns obj. for badgerfish and val for hbf. Appropriate for nested literals | Below is the the instruction that describes the task:
### Input:
Returns obj. for badgerfish and val for hbf. Appropriate for nested literals
### Response:
def find_nested_meta_first(d, prop_name, version):
"""Returns obj. for badgerfish and val for hbf. Appropriate for nested literals"""
if _is_badgerfish... |
def find_best_step(err_vals):
"""
Returns the index of the lowest of the passed values. Catches nans etc.
"""
if np.all(np.isnan(err_vals)):
raise ValueError('All err_vals are nans!')
return np.nanargmin(err_vals) | Returns the index of the lowest of the passed values. Catches nans etc. | Below is the the instruction that describes the task:
### Input:
Returns the index of the lowest of the passed values. Catches nans etc.
### Response:
def find_best_step(err_vals):
"""
Returns the index of the lowest of the passed values. Catches nans etc.
"""
if np.all(np.isnan(err_vals)):
... |
def _banner_default(self):
"""
Reimplement banner creation to let the user decide if he wants a
banner or not
"""
# Don't change banner for external kernels
if self.external_kernel:
return ''
show_banner_o = self.additional_options['show_banner']
... | Reimplement banner creation to let the user decide if he wants a
banner or not | Below is the the instruction that describes the task:
### Input:
Reimplement banner creation to let the user decide if he wants a
banner or not
### Response:
def _banner_default(self):
"""
Reimplement banner creation to let the user decide if he wants a
banner or not
"""
... |
def set_password(query, password, send_email):
"""
Set a user's password.
"""
user = _query_to_user(query)
if click.confirm(f'Are you sure you want to change {user!r}\'s password?'):
security_service.change_password(user, password, send_email=send_email)
user_manager.save(user, commi... | Set a user's password. | Below is the the instruction that describes the task:
### Input:
Set a user's password.
### Response:
def set_password(query, password, send_email):
"""
Set a user's password.
"""
user = _query_to_user(query)
if click.confirm(f'Are you sure you want to change {user!r}\'s password?'):
se... |
def scan(self, pattern):
"""
Scan the text for the given pattern and update pos/match
and related fields. The return value is a boolen that
indicates if the pattern matched. The matched value is
stored on the instance as ``match``, the last value is
stored as ``last``. ``... | Scan the text for the given pattern and update pos/match
and related fields. The return value is a boolen that
indicates if the pattern matched. The matched value is
stored on the instance as ``match``, the last value is
stored as ``last``. ``start_pos`` is the position of the
po... | Below is the the instruction that describes the task:
### Input:
Scan the text for the given pattern and update pos/match
and related fields. The return value is a boolen that
indicates if the pattern matched. The matched value is
stored on the instance as ``match``, the last value is
... |
def install(packages, options=None, fatal=False):
"""Install one or more packages."""
cmd = ['yum', '--assumeyes']
if options is not None:
cmd.extend(options)
cmd.append('install')
if isinstance(packages, six.string_types):
cmd.append(packages)
else:
cmd.extend(packages)
... | Install one or more packages. | Below is the the instruction that describes the task:
### Input:
Install one or more packages.
### Response:
def install(packages, options=None, fatal=False):
"""Install one or more packages."""
cmd = ['yum', '--assumeyes']
if options is not None:
cmd.extend(options)
cmd.append('install')
... |
def _get_value(self, epoch_data: EpochData) -> float:
"""
Retrieve the value of the monitored variable from the given epoch data.
:param epoch_data: epoch data which determine whether the model will be saved or not
:raise KeyError: if any of the specified stream, variable or aggregation... | Retrieve the value of the monitored variable from the given epoch data.
:param epoch_data: epoch data which determine whether the model will be saved or not
:raise KeyError: if any of the specified stream, variable or aggregation is not present in the ``epoch_data``
:raise TypeError: if the var... | Below is the the instruction that describes the task:
### Input:
Retrieve the value of the monitored variable from the given epoch data.
:param epoch_data: epoch data which determine whether the model will be saved or not
:raise KeyError: if any of the specified stream, variable or aggregation is n... |
def load_files(files):
"""Load and execute a python file."""
for py_file in files:
LOG.debug("exec %s", py_file)
execfile(py_file, globals(), locals()) | Load and execute a python file. | Below is the the instruction that describes the task:
### Input:
Load and execute a python file.
### Response:
def load_files(files):
"""Load and execute a python file."""
for py_file in files:
LOG.debug("exec %s", py_file)
execfile(py_file, globals(), locals()) |
def _get_unique_seqid(self, alias, namespace):
"""given alias and namespace, return seq_id if exactly one distinct
sequence id is found, raise KeyError if there's no match, or
raise ValueError if there's more than one match.
"""
recs = self.aliases.find_aliases(alias=alias, nam... | given alias and namespace, return seq_id if exactly one distinct
sequence id is found, raise KeyError if there's no match, or
raise ValueError if there's more than one match. | Below is the the instruction that describes the task:
### Input:
given alias and namespace, return seq_id if exactly one distinct
sequence id is found, raise KeyError if there's no match, or
raise ValueError if there's more than one match.
### Response:
def _get_unique_seqid(self, alias, namespace)... |
def update(self, d, ignore_errors=True, block_user_signals=False):
"""
Supply a dictionary or databox with a header of the same format
and see what happens! (Hint: it updates the existing values.)
This will store non-existent key-value pairs in the dictionary
self._lazy... | Supply a dictionary or databox with a header of the same format
and see what happens! (Hint: it updates the existing values.)
This will store non-existent key-value pairs in the dictionary
self._lazy_load. When you add settings in the future,
these will be checked for the defau... | Below is the the instruction that describes the task:
### Input:
Supply a dictionary or databox with a header of the same format
and see what happens! (Hint: it updates the existing values.)
This will store non-existent key-value pairs in the dictionary
self._lazy_load. When you ad... |
def adjustReplicas(self,
old_required_number_of_instances: int,
new_required_number_of_instances: int):
"""
Add or remove replicas depending on `f`
"""
# TODO: refactor this
replica_num = old_required_number_of_instances
while... | Add or remove replicas depending on `f` | Below is the the instruction that describes the task:
### Input:
Add or remove replicas depending on `f`
### Response:
def adjustReplicas(self,
old_required_number_of_instances: int,
new_required_number_of_instances: int):
"""
Add or remove replicas dep... |
def _get_file_paths(self, tax_ids, file_type):
"""
Assemble file paths from tax ids
Args:
:param tax_ids (list) list of taxa
Returns:
:return file dict
"""
file_paths = dict()
if file_type not in self.files:
raise KeyError("file... | Assemble file paths from tax ids
Args:
:param tax_ids (list) list of taxa
Returns:
:return file dict | Below is the the instruction that describes the task:
### Input:
Assemble file paths from tax ids
Args:
:param tax_ids (list) list of taxa
Returns:
:return file dict
### Response:
def _get_file_paths(self, tax_ids, file_type):
"""
Assemble file paths from tax... |
def copy(self):
"""
Copy this object into a new object of the same type.
The returned object will not have a parent object.
"""
copyClass = self.copyClass
if copyClass is None:
copyClass = self.__class__
copied = copyClass()
copied.copyData(sel... | Copy this object into a new object of the same type.
The returned object will not have a parent object. | Below is the the instruction that describes the task:
### Input:
Copy this object into a new object of the same type.
The returned object will not have a parent object.
### Response:
def copy(self):
"""
Copy this object into a new object of the same type.
The returned object will no... |
def get_filename(self, failobj=None):
"""Return the filename associated with the payload if present.
The filename is extracted from the Content-Disposition header's
`filename' parameter, and it is unquoted. If that header is missing
the `filename' parameter, this method falls back to l... | Return the filename associated with the payload if present.
The filename is extracted from the Content-Disposition header's
`filename' parameter, and it is unquoted. If that header is missing
the `filename' parameter, this method falls back to looking for the
`name' parameter. | Below is the the instruction that describes the task:
### Input:
Return the filename associated with the payload if present.
The filename is extracted from the Content-Disposition header's
`filename' parameter, and it is unquoted. If that header is missing
the `filename' parameter, this me... |
def _load_templates(self, config):
""" load templates
@dict: configuration of ldapcherry
"""
# definition of the template directory
self.template_dir = self._get_param(
'resources',
'templates.dir',
config
)
cherrypy.log.err... | load templates
@dict: configuration of ldapcherry | Below is the the instruction that describes the task:
### Input:
load templates
@dict: configuration of ldapcherry
### Response:
def _load_templates(self, config):
""" load templates
@dict: configuration of ldapcherry
"""
# definition of the template directory
self.t... |
def trim_reference_sequence(fasta):
"""
If doing PE and R1/R2 don't overlap then the reference sequence
will be quite long and will cause indel hell during the
alignment stage. Here trim the reference sequence to the length
of the merged reads. Input is a list of alternating locus labels
and se... | If doing PE and R1/R2 don't overlap then the reference sequence
will be quite long and will cause indel hell during the
alignment stage. Here trim the reference sequence to the length
of the merged reads. Input is a list of alternating locus labels
and sequence data. The first locus label is the refere... | Below is the the instruction that describes the task:
### Input:
If doing PE and R1/R2 don't overlap then the reference sequence
will be quite long and will cause indel hell during the
alignment stage. Here trim the reference sequence to the length
of the merged reads. Input is a list of alternating lo... |
def setGridColor(self, color):
"""
Sets the color for the grid for this instance to the given color.
:param color | <QColor>
"""
palette = self.palette()
palette.setColor(palette.GridForeground, QColor(color)) | Sets the color for the grid for this instance to the given color.
:param color | <QColor> | Below is the the instruction that describes the task:
### Input:
Sets the color for the grid for this instance to the given color.
:param color | <QColor>
### Response:
def setGridColor(self, color):
"""
Sets the color for the grid for this instance to the given color.
... |
def map_single_axis(low, high, dead_zone, hot_zone, value):
"""
Apply dead and hot zones before mapping a value to a range. The dead and hot zones are both expressed as the
proportion of the axis range which should be regarded as 0.0 or 1.0 (or -1.0 depending on cardinality) respectively,
so for example... | Apply dead and hot zones before mapping a value to a range. The dead and hot zones are both expressed as the
proportion of the axis range which should be regarded as 0.0 or 1.0 (or -1.0 depending on cardinality) respectively,
so for example setting dead zone to 0.2 means the first 20% of the range of the axis w... | Below is the the instruction that describes the task:
### Input:
Apply dead and hot zones before mapping a value to a range. The dead and hot zones are both expressed as the
proportion of the axis range which should be regarded as 0.0 or 1.0 (or -1.0 depending on cardinality) respectively,
so for example se... |
def _activate_inbound(self):
"""switch on newly negotiated encryption parameters for inbound traffic"""
block_size = self._cipher_info[self.remote_cipher]['block-size']
if self.server_mode:
IV_in = self._compute_key('A', block_size)
key_in = self._compute_key('C', self._c... | switch on newly negotiated encryption parameters for inbound traffic | Below is the the instruction that describes the task:
### Input:
switch on newly negotiated encryption parameters for inbound traffic
### Response:
def _activate_inbound(self):
"""switch on newly negotiated encryption parameters for inbound traffic"""
block_size = self._cipher_info[self.remote_ciph... |
def _calc_timestamps(self, st_time, end_time):
"""Calculate timesteps between start time and end time.
Use this method only when start time month is before end time month.
"""
# calculate based on minutes
# I have to convert the object to DateTime because of how Dynamo
#... | Calculate timesteps between start time and end time.
Use this method only when start time month is before end time month. | Below is the the instruction that describes the task:
### Input:
Calculate timesteps between start time and end time.
Use this method only when start time month is before end time month.
### Response:
def _calc_timestamps(self, st_time, end_time):
"""Calculate timesteps between start time and end ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.