code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def create_custom_dag_permission_view(self, session=None):
"""
Workflow:
1. Fetch all the existing (permissions, view-menu) from Airflow DB.
2. Fetch all the existing dag models that are either active or paused. Exclude the subdags.
3. Create both read and write permission view-m... | Workflow:
1. Fetch all the existing (permissions, view-menu) from Airflow DB.
2. Fetch all the existing dag models that are either active or paused. Exclude the subdags.
3. Create both read and write permission view-menus relation for every dags from step 2
4. Find out all the dag specif... | Below is the the instruction that describes the task:
### Input:
Workflow:
1. Fetch all the existing (permissions, view-menu) from Airflow DB.
2. Fetch all the existing dag models that are either active or paused. Exclude the subdags.
3. Create both read and write permission view-menus relat... |
def list_subtitles(videos, languages, pool_class=ProviderPool, **kwargs):
"""List subtitles.
The `videos` must pass the `languages` check of :func:`check_video`.
:param videos: videos to list subtitles for.
:type videos: set of :class:`~subliminal.video.Video`
:param languages: languages to search... | List subtitles.
The `videos` must pass the `languages` check of :func:`check_video`.
:param videos: videos to list subtitles for.
:type videos: set of :class:`~subliminal.video.Video`
:param languages: languages to search for.
:type languages: set of :class:`~babelfish.language.Language`
:para... | Below is the the instruction that describes the task:
### Input:
List subtitles.
The `videos` must pass the `languages` check of :func:`check_video`.
:param videos: videos to list subtitles for.
:type videos: set of :class:`~subliminal.video.Video`
:param languages: languages to search for.
:t... |
def random_secret_exponent(curve_order):
""" Generates a random secret exponent. """
# run a rejection sampling algorithm to ensure the random int is less
# than the curve order
while True:
# generate a random 256 bit hex string
random_hex = hexlify(dev_random_entropy(32))
random... | Generates a random secret exponent. | Below is the the instruction that describes the task:
### Input:
Generates a random secret exponent.
### Response:
def random_secret_exponent(curve_order):
""" Generates a random secret exponent. """
# run a rejection sampling algorithm to ensure the random int is less
# than the curve order
while ... |
def is_terminal(self, symbol: str) -> bool:
"""
This function will be called on nodes of a logical form tree, which are either non-terminal
symbols that can be expanded or terminal symbols that must be leaf nodes. Returns ``True``
if the given symbol is a terminal symbol.
"""
... | This function will be called on nodes of a logical form tree, which are either non-terminal
symbols that can be expanded or terminal symbols that must be leaf nodes. Returns ``True``
if the given symbol is a terminal symbol. | Below is the the instruction that describes the task:
### Input:
This function will be called on nodes of a logical form tree, which are either non-terminal
symbols that can be expanded or terminal symbols that must be leaf nodes. Returns ``True``
if the given symbol is a terminal symbol.
### Respo... |
async def rename(self, source, destination):
"""
:py:func:`asyncio.coroutine`
Rename (move) file or directory.
:param source: path to rename
:type source: :py:class:`str` or :py:class:`pathlib.PurePosixPath`
:param destination: path new name
:type destination: ... | :py:func:`asyncio.coroutine`
Rename (move) file or directory.
:param source: path to rename
:type source: :py:class:`str` or :py:class:`pathlib.PurePosixPath`
:param destination: path new name
:type destination: :py:class:`str` or :py:class:`pathlib.PurePosixPath` | Below is the the instruction that describes the task:
### Input:
:py:func:`asyncio.coroutine`
Rename (move) file or directory.
:param source: path to rename
:type source: :py:class:`str` or :py:class:`pathlib.PurePosixPath`
:param destination: path new name
:type destinati... |
def tunnel_settings_system_tunnel_replicator_load_balance(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
tunnel_settings = ET.SubElement(config, "tunnel-settings", xmlns="urn:brocade.com:mgmt:brocade-tunnels")
system = ET.SubElement(tunnel_settings, "sy... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def tunnel_settings_system_tunnel_replicator_load_balance(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
tunnel_settings = ET.SubElement(config, "tunnel-sett... |
def draw_categories(self):
"""Draw the category labels on the Canvas"""
for label in self._category_labels.values():
label.destroy()
self._category_labels.clear()
canvas_width = 0
for category in (sorted(self._categories.keys() if isinstance(self._categories, dict) el... | Draw the category labels on the Canvas | Below is the the instruction that describes the task:
### Input:
Draw the category labels on the Canvas
### Response:
def draw_categories(self):
"""Draw the category labels on the Canvas"""
for label in self._category_labels.values():
label.destroy()
self._category_labels.clear(... |
def get_integer_value(self, label):
"""stub"""
if self.has_integer_value(label):
return int(self.my_osid_object._my_map['integerValues'][label])
raise IllegalState() | stub | Below is the the instruction that describes the task:
### Input:
stub
### Response:
def get_integer_value(self, label):
"""stub"""
if self.has_integer_value(label):
return int(self.my_osid_object._my_map['integerValues'][label])
raise IllegalState() |
def idle_task(self):
'''called on idle'''
for m in self.mpstate.mav_outputs:
m.source_system = self.settings.source_system
m.mav.srcSystem = m.source_system
m.mav.srcComponent = self.settings.source_component | called on idle | Below is the the instruction that describes the task:
### Input:
called on idle
### Response:
def idle_task(self):
'''called on idle'''
for m in self.mpstate.mav_outputs:
m.source_system = self.settings.source_system
m.mav.srcSystem = m.source_system
m.mav.srcCom... |
def cornice_enable_openapi_explorer(
config,
api_explorer_path='/api-explorer',
permission=NO_PERMISSION_REQUIRED,
route_factory=None,
**kwargs):
"""
:param config:
Pyramid configurator object
:param api_explorer_path:
where to expose Swagger UI interf... | :param config:
Pyramid configurator object
:param api_explorer_path:
where to expose Swagger UI interface view
:param permission:
pyramid permission for those views
:param route_factory:
factory for context object for those routes
This registers and configures the view t... | Below is the the instruction that describes the task:
### Input:
:param config:
Pyramid configurator object
:param api_explorer_path:
where to expose Swagger UI interface view
:param permission:
pyramid permission for those views
:param route_factory:
factory for context ... |
def supplier_elements(self):
"""A |Elements| collection of all "supplying" basins.
(All river basins are assumed to supply something to the downstream
basin.)
>>> from hydpy import RiverBasinNumbers2Selection
>>> rbns2s = RiverBasinNumbers2Selection(
... ... | A |Elements| collection of all "supplying" basins.
(All river basins are assumed to supply something to the downstream
basin.)
>>> from hydpy import RiverBasinNumbers2Selection
>>> rbns2s = RiverBasinNumbers2Selection(
... (111, 113, 1129, 11269, 1125... | Below is the the instruction that describes the task:
### Input:
A |Elements| collection of all "supplying" basins.
(All river basins are assumed to supply something to the downstream
basin.)
>>> from hydpy import RiverBasinNumbers2Selection
>>> rbns2s = RiverBasinNumbers2Selection... |
def get_default_value(self):
""" return default value """
default = self.default_value
if isinstance(default, collections.Callable):
default = default()
return default | return default value | Below is the the instruction that describes the task:
### Input:
return default value
### Response:
def get_default_value(self):
""" return default value """
default = self.default_value
if isinstance(default, collections.Callable):
default = default()
return default |
def check_python_import(package_or_module):
'''
Checks if a python package or module is importable.
Arguments:
package_or_module -- the package or module name to check
Returns:
True or False
'''
logger = logging.getLogger(__name__)
logger.debug("Checking python import '%s'...... | Checks if a python package or module is importable.
Arguments:
package_or_module -- the package or module name to check
Returns:
True or False | Below is the the instruction that describes the task:
### Input:
Checks if a python package or module is importable.
Arguments:
package_or_module -- the package or module name to check
Returns:
True or False
### Response:
def check_python_import(package_or_module):
'''
Checks if a p... |
def async_thread(sol, args, node_attr, node_id, *a, **kw):
"""
Execute `sol._evaluate_node` in an asynchronous thread.
:param sol:
Solution to be updated.
:type sol: schedula.utils.sol.Solution
:param args:
Arguments to be passed to node calls.
:type args: tuple
:param nod... | Execute `sol._evaluate_node` in an asynchronous thread.
:param sol:
Solution to be updated.
:type sol: schedula.utils.sol.Solution
:param args:
Arguments to be passed to node calls.
:type args: tuple
:param node_attr:
Dictionary of node attributes.
:type node_attr: dic... | Below is the the instruction that describes the task:
### Input:
Execute `sol._evaluate_node` in an asynchronous thread.
:param sol:
Solution to be updated.
:type sol: schedula.utils.sol.Solution
:param args:
Arguments to be passed to node calls.
:type args: tuple
:param node_... |
def parameters_dict(self):
"""
Get the tool parameters as a simple dictionary
:return: The tool parameters
"""
d = {}
for k, v in self.__dict__.items():
if not k.startswith("_"):
d[k] = v
return d | Get the tool parameters as a simple dictionary
:return: The tool parameters | Below is the the instruction that describes the task:
### Input:
Get the tool parameters as a simple dictionary
:return: The tool parameters
### Response:
def parameters_dict(self):
"""
Get the tool parameters as a simple dictionary
:return: The tool parameters
"""
... |
def update_remote_ids(self, remote_file):
"""
Based on a remote file try to assign a remote_id and compare hash info.
:param remote_file: RemoteFile remote data pull remote_id from
"""
self.remote_id = remote_file.id
hash_data = self.path_data.get_hash()
if hash_d... | Based on a remote file try to assign a remote_id and compare hash info.
:param remote_file: RemoteFile remote data pull remote_id from | Below is the the instruction that describes the task:
### Input:
Based on a remote file try to assign a remote_id and compare hash info.
:param remote_file: RemoteFile remote data pull remote_id from
### Response:
def update_remote_ids(self, remote_file):
"""
Based on a remote file try to a... |
def get_other_answers_random(pool, seeded_answers, get_student_item_dict, num_responses):
"""
Get answers from others with random algorithm, which randomly select answer from the pool.
Student may get three answers for option 1 or one answer for option 1 and two answers for option 2.
Args:
see... | Get answers from others with random algorithm, which randomly select answer from the pool.
Student may get three answers for option 1 or one answer for option 1 and two answers for option 2.
Args:
see `get_other_answers`
num_responses (int): the number of responses to be returned. This value m... | Below is the the instruction that describes the task:
### Input:
Get answers from others with random algorithm, which randomly select answer from the pool.
Student may get three answers for option 1 or one answer for option 1 and two answers for option 2.
Args:
see `get_other_answers`
num_... |
def to_matrix(self, smooth_fwhm=0, outdtype=None):
"""Return numpy.ndarray with the masked or flatten image data and
the relevant information (mask indices and volume shape).
Parameters
----------
smooth__fwhm: int
Integer indicating the size of the FWHM Gaussian ... | Return numpy.ndarray with the masked or flatten image data and
the relevant information (mask indices and volume shape).
Parameters
----------
smooth__fwhm: int
Integer indicating the size of the FWHM Gaussian smoothing kernel
to smooth the subject volumes bef... | Below is the the instruction that describes the task:
### Input:
Return numpy.ndarray with the masked or flatten image data and
the relevant information (mask indices and volume shape).
Parameters
----------
smooth__fwhm: int
Integer indicating the size of the FWHM Ga... |
def removerepeats(consens, arrayed):
"""
Checks for interior Ns in consensus seqs and removes those that are at
low depth, here defined as less than 1/3 of the average depth. The prop 1/3
is chosen so that mindepth=6 requires 2 base calls that are not in [N,-].
"""
## default trim no edges
... | Checks for interior Ns in consensus seqs and removes those that are at
low depth, here defined as less than 1/3 of the average depth. The prop 1/3
is chosen so that mindepth=6 requires 2 base calls that are not in [N,-]. | Below is the the instruction that describes the task:
### Input:
Checks for interior Ns in consensus seqs and removes those that are at
low depth, here defined as less than 1/3 of the average depth. The prop 1/3
is chosen so that mindepth=6 requires 2 base calls that are not in [N,-].
### Response:
def rem... |
def write_client(captures, options):
"""
Write the TypeFactory classes to _client.py, along with some
imports and tables so that we can look up versioned Facades.
"""
with open("{}/_client.py".format(options.output_dir), "w") as f:
f.write(HEADER)
f.write("from juju.client._definiti... | Write the TypeFactory classes to _client.py, along with some
imports and tables so that we can look up versioned Facades. | Below is the the instruction that describes the task:
### Input:
Write the TypeFactory classes to _client.py, along with some
imports and tables so that we can look up versioned Facades.
### Response:
def write_client(captures, options):
"""
Write the TypeFactory classes to _client.py, along with some
... |
def curvature_matrix_from_blurred_mapping_matrix(blurred_mapping_matrix, noise_map_1d):
"""Compute the curvature matrix *F* from a blurred mapping matrix *f* and the 1D noise-map *\sigma* \
(see Warren & Dye 2003).
Parameters
-----------
blurred_mapping_matrix : ndarray
The matrix represen... | Compute the curvature matrix *F* from a blurred mapping matrix *f* and the 1D noise-map *\sigma* \
(see Warren & Dye 2003).
Parameters
-----------
blurred_mapping_matrix : ndarray
The matrix representing the blurred mappings between sub-grid pixels and pixelization pixels.
noise_map_1d : n... | Below is the the instruction that describes the task:
### Input:
Compute the curvature matrix *F* from a blurred mapping matrix *f* and the 1D noise-map *\sigma* \
(see Warren & Dye 2003).
Parameters
-----------
blurred_mapping_matrix : ndarray
The matrix representing the blurred mappings ... |
def __clean(self, misp_response):
"""
:param misp_response:
:return:
"""
response = []
for event in misp_response.get('response', []):
response.append(self.__clean_event(event['Event']))
return response | :param misp_response:
:return: | Below is the the instruction that describes the task:
### Input:
:param misp_response:
:return:
### Response:
def __clean(self, misp_response):
"""
:param misp_response:
:return:
"""
response = []
for event in misp_response.get('response', []):
... |
def axes(mark=None, options={}, **kwargs):
"""Draws axes corresponding to the scales of a given mark.
It also returns a dictionary of drawn axes. If the mark is not provided,
the last drawn mark is used.
Parameters
----------
mark: Mark or None (default: None)
The mark to inspect to cr... | Draws axes corresponding to the scales of a given mark.
It also returns a dictionary of drawn axes. If the mark is not provided,
the last drawn mark is used.
Parameters
----------
mark: Mark or None (default: None)
The mark to inspect to create axes. If None, the last mark drawn is
... | Below is the the instruction that describes the task:
### Input:
Draws axes corresponding to the scales of a given mark.
It also returns a dictionary of drawn axes. If the mark is not provided,
the last drawn mark is used.
Parameters
----------
mark: Mark or None (default: None)
The ma... |
def _block_collection(iterator, dtype, bsize=-1):
"""Pack rdd with a specific collection constructor."""
i = 0
accumulated = []
for a in iterator:
if (bsize > 0) and (i >= bsize):
yield _pack_accumulated(accumulated, dtype)
accumulated = []
i = 0
accum... | Pack rdd with a specific collection constructor. | Below is the the instruction that describes the task:
### Input:
Pack rdd with a specific collection constructor.
### Response:
def _block_collection(iterator, dtype, bsize=-1):
"""Pack rdd with a specific collection constructor."""
i = 0
accumulated = []
for a in iterator:
if (bsize > 0) a... |
def itemsize_bits(self):
"""Number of bits per element"""
if self.dtype is not None:
return self.dtype.itemsize * 8
else:
return sum(x[1] for x in self.format) | Number of bits per element | Below is the the instruction that describes the task:
### Input:
Number of bits per element
### Response:
def itemsize_bits(self):
"""Number of bits per element"""
if self.dtype is not None:
return self.dtype.itemsize * 8
else:
return sum(x[1] for x in self.format) |
def build_packages(ctx, hide=False):
"""Build packages for this release."""
print("build_packages:")
ctx.run("python setup.py sdist bdist_wheel", echo=True, hide=hide) | Build packages for this release. | Below is the the instruction that describes the task:
### Input:
Build packages for this release.
### Response:
def build_packages(ctx, hide=False):
"""Build packages for this release."""
print("build_packages:")
ctx.run("python setup.py sdist bdist_wheel", echo=True, hide=hide) |
def get_sdb_id_by_path(self, sdb_path):
""" Given the path, return the ID for the given safe deposit box."""
json_resp = self.get_sdbs()
# Deal with the supplied path possibly missing an ending slash
path = self._add_slash(sdb_path)
for r in json_resp:
if r['path'] ... | Given the path, return the ID for the given safe deposit box. | Below is the the instruction that describes the task:
### Input:
Given the path, return the ID for the given safe deposit box.
### Response:
def get_sdb_id_by_path(self, sdb_path):
""" Given the path, return the ID for the given safe deposit box."""
json_resp = self.get_sdbs()
# Deal with ... |
def insertDataset(self, businput):
"""
input dictionary must have the following keys:
dataset, primary_ds_name(name), processed_ds(name), data_tier(name),
acquisition_era(name), processing_version
It may have following keys:
physics_group(name), xtcrosssection, creation_d... | input dictionary must have the following keys:
dataset, primary_ds_name(name), processed_ds(name), data_tier(name),
acquisition_era(name), processing_version
It may have following keys:
physics_group(name), xtcrosssection, creation_date, create_by,
last_modification_date, last_m... | Below is the the instruction that describes the task:
### Input:
input dictionary must have the following keys:
dataset, primary_ds_name(name), processed_ds(name), data_tier(name),
acquisition_era(name), processing_version
It may have following keys:
physics_group(name), xtcrosssecti... |
def channel_dict(self, channel_name, datatype, channel_type, data_url,
file_format, file_type, exceptions, resolution,
windowrange, readonly):
"""
Generate the project dictionary.
"""
channel_dict = {}
channel_dict['channel_name'] = chann... | Generate the project dictionary. | Below is the the instruction that describes the task:
### Input:
Generate the project dictionary.
### Response:
def channel_dict(self, channel_name, datatype, channel_type, data_url,
file_format, file_type, exceptions, resolution,
windowrange, readonly):
"""
... |
def tokens2text(docgraph, token_ids):
"""
given a list of token node IDs, returns a their string representation
(concatenated token strings).
"""
return ' '.join(docgraph.node[token_id][docgraph.ns+':token']
for token_id in token_ids) | given a list of token node IDs, returns a their string representation
(concatenated token strings). | Below is the the instruction that describes the task:
### Input:
given a list of token node IDs, returns a their string representation
(concatenated token strings).
### Response:
def tokens2text(docgraph, token_ids):
"""
given a list of token node IDs, returns a their string representation
(concate... |
def findClosestMatchingGesture(strokes, gestureList, maxDifference=None):
"""
Returns the gesture(s) in `gestureList` that closest matches the gesture in
`strokes`. The `maxDifference` is how many differences there can be and still
be considered a match.
"""
if len(gestureList) == 0:
ret... | Returns the gesture(s) in `gestureList` that closest matches the gesture in
`strokes`. The `maxDifference` is how many differences there can be and still
be considered a match. | Below is the the instruction that describes the task:
### Input:
Returns the gesture(s) in `gestureList` that closest matches the gesture in
`strokes`. The `maxDifference` is how many differences there can be and still
be considered a match.
### Response:
def findClosestMatchingGesture(strokes, gestureList... |
def DTAgentProgram(belief_state):
"A decision-theoretic agent. [Fig. 13.1]"
def program(percept):
belief_state.observe(program.action, percept)
program.action = argmax(belief_state.actions(),
belief_state.expected_outcome_utility)
return program.action
... | A decision-theoretic agent. [Fig. 13.1] | Below is the the instruction that describes the task:
### Input:
A decision-theoretic agent. [Fig. 13.1]
### Response:
def DTAgentProgram(belief_state):
"A decision-theoretic agent. [Fig. 13.1]"
def program(percept):
belief_state.observe(program.action, percept)
program.action = argmax(beli... |
def get(self, block=True, timeout=None):
"""Remove and return an item from the queue.
If optional args ``block`` is ``True`` and ``timeout`` is
``None`` (the default), block if necessary until an item is
available. If ``timeout`` is a positive number, it blocks at
most ``timeou... | Remove and return an item from the queue.
If optional args ``block`` is ``True`` and ``timeout`` is
``None`` (the default), block if necessary until an item is
available. If ``timeout`` is a positive number, it blocks at
most ``timeout`` seconds and raises the :exc:`Queue.Empty` except... | Below is the the instruction that describes the task:
### Input:
Remove and return an item from the queue.
If optional args ``block`` is ``True`` and ``timeout`` is
``None`` (the default), block if necessary until an item is
available. If ``timeout`` is a positive number, it blocks at
... |
def get_recipe_instances(self, badges=None, excluded=None):
"""
Returns all recipe instances or just those for the given badges.
"""
if badges:
if not isinstance(badges, (list, tuple)):
badges = [badges]
if excluded:
if not isinstance(excl... | Returns all recipe instances or just those for the given badges. | Below is the the instruction that describes the task:
### Input:
Returns all recipe instances or just those for the given badges.
### Response:
def get_recipe_instances(self, badges=None, excluded=None):
"""
Returns all recipe instances or just those for the given badges.
"""
if bad... |
def generate_documentation(schema):
"""
Generates reStructuredText documentation from a Confirm file.
:param schema: Dictionary representing the Confirm schema.
:returns: String representing the reStructuredText documentation.
"""
documentation_title = "Configuration documentation"
docume... | Generates reStructuredText documentation from a Confirm file.
:param schema: Dictionary representing the Confirm schema.
:returns: String representing the reStructuredText documentation. | Below is the the instruction that describes the task:
### Input:
Generates reStructuredText documentation from a Confirm file.
:param schema: Dictionary representing the Confirm schema.
:returns: String representing the reStructuredText documentation.
### Response:
def generate_documentation(schema):
... |
def _create_filefunction(self, name, spectrum_pars):
"""Replace the spectrum of an existing source with a
FileFunction."""
spectrum_pars = {} if spectrum_pars is None else spectrum_pars
if 'loge' in spectrum_pars:
loge = spectrum_pars.get('loge')
else:
e... | Replace the spectrum of an existing source with a
FileFunction. | Below is the the instruction that describes the task:
### Input:
Replace the spectrum of an existing source with a
FileFunction.
### Response:
def _create_filefunction(self, name, spectrum_pars):
"""Replace the spectrum of an existing source with a
FileFunction."""
spectrum_pars = ... |
def status_to_string(dbus_status):
'''
Converts a numeric dbus snapper status into a string
CLI Example:
.. code-block:: bash
salt '*' snapper.status_to_string <dbus_status>
'''
status_tuple = (
dbus_status & 0b000000001, dbus_status & 0b000000010, dbus_status & 0b000000100,
... | Converts a numeric dbus snapper status into a string
CLI Example:
.. code-block:: bash
salt '*' snapper.status_to_string <dbus_status> | Below is the the instruction that describes the task:
### Input:
Converts a numeric dbus snapper status into a string
CLI Example:
.. code-block:: bash
salt '*' snapper.status_to_string <dbus_status>
### Response:
def status_to_string(dbus_status):
'''
Converts a numeric dbus snapper sta... |
def handle_interceptors(args):
"""usage: {program} interceptors
List the available interceptor plugins.
"""
assert args
print('\n'.join(cosmic_ray.plugins.interceptor_names()))
return ExitCode.OK | usage: {program} interceptors
List the available interceptor plugins. | Below is the the instruction that describes the task:
### Input:
usage: {program} interceptors
List the available interceptor plugins.
### Response:
def handle_interceptors(args):
"""usage: {program} interceptors
List the available interceptor plugins.
"""
assert args
print('\n'.join(cosm... |
def run(config):
"""
Time to run.
"""
setup(config)
if config.exitfirst:
ivoire.current_result.failfast = True
ivoire.current_result.startTestRun()
for spec in config.specs:
try:
load_by_name(spec)
except Exception:
ivoire.current_result.a... | Time to run. | Below is the the instruction that describes the task:
### Input:
Time to run.
### Response:
def run(config):
"""
Time to run.
"""
setup(config)
if config.exitfirst:
ivoire.current_result.failfast = True
ivoire.current_result.startTestRun()
for spec in config.specs:
... |
def nack(self):
"""Decline to acknowldge the given message.
This will cause the message to be re-delivered to the subscription.
"""
self._request_queue.put(
requests.NackRequest(ack_id=self._ack_id, byte_size=self.size)
) | Decline to acknowldge the given message.
This will cause the message to be re-delivered to the subscription. | Below is the the instruction that describes the task:
### Input:
Decline to acknowldge the given message.
This will cause the message to be re-delivered to the subscription.
### Response:
def nack(self):
"""Decline to acknowldge the given message.
This will cause the message to be re-deli... |
def zone_compare(timezone):
'''
Compares the given timezone with the machine timezone. Mostly useful for
running state checks.
Args:
timezone (str):
The timezone to compare. This can be in Windows or Unix format. Can
be any of the values returned by the ``timezone.list``... | Compares the given timezone with the machine timezone. Mostly useful for
running state checks.
Args:
timezone (str):
The timezone to compare. This can be in Windows or Unix format. Can
be any of the values returned by the ``timezone.list`` function
Returns:
bool: ``... | Below is the the instruction that describes the task:
### Input:
Compares the given timezone with the machine timezone. Mostly useful for
running state checks.
Args:
timezone (str):
The timezone to compare. This can be in Windows or Unix format. Can
be any of the values retu... |
def insertPhenotypeAssociationSet(self, phenotypeAssociationSet):
"""
Inserts the specified phenotype annotation set into this repository.
"""
datasetId = phenotypeAssociationSet.getParentContainer().getId()
attributes = json.dumps(phenotypeAssociationSet.getAttributes())
... | Inserts the specified phenotype annotation set into this repository. | Below is the the instruction that describes the task:
### Input:
Inserts the specified phenotype annotation set into this repository.
### Response:
def insertPhenotypeAssociationSet(self, phenotypeAssociationSet):
"""
Inserts the specified phenotype annotation set into this repository.
"""
... |
def natural_sort(item):
"""
Sort strings that contain numbers correctly.
>>> l = ['v1.3.12', 'v1.3.3', 'v1.2.5', 'v1.2.15', 'v1.2.3', 'v1.2.1']
>>> l.sort(key=natural_sort)
>>> print l
"['v1.2.1', 'v1.2.3', 'v1.2.5', 'v1.2.15', 'v1.3.3', 'v1.3.12']"
"""
if item is None:
return 0... | Sort strings that contain numbers correctly.
>>> l = ['v1.3.12', 'v1.3.3', 'v1.2.5', 'v1.2.15', 'v1.2.3', 'v1.2.1']
>>> l.sort(key=natural_sort)
>>> print l
"['v1.2.1', 'v1.2.3', 'v1.2.5', 'v1.2.15', 'v1.3.3', 'v1.3.12']" | Below is the the instruction that describes the task:
### Input:
Sort strings that contain numbers correctly.
>>> l = ['v1.3.12', 'v1.3.3', 'v1.2.5', 'v1.2.15', 'v1.2.3', 'v1.2.1']
>>> l.sort(key=natural_sort)
>>> print l
"['v1.2.1', 'v1.2.3', 'v1.2.5', 'v1.2.15', 'v1.3.3', 'v1.3.12']"
### Response... |
def _connect_control_flow_node(control_flow_node, next_node):
"""Connect a ControlFlowNode properly to the next_node."""
for last in control_flow_node.last_nodes:
if isinstance(next_node, ControlFlowNode):
last.connect(next_node.test) # connect to next if test case
elif isinstance(n... | Connect a ControlFlowNode properly to the next_node. | Below is the the instruction that describes the task:
### Input:
Connect a ControlFlowNode properly to the next_node.
### Response:
def _connect_control_flow_node(control_flow_node, next_node):
"""Connect a ControlFlowNode properly to the next_node."""
for last in control_flow_node.last_nodes:
if i... |
def generate_help():
"""Generates help text with alphabetically sorted recipes."""
help_text = '\nAvailable recipes:\n\n'
recipes = config.Config.get_registered_recipes()
for contents, _, _ in sorted(recipes, key=lambda k: k[0]['name']):
help_text += ' {0:<35s}{1:s}\n'.format(
contents['name'], cont... | Generates help text with alphabetically sorted recipes. | Below is the the instruction that describes the task:
### Input:
Generates help text with alphabetically sorted recipes.
### Response:
def generate_help():
"""Generates help text with alphabetically sorted recipes."""
help_text = '\nAvailable recipes:\n\n'
recipes = config.Config.get_registered_recipes()
f... |
def run_step(self, representer):
"""Do the object in-out rewrite.
Args:
representer: A pypyr.filesystem.ObjectRepresenter instance.
"""
assert representer, ("ObjectRepresenter instance required to run "
"ObjectRewriterStep.")
rewriter = ... | Do the object in-out rewrite.
Args:
representer: A pypyr.filesystem.ObjectRepresenter instance. | Below is the the instruction that describes the task:
### Input:
Do the object in-out rewrite.
Args:
representer: A pypyr.filesystem.ObjectRepresenter instance.
### Response:
def run_step(self, representer):
"""Do the object in-out rewrite.
Args:
representer: A pyp... |
def start_pymol(quiet=False, options='-p', run=False):
"""Starts up PyMOL and sets general options. Quiet mode suppresses all PyMOL output.
Command line options can be passed as the second argument."""
import pymol
pymol.pymol_argv = ['pymol', '%s' % options] + sys.argv[1:]
if run:
initializ... | Starts up PyMOL and sets general options. Quiet mode suppresses all PyMOL output.
Command line options can be passed as the second argument. | Below is the the instruction that describes the task:
### Input:
Starts up PyMOL and sets general options. Quiet mode suppresses all PyMOL output.
Command line options can be passed as the second argument.
### Response:
def start_pymol(quiet=False, options='-p', run=False):
"""Starts up PyMOL and sets gene... |
def split_input(self, input_filepath):
"""Splits the input file into the 'merge file' (which contains
the EDUs) and the 'parsetree file'."""
with open(input_filepath, 'r') as input_file:
input_file_str = input_file.read()
merge_file_str, parsetree_str = input_file_str.spl... | Splits the input file into the 'merge file' (which contains
the EDUs) and the 'parsetree file'. | Below is the the instruction that describes the task:
### Input:
Splits the input file into the 'merge file' (which contains
the EDUs) and the 'parsetree file'.
### Response:
def split_input(self, input_filepath):
"""Splits the input file into the 'merge file' (which contains
the EDUs) and ... |
def map_with_retries(self, requests, responses_for_requests):
"""Provides session-based retry functionality
:param requests: A collection of Request objects.
:param responses_for_requests: Dictionary mapping of requests to responses
:param max_retries: The maximum number of retries to p... | Provides session-based retry functionality
:param requests: A collection of Request objects.
:param responses_for_requests: Dictionary mapping of requests to responses
:param max_retries: The maximum number of retries to perform per session
:param args: Additional arguments to pass into... | Below is the the instruction that describes the task:
### Input:
Provides session-based retry functionality
:param requests: A collection of Request objects.
:param responses_for_requests: Dictionary mapping of requests to responses
:param max_retries: The maximum number of retries to perfo... |
def bottom(self, z=0, radius=0, degrees=0, reference=None):
"""
Returns (:Placeable, :Vector:) tuple where :Vector:
corresponds to the bottom of a :Placeable:
If :reference: :Placeable: is provided, returns
the :Vector: within :reference: coordinate system
"""
co... | Returns (:Placeable, :Vector:) tuple where :Vector:
corresponds to the bottom of a :Placeable:
If :reference: :Placeable: is provided, returns
the :Vector: within :reference: coordinate system | Below is the the instruction that describes the task:
### Input:
Returns (:Placeable, :Vector:) tuple where :Vector:
corresponds to the bottom of a :Placeable:
If :reference: :Placeable: is provided, returns
the :Vector: within :reference: coordinate system
### Response:
def bottom(self, z... |
def doDynamicValidation(self, request: Request):
"""
State based validation
"""
self.execute_hook(NodeHooks.PRE_DYNAMIC_VALIDATION, request=request)
# Digest validation
ledger_id, seq_no = self.seqNoDB.get_by_payload_digest(request.payload_digest)
if ledger_id is... | State based validation | Below is the the instruction that describes the task:
### Input:
State based validation
### Response:
def doDynamicValidation(self, request: Request):
"""
State based validation
"""
self.execute_hook(NodeHooks.PRE_DYNAMIC_VALIDATION, request=request)
# Digest validation
... |
def _udf_get_file_from_iso_fp(self, outfp, blocksize, udf_path):
# type: (BinaryIO, int, bytes) -> None
'''
An internal method to fetch a single UDF file from the ISO and write it
out to the file object.
Parameters:
outfp - The file object to write data to.
blo... | An internal method to fetch a single UDF file from the ISO and write it
out to the file object.
Parameters:
outfp - The file object to write data to.
blocksize - The number of bytes in each transfer.
udf_path - The absolute UDF path to lookup on the ISO.
Returns:
... | Below is the the instruction that describes the task:
### Input:
An internal method to fetch a single UDF file from the ISO and write it
out to the file object.
Parameters:
outfp - The file object to write data to.
blocksize - The number of bytes in each transfer.
udf_pat... |
def file_decrypt_from_key_info( sender_key_info, blockchain_id, key_index, hostname, input_path, output_path, passphrase=None, config_path=CONFIG_PATH, wallet_keys=None ):
"""
Try to decrypt data with one of the receiver's keys
Return {'status': True} if we succeeded
Return {'error': ..., 'status': Fals... | Try to decrypt data with one of the receiver's keys
Return {'status': True} if we succeeded
Return {'error': ..., 'status': False} if we failed permanently
Return {'error': ..., 'status': True} if the key failed, and we should try the next one. | Below is the the instruction that describes the task:
### Input:
Try to decrypt data with one of the receiver's keys
Return {'status': True} if we succeeded
Return {'error': ..., 'status': False} if we failed permanently
Return {'error': ..., 'status': True} if the key failed, and we should try the next... |
def makeBasicSolution(self,EndOfPrdvP,aLvl,interpolator):
'''
Given end of period assets and end of period marginal value, construct
the basic solution for this period.
Parameters
----------
EndOfPrdvP : np.array
Array of end-of-period marginal values.
... | Given end of period assets and end of period marginal value, construct
the basic solution for this period.
Parameters
----------
EndOfPrdvP : np.array
Array of end-of-period marginal values.
aLvl : np.array
Array of end-of-period asset values that yield t... | Below is the the instruction that describes the task:
### Input:
Given end of period assets and end of period marginal value, construct
the basic solution for this period.
Parameters
----------
EndOfPrdvP : np.array
Array of end-of-period marginal values.
aLvl : ... |
def getTreeWalker(treeType, implementation=None, **kwargs):
"""Get a TreeWalker class for various types of tree with built-in support
:arg str treeType: the name of the tree type required (case-insensitive).
Supported values are:
* "dom": The xml.dom.minidom DOM implementation
* "etree... | Get a TreeWalker class for various types of tree with built-in support
:arg str treeType: the name of the tree type required (case-insensitive).
Supported values are:
* "dom": The xml.dom.minidom DOM implementation
* "etree": A generic walker for tree implementations exposing an
... | Below is the the instruction that describes the task:
### Input:
Get a TreeWalker class for various types of tree with built-in support
:arg str treeType: the name of the tree type required (case-insensitive).
Supported values are:
* "dom": The xml.dom.minidom DOM implementation
* "etr... |
def expand(sconf, cwd=None, parent=None):
"""Return config with shorthand and inline properties expanded.
This is necessary to keep the code in the :class:`WorkspaceBuilder` clean
and also allow for neat, short-hand configurations.
As a simple example, internally, tmuxp expects that config options
... | Return config with shorthand and inline properties expanded.
This is necessary to keep the code in the :class:`WorkspaceBuilder` clean
and also allow for neat, short-hand configurations.
As a simple example, internally, tmuxp expects that config options
like ``shell_command`` are a list (array)::
... | Below is the the instruction that describes the task:
### Input:
Return config with shorthand and inline properties expanded.
This is necessary to keep the code in the :class:`WorkspaceBuilder` clean
and also allow for neat, short-hand configurations.
As a simple example, internally, tmuxp expects tha... |
def connect_job(job_id,
deployment_name,
token_manager=None,
app_url=defaults.APP_URL,
persist=False,
websocket=None,
data_url=None):
"""
connect to a running Juttle program by job_id
"""
if data_url == Non... | connect to a running Juttle program by job_id | Below is the the instruction that describes the task:
### Input:
connect to a running Juttle program by job_id
### Response:
def connect_job(job_id,
deployment_name,
token_manager=None,
app_url=defaults.APP_URL,
persist=False,
websocke... |
def inasafe_analysis_summary_field_value(field, feature, parent):
"""Retrieve a value from a field in the analysis summary layer.
e.g. inasafe_analysis_summary_field_value('total_not_exposed') -> 3
"""
_ = feature, parent # NOQA
project_context_scope = QgsExpressionContextUtils.projectScope(
... | Retrieve a value from a field in the analysis summary layer.
e.g. inasafe_analysis_summary_field_value('total_not_exposed') -> 3 | Below is the the instruction that describes the task:
### Input:
Retrieve a value from a field in the analysis summary layer.
e.g. inasafe_analysis_summary_field_value('total_not_exposed') -> 3
### Response:
def inasafe_analysis_summary_field_value(field, feature, parent):
"""Retrieve a value from a field... |
def get_action(self, brain_info: BrainInfo) -> ActionInfo:
"""
Decides actions given observations information, and takes them in environment.
:param brain_info: A dictionary of brain names and BrainInfo from environment.
:return: an ActionInfo containing action, memories, values and an o... | Decides actions given observations information, and takes them in environment.
:param brain_info: A dictionary of brain names and BrainInfo from environment.
:return: an ActionInfo containing action, memories, values and an object
to be passed to add experiences | Below is the the instruction that describes the task:
### Input:
Decides actions given observations information, and takes them in environment.
:param brain_info: A dictionary of brain names and BrainInfo from environment.
:return: an ActionInfo containing action, memories, values and an object
... |
def get_flow(self, name):
""" Returns a FlowConfig """
config = getattr(self, "flows__{}".format(name))
if not config:
raise FlowNotFoundError("Flow not found: {}".format(name))
return FlowConfig(config) | Returns a FlowConfig | Below is the the instruction that describes the task:
### Input:
Returns a FlowConfig
### Response:
def get_flow(self, name):
""" Returns a FlowConfig """
config = getattr(self, "flows__{}".format(name))
if not config:
raise FlowNotFoundError("Flow not found: {}".format(name))
... |
def get_repositories_by_ids(self, repository_ids):
"""Gets a ``RepositoryList`` corresponding to the given ``IdList``.
In plenary mode, the returned list contains all of the
repositories specified in the ``Id`` list, in the order of the
list, including duplicates, or an error results if... | Gets a ``RepositoryList`` corresponding to the given ``IdList``.
In plenary mode, the returned list contains all of the
repositories specified in the ``Id`` list, in the order of the
list, including duplicates, or an error results if an ``Id`` in
the supplied list is not found or inacce... | Below is the the instruction that describes the task:
### Input:
Gets a ``RepositoryList`` corresponding to the given ``IdList``.
In plenary mode, the returned list contains all of the
repositories specified in the ``Id`` list, in the order of the
list, including duplicates, or an error res... |
def smooth_lines(lns, n=1, inertia=0.5):
'''
smooth_lines(matrix) runs one smoothing iteration on the lines implied by the {2,3}xN matrix.
smooth_lines(collection) iteratively descends lists, sets, and the values of maps, converting
all valid matrices that it finds; note that if it encounters anything... | smooth_lines(matrix) runs one smoothing iteration on the lines implied by the {2,3}xN matrix.
smooth_lines(collection) iteratively descends lists, sets, and the values of maps, converting
all valid matrices that it finds; note that if it encounters anything that cannot be
interpreted as a line matrix (s... | Below is the the instruction that describes the task:
### Input:
smooth_lines(matrix) runs one smoothing iteration on the lines implied by the {2,3}xN matrix.
smooth_lines(collection) iteratively descends lists, sets, and the values of maps, converting
all valid matrices that it finds; note that if it enc... |
def path(self, *names):
"""Look up and return the complete path of an atom.
For example, atoms.path('moov', 'udta', 'meta') will return a
list of three atoms, corresponding to the moov, udta, and meta
atoms.
"""
path = [self]
for name in names:
path.... | Look up and return the complete path of an atom.
For example, atoms.path('moov', 'udta', 'meta') will return a
list of three atoms, corresponding to the moov, udta, and meta
atoms. | Below is the the instruction that describes the task:
### Input:
Look up and return the complete path of an atom.
For example, atoms.path('moov', 'udta', 'meta') will return a
list of three atoms, corresponding to the moov, udta, and meta
atoms.
### Response:
def path(self, *names):
... |
def as_phononwebsite(self):
"""
Return a dictionary with the phononwebsite format:
http://henriquemiranda.github.io/phononwebsite
"""
d = {}
#define the lattice
d["lattice"] = self.structure.lattice._matrix.tolist()
#define atoms
atom_pos_c... | Return a dictionary with the phononwebsite format:
http://henriquemiranda.github.io/phononwebsite | Below is the the instruction that describes the task:
### Input:
Return a dictionary with the phononwebsite format:
http://henriquemiranda.github.io/phononwebsite
### Response:
def as_phononwebsite(self):
"""
Return a dictionary with the phononwebsite format:
http://henriquemiranda.... |
def _broadcast_compat_variables(*variables):
"""Create broadcast compatible variables, with the same dimensions.
Unlike the result of broadcast_variables(), some variables may have
dimensions of size 1 instead of the the size of the broadcast dimension.
"""
dims = tuple(_unified_dims(variables))
... | Create broadcast compatible variables, with the same dimensions.
Unlike the result of broadcast_variables(), some variables may have
dimensions of size 1 instead of the the size of the broadcast dimension. | Below is the the instruction that describes the task:
### Input:
Create broadcast compatible variables, with the same dimensions.
Unlike the result of broadcast_variables(), some variables may have
dimensions of size 1 instead of the the size of the broadcast dimension.
### Response:
def _broadcast_compat... |
def update_css(self, css_in=None, clear_css=False):
"""Add additional CSS rules, optionally replacing all."""
if clear_css:
self.matchers = {}
# CSS is changing, so clear processing state
self.clear_state()
if css_in is None:
return
try:
... | Add additional CSS rules, optionally replacing all. | Below is the the instruction that describes the task:
### Input:
Add additional CSS rules, optionally replacing all.
### Response:
def update_css(self, css_in=None, clear_css=False):
"""Add additional CSS rules, optionally replacing all."""
if clear_css:
self.matchers = {}
# CS... |
def delete_network(context, id):
"""Delete a network.
: param context: neutron api request context
: param id: UUID representing the network to delete.
"""
LOG.info("delete_network %s for tenant %s" % (id, context.tenant_id))
with context.session.begin():
net = db_api.network_find(conte... | Delete a network.
: param context: neutron api request context
: param id: UUID representing the network to delete. | Below is the the instruction that describes the task:
### Input:
Delete a network.
: param context: neutron api request context
: param id: UUID representing the network to delete.
### Response:
def delete_network(context, id):
"""Delete a network.
: param context: neutron api request context
... |
def qpop_front(self, name, size=1):
"""
Remove and return the first ``size`` item of the list ``name``
Like **Redis.LPOP**
:param string name: the queue name
:param int size: the length of result
:return: the list of pop elements
:rtype: list
... | Remove and return the first ``size`` item of the list ``name``
Like **Redis.LPOP**
:param string name: the queue name
:param int size: the length of result
:return: the list of pop elements
:rtype: list | Below is the the instruction that describes the task:
### Input:
Remove and return the first ``size`` item of the list ``name``
Like **Redis.LPOP**
:param string name: the queue name
:param int size: the length of result
:return: the list of pop elements
:rtype: lis... |
def _find_base_type(data_type):
"""Find the Nani's base type for a given data type.
This is useful when Nani's data types were subclassed and the original type
is required.
"""
bases = type(data_type).__mro__
for base in bases:
if base in _ALL:
return base
return None | Find the Nani's base type for a given data type.
This is useful when Nani's data types were subclassed and the original type
is required. | Below is the the instruction that describes the task:
### Input:
Find the Nani's base type for a given data type.
This is useful when Nani's data types were subclassed and the original type
is required.
### Response:
def _find_base_type(data_type):
"""Find the Nani's base type for a given data type.
... |
def parse(self):
"Parses the *rpc-reply*."
if self._parsed: return
root = self._root = to_ele(self._raw) # The <rpc-reply> element
# Per RFC 4741 an <ok/> tag is sent when there are no errors or warnings
ok = root.find(qualify("ok"))
if ok is None:
# Create RP... | Parses the *rpc-reply*. | Below is the the instruction that describes the task:
### Input:
Parses the *rpc-reply*.
### Response:
def parse(self):
"Parses the *rpc-reply*."
if self._parsed: return
root = self._root = to_ele(self._raw) # The <rpc-reply> element
# Per RFC 4741 an <ok/> tag is sent when there ar... |
def _z2deriv(self,R,z,phi=0.,t=0.):
"""
NAME:
_z2deriv
PURPOSE:
evaluate the second vertical derivative for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t- time
... | NAME:
_z2deriv
PURPOSE:
evaluate the second vertical derivative for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t- time
OUTPUT:
the second vertical derivative
... | Below is the the instruction that describes the task:
### Input:
NAME:
_z2deriv
PURPOSE:
evaluate the second vertical derivative for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t... |
def bootstrappable_neighbors(self):
"""
Get a :class:`list` of (ip, port) :class:`tuple` pairs suitable for
use as an argument to the bootstrap method.
The server should have been bootstrapped
already - this is just a utility for getting some neighbors and then
storing t... | Get a :class:`list` of (ip, port) :class:`tuple` pairs suitable for
use as an argument to the bootstrap method.
The server should have been bootstrapped
already - this is just a utility for getting some neighbors and then
storing them if this server is going down for a while. When it c... | Below is the the instruction that describes the task:
### Input:
Get a :class:`list` of (ip, port) :class:`tuple` pairs suitable for
use as an argument to the bootstrap method.
The server should have been bootstrapped
already - this is just a utility for getting some neighbors and then
... |
def _is_used_deprecated(self):
'''
Returns True, if a component configuration explicitly is
asking to use an old version of the deprecated function.
:return:
'''
func_path = "{m_name}.{f_name}".format(
m_name=self._globals.get(self.MODULE_NAME, '') or self._g... | Returns True, if a component configuration explicitly is
asking to use an old version of the deprecated function.
:return: | Below is the the instruction that describes the task:
### Input:
Returns True, if a component configuration explicitly is
asking to use an old version of the deprecated function.
:return:
### Response:
def _is_used_deprecated(self):
'''
Returns True, if a component configuration ex... |
def transfer(self, name, local, remote, **kwargs):
"""
Transfers the file with the given name from the local to the remote
storage backend.
:param name: The name of the file to transfer
:param local: The local storage backend instance
:param remote: The remote storage ba... | Transfers the file with the given name from the local to the remote
storage backend.
:param name: The name of the file to transfer
:param local: The local storage backend instance
:param remote: The remote storage backend instance
:returns: `True` when the transfer succeeded, `F... | Below is the the instruction that describes the task:
### Input:
Transfers the file with the given name from the local to the remote
storage backend.
:param name: The name of the file to transfer
:param local: The local storage backend instance
:param remote: The remote storage back... |
def _call(self, vf, out):
"""Implement ``self(vf, out)``."""
if self.domain.field == ComplexNumbers():
vf[0].multiply(self._vecfield[0].conj(), out=out)
else:
vf[0].multiply(self._vecfield[0], out=out)
if self.is_weighted:
out *= self.weights[0]
... | Implement ``self(vf, out)``. | Below is the the instruction that describes the task:
### Input:
Implement ``self(vf, out)``.
### Response:
def _call(self, vf, out):
"""Implement ``self(vf, out)``."""
if self.domain.field == ComplexNumbers():
vf[0].multiply(self._vecfield[0].conj(), out=out)
else:
... |
def fix(args):
"""
%prog fix bedfile > newbedfile
Fix non-standard bed files. One typical problem is start > end.
"""
p = OptionParser(fix.__doc__)
p.add_option("--minspan", default=0, type="int",
help="Enforce minimum span [default: %default]")
p.set_outfile()
opts, ar... | %prog fix bedfile > newbedfile
Fix non-standard bed files. One typical problem is start > end. | Below is the the instruction that describes the task:
### Input:
%prog fix bedfile > newbedfile
Fix non-standard bed files. One typical problem is start > end.
### Response:
def fix(args):
"""
%prog fix bedfile > newbedfile
Fix non-standard bed files. One typical problem is start > end.
"""
... |
def _sc_decode(soundcheck):
"""Convert a Sound Check bytestring value to a (gain, peak) tuple as
used by ReplayGain.
"""
# We decode binary data. If one of the formats gives us a text
# string, interpret it as UTF-8.
if isinstance(soundcheck, six.text_type):
soundcheck = soundcheck.encod... | Convert a Sound Check bytestring value to a (gain, peak) tuple as
used by ReplayGain. | Below is the the instruction that describes the task:
### Input:
Convert a Sound Check bytestring value to a (gain, peak) tuple as
used by ReplayGain.
### Response:
def _sc_decode(soundcheck):
"""Convert a Sound Check bytestring value to a (gain, peak) tuple as
used by ReplayGain.
"""
# We deco... |
def _ensure_insert(self, new_items, insert_to):
"""Ensure an item is inserted to a list or create a new empty list
:param new_items: the item(s) to insert
:type new_items: list(obj)
:param insert_to: the list on which to insert the items at index 0
:type insert_to: list()
... | Ensure an item is inserted to a list or create a new empty list
:param new_items: the item(s) to insert
:type new_items: list(obj)
:param insert_to: the list on which to insert the items at index 0
:type insert_to: list() | Below is the the instruction that describes the task:
### Input:
Ensure an item is inserted to a list or create a new empty list
:param new_items: the item(s) to insert
:type new_items: list(obj)
:param insert_to: the list on which to insert the items at index 0
:type insert_to: lis... |
def check_infile_and_wp(curinf, curwp):
"""Check the existence of the given file and directory path.
1. Raise Runtime exception of both not existed.
2. If the ``curwp`` is None, the set the base folder of ``curinf`` to it.
"""
if not os.path.exists(curinf):
if c... | Check the existence of the given file and directory path.
1. Raise Runtime exception of both not existed.
2. If the ``curwp`` is None, the set the base folder of ``curinf`` to it. | Below is the the instruction that describes the task:
### Input:
Check the existence of the given file and directory path.
1. Raise Runtime exception of both not existed.
2. If the ``curwp`` is None, the set the base folder of ``curinf`` to it.
### Response:
def check_infile_and_wp(curinf, cu... |
def difflag1(self):
"""
Conduct a diff-1 transform on a numeric frame column.
:returns: an H2OFrame where each element is equal to the corresponding element in the source
frame minus the previous-row element in the same frame.
"""
if self.ncols > 1:
raise... | Conduct a diff-1 transform on a numeric frame column.
:returns: an H2OFrame where each element is equal to the corresponding element in the source
frame minus the previous-row element in the same frame. | Below is the the instruction that describes the task:
### Input:
Conduct a diff-1 transform on a numeric frame column.
:returns: an H2OFrame where each element is equal to the corresponding element in the source
frame minus the previous-row element in the same frame.
### Response:
def difflag1... |
def get_mask_from_sequence_lengths(sequence_lengths: torch.Tensor, max_length: int) -> torch.Tensor:
"""
Given a variable of shape ``(batch_size,)`` that represents the sequence lengths of each batch
element, this function returns a ``(batch_size, max_length)`` mask variable. For example, if
our input ... | Given a variable of shape ``(batch_size,)`` that represents the sequence lengths of each batch
element, this function returns a ``(batch_size, max_length)`` mask variable. For example, if
our input was ``[2, 2, 3]``, with a ``max_length`` of 4, we'd return
``[[1, 1, 0, 0], [1, 1, 0, 0], [1, 1, 1, 0]]``.
... | Below is the the instruction that describes the task:
### Input:
Given a variable of shape ``(batch_size,)`` that represents the sequence lengths of each batch
element, this function returns a ``(batch_size, max_length)`` mask variable. For example, if
our input was ``[2, 2, 3]``, with a ``max_length`` of ... |
def masquerade(origin: str, orig: Type[TA], new: Type[TB], **map: str) -> str:
"""Make ``orig`` appear as new"""
return _masquerade(origin, cache_get(orig), cache_get(new), **map) | Make ``orig`` appear as new | Below is the the instruction that describes the task:
### Input:
Make ``orig`` appear as new
### Response:
def masquerade(origin: str, orig: Type[TA], new: Type[TB], **map: str) -> str:
"""Make ``orig`` appear as new"""
return _masquerade(origin, cache_get(orig), cache_get(new), **map) |
def get_thumbprint(self):
"""
Calculates the current thumbprint of the item being tracked.
"""
d = {}
settings = dj.get_settings()
for name in self.names:
d[name] = getattr(settings, name)
return d | Calculates the current thumbprint of the item being tracked. | Below is the the instruction that describes the task:
### Input:
Calculates the current thumbprint of the item being tracked.
### Response:
def get_thumbprint(self):
"""
Calculates the current thumbprint of the item being tracked.
"""
d = {}
settings = dj.get_settings()
... |
def realtime_comment_classifier(sender, instance, created, **kwargs):
"""
Classifies a comment after it has been created.
This behaviour is configurable by the REALTIME_CLASSIFICATION MODERATOR,
default behaviour is to classify(True).
"""
# Only classify if newly created.
if created:
... | Classifies a comment after it has been created.
This behaviour is configurable by the REALTIME_CLASSIFICATION MODERATOR,
default behaviour is to classify(True). | Below is the the instruction that describes the task:
### Input:
Classifies a comment after it has been created.
This behaviour is configurable by the REALTIME_CLASSIFICATION MODERATOR,
default behaviour is to classify(True).
### Response:
def realtime_comment_classifier(sender, instance, created, **kwarg... |
def find_list_of_ids(self, resource, ids, client_projection=None):
"""Find documents by ids."""
args = self._es_args(resource)
return self._parse_hits(self.elastic(resource).mget(body={'ids': ids}, **args), resource) | Find documents by ids. | Below is the the instruction that describes the task:
### Input:
Find documents by ids.
### Response:
def find_list_of_ids(self, resource, ids, client_projection=None):
"""Find documents by ids."""
args = self._es_args(resource)
return self._parse_hits(self.elastic(resource).mget(body={'ids... |
def eigenvalues_rev(T, k=None, mu=None):
r"""Compute eigenvalues of reversible transition matrix.
Parameters
----------
T : (d, d) ndarray
Transition matrix (stochastic matrix)
k : int or tuple of ints, optional
Compute the first k eigenvalues of T
mu : (d,) ndarray, optional
... | r"""Compute eigenvalues of reversible transition matrix.
Parameters
----------
T : (d, d) ndarray
Transition matrix (stochastic matrix)
k : int or tuple of ints, optional
Compute the first k eigenvalues of T
mu : (d,) ndarray, optional
Stationary distribution of T
Retur... | Below is the the instruction that describes the task:
### Input:
r"""Compute eigenvalues of reversible transition matrix.
Parameters
----------
T : (d, d) ndarray
Transition matrix (stochastic matrix)
k : int or tuple of ints, optional
Compute the first k eigenvalues of T
mu : (... |
def run(func, keys, max_procs=None, show_proc=False, affinity=None, **kwargs):
"""
Provide interface for multiprocessing
Args:
func: callable functions
keys: keys in kwargs that want to use process
max_procs: max number of processes
show_proc: whether to show process
... | Provide interface for multiprocessing
Args:
func: callable functions
keys: keys in kwargs that want to use process
max_procs: max number of processes
show_proc: whether to show process
affinity: CPU affinity
**kwargs: kwargs for func | Below is the the instruction that describes the task:
### Input:
Provide interface for multiprocessing
Args:
func: callable functions
keys: keys in kwargs that want to use process
max_procs: max number of processes
show_proc: whether to show process
affinity: CPU affinit... |
def move_messages(self, ids, folder_id):
""" Move selected messages to an other folder
:param msg_ids: list of message's ids to move
:param folder_id: folder's id where to move messages
"""
str_ids = self._return_comma_list(ids)
params = {'action': {
'id': st... | Move selected messages to an other folder
:param msg_ids: list of message's ids to move
:param folder_id: folder's id where to move messages | Below is the the instruction that describes the task:
### Input:
Move selected messages to an other folder
:param msg_ids: list of message's ids to move
:param folder_id: folder's id where to move messages
### Response:
def move_messages(self, ids, folder_id):
""" Move selected messages to... |
def _prepare_colors(color, values, limits_c, colormap, alpha, chan=None):
"""Return colors for all the channels based on various inputs.
Parameters
----------
color : tuple
3-, 4-element tuple, representing RGB and alpha, between 0 and 1
values : ndarray
array with values for each c... | Return colors for all the channels based on various inputs.
Parameters
----------
color : tuple
3-, 4-element tuple, representing RGB and alpha, between 0 and 1
values : ndarray
array with values for each channel
limits_c : tuple of 2 floats, optional
min and max values to n... | Below is the the instruction that describes the task:
### Input:
Return colors for all the channels based on various inputs.
Parameters
----------
color : tuple
3-, 4-element tuple, representing RGB and alpha, between 0 and 1
values : ndarray
array with values for each channel
l... |
def _advapi32_create_handles(cipher, key, iv):
"""
Creates an HCRYPTPROV and HCRYPTKEY for symmetric encryption/decryption. The
HCRYPTPROV must be released by close_context_handle() and the
HCRYPTKEY must be released by advapi32.CryptDestroyKey() when done.
:param cipher:
A unicode string o... | Creates an HCRYPTPROV and HCRYPTKEY for symmetric encryption/decryption. The
HCRYPTPROV must be released by close_context_handle() and the
HCRYPTKEY must be released by advapi32.CryptDestroyKey() when done.
:param cipher:
A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key",
... | Below is the the instruction that describes the task:
### Input:
Creates an HCRYPTPROV and HCRYPTKEY for symmetric encryption/decryption. The
HCRYPTPROV must be released by close_context_handle() and the
HCRYPTKEY must be released by advapi32.CryptDestroyKey() when done.
:param cipher:
A unicod... |
def run_and_measure(self, quil_program, qubits, trials=1):
"""
Run a Quil program once to determine the final wavefunction, and measure multiple times.
:note: If the execution of ``quil_program`` is **non-deterministic**, i.e., if it includes
measurements and/or noisy quantum gates,... | Run a Quil program once to determine the final wavefunction, and measure multiple times.
:note: If the execution of ``quil_program`` is **non-deterministic**, i.e., if it includes
measurements and/or noisy quantum gates, then the final wavefunction from which the
returned bitstrings are... | Below is the the instruction that describes the task:
### Input:
Run a Quil program once to determine the final wavefunction, and measure multiple times.
:note: If the execution of ``quil_program`` is **non-deterministic**, i.e., if it includes
measurements and/or noisy quantum gates, then the ... |
def top3_full(votes):
"""
Description:
Top m - 1 alternatives q = m(m - 1) + 2m moment conditions values calculation
Parameters:
votes: ordinal preference data (numpy ndarray of integers)
"""
#create array of zeros, length = q
res = np.zeros(2 * len(votes[0]) + (len(votes[0]) * (... | Description:
Top m - 1 alternatives q = m(m - 1) + 2m moment conditions values calculation
Parameters:
votes: ordinal preference data (numpy ndarray of integers) | Below is the the instruction that describes the task:
### Input:
Description:
Top m - 1 alternatives q = m(m - 1) + 2m moment conditions values calculation
Parameters:
votes: ordinal preference data (numpy ndarray of integers)
### Response:
def top3_full(votes):
"""
Description:
... |
def get_url(self):
"""API url
:return: url
:rtype: str
"""
url = self.data[self.execute_name]
parsed = urlparse(url)
if not parsed.scheme:
url = '{}://{}'.format(self.default_protocol, url)
if not url.split(':')[-1].isalnum():
url ... | API url
:return: url
:rtype: str | Below is the the instruction that describes the task:
### Input:
API url
:return: url
:rtype: str
### Response:
def get_url(self):
"""API url
:return: url
:rtype: str
"""
url = self.data[self.execute_name]
parsed = urlparse(url)
if not parse... |
def get_album_time(self, round_number=2):
"""
Retrieves all of the track's length and returns the sum of all
:param round_number: Int. Number of decimals to round the sum
:return: Int. Sum of all the track's length
"""
if not self._track_list:
self.get_tracks(... | Retrieves all of the track's length and returns the sum of all
:param round_number: Int. Number of decimals to round the sum
:return: Int. Sum of all the track's length | Below is the the instruction that describes the task:
### Input:
Retrieves all of the track's length and returns the sum of all
:param round_number: Int. Number of decimals to round the sum
:return: Int. Sum of all the track's length
### Response:
def get_album_time(self, round_number=2):
"... |
def _display_error(normalized_data, stream):
"""
print error message from docker-py stream and raise Exception.
{
u'message': u"Error getting container 981c3e17bfc6138d1985c0c8f5616e9064e56559e817646ad38211a456d6bcf2 from driver
devicemapper: Error mounting '/dev/mapper/docker-8:3-34393696-9... | print error message from docker-py stream and raise Exception.
{
u'message': u"Error getting container 981c3e17bfc6138d1985c0c8f5616e9064e56559e817646ad38211a456d6bcf2 from driver
devicemapper: Error mounting '/dev/mapper/docker-8:3-34393696-981c3e17bfc6138d1985c0c8f5616e9064e56559e817646ad38211a456... | Below is the the instruction that describes the task:
### Input:
print error message from docker-py stream and raise Exception.
{
u'message': u"Error getting container 981c3e17bfc6138d1985c0c8f5616e9064e56559e817646ad38211a456d6bcf2 from driver
devicemapper: Error mounting '/dev/mapper/docker-8:... |
def _ok(self, packets=None, headers=None, b64=False):
"""Generate a successful HTTP response."""
if packets is not None:
if headers is None:
headers = []
if b64:
headers += [('Content-Type', 'text/plain; charset=UTF-8')]
else:
... | Generate a successful HTTP response. | Below is the the instruction that describes the task:
### Input:
Generate a successful HTTP response.
### Response:
def _ok(self, packets=None, headers=None, b64=False):
"""Generate a successful HTTP response."""
if packets is not None:
if headers is None:
headers = []
... |
def create_external_account(resource_root, name, display_name, type_name,
account_configs=None):
"""
Create an external account
@param resource_root: The root Resource object.
@param name: Immutable external account name
@param display_name: Display name
@param type_name: Account... | Create an external account
@param resource_root: The root Resource object.
@param name: Immutable external account name
@param display_name: Display name
@param type_name: Account type
@param account_configs: Optional account configuration (ApiList of ApiConfig objects)
@return: An ApiExternalAccount object... | Below is the the instruction that describes the task:
### Input:
Create an external account
@param resource_root: The root Resource object.
@param name: Immutable external account name
@param display_name: Display name
@param type_name: Account type
@param account_configs: Optional account configuration (... |
def requests_search(self, cc_id=None, organization_id=None, query=None, status=None, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/requests#search-requests"
api_path = "/api/v2/requests/search.json"
api_query = {}
if "query" in kwargs.keys():
api_query.update(k... | https://developer.zendesk.com/rest_api/docs/core/requests#search-requests | Below is the the instruction that describes the task:
### Input:
https://developer.zendesk.com/rest_api/docs/core/requests#search-requests
### Response:
def requests_search(self, cc_id=None, organization_id=None, query=None, status=None, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/requests... |
def colorize_text(self, text):
"""Adds escape sequences to colorize text and make it
beautiful. To colorize text, prefix the text you want to color
with the color (capitalized) wrapped in double angle brackets
(i.e.: <<GREEN>>). End your string with <<NORMAL>>. If you
don't, it w... | Adds escape sequences to colorize text and make it
beautiful. To colorize text, prefix the text you want to color
with the color (capitalized) wrapped in double angle brackets
(i.e.: <<GREEN>>). End your string with <<NORMAL>>. If you
don't, it will be done for you (assuming you used a c... | Below is the the instruction that describes the task:
### Input:
Adds escape sequences to colorize text and make it
beautiful. To colorize text, prefix the text you want to color
with the color (capitalized) wrapped in double angle brackets
(i.e.: <<GREEN>>). End your string with <<NORMAL>>.... |
def _get_repetition(extractor, text, *, bounds=(0, None), ignore_whitespace=False):
"""Tries to pull text with extractor repeatedly.
Bounds is a 2-tuple of (lbound, ubound) where lbound is a number and ubound is a number or None.
If the ubound is None, this method will execute extractor on text until extrator ra... | Tries to pull text with extractor repeatedly.
Bounds is a 2-tuple of (lbound, ubound) where lbound is a number and ubound is a number or None.
If the ubound is None, this method will execute extractor on text until extrator raises DeadEnd.
Otherwise, extractor will be called until it raises DeadEnd, or it has ex... | Below is the the instruction that describes the task:
### Input:
Tries to pull text with extractor repeatedly.
Bounds is a 2-tuple of (lbound, ubound) where lbound is a number and ubound is a number or None.
If the ubound is None, this method will execute extractor on text until extrator raises DeadEnd.
Othe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.