code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def ast_smart(val):
"""Return a suitable subclass of :class:`ast.AST` for storing numbers
or strings. For other type of objects, return a node class that will
indicate that the variable is contained in one of global or local
namespaces."""
if isinstance(val, Number):
return Num(n=val)
e... | Return a suitable subclass of :class:`ast.AST` for storing numbers
or strings. For other type of objects, return a node class that will
indicate that the variable is contained in one of global or local
namespaces. | Below is the the instruction that describes the task:
### Input:
Return a suitable subclass of :class:`ast.AST` for storing numbers
or strings. For other type of objects, return a node class that will
indicate that the variable is contained in one of global or local
namespaces.
### Response:
def ast_sm... |
def initialize(config=None):
"""Initializes oz"""
# Load the config file
if config == None:
config = {}
config_source = None
try:
with open(os.environ.get("OZ_CONFIG", "config.py")) as f:
config_source = f.read()
except Exception:
tor... | Initializes oz | Below is the the instruction that describes the task:
### Input:
Initializes oz
### Response:
def initialize(config=None):
"""Initializes oz"""
# Load the config file
if config == None:
config = {}
config_source = None
try:
with open(os.environ.get("OZ_CONFIG", "co... |
def as_boxes(self, colors=None):
"""
A rough Trimesh representation of the voxels with a box
for each filled voxel.
Parameters
----------
colors : (3,) or (4,) float or uint8
(X, Y, Z, 3) or (X, Y, Z, 4) float or uint8
Where matrix.shape == (X, ... | A rough Trimesh representation of the voxels with a box
for each filled voxel.
Parameters
----------
colors : (3,) or (4,) float or uint8
(X, Y, Z, 3) or (X, Y, Z, 4) float or uint8
Where matrix.shape == (X, Y, Z)
Returns
---------
mesh... | Below is the the instruction that describes the task:
### Input:
A rough Trimesh representation of the voxels with a box
for each filled voxel.
Parameters
----------
colors : (3,) or (4,) float or uint8
(X, Y, Z, 3) or (X, Y, Z, 4) float or uint8
Where matr... |
def _GetAction(self, action, text):
"""Parse the well known actions for easy reading.
Args:
action (str): the function or action called by the agent.
text (str): mac Wifi log text.
Returns:
str: a formatted string representing the known (or common) action.
If the action is no... | Parse the well known actions for easy reading.
Args:
action (str): the function or action called by the agent.
text (str): mac Wifi log text.
Returns:
str: a formatted string representing the known (or common) action.
If the action is not known the original log text is returned. | Below is the the instruction that describes the task:
### Input:
Parse the well known actions for easy reading.
Args:
action (str): the function or action called by the agent.
text (str): mac Wifi log text.
Returns:
str: a formatted string representing the known (or common) action.
... |
def get_parent_gradebook_nodes(self):
"""Gets the parents of this gradebook.
return: (osid.grading.GradebookNodeList) - the parents of the
``id``
*compliance: mandatory -- This method must be implemented.*
"""
parent_gradebook_nodes = []
for node in self... | Gets the parents of this gradebook.
return: (osid.grading.GradebookNodeList) - the parents of the
``id``
*compliance: mandatory -- This method must be implemented.* | Below is the the instruction that describes the task:
### Input:
Gets the parents of this gradebook.
return: (osid.grading.GradebookNodeList) - the parents of the
``id``
*compliance: mandatory -- This method must be implemented.*
### Response:
def get_parent_gradebook_nodes(self):
... |
def _get_step_inout(step):
"""Retrieve set of inputs and outputs connecting steps.
"""
inputs = []
outputs = []
assert step.inputs_record_schema["type"] == "record"
for inp in step.inputs_record_schema["fields"]:
source = inp["source"].split("#")[-1].replace("/", ".")
# Check if ... | Retrieve set of inputs and outputs connecting steps. | Below is the the instruction that describes the task:
### Input:
Retrieve set of inputs and outputs connecting steps.
### Response:
def _get_step_inout(step):
"""Retrieve set of inputs and outputs connecting steps.
"""
inputs = []
outputs = []
assert step.inputs_record_schema["type"] == "record... |
def get_gradebook_form(self, *args, **kwargs):
"""Pass through to provider GradebookAdminSession.get_gradebook_form_for_update"""
# Implemented from kitosid template for -
# osid.resource.BinAdminSession.get_bin_form_for_update_template
# This method might be a bit sketchy. Time will tel... | Pass through to provider GradebookAdminSession.get_gradebook_form_for_update | Below is the the instruction that describes the task:
### Input:
Pass through to provider GradebookAdminSession.get_gradebook_form_for_update
### Response:
def get_gradebook_form(self, *args, **kwargs):
"""Pass through to provider GradebookAdminSession.get_gradebook_form_for_update"""
# Implemented... |
def unormg(v1, ndim):
"""
Normalize a double precision vector of arbitrary dimension and
return its magnitude.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/unormg_c.html
:param v1: Vector to be normalized.
:type v1: Array of floats
:param ndim: This is the dimension of v1 and v... | Normalize a double precision vector of arbitrary dimension and
return its magnitude.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/unormg_c.html
:param v1: Vector to be normalized.
:type v1: Array of floats
:param ndim: This is the dimension of v1 and vout.
:type ndim: int
:ret... | Below is the the instruction that describes the task:
### Input:
Normalize a double precision vector of arbitrary dimension and
return its magnitude.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/unormg_c.html
:param v1: Vector to be normalized.
:type v1: Array of floats
:param ndim... |
def cli(env, identifier, enable):
"""Toggle the IPMI interface on and off"""
mgr = SoftLayer.HardwareManager(env.client)
hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware')
result = env.client['Hardware_Server'].toggleManagementInterface(enable, id=hw_id)
env.fout(result) | Toggle the IPMI interface on and off | Below is the the instruction that describes the task:
### Input:
Toggle the IPMI interface on and off
### Response:
def cli(env, identifier, enable):
"""Toggle the IPMI interface on and off"""
mgr = SoftLayer.HardwareManager(env.client)
hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware... |
def file_list(self, tgt_env):
'''
Get file list for the target environment using GitPython
'''
files = set()
symlinks = {}
tree = self.get_tree(tgt_env)
if not tree:
# Not found, return empty objects
return files, symlinks
if self.r... | Get file list for the target environment using GitPython | Below is the the instruction that describes the task:
### Input:
Get file list for the target environment using GitPython
### Response:
def file_list(self, tgt_env):
'''
Get file list for the target environment using GitPython
'''
files = set()
symlinks = {}
tree = s... |
def get(self, request, bot_id, format=None):
"""
Get list of chat state
---
serializer: TelegramChatStateSerializer
responseMessages:
- code: 401
message: Not authenticated
"""
return super(TelegramChatStateList, self).get(request, bot_id... | Get list of chat state
---
serializer: TelegramChatStateSerializer
responseMessages:
- code: 401
message: Not authenticated | Below is the the instruction that describes the task:
### Input:
Get list of chat state
---
serializer: TelegramChatStateSerializer
responseMessages:
- code: 401
message: Not authenticated
### Response:
def get(self, request, bot_id, format=None):
"""
... |
def save_model(model, output_file=None, output_dir=None, output_prefix='pymzn'):
"""Save a model to file.
Parameters
----------
model : str
The minizinc model (i.e. the content of a ``.mzn`` file).
output_file : str
The path to the output file. If this parameter is ``None`` (default... | Save a model to file.
Parameters
----------
model : str
The minizinc model (i.e. the content of a ``.mzn`` file).
output_file : str
The path to the output file. If this parameter is ``None`` (default), a
temporary file is created with the given model in the specified output
... | Below is the the instruction that describes the task:
### Input:
Save a model to file.
Parameters
----------
model : str
The minizinc model (i.e. the content of a ``.mzn`` file).
output_file : str
The path to the output file. If this parameter is ``None`` (default), a
tempor... |
def ext_pillar(minion_id, # pylint: disable=W0613
pillar, # pylint: disable=W0613
pillar_name,
project_path,
settings_module,
django_app,
env=None,
env_file=None,
*args, # pylint: disable=W0613
... | Connect to a Django database through the ORM and retrieve model fields
:type pillar_name: str
:param pillar_name: The name of the pillar to be returned
:type project_path: str
:param project_path: The full path to your Django project (the directory
manage.py is in)
:type settings_module: ... | Below is the the instruction that describes the task:
### Input:
Connect to a Django database through the ORM and retrieve model fields
:type pillar_name: str
:param pillar_name: The name of the pillar to be returned
:type project_path: str
:param project_path: The full path to your Django project... |
def longest_unique_prefix(query, targets, remove_self=True):
"""
Find the longest unique prefix for filename, when compared against a list of
filenames. Useful to simplify file names in a pool of files. See usage in
formats.fasta.pool().
"""
query = op.basename(query)
targets = [op.basename(... | Find the longest unique prefix for filename, when compared against a list of
filenames. Useful to simplify file names in a pool of files. See usage in
formats.fasta.pool(). | Below is the the instruction that describes the task:
### Input:
Find the longest unique prefix for filename, when compared against a list of
filenames. Useful to simplify file names in a pool of files. See usage in
formats.fasta.pool().
### Response:
def longest_unique_prefix(query, targets, remove_self=T... |
def jhk_to_sdssu(jmag,hmag,kmag):
'''Converts given J, H, Ks mags to an SDSS u magnitude value.
Parameters
----------
jmag,hmag,kmag : float
2MASS J, H, Ks mags of the object.
Returns
-------
float
The converted SDSS u band magnitude.
'''
return convert_constant... | Converts given J, H, Ks mags to an SDSS u magnitude value.
Parameters
----------
jmag,hmag,kmag : float
2MASS J, H, Ks mags of the object.
Returns
-------
float
The converted SDSS u band magnitude. | Below is the the instruction that describes the task:
### Input:
Converts given J, H, Ks mags to an SDSS u magnitude value.
Parameters
----------
jmag,hmag,kmag : float
2MASS J, H, Ks mags of the object.
Returns
-------
float
The converted SDSS u band magnitude.
### Respo... |
def delete(self, *args, **kwargs):
"""
This method implements retries for object deletion.
"""
count = 0
max_retries=3
while True:
try:
return super(BaseModel, self).delete(*args, **kwargs)
except django.db.utils.OperationalError:
... | This method implements retries for object deletion. | Below is the the instruction that describes the task:
### Input:
This method implements retries for object deletion.
### Response:
def delete(self, *args, **kwargs):
"""
This method implements retries for object deletion.
"""
count = 0
max_retries=3
while True:
... |
def rounded(self, image, geometry, options):
"""
Wrapper for ``_rounded``
"""
r = options['rounded']
if not r:
return image
return self._rounded(image, int(r)) | Wrapper for ``_rounded`` | Below is the the instruction that describes the task:
### Input:
Wrapper for ``_rounded``
### Response:
def rounded(self, image, geometry, options):
"""
Wrapper for ``_rounded``
"""
r = options['rounded']
if not r:
return image
return self._rounded(image,... |
def _verify_views():
'''
Verify that you have the views you need. This can be disabled by
adding couchbase.skip_verify_views: True in config
'''
global VERIFIED_VIEWS
if VERIFIED_VIEWS or __opts__.get('couchbase.skip_verify_views', False):
return
cb_ = _get_connection()
ddoc = {... | Verify that you have the views you need. This can be disabled by
adding couchbase.skip_verify_views: True in config | Below is the the instruction that describes the task:
### Input:
Verify that you have the views you need. This can be disabled by
adding couchbase.skip_verify_views: True in config
### Response:
def _verify_views():
'''
Verify that you have the views you need. This can be disabled by
adding couchba... |
def handle_cannot(reference_answers: List[str]):
"""
Process a list of reference answers.
If equal or more than half of the reference answers are "CANNOTANSWER", take it as gold.
Otherwise, return answers that are not "CANNOTANSWER".
"""
num_cannot = 0
num_spans = 0
for ref in reference_... | Process a list of reference answers.
If equal or more than half of the reference answers are "CANNOTANSWER", take it as gold.
Otherwise, return answers that are not "CANNOTANSWER". | Below is the the instruction that describes the task:
### Input:
Process a list of reference answers.
If equal or more than half of the reference answers are "CANNOTANSWER", take it as gold.
Otherwise, return answers that are not "CANNOTANSWER".
### Response:
def handle_cannot(reference_answers: List[str])... |
def list(self, order_id, **params):
"""
Retrieve order's line items
Returns all line items associated to order
:calls: ``get /orders/{order_id}/line_items``
:param int order_id: Unique identifier of a Order.
:param dict params: (optional) Search options.
:return... | Retrieve order's line items
Returns all line items associated to order
:calls: ``get /orders/{order_id}/line_items``
:param int order_id: Unique identifier of a Order.
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style acce... | Below is the the instruction that describes the task:
### Input:
Retrieve order's line items
Returns all line items associated to order
:calls: ``get /orders/{order_id}/line_items``
:param int order_id: Unique identifier of a Order.
:param dict params: (optional) Search options.
... |
def SetForegroundWindow(handle: int) -> bool:
"""
SetForegroundWindow from Win32.
handle: int, the handle of a native window.
Return bool, True if succeed otherwise False.
"""
return bool(ctypes.windll.user32.SetForegroundWindow(ctypes.c_void_p(handle))) | SetForegroundWindow from Win32.
handle: int, the handle of a native window.
Return bool, True if succeed otherwise False. | Below is the the instruction that describes the task:
### Input:
SetForegroundWindow from Win32.
handle: int, the handle of a native window.
Return bool, True if succeed otherwise False.
### Response:
def SetForegroundWindow(handle: int) -> bool:
"""
SetForegroundWindow from Win32.
handle: int,... |
def _create_buffers(self, number):
"""
Creates a SecBufferDesc struct and contained SecBuffer structs
:param number:
The number of contains SecBuffer objects to create
:return:
A tuple of (SecBufferDesc pointer, SecBuffer array)
"""
buffers = ne... | Creates a SecBufferDesc struct and contained SecBuffer structs
:param number:
The number of contains SecBuffer objects to create
:return:
A tuple of (SecBufferDesc pointer, SecBuffer array) | Below is the the instruction that describes the task:
### Input:
Creates a SecBufferDesc struct and contained SecBuffer structs
:param number:
The number of contains SecBuffer objects to create
:return:
A tuple of (SecBufferDesc pointer, SecBuffer array)
### Response:
def ... |
def skip_inasafe_field(layer, inasafe_fields):
"""Check if it possible to skip inasafe field step.
The function will check if the layer has a specified field type.
:param layer: A Qgis Vector Layer.
:type layer: QgsVectorLayer
:param inasafe_fields: List of non compulsory InaSAFE fields default.
... | Check if it possible to skip inasafe field step.
The function will check if the layer has a specified field type.
:param layer: A Qgis Vector Layer.
:type layer: QgsVectorLayer
:param inasafe_fields: List of non compulsory InaSAFE fields default.
:type inasafe_fields: list
:returns: True if ... | Below is the the instruction that describes the task:
### Input:
Check if it possible to skip inasafe field step.
The function will check if the layer has a specified field type.
:param layer: A Qgis Vector Layer.
:type layer: QgsVectorLayer
:param inasafe_fields: List of non compulsory InaSAFE f... |
def _get_group_difference(self, sp_groups):
"""Helper method for gettings the groups that
are present in the local db but not on stormpath
and the other way around."""
db_groups = set(Group.objects.all().values_list('name', flat=True))
missing_from_db = set(sp_groups).difference(... | Helper method for gettings the groups that
are present in the local db but not on stormpath
and the other way around. | Below is the the instruction that describes the task:
### Input:
Helper method for gettings the groups that
are present in the local db but not on stormpath
and the other way around.
### Response:
def _get_group_difference(self, sp_groups):
"""Helper method for gettings the groups that
... |
def is_self_hit(self):
'''Returns true iff the alignment is of a sequence to itself: names and all coordinates are the same and 100 percent identity'''
return self.ref_name == self.qry_name \
and self.ref_start == self.qry_start \
and self.ref_end == self.qry_end \
... | Returns true iff the alignment is of a sequence to itself: names and all coordinates are the same and 100 percent identity | Below is the the instruction that describes the task:
### Input:
Returns true iff the alignment is of a sequence to itself: names and all coordinates are the same and 100 percent identity
### Response:
def is_self_hit(self):
'''Returns true iff the alignment is of a sequence to itself: names and all coordi... |
def parse(self, data):
"""Parse a 12 bytes packet in the Rain format and return a
dictionary containing the data extracted. An example of a return value
would be:
.. code-block:: python
{
'id': "0x2EB2",
'packet_length': 11,
'... | Parse a 12 bytes packet in the Rain format and return a
dictionary containing the data extracted. An example of a return value
would be:
.. code-block:: python
{
'id': "0x2EB2",
'packet_length': 11,
'packet_type': 85,
... | Below is the the instruction that describes the task:
### Input:
Parse a 12 bytes packet in the Rain format and return a
dictionary containing the data extracted. An example of a return value
would be:
.. code-block:: python
{
'id': "0x2EB2",
'pa... |
def showHeaderMenu( self, pos):
"""
Displays the header menu for this tree widget.
:param pos | <QtCore.QPoint> || None
"""
header = self.header()
index = header.logicalIndexAt(pos)
self._headerIndex = index
# show a pre-s... | Displays the header menu for this tree widget.
:param pos | <QtCore.QPoint> || None | Below is the the instruction that describes the task:
### Input:
Displays the header menu for this tree widget.
:param pos | <QtCore.QPoint> || None
### Response:
def showHeaderMenu( self, pos):
"""
Displays the header menu for this tree widget.
:param ... |
def damping(self):
"""Strain-compatible damping."""
try:
value = self._damping.value
except AttributeError:
value = self._damping
return value | Strain-compatible damping. | Below is the the instruction that describes the task:
### Input:
Strain-compatible damping.
### Response:
def damping(self):
"""Strain-compatible damping."""
try:
value = self._damping.value
except AttributeError:
value = self._damping
return value |
def get_channelstate_open(
chain_state: ChainState,
payment_network_id: PaymentNetworkID,
token_address: TokenAddress,
) -> List[NettingChannelState]:
"""Return the state of open channels in a token network."""
return get_channelstate_filter(
chain_state,
payment_network_... | Return the state of open channels in a token network. | Below is the the instruction that describes the task:
### Input:
Return the state of open channels in a token network.
### Response:
def get_channelstate_open(
chain_state: ChainState,
payment_network_id: PaymentNetworkID,
token_address: TokenAddress,
) -> List[NettingChannelState]:
"""... |
def setup_tmpltbank_without_frames(workflow, output_dir,
tags=None, independent_ifos=False,
psd_files=None):
'''
Setup CBC workflow to use a template bank (or banks) that are generated in
the workflow, but do not use the data to estimate ... | Setup CBC workflow to use a template bank (or banks) that are generated in
the workflow, but do not use the data to estimate a PSD, and therefore do
not vary over the duration of the workflow. This can either generate one
bank that is valid for all ifos at all times, or multiple banks that are
valid onl... | Below is the the instruction that describes the task:
### Input:
Setup CBC workflow to use a template bank (or banks) that are generated in
the workflow, but do not use the data to estimate a PSD, and therefore do
not vary over the duration of the workflow. This can either generate one
bank that is vali... |
def match(self, filename, line, codes):
"""Match rule."""
if ((not self.file_selectors or self.file_match_any(filename)) and
(not self.environment_marker_selector or
self.environment_marker_evaluate()) and
(not self.code_selectors or self.codes_match_any(... | Match rule. | Below is the the instruction that describes the task:
### Input:
Match rule.
### Response:
def match(self, filename, line, codes):
"""Match rule."""
if ((not self.file_selectors or self.file_match_any(filename)) and
(not self.environment_marker_selector or
self.envi... |
def _loglikelihood(params, x, tx, T):
warnings.simplefilter(action="ignore", category=FutureWarning)
"""Log likelihood for optimizer."""
alpha, beta, gamma, delta = params
betaln_ab = betaln(alpha, beta)
betaln_gd = betaln(gamma, delta)
A = betaln(alpha + x, beta + T -... | Log likelihood for optimizer. | Below is the the instruction that describes the task:
### Input:
Log likelihood for optimizer.
### Response:
def _loglikelihood(params, x, tx, T):
warnings.simplefilter(action="ignore", category=FutureWarning)
"""Log likelihood for optimizer."""
alpha, beta, gamma, delta = params
... |
def add_to_submenu(self, submenu_path, item):
'''
add an item to a submenu using a menu path array
'''
for m in self.items:
if m.name == submenu_path[0]:
m.add_to_submenu(submenu_path[1:], item)
return
raise(ValueError("No submenu (%s) ... | add an item to a submenu using a menu path array | Below is the the instruction that describes the task:
### Input:
add an item to a submenu using a menu path array
### Response:
def add_to_submenu(self, submenu_path, item):
'''
add an item to a submenu using a menu path array
'''
for m in self.items:
if m.name == submen... |
def flush(self, batch_size=1000):
"""
Delete all autocomplete indexes and metadata.
"""
keys = self.database.keys(self.namespace + ':*')
for i in range(0, len(keys), batch_size):
self.database.delete(*keys[i:i + batch_size]) | Delete all autocomplete indexes and metadata. | Below is the the instruction that describes the task:
### Input:
Delete all autocomplete indexes and metadata.
### Response:
def flush(self, batch_size=1000):
"""
Delete all autocomplete indexes and metadata.
"""
keys = self.database.keys(self.namespace + ':*')
for i in rang... |
def delete(self, id, id_name='id', **kwargs):
"""
Deletes the item corresponding to ``id``.
"""
response = self._new_response()
if self._check_supported_op('delete', response):
params = {'Key': {id_name: id}}
self._call_ddb_method(self.table.delete_item, p... | Deletes the item corresponding to ``id``. | Below is the the instruction that describes the task:
### Input:
Deletes the item corresponding to ``id``.
### Response:
def delete(self, id, id_name='id', **kwargs):
"""
Deletes the item corresponding to ``id``.
"""
response = self._new_response()
if self._check_supported_o... |
def sg_producer_func(func):
r"""Decorates a function `func` as sg_producer_func.
Args:
func: A function to decorate.
"""
@wraps(func)
def wrapper(**kwargs):
r"""Manages arguments of `tf.sg_opt`.
Args:
**kwargs:
source: A source queue list to enqueue
... | r"""Decorates a function `func` as sg_producer_func.
Args:
func: A function to decorate. | Below is the the instruction that describes the task:
### Input:
r"""Decorates a function `func` as sg_producer_func.
Args:
func: A function to decorate.
### Response:
def sg_producer_func(func):
r"""Decorates a function `func` as sg_producer_func.
Args:
func: A function to decorate.
... |
def complete_timeframe(timeframe, config, partial=False):
"""
Apply fallback strategy to incomplete timeframes.
Our fallback strategy is as follows:
* Missing start-date: Fallback to ``today``.
* Missing start-time: Fallback to ``store.config['day_start']``.
* Missing end-date: Fall... | Apply fallback strategy to incomplete timeframes.
Our fallback strategy is as follows:
* Missing start-date: Fallback to ``today``.
* Missing start-time: Fallback to ``store.config['day_start']``.
* Missing end-date: Fallback to ``today`` for ``day_start='00:00`,
``tomorrow`` othe... | Below is the the instruction that describes the task:
### Input:
Apply fallback strategy to incomplete timeframes.
Our fallback strategy is as follows:
* Missing start-date: Fallback to ``today``.
* Missing start-time: Fallback to ``store.config['day_start']``.
* Missing end-date: Fallb... |
def cache_items(values):
"""Cache indicators that were successfully sent to avoid dups."""
import os
config_path = os.path.expanduser('~/.config/blockade')
file_path = os.path.join(config_path, 'cache.txt')
if not os.path.isfile(file_path):
file(file_path, 'w').close()
written = [x.strip... | Cache indicators that were successfully sent to avoid dups. | Below is the the instruction that describes the task:
### Input:
Cache indicators that were successfully sent to avoid dups.
### Response:
def cache_items(values):
"""Cache indicators that were successfully sent to avoid dups."""
import os
config_path = os.path.expanduser('~/.config/blockade')
file... |
def put(
self,
id,
name,
description,
command_to_run,
environment_variables,
required_arguments,
required_arguments_default_values,
extra_data_to_put=None,
):
"""Updates a task type on the saltant server.
Args:
id (... | Updates a task type on the saltant server.
Args:
id (int): The ID of the task type.
name (str): The name of the task type.
description (str): The description of the task type.
command_to_run (str): The command to run to execute the task.
environment_v... | Below is the the instruction that describes the task:
### Input:
Updates a task type on the saltant server.
Args:
id (int): The ID of the task type.
name (str): The name of the task type.
description (str): The description of the task type.
command_to_run (st... |
def set_option(self, optname, value, action=None, optdict=None):
"""method called to set an option (registered in the options list)
overridden to report options setting to Similar
"""
BaseChecker.set_option(self, optname, value, action, optdict)
if optname == "min-similarity-lin... | method called to set an option (registered in the options list)
overridden to report options setting to Similar | Below is the the instruction that describes the task:
### Input:
method called to set an option (registered in the options list)
overridden to report options setting to Similar
### Response:
def set_option(self, optname, value, action=None, optdict=None):
"""method called to set an option (registe... |
def set_stylesheet(self, subreddit, stylesheet):
"""Set stylesheet for the given subreddit.
:returns: The json response from the server.
"""
subreddit = six.text_type(subreddit)
data = {'r': subreddit,
'stylesheet_contents': stylesheet,
'op': 'sa... | Set stylesheet for the given subreddit.
:returns: The json response from the server. | Below is the the instruction that describes the task:
### Input:
Set stylesheet for the given subreddit.
:returns: The json response from the server.
### Response:
def set_stylesheet(self, subreddit, stylesheet):
"""Set stylesheet for the given subreddit.
:returns: The json response from ... |
def mgmt_request(self, message, operation, op_type=None, node=None, callback=None, **kwargs):
"""Run a request/response operation. These are frequently used for management
tasks against a $management node, however any node name can be specified
and the available options will depend on the target... | Run a request/response operation. These are frequently used for management
tasks against a $management node, however any node name can be specified
and the available options will depend on the target service.
:param message: The message to send in the management request.
:type message: ... | Below is the the instruction that describes the task:
### Input:
Run a request/response operation. These are frequently used for management
tasks against a $management node, however any node name can be specified
and the available options will depend on the target service.
:param message: T... |
def write(self, s, *args, **kwargs):
"""Wrapper around handle.write"""
if args or kwargs:
self.handle.write(s.format(*args, **kwargs))
else:
self.handle.write(s) | Wrapper around handle.write | Below is the the instruction that describes the task:
### Input:
Wrapper around handle.write
### Response:
def write(self, s, *args, **kwargs):
"""Wrapper around handle.write"""
if args or kwargs:
self.handle.write(s.format(*args, **kwargs))
else:
self.handle.write(s... |
def _set_fcoe_map_cee_map(self, v, load=False):
"""
Setter method for fcoe_map_cee_map, mapped from YANG variable /fcoe/fcoe_map/fcoe_map_cee_map (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_fcoe_map_cee_map is considered as a private
method. Backends ... | Setter method for fcoe_map_cee_map, mapped from YANG variable /fcoe/fcoe_map/fcoe_map_cee_map (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_fcoe_map_cee_map is considered as a private
method. Backends looking to populate this variable should
do so via calli... | Below is the the instruction that describes the task:
### Input:
Setter method for fcoe_map_cee_map, mapped from YANG variable /fcoe/fcoe_map/fcoe_map_cee_map (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_fcoe_map_cee_map is considered as a private
method. ... |
def clear_cursor(self, body, params=None):
"""
`<Clear SQL cursor>`_
:arg body: Specify the cursor value in the `cursor` element to clean the
cursor.
"""
if body in SKIP_IN_PATH:
raise ValueError("Empty value passed for a required argument 'body'.")
... | `<Clear SQL cursor>`_
:arg body: Specify the cursor value in the `cursor` element to clean the
cursor. | Below is the the instruction that describes the task:
### Input:
`<Clear SQL cursor>`_
:arg body: Specify the cursor value in the `cursor` element to clean the
cursor.
### Response:
def clear_cursor(self, body, params=None):
"""
`<Clear SQL cursor>`_
:arg body: Specify... |
def get_list(client, list_id):
''' Gets the given list '''
endpoint = '/'.join([client.api.Endpoints.LISTS, str(list_id)])
response = client.authenticated_request(endpoint)
return response.json() | Gets the given list | Below is the the instruction that describes the task:
### Input:
Gets the given list
### Response:
def get_list(client, list_id):
''' Gets the given list '''
endpoint = '/'.join([client.api.Endpoints.LISTS, str(list_id)])
response = client.authenticated_request(endpoint)
return response.json() |
def split_into_batches(input_list, batch_size, batch_storage_dir, checkpoint=False):
"""
Break the input data into smaller batches, optionally saving each one to disk.
Args:
input_list: An input object that has a list-like interface (indexing and slicing).
batch_size: The maximum number of ... | Break the input data into smaller batches, optionally saving each one to disk.
Args:
input_list: An input object that has a list-like interface (indexing and slicing).
batch_size: The maximum number of input items in each batch.
batch_storage_dir: The directory to save the checkpoints to.
... | Below is the the instruction that describes the task:
### Input:
Break the input data into smaller batches, optionally saving each one to disk.
Args:
input_list: An input object that has a list-like interface (indexing and slicing).
batch_size: The maximum number of input items in each batch.
... |
def _RegisterFlowProcessingHandler(self, handler):
"""Registers a handler to receive flow processing messages."""
self.flow_handler_stop = False
self.flow_handler_thread = threading.Thread(
name="flow_processing_handler",
target=self._HandleFlowProcessingRequestLoop,
args=(handler,))... | Registers a handler to receive flow processing messages. | Below is the the instruction that describes the task:
### Input:
Registers a handler to receive flow processing messages.
### Response:
def _RegisterFlowProcessingHandler(self, handler):
"""Registers a handler to receive flow processing messages."""
self.flow_handler_stop = False
self.flow_handler_thre... |
def _add_user_from_conv_part(self, conv_part):
"""Add or upgrade User from ConversationParticipantData."""
user_ = User.from_conv_part_data(conv_part, self._self_user.id_)
existing = self._user_dict.get(user_.id_)
if existing is None:
logger.warning('Adding fallback User wit... | Add or upgrade User from ConversationParticipantData. | Below is the the instruction that describes the task:
### Input:
Add or upgrade User from ConversationParticipantData.
### Response:
def _add_user_from_conv_part(self, conv_part):
"""Add or upgrade User from ConversationParticipantData."""
user_ = User.from_conv_part_data(conv_part, self._self_user... |
def check(self, request, secret):
"""Verifies whether or not the request bears an authorization appropriate and valid for this version of the signature.
This verifies every element of the signature, including headers other than Authorization.
Keyword arguments:
request -- A request obje... | Verifies whether or not the request bears an authorization appropriate and valid for this version of the signature.
This verifies every element of the signature, including headers other than Authorization.
Keyword arguments:
request -- A request object which can be consumed by this API.
... | Below is the the instruction that describes the task:
### Input:
Verifies whether or not the request bears an authorization appropriate and valid for this version of the signature.
This verifies every element of the signature, including headers other than Authorization.
Keyword arguments:
r... |
def node_definitions(id_fetcher, type_resolver=None, id_resolver=None):
'''
Given a function to map from an ID to an underlying object, and a function
to map from an underlying object to the concrete GraphQLObjectType it
corresponds to, constructs a `Node` interface that objects can implement,
and a... | Given a function to map from an ID to an underlying object, and a function
to map from an underlying object to the concrete GraphQLObjectType it
corresponds to, constructs a `Node` interface that objects can implement,
and a field config for a `node` root field.
If the type_resolver is omitted, object ... | Below is the the instruction that describes the task:
### Input:
Given a function to map from an ID to an underlying object, and a function
to map from an underlying object to the concrete GraphQLObjectType it
corresponds to, constructs a `Node` interface that objects can implement,
and a field config f... |
def rm_raw(ctx, dataset, kwargs):
"removes the raw unprocessed data"
kwargs = parse_kwargs(kwargs)
data(dataset, **ctx.obj).rm_raw(**kwargs) | removes the raw unprocessed data | Below is the the instruction that describes the task:
### Input:
removes the raw unprocessed data
### Response:
def rm_raw(ctx, dataset, kwargs):
"removes the raw unprocessed data"
kwargs = parse_kwargs(kwargs)
data(dataset, **ctx.obj).rm_raw(**kwargs) |
def event_gen(self, ignore_missing_new_folders=False, **kwargs):
"""This is a secondary generator that wraps the principal one, and
adds/removes watches as directories are added/removed.
If we're doing anything funky and allowing the events to queue while a
rename occurs then the folder... | This is a secondary generator that wraps the principal one, and
adds/removes watches as directories are added/removed.
If we're doing anything funky and allowing the events to queue while a
rename occurs then the folder may no longer exist. In this case, set
`ignore_missing_new_folders`... | Below is the the instruction that describes the task:
### Input:
This is a secondary generator that wraps the principal one, and
adds/removes watches as directories are added/removed.
If we're doing anything funky and allowing the events to queue while a
rename occurs then the folder may no... |
def convert(model, feature_names, target):
"""Convert a boosted tree model to protobuf format.
Parameters
----------
decision_tree : GradientBoostingClassifier
A trained scikit-learn tree model.
feature_names: [str]
Name of the input columns.
target: str
Name of the ou... | Convert a boosted tree model to protobuf format.
Parameters
----------
decision_tree : GradientBoostingClassifier
A trained scikit-learn tree model.
feature_names: [str]
Name of the input columns.
target: str
Name of the output column.
Returns
-------
model_sp... | Below is the the instruction that describes the task:
### Input:
Convert a boosted tree model to protobuf format.
Parameters
----------
decision_tree : GradientBoostingClassifier
A trained scikit-learn tree model.
feature_names: [str]
Name of the input columns.
target: str
... |
def InputDNAQuantity(seq_length, n_features=1, name=None, **kwargs):
"""Convenience wrapper around `keras.layers.Input`:
`Input((seq_length, n_features), name=name, **kwargs)`
"""
return Input((seq_length, n_features), name=name, **kwargs) | Convenience wrapper around `keras.layers.Input`:
`Input((seq_length, n_features), name=name, **kwargs)` | Below is the the instruction that describes the task:
### Input:
Convenience wrapper around `keras.layers.Input`:
`Input((seq_length, n_features), name=name, **kwargs)`
### Response:
def InputDNAQuantity(seq_length, n_features=1, name=None, **kwargs):
"""Convenience wrapper around `keras.layers.Input`:
... |
def pos(self):
''' Tries to decide about the part of speech. '''
tags = []
if self.tree.xpath('//div[@class="grad733100"]/h2[@class="inline"]//text()'):
info = self.tree.xpath('//div[@class="grad733100"]/h2[@class="inline"]')[0].text_content()
info = info.strip('I ')
if info.startswith(('de', 'het')):
... | Tries to decide about the part of speech. | Below is the the instruction that describes the task:
### Input:
Tries to decide about the part of speech.
### Response:
def pos(self):
''' Tries to decide about the part of speech. '''
tags = []
if self.tree.xpath('//div[@class="grad733100"]/h2[@class="inline"]//text()'):
info = self.tree.xpath('//div[@... |
def blurring_kernel(shape=None):
"""Blurring kernel for convolution simulations.
The kernel is scaled to sum to one.
Returns
-------
An image with the following properties:
image type: gray scales
size: [100, 100] (if not specified by `size`)
scale: [0, 1]
type: flo... | Blurring kernel for convolution simulations.
The kernel is scaled to sum to one.
Returns
-------
An image with the following properties:
image type: gray scales
size: [100, 100] (if not specified by `size`)
scale: [0, 1]
type: float64 | Below is the the instruction that describes the task:
### Input:
Blurring kernel for convolution simulations.
The kernel is scaled to sum to one.
Returns
-------
An image with the following properties:
image type: gray scales
size: [100, 100] (if not specified by `size`)
sc... |
def get_list(self, list_name, options=None):
"""
Get detailed metadata information about a list.
"""
options = options or {}
data = {'list': list_name}
data.update(options)
return self.api_get('list', data) | Get detailed metadata information about a list. | Below is the the instruction that describes the task:
### Input:
Get detailed metadata information about a list.
### Response:
def get_list(self, list_name, options=None):
"""
Get detailed metadata information about a list.
"""
options = options or {}
data = {'list': list_na... |
def delete_exchange_for_vhost(self, exchange, vhost, if_unused=False):
"""
Delete an individual exchange. You can add the parameter
``if_unused=True``. This prevents the delete from succeeding if the
exchange is bound to a queue or as a source to another exchange.
:param exchang... | Delete an individual exchange. You can add the parameter
``if_unused=True``. This prevents the delete from succeeding if the
exchange is bound to a queue or as a source to another exchange.
:param exchange: The exchange name
:type exchange: str
:param vhost: The vhost name
... | Below is the the instruction that describes the task:
### Input:
Delete an individual exchange. You can add the parameter
``if_unused=True``. This prevents the delete from succeeding if the
exchange is bound to a queue or as a source to another exchange.
:param exchange: The exchange name
... |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'party') and self.party is not None:
_dict['party'] = self.party
if hasattr(self, 'importance') and self.importance is not None:
_dict['importance'] = self.impo... | Return a json dictionary representing this model. | Below is the the instruction that describes the task:
### Input:
Return a json dictionary representing this model.
### Response:
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'party') and self.party is not None:
_dict['pa... |
def replace_custom_resource_definition_status(self, name, body, **kwargs): # noqa: E501
"""replace_custom_resource_definition_status # noqa: E501
replace status of the specified CustomResourceDefinition # noqa: E501
This method makes a synchronous HTTP request by default. To make an
... | replace_custom_resource_definition_status # noqa: E501
replace status of the specified CustomResourceDefinition # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_custom_resour... | Below is the the instruction that describes the task:
### Input:
replace_custom_resource_definition_status # noqa: E501
replace status of the specified CustomResourceDefinition # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, plea... |
def preferred_forms_check(text, list, err, msg, ignore_case=True, offset=0,
max_errors=float("inf")):
"""Build a checker that suggests the preferred form."""
if ignore_case:
flags = re.IGNORECASE
else:
flags = 0
msg = " ".join(msg.split())
errors = []
... | Build a checker that suggests the preferred form. | Below is the the instruction that describes the task:
### Input:
Build a checker that suggests the preferred form.
### Response:
def preferred_forms_check(text, list, err, msg, ignore_case=True, offset=0,
max_errors=float("inf")):
"""Build a checker that suggests the preferred form.""... |
def create_logout_response(self, request, bindings=None, status=None,
sign=False, issuer=None, sign_alg=None,
digest_alg=None):
""" Create a LogoutResponse.
:param request: The request this is a response to
:param bindings: Which bin... | Create a LogoutResponse.
:param request: The request this is a response to
:param bindings: Which bindings that can be used for the response
If None the preferred bindings are gathered from the configuration
:param status: The return status of the response operation
If N... | Below is the the instruction that describes the task:
### Input:
Create a LogoutResponse.
:param request: The request this is a response to
:param bindings: Which bindings that can be used for the response
If None the preferred bindings are gathered from the configuration
:param... |
def parse_s3_url(url):
"""Returns an (s3 bucket, key name/prefix) tuple from a url with an s3 scheme
Args:
url (str):
Returns:
tuple: A tuple containing:
str: S3 bucket name
str: S3 key
"""
parsed_url = urlparse(url)
if parsed_url.scheme != "s3":
... | Returns an (s3 bucket, key name/prefix) tuple from a url with an s3 scheme
Args:
url (str):
Returns:
tuple: A tuple containing:
str: S3 bucket name
str: S3 key | Below is the the instruction that describes the task:
### Input:
Returns an (s3 bucket, key name/prefix) tuple from a url with an s3 scheme
Args:
url (str):
Returns:
tuple: A tuple containing:
str: S3 bucket name
str: S3 key
### Response:
def parse_s3_url(url):
... |
def grantxml2json(self, grant_xml):
"""Convert OpenAIRE grant XML into JSON."""
tree = etree.fromstring(grant_xml)
# XML harvested from OAI-PMH has a different format/structure
if tree.prefix == 'oai':
ptree = self.get_subtree(
tree, '/oai:record/oai:metadata/... | Convert OpenAIRE grant XML into JSON. | Below is the the instruction that describes the task:
### Input:
Convert OpenAIRE grant XML into JSON.
### Response:
def grantxml2json(self, grant_xml):
"""Convert OpenAIRE grant XML into JSON."""
tree = etree.fromstring(grant_xml)
# XML harvested from OAI-PMH has a different format/structu... |
def _parse_rs_map_file(rsfile):
"""
Parses rsID mapping file from dbSNP
Outputs dict where keys are coordinates in the format
{chromsome}-{position}
{
chr1-1234: [
{
'type': 'snp'
'rs_id': 'rs1234'
... | Parses rsID mapping file from dbSNP
Outputs dict where keys are coordinates in the format
{chromsome}-{position}
{
chr1-1234: [
{
'type': 'snp'
'rs_id': 'rs1234'
'alleles': 'A/G/T'
}
... | Below is the the instruction that describes the task:
### Input:
Parses rsID mapping file from dbSNP
Outputs dict where keys are coordinates in the format
{chromsome}-{position}
{
chr1-1234: [
{
'type': 'snp'
'rs_id': 'rs12... |
def remove_draft_child(self):
"""Remove the draft child from versioning."""
if self.draft_child:
with db.session.begin_nested():
super(PIDNodeVersioning, self).remove_child(self.draft_child,
reorder=True) | Remove the draft child from versioning. | Below is the the instruction that describes the task:
### Input:
Remove the draft child from versioning.
### Response:
def remove_draft_child(self):
"""Remove the draft child from versioning."""
if self.draft_child:
with db.session.begin_nested():
super(PIDNodeVersioning... |
def translate_identifier(self, identifier, target_namespaces=None, translate_ncbi_namespace=None):
"""Given a string identifier, return a list of aliases (as
identifiers) that refer to the same sequence.
"""
namespace, alias = identifier.split(nsa_sep) if nsa_sep in identifier else (Non... | Given a string identifier, return a list of aliases (as
identifiers) that refer to the same sequence. | Below is the the instruction that describes the task:
### Input:
Given a string identifier, return a list of aliases (as
identifiers) that refer to the same sequence.
### Response:
def translate_identifier(self, identifier, target_namespaces=None, translate_ncbi_namespace=None):
"""Given a string i... |
def get_codec(path):
"""Find the codec implementation for this path."""
if '.' not in path or path.rfind('/') > path.rfind('.'):
return Codec
for endings, codec_class in FILE_ENDINGS:
if any(path.endswith(e) for e in endings):
log.debug('Using {0} codec: {1}'.format(endings, pat... | Find the codec implementation for this path. | Below is the the instruction that describes the task:
### Input:
Find the codec implementation for this path.
### Response:
def get_codec(path):
"""Find the codec implementation for this path."""
if '.' not in path or path.rfind('/') > path.rfind('.'):
return Codec
for endings, codec_class in ... |
def _create_local_udp_tunnel(self):
"""
Creates a local UDP tunnel (pair of 2 NIOs, one for each direction)
:returns: source NIO and destination NIO.
"""
m = PortManager.instance()
lport = m.get_free_udp_port(self.project)
rport = m.get_free_udp_port(self.projec... | Creates a local UDP tunnel (pair of 2 NIOs, one for each direction)
:returns: source NIO and destination NIO. | Below is the the instruction that describes the task:
### Input:
Creates a local UDP tunnel (pair of 2 NIOs, one for each direction)
:returns: source NIO and destination NIO.
### Response:
def _create_local_udp_tunnel(self):
"""
Creates a local UDP tunnel (pair of 2 NIOs, one for each dire... |
def _all_extract_insert_dict(self, item, colnames, additional_info=None):
"""Extracts information from a given item to be stored into a pytable row.
Items can be a variety of things here, trajectories, single runs, group node,
parameters, results.
:param item: Item from which data shou... | Extracts information from a given item to be stored into a pytable row.
Items can be a variety of things here, trajectories, single runs, group node,
parameters, results.
:param item: Item from which data should be extracted
:param colnames: Names of the columns in the pytable
... | Below is the the instruction that describes the task:
### Input:
Extracts information from a given item to be stored into a pytable row.
Items can be a variety of things here, trajectories, single runs, group node,
parameters, results.
:param item: Item from which data should be extracted
... |
def smooth_frames(self, sigtype='physical'):
"""
Convert expanded signals with different samples/frame into
a uniform numpy array.
Input parameters
- sigtype (default='physical'): Specifies whether to mooth
the e_p_signal field ('physical'), or the e_d_signal
... | Convert expanded signals with different samples/frame into
a uniform numpy array.
Input parameters
- sigtype (default='physical'): Specifies whether to mooth
the e_p_signal field ('physical'), or the e_d_signal
field ('digital'). | Below is the the instruction that describes the task:
### Input:
Convert expanded signals with different samples/frame into
a uniform numpy array.
Input parameters
- sigtype (default='physical'): Specifies whether to mooth
the e_p_signal field ('physical'), or the e_d_signal
... |
def receive_message(queue, region, num=1, opts=None, user=None):
'''
Receive one or more messages from a queue in a region
queue
The name of the queue to receive messages from
region
Region where SQS queues exists
num : 1
The max number of messages to receive
opts : N... | Receive one or more messages from a queue in a region
queue
The name of the queue to receive messages from
region
Region where SQS queues exists
num : 1
The max number of messages to receive
opts : None
Any additional options to add to the command line
user : Non... | Below is the the instruction that describes the task:
### Input:
Receive one or more messages from a queue in a region
queue
The name of the queue to receive messages from
region
Region where SQS queues exists
num : 1
The max number of messages to receive
opts : None
... |
def _find_fld_pkt_val(self, pkt, val):
"""Given a Packet instance `pkt` and the value `val` to be set,
returns the Field subclass to be used, and the updated `val` if necessary.
"""
fld = self._iterate_fields_cond(pkt, val, True)
# Default ? (in this case, let's make sure it's up-do-dat... | Given a Packet instance `pkt` and the value `val` to be set,
returns the Field subclass to be used, and the updated `val` if necessary. | Below is the the instruction that describes the task:
### Input:
Given a Packet instance `pkt` and the value `val` to be set,
returns the Field subclass to be used, and the updated `val` if necessary.
### Response:
def _find_fld_pkt_val(self, pkt, val):
"""Given a Packet instance `pkt` and the value `val` ... |
def set_shuffle_on(self):
"""Sets playback to shuffle."""
self.publish(
action='set',
resource='audioPlayback/config',
publish_response=False,
properties={'config': {'shuffleActive': True}}
) | Sets playback to shuffle. | Below is the the instruction that describes the task:
### Input:
Sets playback to shuffle.
### Response:
def set_shuffle_on(self):
"""Sets playback to shuffle."""
self.publish(
action='set',
resource='audioPlayback/config',
publish_response=False,
pro... |
def get_user(self):
"""
Method that gets the authenticated user. The returning user has
the token, email and the provider data.
"""
token = self.authenticator.create_token(self.extra)
user_id = self.extra.get('id')
return FirebaseUser(self.email, token, self.provi... | Method that gets the authenticated user. The returning user has
the token, email and the provider data. | Below is the the instruction that describes the task:
### Input:
Method that gets the authenticated user. The returning user has
the token, email and the provider data.
### Response:
def get_user(self):
"""
Method that gets the authenticated user. The returning user has
the token, e... |
def hit_expire(self, all_hits, hit_ids=None):
''' Expire all HITs. '''
if all_hits:
hits_data = self.get_active_hits()
hit_ids = [hit.options['hitid'] for hit in hits_data]
for hit in hit_ids:
success = self.amt_services.expire_hit(hit)
if success:... | Expire all HITs. | Below is the the instruction that describes the task:
### Input:
Expire all HITs.
### Response:
def hit_expire(self, all_hits, hit_ids=None):
''' Expire all HITs. '''
if all_hits:
hits_data = self.get_active_hits()
hit_ids = [hit.options['hitid'] for hit in hits_data]
... |
def replace_nodes(root, old, new):
'''
Replace the old node with the new one.
Old must be an indirect child of root
:param root: ast node that contains an indirect reference to old
:param old: node to replace
:param new: node to replace `old` with
'''
rep = Replacer(old, new)
... | Replace the old node with the new one.
Old must be an indirect child of root
:param root: ast node that contains an indirect reference to old
:param old: node to replace
:param new: node to replace `old` with | Below is the the instruction that describes the task:
### Input:
Replace the old node with the new one.
Old must be an indirect child of root
:param root: ast node that contains an indirect reference to old
:param old: node to replace
:param new: node to replace `old` with
### Response:
def ... |
def signable(self, request, authheaders, bodyhash=None):
"""Creates the signable string for a request and returns it.
Keyword arguments:
request -- A request object which can be consumed by this API.
authheaders -- A string-indexable object which contains the headers appropriate for thi... | Creates the signable string for a request and returns it.
Keyword arguments:
request -- A request object which can be consumed by this API.
authheaders -- A string-indexable object which contains the headers appropriate for this signature version.
bodyhash -- The hash for the body of th... | Below is the the instruction that describes the task:
### Input:
Creates the signable string for a request and returns it.
Keyword arguments:
request -- A request object which can be consumed by this API.
authheaders -- A string-indexable object which contains the headers appropriate for th... |
def delete_video(self, video_id):
"""
Deletes the video
Authentication is required
Params:
entry: video entry fetch via 'fetch_video()'
Return:
True if successful
Raise:
OperationError: on unsuccessful deletion
"""
#... | Deletes the video
Authentication is required
Params:
entry: video entry fetch via 'fetch_video()'
Return:
True if successful
Raise:
OperationError: on unsuccessful deletion | Below is the the instruction that describes the task:
### Input:
Deletes the video
Authentication is required
Params:
entry: video entry fetch via 'fetch_video()'
Return:
True if successful
Raise:
OperationError: on unsuccessful deletion
### Re... |
def to_file(self, filename):
"""
Write the ANTsImage to file
Args
----
filename : string
filepath to which the image will be written
"""
filename = os.path.expanduser(filename)
libfn = utils.get_lib_fn('toFile%s'%self._libsuffix)
libfn... | Write the ANTsImage to file
Args
----
filename : string
filepath to which the image will be written | Below is the the instruction that describes the task:
### Input:
Write the ANTsImage to file
Args
----
filename : string
filepath to which the image will be written
### Response:
def to_file(self, filename):
"""
Write the ANTsImage to file
Args
... |
def add_download_total(rows):
"""Add a final row to rows showing the total downloads"""
total_row = [""] * len(rows[0])
total_row[0] = "Total"
total_downloads, downloads_column = get_download_total(rows)
total_row[downloads_column] = str(total_downloads)
rows.append(total_row)
return rows | Add a final row to rows showing the total downloads | Below is the the instruction that describes the task:
### Input:
Add a final row to rows showing the total downloads
### Response:
def add_download_total(rows):
"""Add a final row to rows showing the total downloads"""
total_row = [""] * len(rows[0])
total_row[0] = "Total"
total_downloads, download... |
def init_argparser(self, argparser):
"""
This should not be called with an external argparser as it will
corrupt tracking data if forced.
"""
def prepare_argparser():
if argparser in self.argparser_details:
return False
result = self.argpa... | This should not be called with an external argparser as it will
corrupt tracking data if forced. | Below is the the instruction that describes the task:
### Input:
This should not be called with an external argparser as it will
corrupt tracking data if forced.
### Response:
def init_argparser(self, argparser):
"""
This should not be called with an external argparser as it will
co... |
def Popup(*args, **_3to2kwargs):
if 'location' in _3to2kwargs: location = _3to2kwargs['location']; del _3to2kwargs['location']
else: location = (None, None)
if 'keep_on_top' in _3to2kwargs: keep_on_top = _3to2kwargs['keep_on_top']; del _3to2kwargs['keep_on_top']
else: keep_on_top = False
if 'grab_an... | Popup - Display a popup box with as many parms as you wish to include
:param args:
:param button_color:
:param background_color:
:param text_color:
:param button_type:
:param auto_close:
:param auto_close_duration:
:param non_blocking:
:param icon:
:param line_width:
:param f... | Below is the the instruction that describes the task:
### Input:
Popup - Display a popup box with as many parms as you wish to include
:param args:
:param button_color:
:param background_color:
:param text_color:
:param button_type:
:param auto_close:
:param auto_close_duration:
:par... |
def selected_option(self):
" Return the currently selected option. "
i = 0
for category in self.options:
for o in category.options:
if i == self.selected_option_index:
return o
else:
i += 1 | Return the currently selected option. | Below is the the instruction that describes the task:
### Input:
Return the currently selected option.
### Response:
def selected_option(self):
" Return the currently selected option. "
i = 0
for category in self.options:
for o in category.options:
if i == self.s... |
def on_enter_fit_name(self, event):
"""
Allows the entering of new fit names in the fit combobox
Parameters
----------
event : the wx.ComboBoxEvent that triggers this function
Alters
------
current_fit.name
"""
if self.current_fit == None... | Allows the entering of new fit names in the fit combobox
Parameters
----------
event : the wx.ComboBoxEvent that triggers this function
Alters
------
current_fit.name | Below is the the instruction that describes the task:
### Input:
Allows the entering of new fit names in the fit combobox
Parameters
----------
event : the wx.ComboBoxEvent that triggers this function
Alters
------
current_fit.name
### Response:
def on_enter_fit_na... |
def _add_cpu_percent(self, cur_read):
"""Compute cpu percent basing on the provided utilisation
"""
for executor_id, cur_data in cur_read.items():
stats = cur_data['statistics']
cpus_limit = stats.get('cpus_limit')
cpus_utilisation = stats.get('cpus_utilisatio... | Compute cpu percent basing on the provided utilisation | Below is the the instruction that describes the task:
### Input:
Compute cpu percent basing on the provided utilisation
### Response:
def _add_cpu_percent(self, cur_read):
"""Compute cpu percent basing on the provided utilisation
"""
for executor_id, cur_data in cur_read.items():
... |
def update_group(self, ID, data):
"""Update a Group."""
# http://teampasswordmanager.com/docs/api-groups/#update_group
log.info('Update group %s with %s' % (ID, data))
self.put('groups/%s.json' % ID, data) | Update a Group. | Below is the the instruction that describes the task:
### Input:
Update a Group.
### Response:
def update_group(self, ID, data):
"""Update a Group."""
# http://teampasswordmanager.com/docs/api-groups/#update_group
log.info('Update group %s with %s' % (ID, data))
self.put('groups/%s.... |
def splitread(args):
"""
%prog splitread fastqfile
Split fastqfile into two read fastqfiles, cut in the middle.
"""
p = OptionParser(splitread.__doc__)
p.add_option("-n", dest="n", default=76, type="int",
help="Split at N-th base position [default: %default]")
p.add_option("--rc... | %prog splitread fastqfile
Split fastqfile into two read fastqfiles, cut in the middle. | Below is the the instruction that describes the task:
### Input:
%prog splitread fastqfile
Split fastqfile into two read fastqfiles, cut in the middle.
### Response:
def splitread(args):
"""
%prog splitread fastqfile
Split fastqfile into two read fastqfiles, cut in the middle.
"""
p = Opt... |
def extract_number_oscillations(self, index, amplitude_threshold):
"""!
@brief Extracts number of oscillations of specified oscillator.
@param[in] index (uint): Index of oscillator whose dynamic is considered.
@param[in] amplitude_threshold (double): Amplitude threshold whe... | !
@brief Extracts number of oscillations of specified oscillator.
@param[in] index (uint): Index of oscillator whose dynamic is considered.
@param[in] amplitude_threshold (double): Amplitude threshold when oscillation is taken into account, for example,
when osc... | Below is the the instruction that describes the task:
### Input:
!
@brief Extracts number of oscillations of specified oscillator.
@param[in] index (uint): Index of oscillator whose dynamic is considered.
@param[in] amplitude_threshold (double): Amplitude threshold when oscillat... |
def handle_error(
self,
error: ValidationError,
req: Request,
schema: Schema,
error_status_code: typing.Union[int, None] = None,
error_headers: typing.Union[typing.Mapping[str, str], None] = None,
) -> "typing.NoReturn":
"""Handle ValidationErrors and return a... | Handle ValidationErrors and return a JSON response of error messages
to the client. | Below is the the instruction that describes the task:
### Input:
Handle ValidationErrors and return a JSON response of error messages
to the client.
### Response:
def handle_error(
self,
error: ValidationError,
req: Request,
schema: Schema,
error_status_code: typing.... |
def __receiver(self):
"""Receive-loop."""
# If we're ignoring the quit, the connections will have to be closed
# by the server.
while (self.__ignore_quit is True or \
self.__nice_quit_ev.is_set() is False) and \
self.__force_quit_ev.is_set() is False:
# TO... | Receive-loop. | Below is the the instruction that describes the task:
### Input:
Receive-loop.
### Response:
def __receiver(self):
"""Receive-loop."""
# If we're ignoring the quit, the connections will have to be closed
# by the server.
while (self.__ignore_quit is True or \
self._... |
def get_tx_out(self, tx_hash, index, **kwargs):
""" Returns the transaction output information corresponding to a hash and index.
:param tx_hash: transaction hash
:param index:
index of the transaction output to be obtained in the transaction (starts from 0)
:type tx_hash: s... | Returns the transaction output information corresponding to a hash and index.
:param tx_hash: transaction hash
:param index:
index of the transaction output to be obtained in the transaction (starts from 0)
:type tx_hash: str
:type index: int
:return: dictionary cont... | Below is the the instruction that describes the task:
### Input:
Returns the transaction output information corresponding to a hash and index.
:param tx_hash: transaction hash
:param index:
index of the transaction output to be obtained in the transaction (starts from 0)
:type t... |
def installUpdate(self):
""" Install the newest version of Plex Media Server. """
# We can add this but dunno how useful this is since it sometimes
# requires user action using a gui.
part = '/updater/apply'
release = self.check_for_update(force=True, download=True)
if re... | Install the newest version of Plex Media Server. | Below is the the instruction that describes the task:
### Input:
Install the newest version of Plex Media Server.
### Response:
def installUpdate(self):
""" Install the newest version of Plex Media Server. """
# We can add this but dunno how useful this is since it sometimes
# requires user... |
def createFinalTPEDandTFAM(tped, toReadPrefix, prefix, snpToRemove):
"""Creates the final TPED and TFAM.
:param tped: a representation of the ``tped`` of duplicated markers.
:param toReadPrefix: the prefix of the unique files.
:param prefix: the prefix of the output files.
:param snpToRemove: the m... | Creates the final TPED and TFAM.
:param tped: a representation of the ``tped`` of duplicated markers.
:param toReadPrefix: the prefix of the unique files.
:param prefix: the prefix of the output files.
:param snpToRemove: the markers to remove.
:type tped: numpy.array
:type toReadPrefix: str
... | Below is the the instruction that describes the task:
### Input:
Creates the final TPED and TFAM.
:param tped: a representation of the ``tped`` of duplicated markers.
:param toReadPrefix: the prefix of the unique files.
:param prefix: the prefix of the output files.
:param snpToRemove: the markers ... |
def rcfile(appname, args={}, strip_dashes=True, module_name=None):
"""
Read environment variables and config files and return them merged with predefined list of arguments.
Arguments:
appname - application name, used for config files and environemnt variable names.
args - ar... | Read environment variables and config files and return them merged with predefined list of arguments.
Arguments:
appname - application name, used for config files and environemnt variable names.
args - arguments from command line (optparse, docopt, etc).
strip_dashes - strip... | Below is the the instruction that describes the task:
### Input:
Read environment variables and config files and return them merged with predefined list of arguments.
Arguments:
appname - application name, used for config files and environemnt variable names.
args - arguments from c... |
def create_iam(self):
"""Create IAM resources."""
utils.banner("Creating IAM")
iam.create_iam_resources(env=self.env, app=self.app) | Create IAM resources. | Below is the the instruction that describes the task:
### Input:
Create IAM resources.
### Response:
def create_iam(self):
"""Create IAM resources."""
utils.banner("Creating IAM")
iam.create_iam_resources(env=self.env, app=self.app) |
def get_default_project_directory():
"""
Return the default location for the project directory
depending of the operating system
"""
server_config = Config.instance().get_section_config("Server")
path = os.path.expanduser(server_config.get("projects_path", "~/GNS3/projects"))
path = os.path... | Return the default location for the project directory
depending of the operating system | Below is the the instruction that describes the task:
### Input:
Return the default location for the project directory
depending of the operating system
### Response:
def get_default_project_directory():
"""
Return the default location for the project directory
depending of the operating system
... |
def word_tokenize(text):
"""
Split string `text` into word tokens using the Penn Treebank rules
"""
for (regexp, replacement) in RULES1:
text = sub(regexp, replacement, text)
# add extra space to make things easier
text = " " + text + " "
for (regexp, replacement) in RULES2:
... | Split string `text` into word tokens using the Penn Treebank rules | Below is the the instruction that describes the task:
### Input:
Split string `text` into word tokens using the Penn Treebank rules
### Response:
def word_tokenize(text):
"""
Split string `text` into word tokens using the Penn Treebank rules
"""
for (regexp, replacement) in RULES1:
text = s... |
def get(self):
""" get method """
try:
cluster = self.get_argument_cluster()
role = self.get_argument_role()
environ = self.get_argument_environ()
topology_name = self.get_argument_topology()
component = self.get_argument_component()
metric_names = self.get_required_arguments... | get method | Below is the the instruction that describes the task:
### Input:
get method
### Response:
def get(self):
""" get method """
try:
cluster = self.get_argument_cluster()
role = self.get_argument_role()
environ = self.get_argument_environ()
topology_name = self.get_argument_topology()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.