code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _htpasswd(username, password, **kwargs):
'''
Provide authentication via Apache-style htpasswd files
'''
from passlib.apache import HtpasswdFile
pwfile = HtpasswdFile(kwargs['filename'])
# passlib below version 1.6 uses 'verify' function instead of 'check_password'
if salt.utils.versio... | Provide authentication via Apache-style htpasswd files | Below is the the instruction that describes the task:
### Input:
Provide authentication via Apache-style htpasswd files
### Response:
def _htpasswd(username, password, **kwargs):
'''
Provide authentication via Apache-style htpasswd files
'''
from passlib.apache import HtpasswdFile
pwfile = Ht... |
def to_png_file(self, fname: str):
"""
write a '.png' file.
"""
cmd = pipes.Template()
cmd.append('dot -Tpng > %s' % fname, '-.')
with cmd.open('pipefile', 'w') as f:
f.write(self.to_dot()) | write a '.png' file. | Below is the the instruction that describes the task:
### Input:
write a '.png' file.
### Response:
def to_png_file(self, fname: str):
"""
write a '.png' file.
"""
cmd = pipes.Template()
cmd.append('dot -Tpng > %s' % fname, '-.')
with cmd.open('pipefile', 'w') as f:
... |
def load(self, coll):
"""Load and receive the metadata associated with a collection.
If the metadata for the collection is not cached yet its metadata file is read in and stored.
If the cache has seen the collection before the mtime of the metadata file is checked and if it is more recent
... | Load and receive the metadata associated with a collection.
If the metadata for the collection is not cached yet its metadata file is read in and stored.
If the cache has seen the collection before the mtime of the metadata file is checked and if it is more recent
than the cached time, the cach... | Below is the the instruction that describes the task:
### Input:
Load and receive the metadata associated with a collection.
If the metadata for the collection is not cached yet its metadata file is read in and stored.
If the cache has seen the collection before the mtime of the metadata file is ch... |
def search_in_rubric(self, **kwargs):
"""Firms search in rubric
http://api.2gis.ru/doc/firms/searches/searchinrubric/
"""
point = kwargs.pop('point', False)
if point:
kwargs['point'] = '%s,%s' % point
bound = kwargs.pop('bound', False)
if bound:
... | Firms search in rubric
http://api.2gis.ru/doc/firms/searches/searchinrubric/ | Below is the the instruction that describes the task:
### Input:
Firms search in rubric
http://api.2gis.ru/doc/firms/searches/searchinrubric/
### Response:
def search_in_rubric(self, **kwargs):
"""Firms search in rubric
http://api.2gis.ru/doc/firms/searches/searchinrubric/
"""
... |
def hash_dir(path):
"""Write directory at path to Git index, return its SHA1 as a string."""
dir_hash = {}
for root, dirs, files in os.walk(path, topdown=False):
f_hash = ((f, hash_file(join(root, f))) for f in files)
d_hash = ((d, dir_hash[join(root, d)]) for d in dirs)
# split+joi... | Write directory at path to Git index, return its SHA1 as a string. | Below is the the instruction that describes the task:
### Input:
Write directory at path to Git index, return its SHA1 as a string.
### Response:
def hash_dir(path):
"""Write directory at path to Git index, return its SHA1 as a string."""
dir_hash = {}
for root, dirs, files in os.walk(path, topdown=Fa... |
def namespacereveal_sanity_check( namespace_id, version, lifetime, coeff, base, bucket_exponents, nonalpha_discount, no_vowel_discount ):
"""
Verify the validity of a namespace reveal.
Return True if valid
Raise an Exception if not valid.
"""
# sanity check
if not is_b40( namespace_id ) or "+" in ... | Verify the validity of a namespace reveal.
Return True if valid
Raise an Exception if not valid. | Below is the the instruction that describes the task:
### Input:
Verify the validity of a namespace reveal.
Return True if valid
Raise an Exception if not valid.
### Response:
def namespacereveal_sanity_check( namespace_id, version, lifetime, coeff, base, bucket_exponents, nonalpha_discount, no_vowel_discoun... |
def run_local(
context: cli.CommandContext,
project: projects.Project,
project_steps: typing.List[projects.ProjectStep],
force: bool,
continue_after: bool,
single_step: bool,
limit: int,
print_status: bool,
skip_library_reload: bool = False
) -> en... | Execute the run command locally within this cauldron environment
:param context:
:param project:
:param project_steps:
:param force:
:param continue_after:
:param single_step:
:param limit:
:param print_status:
:param skip_library_reload:
Whether or not to skip reloading all... | Below is the the instruction that describes the task:
### Input:
Execute the run command locally within this cauldron environment
:param context:
:param project:
:param project_steps:
:param force:
:param continue_after:
:param single_step:
:param limit:
:param print_status:
:pa... |
def read_iiasa(name, meta=False, **kwargs):
"""
Query an IIASA database. See Connection.query() for more documentation
Parameters
----------
name : str
A valid IIASA database name, see pyam.iiasa.valid_connection_names()
meta : bool or list of strings
If not False, also include ... | Query an IIASA database. See Connection.query() for more documentation
Parameters
----------
name : str
A valid IIASA database name, see pyam.iiasa.valid_connection_names()
meta : bool or list of strings
If not False, also include metadata indicators (or subset if provided).
kwargs ... | Below is the the instruction that describes the task:
### Input:
Query an IIASA database. See Connection.query() for more documentation
Parameters
----------
name : str
A valid IIASA database name, see pyam.iiasa.valid_connection_names()
meta : bool or list of strings
If not False, ... |
def select(self, *features):
"""
selects the features given as string
e.g
passing 'hello' and 'world' will result in imports of
'hello' and 'world'. Then, if possible 'hello.feature'
and 'world.feature' are imported and select is called
in each feature module.
... | selects the features given as string
e.g
passing 'hello' and 'world' will result in imports of
'hello' and 'world'. Then, if possible 'hello.feature'
and 'world.feature' are imported and select is called
in each feature module. | Below is the the instruction that describes the task:
### Input:
selects the features given as string
e.g
passing 'hello' and 'world' will result in imports of
'hello' and 'world'. Then, if possible 'hello.feature'
and 'world.feature' are imported and select is called
in each... |
def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):
'''
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the vers... | List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
... | Below is the the instruction that describes the task:
### Input:
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided ... |
def SetProtocol(self, protocol):
"""Sets the protocol that will be used to query Viper.
Args:
protocol (str): protocol to use to query Viper. Either 'http' or 'https'.
Raises:
ValueError: If an invalid protocol is selected.
"""
protocol = protocol.lower().strip()
if protocol not in... | Sets the protocol that will be used to query Viper.
Args:
protocol (str): protocol to use to query Viper. Either 'http' or 'https'.
Raises:
ValueError: If an invalid protocol is selected. | Below is the the instruction that describes the task:
### Input:
Sets the protocol that will be used to query Viper.
Args:
protocol (str): protocol to use to query Viper. Either 'http' or 'https'.
Raises:
ValueError: If an invalid protocol is selected.
### Response:
def SetProtocol(self, prot... |
def merge_groundings(stmts_in):
"""Gather and merge original grounding information from evidences.
Each Statement's evidences are traversed to find original grounding
information. These groundings are then merged into an overall consensus
grounding dict with as much detail as possible.
The current... | Gather and merge original grounding information from evidences.
Each Statement's evidences are traversed to find original grounding
information. These groundings are then merged into an overall consensus
grounding dict with as much detail as possible.
The current implementation is only applicable to S... | Below is the the instruction that describes the task:
### Input:
Gather and merge original grounding information from evidences.
Each Statement's evidences are traversed to find original grounding
information. These groundings are then merged into an overall consensus
grounding dict with as much detail... |
def ext_xsect(scatterer, h_pol=True):
"""Extinction cross section for the current setup, with polarization.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.
Returns:
The extinction cross s... | Extinction cross section for the current setup, with polarization.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.
Returns:
The extinction cross section. | Below is the the instruction that describes the task:
### Input:
Extinction cross section for the current setup, with polarization.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.
Returns:
... |
def FileEntryExistsByPathSpec(self, path_spec):
"""Determines if a file entry for a path specification exists.
Args:
path_spec (PathSpec): path specification of the file entry.
Returns:
bool: True if the file entry exists.
"""
location = getattr(path_spec, 'location', None)
if (lo... | Determines if a file entry for a path specification exists.
Args:
path_spec (PathSpec): path specification of the file entry.
Returns:
bool: True if the file entry exists. | Below is the the instruction that describes the task:
### Input:
Determines if a file entry for a path specification exists.
Args:
path_spec (PathSpec): path specification of the file entry.
Returns:
bool: True if the file entry exists.
### Response:
def FileEntryExistsByPathSpec(self, path_s... |
def describe_alias(FunctionName, Name, region=None, key=None,
keyid=None, profile=None):
'''
Given a function name and alias name describe the properties of the alias.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_... | Given a function name and alias name describe the properties of the alias.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_lambda.describe_alias myalias | Below is the the instruction that describes the task:
### Input:
Given a function name and alias name describe the properties of the alias.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_lambda.describe_alias myalias
### Response:
def de... |
def _get_seo_content_types(seo_models):
"""Returns a list of content types from the models defined in settings."""
try:
return [ContentType.objects.get_for_model(m).id for m in seo_models]
except Exception: # previously caught DatabaseError
# Return an empty list if this is called too early... | Returns a list of content types from the models defined in settings. | Below is the the instruction that describes the task:
### Input:
Returns a list of content types from the models defined in settings.
### Response:
def _get_seo_content_types(seo_models):
"""Returns a list of content types from the models defined in settings."""
try:
return [ContentType.objects.get... |
def set_poll_func(self, func, func_err_handler=None):
'''Can be used to integrate pulse client into existing eventloop.
Function will be passed a list of pollfd structs and timeout value (seconds, float),
which it is responsible to use and modify (set poll flags) accordingly,
returning int value >= 0 with ... | Can be used to integrate pulse client into existing eventloop.
Function will be passed a list of pollfd structs and timeout value (seconds, float),
which it is responsible to use and modify (set poll flags) accordingly,
returning int value >= 0 with number of fds that had any new events within timeout.
fu... | Below is the the instruction that describes the task:
### Input:
Can be used to integrate pulse client into existing eventloop.
Function will be passed a list of pollfd structs and timeout value (seconds, float),
which it is responsible to use and modify (set poll flags) accordingly,
returning int value ... |
def create_networking_resource_from_context(shell_name, supported_os, context):
"""
Creates an instance of Networking Resource by given context
:param shell_name: Shell Name
:type shell_name: str
:param supported_os: list of supported OS
:type supported_os: list
:param context: cloudshell.sh... | Creates an instance of Networking Resource by given context
:param shell_name: Shell Name
:type shell_name: str
:param supported_os: list of supported OS
:type supported_os: list
:param context: cloudshell.shell.core.driver_context.ResourceCommandContext
:type context: cloudshell.shell.core.driv... | Below is the the instruction that describes the task:
### Input:
Creates an instance of Networking Resource by given context
:param shell_name: Shell Name
:type shell_name: str
:param supported_os: list of supported OS
:type supported_os: list
:param context: cloudshell.shell.core.driver_context... |
def pre_dissect(self, s):
"""
Check that the payload is long enough to build a NTP packet.
"""
length = len(s)
if length < _NTP_PACKET_MIN_SIZE:
err = " ({}".format(length) + " is < _NTP_PACKET_MIN_SIZE "
err += "({})).".format(_NTP_PACKET_MIN_SIZE)
... | Check that the payload is long enough to build a NTP packet. | Below is the the instruction that describes the task:
### Input:
Check that the payload is long enough to build a NTP packet.
### Response:
def pre_dissect(self, s):
"""
Check that the payload is long enough to build a NTP packet.
"""
length = len(s)
if length < _NTP_PACKET_... |
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Read the data encoding the QueryResponsePayload object and decode it
into its constituent parts.
Args:
input_buffer (Stream): A data stream containing encoded object
data, supporting a... | Read the data encoding the QueryResponsePayload object and decode it
into its constituent parts.
Args:
input_buffer (Stream): A data stream containing encoded object
data, supporting a read method; usually a BytearrayStream
object.
kmip_version (K... | Below is the the instruction that describes the task:
### Input:
Read the data encoding the QueryResponsePayload object and decode it
into its constituent parts.
Args:
input_buffer (Stream): A data stream containing encoded object
data, supporting a read method; usually ... |
async def send(self, sender, **kwargs):
''' send a signal from the sender to all connected receivers '''
if not self.receivers:
return []
responses = []
futures = []
for receiver in self._get_receivers(sender):
method = receiver()
if callable(m... | send a signal from the sender to all connected receivers | Below is the the instruction that describes the task:
### Input:
send a signal from the sender to all connected receivers
### Response:
async def send(self, sender, **kwargs):
''' send a signal from the sender to all connected receivers '''
if not self.receivers:
return []
respo... |
def _parse_keys(row, line_num):
""" Perform some sanity checks on they keys
Each key in the row should not be named None cause
(that's an overrun). A key named `type` MUST be
present on the row & have a string value.
:param row: dict
:param line_num: int
"""
... | Perform some sanity checks on they keys
Each key in the row should not be named None cause
(that's an overrun). A key named `type` MUST be
present on the row & have a string value.
:param row: dict
:param line_num: int | Below is the the instruction that describes the task:
### Input:
Perform some sanity checks on they keys
Each key in the row should not be named None cause
(that's an overrun). A key named `type` MUST be
present on the row & have a string value.
:param row: dict
:param line... |
def serve_rpc(self):
"""Launches configured # of workers per loaded plugin."""
if cfg.CONF.QUARK_ASYNC.rpc_workers < 1:
cfg.CONF.set_override('rpc_workers', 1, "QUARK_ASYNC")
try:
rpc = service.RpcWorker(self.plugins)
launcher = common_service.ProcessLauncher... | Launches configured # of workers per loaded plugin. | Below is the the instruction that describes the task:
### Input:
Launches configured # of workers per loaded plugin.
### Response:
def serve_rpc(self):
"""Launches configured # of workers per loaded plugin."""
if cfg.CONF.QUARK_ASYNC.rpc_workers < 1:
cfg.CONF.set_override('rpc_workers',... |
def write_pid_file(self, overwrite=False):
"""Create a .pid file in the pid_dir with my pid.
This must be called after pre_construct, which sets `self.pid_dir`.
This raises :exc:`PIDFileError` if the pid file exists already.
"""
pid_file = os.path.join(self.profile_dir.pid_dir, ... | Create a .pid file in the pid_dir with my pid.
This must be called after pre_construct, which sets `self.pid_dir`.
This raises :exc:`PIDFileError` if the pid file exists already. | Below is the the instruction that describes the task:
### Input:
Create a .pid file in the pid_dir with my pid.
This must be called after pre_construct, which sets `self.pid_dir`.
This raises :exc:`PIDFileError` if the pid file exists already.
### Response:
def write_pid_file(self, overwrite=False... |
def process_response(self, request, response, resource):
"""
Do response processing
"""
origin = request.get_header('Origin')
if not settings.DEBUG:
if origin in settings.ALLOWED_ORIGINS or not origin:
response.set_header('Access-Control-Allow-Origin',... | Do response processing | Below is the the instruction that describes the task:
### Input:
Do response processing
### Response:
def process_response(self, request, response, resource):
"""
Do response processing
"""
origin = request.get_header('Origin')
if not settings.DEBUG:
if origin in... |
def get_workflow_actions_for(brain_or_object):
"""Returns a list with the actions (transitions) supported by the workflows
the object pass in is bound to. Note it returns all actions, not only those
allowed for the object based on its current state and permissions.
"""
portal_type = api.get_portal_t... | Returns a list with the actions (transitions) supported by the workflows
the object pass in is bound to. Note it returns all actions, not only those
allowed for the object based on its current state and permissions. | Below is the the instruction that describes the task:
### Input:
Returns a list with the actions (transitions) supported by the workflows
the object pass in is bound to. Note it returns all actions, not only those
allowed for the object based on its current state and permissions.
### Response:
def get_work... |
def run(samples, run_parallel, stage):
"""Run structural variation detection.
The stage indicates which level of structural variant calling to run.
- initial, callers that can be used in subsequent structural variation steps (cnvkit -> lumpy)
- standard, regular batch calling
- ensemble, post... | Run structural variation detection.
The stage indicates which level of structural variant calling to run.
- initial, callers that can be used in subsequent structural variation steps (cnvkit -> lumpy)
- standard, regular batch calling
- ensemble, post-calling, combine other callers or prioritize ... | Below is the the instruction that describes the task:
### Input:
Run structural variation detection.
The stage indicates which level of structural variant calling to run.
- initial, callers that can be used in subsequent structural variation steps (cnvkit -> lumpy)
- standard, regular batch calling... |
def count(cls, session: Optional[Session] = None) -> int:
"""Count all actions."""
if session is None:
session = _make_session()
count = session.query(cls).count()
session.close()
return count | Count all actions. | Below is the the instruction that describes the task:
### Input:
Count all actions.
### Response:
def count(cls, session: Optional[Session] = None) -> int:
"""Count all actions."""
if session is None:
session = _make_session()
count = session.query(cls).count()
session.... |
def restart(name, timeout=10):
'''
Restarts a container
name
Container name or ID
timeout : 10
Timeout in seconds after which the container will be killed (if it has
not yet gracefully shut down)
**RETURN DATA**
A dictionary will be returned, containing the following... | Restarts a container
name
Container name or ID
timeout : 10
Timeout in seconds after which the container will be killed (if it has
not yet gracefully shut down)
**RETURN DATA**
A dictionary will be returned, containing the following keys:
- ``status`` - A dictionary sho... | Below is the the instruction that describes the task:
### Input:
Restarts a container
name
Container name or ID
timeout : 10
Timeout in seconds after which the container will be killed (if it has
not yet gracefully shut down)
**RETURN DATA**
A dictionary will be returned... |
def Append(self, component=None, **kwarg):
"""Append a new pathspec component to this pathspec."""
if component is None:
component = self.__class__(**kwarg)
if self.HasField("pathtype"):
self.last.nested_path = component
else:
for k, v in iteritems(kwarg):
setattr(self, k, v)
... | Append a new pathspec component to this pathspec. | Below is the the instruction that describes the task:
### Input:
Append a new pathspec component to this pathspec.
### Response:
def Append(self, component=None, **kwarg):
"""Append a new pathspec component to this pathspec."""
if component is None:
component = self.__class__(**kwarg)
if self.Ha... |
def changeHS(self):
"""
Change health system interventions
https://github.com/SwissTPH/openmalaria/wiki/GeneratedSchema32Doc#change-health-system
Returns: list of HealthSystems together with timestep when they are applied
"""
health_systems = []
change_hs = self.e... | Change health system interventions
https://github.com/SwissTPH/openmalaria/wiki/GeneratedSchema32Doc#change-health-system
Returns: list of HealthSystems together with timestep when they are applied | Below is the the instruction that describes the task:
### Input:
Change health system interventions
https://github.com/SwissTPH/openmalaria/wiki/GeneratedSchema32Doc#change-health-system
Returns: list of HealthSystems together with timestep when they are applied
### Response:
def changeHS(self):
... |
def PUSH(self, params):
"""
PUSH {RPushList}
Push to the stack from a list of registers
List must contain only low registers or LR
"""
# TODO what registers are allowed to PUSH to? Low registers and LR
# TODO PUSH should reverse the list, not POP
RPushLis... | PUSH {RPushList}
Push to the stack from a list of registers
List must contain only low registers or LR | Below is the the instruction that describes the task:
### Input:
PUSH {RPushList}
Push to the stack from a list of registers
List must contain only low registers or LR
### Response:
def PUSH(self, params):
"""
PUSH {RPushList}
Push to the stack from a list of registers
... |
def add_page(self, orientation=''):
"Start a new page"
if(self.state==0):
self.open()
family=self.font_family
if self.underline:
style = self.font_style + 'U'
else:
style = self.font_style
size=self.font_size_pt
lw=self.line_wid... | Start a new page | Below is the the instruction that describes the task:
### Input:
Start a new page
### Response:
def add_page(self, orientation=''):
"Start a new page"
if(self.state==0):
self.open()
family=self.font_family
if self.underline:
style = self.font_style + 'U'
... |
def unwrap(value):
"""Iterate an NTTable
:returns: An iterator yielding an OrderedDict for each column
"""
ret = []
# build lists of column names, and value
lbl, cols = [], []
for cname, cval in value.value.items():
lbl.append(cname)
cols... | Iterate an NTTable
:returns: An iterator yielding an OrderedDict for each column | Below is the the instruction that describes the task:
### Input:
Iterate an NTTable
:returns: An iterator yielding an OrderedDict for each column
### Response:
def unwrap(value):
"""Iterate an NTTable
:returns: An iterator yielding an OrderedDict for each column
"""
ret = ... |
def require_mapping(self) -> None:
"""Require the node to be a mapping."""
if not isinstance(self.yaml_node, yaml.MappingNode):
raise RecognitionError(('{}{}A mapping is required here').format(
self.yaml_node.start_mark, os.linesep)) | Require the node to be a mapping. | Below is the the instruction that describes the task:
### Input:
Require the node to be a mapping.
### Response:
def require_mapping(self) -> None:
"""Require the node to be a mapping."""
if not isinstance(self.yaml_node, yaml.MappingNode):
raise RecognitionError(('{}{}A mapping is requ... |
def analysis_question_extractor(impact_report, component_metadata):
"""Extracting analysis question from the impact layer.
:param impact_report: the impact report that acts as a proxy to fetch
all the data that extractor needed
:type impact_report: safe.report.impact_report.ImpactReport
:param... | Extracting analysis question from the impact layer.
:param impact_report: the impact report that acts as a proxy to fetch
all the data that extractor needed
:type impact_report: safe.report.impact_report.ImpactReport
:param component_metadata: the component metadata. Used to obtain
informa... | Below is the the instruction that describes the task:
### Input:
Extracting analysis question from the impact layer.
:param impact_report: the impact report that acts as a proxy to fetch
all the data that extractor needed
:type impact_report: safe.report.impact_report.ImpactReport
:param compo... |
def license_name(self, license_name):
"""Sets the license_name of this DatasetNewRequest.
The license that should be associated with the dataset # noqa: E501
:param license_name: The license_name of this DatasetNewRequest. # noqa: E501
:type: str
"""
allowed_values = ... | Sets the license_name of this DatasetNewRequest.
The license that should be associated with the dataset # noqa: E501
:param license_name: The license_name of this DatasetNewRequest. # noqa: E501
:type: str | Below is the the instruction that describes the task:
### Input:
Sets the license_name of this DatasetNewRequest.
The license that should be associated with the dataset # noqa: E501
:param license_name: The license_name of this DatasetNewRequest. # noqa: E501
:type: str
### Response:
de... |
def write_taxonomy_and_seqinfo_files(self, taxonomies, output_taxonomy_file, output_seqinfo_file):
'''Write out taxonomy and seqinfo files as required by taxtastic
from known taxonomies
Parameters
----------
taxonomies:
hash of taxon_id to array of taxonomic ... | Write out taxonomy and seqinfo files as required by taxtastic
from known taxonomies
Parameters
----------
taxonomies:
hash of taxon_id to array of taxonomic information
output_taxonomy_file:
write taxtastic-compatible 'taxonomy' file here
... | Below is the the instruction that describes the task:
### Input:
Write out taxonomy and seqinfo files as required by taxtastic
from known taxonomies
Parameters
----------
taxonomies:
hash of taxon_id to array of taxonomic information
output_taxonomy_file:... |
def finalize_sv(orig_vcf, data, items):
"""Finalize structural variants, adding effects and splitting if needed.
"""
paired = vcfutils.get_paired(items)
# For paired/somatic, attach combined calls to tumor sample
if paired:
sample_vcf = orig_vcf if paired.tumor_name == dd.get_sample_name(dat... | Finalize structural variants, adding effects and splitting if needed. | Below is the the instruction that describes the task:
### Input:
Finalize structural variants, adding effects and splitting if needed.
### Response:
def finalize_sv(orig_vcf, data, items):
"""Finalize structural variants, adding effects and splitting if needed.
"""
paired = vcfutils.get_paired(items)
... |
def update_item(self, jid, name = NO_CHANGE, groups = NO_CHANGE,
callback = None, error_callback = None):
"""Modify a contact in the roster.
:Parameters:
- `jid`: contact's jid
- `name`: a new name for the contact
- `groups`: a sequenc... | Modify a contact in the roster.
:Parameters:
- `jid`: contact's jid
- `name`: a new name for the contact
- `groups`: a sequence of group names the contact should belong to
- `callback`: function to call when the request succeeds. It should
accept a ... | Below is the the instruction that describes the task:
### Input:
Modify a contact in the roster.
:Parameters:
- `jid`: contact's jid
- `name`: a new name for the contact
- `groups`: a sequence of group names the contact should belong to
- `callback`: function... |
def has_blocking_background_send(self):
"""Check whether any blocking background commands are waiting to run.
If any are, return True. If none are, return False.
"""
for background_object in self.background_objects:
# If it's running, or not started yet, it should block other tasks.
if background_ob... | Check whether any blocking background commands are waiting to run.
If any are, return True. If none are, return False. | Below is the the instruction that describes the task:
### Input:
Check whether any blocking background commands are waiting to run.
If any are, return True. If none are, return False.
### Response:
def has_blocking_background_send(self):
"""Check whether any blocking background commands are waiting to ru... |
def analysis_output_to_dict_entries(
self,
inputfile: AnalysisOutput,
previous_inputfile: Optional[AnalysisOutput],
previous_issue_handles: Optional[AnalysisOutput],
linemapfile: Optional[str],
) -> DictEntries:
"""Here we take input generators and return a dict with ... | Here we take input generators and return a dict with issues,
preconditions, and postconditions separated. If there is only a single
generator file, it's simple. If we also pass in a generator from a
previous inputfile then there are a couple extra steps:
1. If an issue was seen in the p... | Below is the the instruction that describes the task:
### Input:
Here we take input generators and return a dict with issues,
preconditions, and postconditions separated. If there is only a single
generator file, it's simple. If we also pass in a generator from a
previous inputfile then ther... |
def _replace_str_html(s):
"""替换html‘"’等转义内容为正常内容
Args:
s: 文字内容
Returns:
s: 处理反转义后的文字
"""
html_str_list = [
(''', '\''),
('"', '"'),
('&', '&'),
('¥', '¥'),
('amp;', ''),
('<', '<'),
('>', '>'),
... | 替换html‘"’等转义内容为正常内容
Args:
s: 文字内容
Returns:
s: 处理反转义后的文字 | Below is the the instruction that describes the task:
### Input:
替换html‘"’等转义内容为正常内容
Args:
s: 文字内容
Returns:
s: 处理反转义后的文字
### Response:
def _replace_str_html(s):
"""替换html‘"’等转义内容为正常内容
Args:
s: 文字内容
Returns:
s: 处理反转义后的文字
"""
html_str_list = [... |
def service_url_parse(url):
"""
Function that parses from url the service and folder of services.
"""
endpoint = get_sanitized_endpoint(url)
url_split_list = url.split(endpoint + '/')
if len(url_split_list) != 0:
url_split_list = url_split_list[1].split('/')
else:
raise Excep... | Function that parses from url the service and folder of services. | Below is the the instruction that describes the task:
### Input:
Function that parses from url the service and folder of services.
### Response:
def service_url_parse(url):
"""
Function that parses from url the service and folder of services.
"""
endpoint = get_sanitized_endpoint(url)
url_split... |
def _get_proto():
'''
Checks configuration to see whether the user has SSL turned on. Default is:
.. code-block:: yaml
use_ssl: True
'''
use_ssl = config.get_cloud_config_value(
'use_ssl',
get_configured_provider(),
__opts__,
search_global=False,
def... | Checks configuration to see whether the user has SSL turned on. Default is:
.. code-block:: yaml
use_ssl: True | Below is the the instruction that describes the task:
### Input:
Checks configuration to see whether the user has SSL turned on. Default is:
.. code-block:: yaml
use_ssl: True
### Response:
def _get_proto():
'''
Checks configuration to see whether the user has SSL turned on. Default is:
... |
def replace_certificate_signing_request_approval(self, name, body, **kwargs):
"""
replace approval of the specified CertificateSigningRequest
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api... | replace approval of the specified CertificateSigningRequest
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_certificate_signing_request_approval(name, body, async_req=True)
>>> result = thr... | Below is the the instruction that describes the task:
### Input:
replace approval of the specified CertificateSigningRequest
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_certificate_signing_... |
def alpha(self, x, y, kwargs, k=None):
"""
deflection angles
:param x: x-position (preferentially arcsec)
:type x: numpy array
:param y: y-position (preferentially arcsec)
:type y: numpy array
:param kwargs: list of keyword arguments of lens model parameters matc... | deflection angles
:param x: x-position (preferentially arcsec)
:type x: numpy array
:param y: y-position (preferentially arcsec)
:type y: numpy array
:param kwargs: list of keyword arguments of lens model parameters matching the lens model classes
:param k: only evaluate ... | Below is the the instruction that describes the task:
### Input:
deflection angles
:param x: x-position (preferentially arcsec)
:type x: numpy array
:param y: y-position (preferentially arcsec)
:type y: numpy array
:param kwargs: list of keyword arguments of lens model parame... |
def dump_relation(api, rel_cfg, pid, data):
"""Dump a specific relation to a data dict."""
schema_class = rel_cfg.schema
if schema_class is not None:
schema = schema_class()
schema.context['pid'] = pid
result, errors = schema.dump(api)
data.setdefault(rel_cfg.name, []).append... | Dump a specific relation to a data dict. | Below is the the instruction that describes the task:
### Input:
Dump a specific relation to a data dict.
### Response:
def dump_relation(api, rel_cfg, pid, data):
"""Dump a specific relation to a data dict."""
schema_class = rel_cfg.schema
if schema_class is not None:
schema = schema_class()
... |
def encode_character(char):
"""Returns URL encoding for a single character
:param char (str) Single character to encode
:returns (str) URL-encoded character
"""
if char == '!': return '%21'
elif char == '"': return '%22'
elif char == '#': return '%23'
elif char == '$': return '%24'
... | Returns URL encoding for a single character
:param char (str) Single character to encode
:returns (str) URL-encoded character | Below is the the instruction that describes the task:
### Input:
Returns URL encoding for a single character
:param char (str) Single character to encode
:returns (str) URL-encoded character
### Response:
def encode_character(char):
"""Returns URL encoding for a single character
:param char (str)... |
def deserialize_bytearray(attr):
"""Deserialize string into bytearray.
:param str attr: response string to be deserialized.
:rtype: bytearray
:raises: TypeError if string format invalid.
"""
if isinstance(attr, ET.Element):
attr = attr.text
return byt... | Deserialize string into bytearray.
:param str attr: response string to be deserialized.
:rtype: bytearray
:raises: TypeError if string format invalid. | Below is the the instruction that describes the task:
### Input:
Deserialize string into bytearray.
:param str attr: response string to be deserialized.
:rtype: bytearray
:raises: TypeError if string format invalid.
### Response:
def deserialize_bytearray(attr):
"""Deserialize stri... |
def _create_gates(self, inputs, memory):
"""Create input and forget gates for this step using `inputs` and `memory`.
Args:
inputs: Tensor input.
memory: The current state of memory.
Returns:
input_gate: A LSTM-like insert gate.
forget_gate: A LSTM-like forget gate.
"""
# We... | Create input and forget gates for this step using `inputs` and `memory`.
Args:
inputs: Tensor input.
memory: The current state of memory.
Returns:
input_gate: A LSTM-like insert gate.
forget_gate: A LSTM-like forget gate. | Below is the the instruction that describes the task:
### Input:
Create input and forget gates for this step using `inputs` and `memory`.
Args:
inputs: Tensor input.
memory: The current state of memory.
Returns:
input_gate: A LSTM-like insert gate.
forget_gate: A LSTM-like forget g... |
def run(self, agent_host):
"""run the agent on the world"""
total_reward = 0
self.prev_s = None
self.prev_a = None
is_first_action = True
# main loop:
world_state = agent_host.getWorldState()
while world_state.is_mission_running... | run the agent on the world | Below is the the instruction that describes the task:
### Input:
run the agent on the world
### Response:
def run(self, agent_host):
"""run the agent on the world"""
total_reward = 0
self.prev_s = None
self.prev_a = None
is_first_action = True
... |
def remove_terms_used_in_less_than_num_docs(self, threshold):
'''
Parameters
----------
threshold: int
Minimum number of documents term should appear in to be kept
Returns
-------
TermDocMatrix, new object with terms removed.
'''
term_... | Parameters
----------
threshold: int
Minimum number of documents term should appear in to be kept
Returns
-------
TermDocMatrix, new object with terms removed. | Below is the the instruction that describes the task:
### Input:
Parameters
----------
threshold: int
Minimum number of documents term should appear in to be kept
Returns
-------
TermDocMatrix, new object with terms removed.
### Response:
def remove_terms_used_i... |
def resources_preparing_factory(app, wrapper):
""" Factory which wrap all resources in settings.
"""
settings = app.app.registry.settings
config = settings.get(CONFIG_RESOURCES, None)
if not config:
return
resources = [(k, [wrapper(r, GroupResource(k, v)) for r in v])
f... | Factory which wrap all resources in settings. | Below is the the instruction that describes the task:
### Input:
Factory which wrap all resources in settings.
### Response:
def resources_preparing_factory(app, wrapper):
""" Factory which wrap all resources in settings.
"""
settings = app.app.registry.settings
config = settings.get(CONFIG_RESOURC... |
def nl_connect(sk, protocol):
"""Create file descriptor and bind socket.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L96
Creates a new Netlink socket using `socket.socket()` and binds the socket to the protocol and local port specified
in the `sk` socket object (if any). Fails if the so... | Create file descriptor and bind socket.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L96
Creates a new Netlink socket using `socket.socket()` and binds the socket to the protocol and local port specified
in the `sk` socket object (if any). Fails if the socket is already connected.
Posit... | Below is the the instruction that describes the task:
### Input:
Create file descriptor and bind socket.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L96
Creates a new Netlink socket using `socket.socket()` and binds the socket to the protocol and local port specified
in the `sk` socket ... |
def SLIT_GAUSSIAN(x,g):
"""
Instrumental (slit) function.
B(x) = sqrt(ln(2)/pi)/γ*exp(-ln(2)*(x/γ)**2),
where γ/2 is a gaussian half-width at half-maximum.
"""
g /= 2
return sqrt(log(2))/(sqrt(pi)*g)*exp(-log(2)*(x/g)**2) | Instrumental (slit) function.
B(x) = sqrt(ln(2)/pi)/γ*exp(-ln(2)*(x/γ)**2),
where γ/2 is a gaussian half-width at half-maximum. | Below is the the instruction that describes the task:
### Input:
Instrumental (slit) function.
B(x) = sqrt(ln(2)/pi)/γ*exp(-ln(2)*(x/γ)**2),
where γ/2 is a gaussian half-width at half-maximum.
### Response:
def SLIT_GAUSSIAN(x,g):
"""
Instrumental (slit) function.
B(x) = sqrt(ln(2)/pi)/γ*exp(-l... |
def OnSafeModeEntry(self, event):
"""Safe mode entry event handler"""
# Enable menu item for leaving safe mode
self.main_window.main_menu.enable_file_approve(True)
self.main_window.grid.Refresh()
event.Skip() | Safe mode entry event handler | Below is the the instruction that describes the task:
### Input:
Safe mode entry event handler
### Response:
def OnSafeModeEntry(self, event):
"""Safe mode entry event handler"""
# Enable menu item for leaving safe mode
self.main_window.main_menu.enable_file_approve(True)
self.ma... |
def ToJson(self):
"""
Convert object members to a dictionary that can be parsed as JSON.
Returns:
dict:
"""
json = {}
json["hash"] = self.Hash.To0xString()
json["size"] = self.Size()
json["version"] = self.Version
json["previousblockh... | Convert object members to a dictionary that can be parsed as JSON.
Returns:
dict: | Below is the the instruction that describes the task:
### Input:
Convert object members to a dictionary that can be parsed as JSON.
Returns:
dict:
### Response:
def ToJson(self):
"""
Convert object members to a dictionary that can be parsed as JSON.
Returns:
... |
def return_resource_name(self, record, resource_type):
""" Removes the trailing AWS domain from a DNS record
to return the resource name
e.g bucketname.s3.amazonaws.com will return bucketname
Args:
record (str): DNS record
resource_type: AWS Resource typ... | Removes the trailing AWS domain from a DNS record
to return the resource name
e.g bucketname.s3.amazonaws.com will return bucketname
Args:
record (str): DNS record
resource_type: AWS Resource type (i.e. S3 Bucket, Elastic Beanstalk, etc..) | Below is the the instruction that describes the task:
### Input:
Removes the trailing AWS domain from a DNS record
to return the resource name
e.g bucketname.s3.amazonaws.com will return bucketname
Args:
record (str): DNS record
resource_type: AWS Resource t... |
def _waitfor(self, mode, mask, may_block, timeout=2):
"""
Wait for the YubiKey to either turn ON or OFF certain bits in the status byte.
mode is either 'and' or 'nand'
timeout is a number of seconds (precision about ~0.5 seconds)
"""
finished = False
sleep = 0.01... | Wait for the YubiKey to either turn ON or OFF certain bits in the status byte.
mode is either 'and' or 'nand'
timeout is a number of seconds (precision about ~0.5 seconds) | Below is the the instruction that describes the task:
### Input:
Wait for the YubiKey to either turn ON or OFF certain bits in the status byte.
mode is either 'and' or 'nand'
timeout is a number of seconds (precision about ~0.5 seconds)
### Response:
def _waitfor(self, mode, mask, may_block, timeo... |
def make_federation_entity(config, eid='', httpcli=None, verify_ssl=True):
"""
Construct a :py:class:`fedoidcmsg.entity.FederationEntity` instance based
on given configuration.
:param config: Federation entity configuration
:param eid: Entity ID
:param httpcli: A http client instance to use whe... | Construct a :py:class:`fedoidcmsg.entity.FederationEntity` instance based
on given configuration.
:param config: Federation entity configuration
:param eid: Entity ID
:param httpcli: A http client instance to use when sending HTTP requests
:param verify_ssl: Whether TLS/SSL certificates should be v... | Below is the the instruction that describes the task:
### Input:
Construct a :py:class:`fedoidcmsg.entity.FederationEntity` instance based
on given configuration.
:param config: Federation entity configuration
:param eid: Entity ID
:param httpcli: A http client instance to use when sending HTTP req... |
def stChromaFeaturesInit(nfft, fs):
"""
This function initializes the chroma matrices used in the calculation of the chroma features
"""
freqs = numpy.array([((f + 1) * fs) / (2 * nfft) for f in range(nfft)])
Cp = 27.50
nChroma = numpy.round(12.0 * numpy.log2(freqs / Cp)).astype(int)
... | This function initializes the chroma matrices used in the calculation of the chroma features | Below is the the instruction that describes the task:
### Input:
This function initializes the chroma matrices used in the calculation of the chroma features
### Response:
def stChromaFeaturesInit(nfft, fs):
"""
This function initializes the chroma matrices used in the calculation of the chroma features
... |
def member_add(self, member_id=None, params=None):
"""add new member into existing configuration"""
member_id = member_id or str(uuid4())
if self.enable_ipv6:
common.enable_ipv6_repl(params)
if 'members' in params:
# is replica set
for member in params... | add new member into existing configuration | Below is the the instruction that describes the task:
### Input:
add new member into existing configuration
### Response:
def member_add(self, member_id=None, params=None):
"""add new member into existing configuration"""
member_id = member_id or str(uuid4())
if self.enable_ipv6:
... |
def getbroker():
'''
return settings dictionnary
'''
if not Configuration.broker_initialized:
Configuration._initconf()
Configuration.broker_settings = Configuration.settings['broker']
Configuration.broker_initialized = True
return Configuratio... | return settings dictionnary | Below is the the instruction that describes the task:
### Input:
return settings dictionnary
### Response:
def getbroker():
'''
return settings dictionnary
'''
if not Configuration.broker_initialized:
Configuration._initconf()
Configuration.broker_settings = ... |
def _validate_token(self, token, scopes_required=None):
"""The actual implementation of validate_token."""
if scopes_required is None:
scopes_required = []
scopes_required = set(scopes_required)
token_info = None
valid_token = False
has_required_scopes = Fals... | The actual implementation of validate_token. | Below is the the instruction that describes the task:
### Input:
The actual implementation of validate_token.
### Response:
def _validate_token(self, token, scopes_required=None):
"""The actual implementation of validate_token."""
if scopes_required is None:
scopes_required = []
... |
def solve_with_glpsol(glp_prob):
"""Solve glpk problem with glpsol commandline solver. Mainly for testing purposes.
# Examples
# --------
# >>> problem = glp_create_prob()
# ... glp_read_lp(problem, None, "../tests/data/model.lp")
# ... solution = solve_with_glpsol(problem)
# ... print 'as... | Solve glpk problem with glpsol commandline solver. Mainly for testing purposes.
# Examples
# --------
# >>> problem = glp_create_prob()
# ... glp_read_lp(problem, None, "../tests/data/model.lp")
# ... solution = solve_with_glpsol(problem)
# ... print 'asdf'
# 'asdf'
# >>> print solutio... | Below is the the instruction that describes the task:
### Input:
Solve glpk problem with glpsol commandline solver. Mainly for testing purposes.
# Examples
# --------
# >>> problem = glp_create_prob()
# ... glp_read_lp(problem, None, "../tests/data/model.lp")
# ... solution = solve_with_glpsol... |
def parent(groups,ID):
"""given a groups dictionary and an ID, return its actual parent ID."""
if ID in groups.keys():
return ID # already a parent
if not ID in groups.keys():
for actualParent in groups.keys():
if ID in groups[actualParent]:
return actualParent # ... | given a groups dictionary and an ID, return its actual parent ID. | Below is the the instruction that describes the task:
### Input:
given a groups dictionary and an ID, return its actual parent ID.
### Response:
def parent(groups,ID):
"""given a groups dictionary and an ID, return its actual parent ID."""
if ID in groups.keys():
return ID # already a parent
if... |
def coords_from_query(query):
"""Transform a query line into a (lng, lat) pair of coordinates."""
try:
coords = json.loads(query)
except ValueError:
vals = re.split(r'[,\s]+', query.strip())
coords = [float(v) for v in vals]
return tuple(coords[:2]) | Transform a query line into a (lng, lat) pair of coordinates. | Below is the the instruction that describes the task:
### Input:
Transform a query line into a (lng, lat) pair of coordinates.
### Response:
def coords_from_query(query):
"""Transform a query line into a (lng, lat) pair of coordinates."""
try:
coords = json.loads(query)
except ValueError:
... |
def revnet_step(name, x, hparams, reverse=True):
"""One step of glow generative flow.
Actnorm + invertible 1X1 conv + affine_coupling.
Args:
name: used for variable scope.
x: input
hparams: coupling_width is the only hparam that is being used in
this function.
reverse: forward or re... | One step of glow generative flow.
Actnorm + invertible 1X1 conv + affine_coupling.
Args:
name: used for variable scope.
x: input
hparams: coupling_width is the only hparam that is being used in
this function.
reverse: forward or reverse pass.
Returns:
z: Output of one step of re... | Below is the the instruction that describes the task:
### Input:
One step of glow generative flow.
Actnorm + invertible 1X1 conv + affine_coupling.
Args:
name: used for variable scope.
x: input
hparams: coupling_width is the only hparam that is being used in
this function.
reverse... |
def reduce_operators(source):
"""
Remove spaces between operators in *source* and returns the result.
Example::
def foo(foo, bar, blah):
test = "This is a %s" % foo
Will become::
def foo(foo,bar,blah):
test="This is a %s"%foo
.. note::
Also remov... | Remove spaces between operators in *source* and returns the result.
Example::
def foo(foo, bar, blah):
test = "This is a %s" % foo
Will become::
def foo(foo,bar,blah):
test="This is a %s"%foo
.. note::
Also removes trailing commas and joins disjointed st... | Below is the the instruction that describes the task:
### Input:
Remove spaces between operators in *source* and returns the result.
Example::
def foo(foo, bar, blah):
test = "This is a %s" % foo
Will become::
def foo(foo,bar,blah):
test="This is a %s"%foo
.. ... |
def output_channels(self):
"""Returns the number of output channels."""
if callable(self._output_channels):
self._output_channels = self._output_channels()
# Channel must be integer.
self._output_channels = int(self._output_channels)
return self._output_channels | Returns the number of output channels. | Below is the the instruction that describes the task:
### Input:
Returns the number of output channels.
### Response:
def output_channels(self):
"""Returns the number of output channels."""
if callable(self._output_channels):
self._output_channels = self._output_channels()
# Channel must be integ... |
def slice(self, tf_tensor, tensor_shape):
""""Slice out the corresponding part of tensor given the pnum variable."""
tensor_layout = self.tensor_layout(tensor_shape)
if tensor_layout.is_fully_replicated:
return self.LaidOutTensor([tf_tensor])
else:
slice_shape = self.slice_shape(tensor_shap... | Slice out the corresponding part of tensor given the pnum variable. | Below is the the instruction that describes the task:
### Input:
Slice out the corresponding part of tensor given the pnum variable.
### Response:
def slice(self, tf_tensor, tensor_shape):
""""Slice out the corresponding part of tensor given the pnum variable."""
tensor_layout = self.tensor_layout(tensor_s... |
def remove_plugin_filepaths(self, filepaths):
"""
Removes `filepaths` from `self.plugin_filepaths`.
Recommend passing in absolute filepaths. Method will
attempt to convert to absolute paths if not passed in.
`filepaths` can be a single object or an iterable.
"""
... | Removes `filepaths` from `self.plugin_filepaths`.
Recommend passing in absolute filepaths. Method will
attempt to convert to absolute paths if not passed in.
`filepaths` can be a single object or an iterable. | Below is the the instruction that describes the task:
### Input:
Removes `filepaths` from `self.plugin_filepaths`.
Recommend passing in absolute filepaths. Method will
attempt to convert to absolute paths if not passed in.
`filepaths` can be a single object or an iterable.
### Response:
de... |
def publish_workflow_status(self, workflow_uuid, status,
logs='', message=None):
"""Publish workflow status using the configured.
:param workflow_uudid: String which represents the workflow UUID.
:param status: Integer which represents the status of the workflow,... | Publish workflow status using the configured.
:param workflow_uudid: String which represents the workflow UUID.
:param status: Integer which represents the status of the workflow,
this is defined in the `reana-db` `Workflow` models.
:param logs: String which represents the logs whic... | Below is the the instruction that describes the task:
### Input:
Publish workflow status using the configured.
:param workflow_uudid: String which represents the workflow UUID.
:param status: Integer which represents the status of the workflow,
this is defined in the `reana-db` `Workflo... |
def azm(self):
"""Corrected azimuth, taking into account backsight, declination, and compass corrections."""
azm1 = self.get('BEARING', None)
azm2 = self.get('AZM2', None)
if azm1 is None and azm2 is None:
return None
if azm2 is None:
return azm1 + self.de... | Corrected azimuth, taking into account backsight, declination, and compass corrections. | Below is the the instruction that describes the task:
### Input:
Corrected azimuth, taking into account backsight, declination, and compass corrections.
### Response:
def azm(self):
"""Corrected azimuth, taking into account backsight, declination, and compass corrections."""
azm1 = self.get('BEARIN... |
def render_tile(cells, ti, tj, render, params, metadata, layout, summary):
"""
Render each cell in the tile and stitch it into a single image
"""
image_size = params["cell_size"] * params["n_tile"]
tile = Image.new("RGB", (image_size, image_size), (255,255,255))
keys = cells.keys()
for i,key in enumerat... | Render each cell in the tile and stitch it into a single image | Below is the the instruction that describes the task:
### Input:
Render each cell in the tile and stitch it into a single image
### Response:
def render_tile(cells, ti, tj, render, params, metadata, layout, summary):
"""
Render each cell in the tile and stitch it into a single image
"""
image_size = para... |
def do_urlize(eval_ctx, value, trim_url_limit=None, nofollow=False,
target=None, rel=None):
"""Converts URLs in plain text into clickable links.
If you pass the filter an additional integer it will shorten the urls
to that number. Also a third argument exists that makes the urls
"nofollow... | Converts URLs in plain text into clickable links.
If you pass the filter an additional integer it will shorten the urls
to that number. Also a third argument exists that makes the urls
"nofollow":
.. sourcecode:: jinja
{{ mytext|urlize(40, true) }}
links are shortened to 40 chars ... | Below is the the instruction that describes the task:
### Input:
Converts URLs in plain text into clickable links.
If you pass the filter an additional integer it will shorten the urls
to that number. Also a third argument exists that makes the urls
"nofollow":
.. sourcecode:: jinja
{{ my... |
def sext(self, width):
"""Sign-extends a word to a larger width. It is an error to specify
a smaller width (use ``extract`` instead to crop off the extra bits).
"""
width = operator.index(width)
if width < self._width:
raise ValueError('sign extending to a smaller wi... | Sign-extends a word to a larger width. It is an error to specify
a smaller width (use ``extract`` instead to crop off the extra bits). | Below is the the instruction that describes the task:
### Input:
Sign-extends a word to a larger width. It is an error to specify
a smaller width (use ``extract`` instead to crop off the extra bits).
### Response:
def sext(self, width):
"""Sign-extends a word to a larger width. It is an error to ... |
def _compress(self):
"""Internal method to compress the cache. This method will
expire any old items in the cache, making the cache smaller"""
# Don't compress too often
now = time.time()
if self._last_compression + self._compression_timer < now:
self._last_compre... | Internal method to compress the cache. This method will
expire any old items in the cache, making the cache smaller | Below is the the instruction that describes the task:
### Input:
Internal method to compress the cache. This method will
expire any old items in the cache, making the cache smaller
### Response:
def _compress(self):
"""Internal method to compress the cache. This method will
expire any... |
def human_sorting(the_list):
"""Sort the given list in the way that humans expect.
From http://stackoverflow.com/a/4623518
:param the_list: The list to sort.
:type the_list: list
:return: The new sorted list.
:rtype: list
"""
def try_int(s):
try:
return int(s)
... | Sort the given list in the way that humans expect.
From http://stackoverflow.com/a/4623518
:param the_list: The list to sort.
:type the_list: list
:return: The new sorted list.
:rtype: list | Below is the the instruction that describes the task:
### Input:
Sort the given list in the way that humans expect.
From http://stackoverflow.com/a/4623518
:param the_list: The list to sort.
:type the_list: list
:return: The new sorted list.
:rtype: list
### Response:
def human_sorting(the_l... |
def getRnaQuantificationSetByName(self, name):
"""
Returns the RnaQuantification set with the specified name, or raises
an exception otherwise.
"""
if name not in self._rnaQuantificationSetNameMap:
raise exceptions.RnaQuantificationSetNameNotFoundException(name)
... | Returns the RnaQuantification set with the specified name, or raises
an exception otherwise. | Below is the the instruction that describes the task:
### Input:
Returns the RnaQuantification set with the specified name, or raises
an exception otherwise.
### Response:
def getRnaQuantificationSetByName(self, name):
"""
Returns the RnaQuantification set with the specified name, or raises... |
def apply_func_to_select_indices(self, axis, func, indices, keep_remaining=False):
"""Applies a function to select indices.
Note: Your internal function must take a kwarg `internal_indices` for
this to work correctly. This prevents information leakage of the
internal index to th... | Applies a function to select indices.
Note: Your internal function must take a kwarg `internal_indices` for
this to work correctly. This prevents information leakage of the
internal index to the external representation.
Args:
axis: The axis to apply the func over.
... | Below is the the instruction that describes the task:
### Input:
Applies a function to select indices.
Note: Your internal function must take a kwarg `internal_indices` for
this to work correctly. This prevents information leakage of the
internal index to the external representation... |
def trigger_event(self, event, *args):
"""Dispatch an event to the proper handler method.
In the most common usage, this method is not overloaded by subclasses,
as it performs the routing of events to methods. However, this
method can be overriden if special dispatching rules are needed... | Dispatch an event to the proper handler method.
In the most common usage, this method is not overloaded by subclasses,
as it performs the routing of events to methods. However, this
method can be overriden if special dispatching rules are needed, or if
having a single method that catche... | Below is the the instruction that describes the task:
### Input:
Dispatch an event to the proper handler method.
In the most common usage, this method is not overloaded by subclasses,
as it performs the routing of events to methods. However, this
method can be overriden if special dispatchi... |
def timeit(stat_tracker_func, name):
"""
Pass in a function and the name of the stat
Will time the function that this is a decorator to and send
the `name` as well as the value (in seconds) to `stat_tracker_func`
`stat_tracker_func` can be used to either print out the data or save it
"""
de... | Pass in a function and the name of the stat
Will time the function that this is a decorator to and send
the `name` as well as the value (in seconds) to `stat_tracker_func`
`stat_tracker_func` can be used to either print out the data or save it | Below is the the instruction that describes the task:
### Input:
Pass in a function and the name of the stat
Will time the function that this is a decorator to and send
the `name` as well as the value (in seconds) to `stat_tracker_func`
`stat_tracker_func` can be used to either print out the data or sa... |
def file_exists(
download_url,
filename=None,
decompress=False,
subdir=None):
"""
Return True if a local file corresponding to these arguments
exists.
"""
filename = build_local_filename(download_url, filename, decompress)
full_path = build_path(filename, subdir)
... | Return True if a local file corresponding to these arguments
exists. | Below is the the instruction that describes the task:
### Input:
Return True if a local file corresponding to these arguments
exists.
### Response:
def file_exists(
download_url,
filename=None,
decompress=False,
subdir=None):
"""
Return True if a local file corresponding... |
def _check_remote_command(self, destination, timeout_ms, success_msgs=None):
"""Open a stream to destination, check for remote errors.
Used for reboot, remount, and root services. If this method returns, the
command was successful, otherwise an appropriate error will have been
raised.
Args:
... | Open a stream to destination, check for remote errors.
Used for reboot, remount, and root services. If this method returns, the
command was successful, otherwise an appropriate error will have been
raised.
Args:
destination: Stream destination to open.
timeout_ms: Timeout in milliseconds ... | Below is the the instruction that describes the task:
### Input:
Open a stream to destination, check for remote errors.
Used for reboot, remount, and root services. If this method returns, the
command was successful, otherwise an appropriate error will have been
raised.
Args:
destination: S... |
def find_in_tree(tree, key, perfect=False):
"""
Helper to perform find in dictionary tree.
"""
if len(key) == 0:
if tree['item'] is not None:
return tree['item'], ()
else:
for i in range(len(tree['subtrees'])):
if not perfect and tree['subtrees'][i... | Helper to perform find in dictionary tree. | Below is the the instruction that describes the task:
### Input:
Helper to perform find in dictionary tree.
### Response:
def find_in_tree(tree, key, perfect=False):
"""
Helper to perform find in dictionary tree.
"""
if len(key) == 0:
if tree['item'] is not None:
return tree['it... |
def Eg(self, **kwargs):
'''
Returns the strain-shifted bandgap, ``Eg``.
'''
return self.unstrained.Eg(**kwargs) + self.Eg_strain_shift(**kwargs) | Returns the strain-shifted bandgap, ``Eg``. | Below is the the instruction that describes the task:
### Input:
Returns the strain-shifted bandgap, ``Eg``.
### Response:
def Eg(self, **kwargs):
'''
Returns the strain-shifted bandgap, ``Eg``.
'''
return self.unstrained.Eg(**kwargs) + self.Eg_strain_shift(**kwargs) |
def _mkdir_p(path):
"""mkdir -p path"""
try:
os.makedirs(path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
else:
logger.info("New: %s%s", path, os.path.sep) | mkdir -p path | Below is the the instruction that describes the task:
### Input:
mkdir -p path
### Response:
def _mkdir_p(path):
"""mkdir -p path"""
try:
os.makedirs(path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
e... |
def uma_rp_get_claims_gathering_url(self, ticket):
"""UMA RP function to get the claims gathering URL.
Parameters:
* **ticket (str):** ticket to pass to the auth server. for 90% of the cases, this will be obtained from 'need_info' error of get_rpt
Returns:
**string** sp... | UMA RP function to get the claims gathering URL.
Parameters:
* **ticket (str):** ticket to pass to the auth server. for 90% of the cases, this will be obtained from 'need_info' error of get_rpt
Returns:
**string** specifying the claims gathering url | Below is the the instruction that describes the task:
### Input:
UMA RP function to get the claims gathering URL.
Parameters:
* **ticket (str):** ticket to pass to the auth server. for 90% of the cases, this will be obtained from 'need_info' error of get_rpt
Returns:
**stri... |
def connect(self, ctx):
"""
establish xbahn connection and store on click context
"""
if hasattr(ctx,"conn") or "host" not in ctx.params:
return
ctx.conn = conn = connect(ctx.params["host"])
lnk = link.Link()
lnk.wire("main", receive=conn, send=conn... | establish xbahn connection and store on click context | Below is the the instruction that describes the task:
### Input:
establish xbahn connection and store on click context
### Response:
def connect(self, ctx):
"""
establish xbahn connection and store on click context
"""
if hasattr(ctx,"conn") or "host" not in ctx.params:
... |
def derive_temporalnetwork(data, params):
"""
Derives connectivity from the data. A lot of data is inherently built with edges
(e.g. communication between two individuals).
However other networks are derived from the covariance of time series
(e.g. brain networks between two regions).
Covaria... | Derives connectivity from the data. A lot of data is inherently built with edges
(e.g. communication between two individuals).
However other networks are derived from the covariance of time series
(e.g. brain networks between two regions).
Covariance based metrics deriving time-resolved networks can ... | Below is the the instruction that describes the task:
### Input:
Derives connectivity from the data. A lot of data is inherently built with edges
(e.g. communication between two individuals).
However other networks are derived from the covariance of time series
(e.g. brain networks between two regions... |
def socket_options(instance):
"""Ensure the keys of the 'options' property of the socket-ext extension of
network-traffic objects are only valid socket options (SO_*).
"""
for key, obj in instance['objects'].items():
if ('type' in obj and obj['type'] == 'network-traffic'):
try:
... | Ensure the keys of the 'options' property of the socket-ext extension of
network-traffic objects are only valid socket options (SO_*). | Below is the the instruction that describes the task:
### Input:
Ensure the keys of the 'options' property of the socket-ext extension of
network-traffic objects are only valid socket options (SO_*).
### Response:
def socket_options(instance):
"""Ensure the keys of the 'options' property of the socket-ext ... |
def cellCenters(self):
"""Get the list of cell centers of the mesh surface.
.. hint:: |delaunay2d| |delaunay2d.py|_
"""
vcen = vtk.vtkCellCenters()
vcen.SetInputData(self.polydata(True))
vcen.Update()
return vtk_to_numpy(vcen.GetOutput().GetPoints().GetData()) | Get the list of cell centers of the mesh surface.
.. hint:: |delaunay2d| |delaunay2d.py|_ | Below is the the instruction that describes the task:
### Input:
Get the list of cell centers of the mesh surface.
.. hint:: |delaunay2d| |delaunay2d.py|_
### Response:
def cellCenters(self):
"""Get the list of cell centers of the mesh surface.
.. hint:: |delaunay2d| |delaunay2d.py|_
... |
def closeEvent(self, event):
"""Verifies the stimulus before closing, warns user with a
dialog if there are any problems"""
self.ok.setText("Checking...")
QtGui.QApplication.processEvents()
self.model().cleanComponents()
self.model().purgeAutoSelected()
msg = self... | Verifies the stimulus before closing, warns user with a
dialog if there are any problems | Below is the the instruction that describes the task:
### Input:
Verifies the stimulus before closing, warns user with a
dialog if there are any problems
### Response:
def closeEvent(self, event):
"""Verifies the stimulus before closing, warns user with a
dialog if there are any problems"""... |
def memset(self, allocation, value, size):
"""set the memory in allocation to the value in value
:param allocation: An Argument for some memory allocation unit
:type allocation: Argument
:param value: The value to set the memory to
:type value: a single 8-bit unsigned int
... | set the memory in allocation to the value in value
:param allocation: An Argument for some memory allocation unit
:type allocation: Argument
:param value: The value to set the memory to
:type value: a single 8-bit unsigned int
:param size: The size of to the allocation unit in... | Below is the the instruction that describes the task:
### Input:
set the memory in allocation to the value in value
:param allocation: An Argument for some memory allocation unit
:type allocation: Argument
:param value: The value to set the memory to
:type value: a single 8-bit uns... |
def execute(self, eopatch):
""" Mask values of `feature` according to the `mask_values` in `mask_feature`
:param eopatch: `eopatch` to be processed
:return: Same `eopatch` instance with masked `feature`
"""
feature_type, feature_name, new_feature_name = next(self.feature(eopatch... | Mask values of `feature` according to the `mask_values` in `mask_feature`
:param eopatch: `eopatch` to be processed
:return: Same `eopatch` instance with masked `feature` | Below is the the instruction that describes the task:
### Input:
Mask values of `feature` according to the `mask_values` in `mask_feature`
:param eopatch: `eopatch` to be processed
:return: Same `eopatch` instance with masked `feature`
### Response:
def execute(self, eopatch):
""" Mask val... |
def DataProcessorsDelete(self, dataProcessorId):
"""
Delete a data processor in CommonSense.
@param dataProcessorId - The id of the data processor that will be deleted.
@return (bool) - Boolean indicating whether GroupsP... | Delete a data processor in CommonSense.
@param dataProcessorId - The id of the data processor that will be deleted.
@return (bool) - Boolean indicating whether GroupsPost was successful. | Below is the the instruction that describes the task:
### Input:
Delete a data processor in CommonSense.
@param dataProcessorId - The id of the data processor that will be deleted.
@return (bool) - Boolean indicating whether GroupsPost wa... |
def initiateCompilation(args, file):
"""
Starts the entire compilation procedure
"""
####commands = finalizeCommands(args, file)
commands = makeCommands(0, file)
if not args['concise'] and args['print_args']:
print_commands = bool(args['watch'])
response = multiCall(*commands, print_... | Starts the entire compilation procedure | Below is the the instruction that describes the task:
### Input:
Starts the entire compilation procedure
### Response:
def initiateCompilation(args, file):
"""
Starts the entire compilation procedure
"""
####commands = finalizeCommands(args, file)
commands = makeCommands(0, file)
if not arg... |
def between(self, left, right, inclusive=True):
"""
Return boolean Series equivalent to left <= series <= right.
This function returns a boolean vector containing `True` wherever the
corresponding Series element is between the boundary values `left` and
`right`. NA values are tr... | Return boolean Series equivalent to left <= series <= right.
This function returns a boolean vector containing `True` wherever the
corresponding Series element is between the boundary values `left` and
`right`. NA values are treated as `False`.
Parameters
----------
lef... | Below is the the instruction that describes the task:
### Input:
Return boolean Series equivalent to left <= series <= right.
This function returns a boolean vector containing `True` wherever the
corresponding Series element is between the boundary values `left` and
`right`. NA values are t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.