code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def percentAt(self, value):
"""
Returns the percentage where the given value lies between this rulers
minimum and maximum values. If the value equals the minimum, then the
percent is 0, if it equals the maximum, then the percent is 1 - any
value between will be a floating p... | Returns the percentage where the given value lies between this rulers
minimum and maximum values. If the value equals the minimum, then the
percent is 0, if it equals the maximum, then the percent is 1 - any
value between will be a floating point. If the ruler is a custom type,
the... | Below is the the instruction that describes the task:
### Input:
Returns the percentage where the given value lies between this rulers
minimum and maximum values. If the value equals the minimum, then the
percent is 0, if it equals the maximum, then the percent is 1 - any
value between w... |
def check_w3_errors (url_data, xml, w3type):
"""Add warnings for W3C HTML or CSS errors in xml format.
w3type is either "W3C HTML" or "W3C CSS"."""
dom = parseString(xml)
for error in dom.getElementsByTagName('m:error'):
warnmsg = _("%(w3type)s validation error at line %(line)s col %(column)s: %... | Add warnings for W3C HTML or CSS errors in xml format.
w3type is either "W3C HTML" or "W3C CSS". | Below is the the instruction that describes the task:
### Input:
Add warnings for W3C HTML or CSS errors in xml format.
w3type is either "W3C HTML" or "W3C CSS".
### Response:
def check_w3_errors (url_data, xml, w3type):
"""Add warnings for W3C HTML or CSS errors in xml format.
w3type is either "W3C HT... |
def partition(lst, n):
"""
Divide list into n equal parts
"""
q, r = divmod(len(lst), n)
indices = [q*i + min(i, r) for i in xrange(n+1)]
return [lst[indices[i]:indices[i+1]] for i in xrange(n)], \
[list(xrange(indices[i], indices[i+1])) for i in xrange(n)] | Divide list into n equal parts | Below is the the instruction that describes the task:
### Input:
Divide list into n equal parts
### Response:
def partition(lst, n):
"""
Divide list into n equal parts
"""
q, r = divmod(len(lst), n)
indices = [q*i + min(i, r) for i in xrange(n+1)]
return [lst[indices[i]:indices[i+1]] fo... |
def delete(self, ids):
"""
Method to delete network-ipv4's by their ids
:param ids: Identifiers of network-ipv4's
:return: None
"""
url = build_uri_with_ids('api/v3/networkv4/%s/', ids)
return super(ApiNetworkIPv4, self).delete(url) | Method to delete network-ipv4's by their ids
:param ids: Identifiers of network-ipv4's
:return: None | Below is the the instruction that describes the task:
### Input:
Method to delete network-ipv4's by their ids
:param ids: Identifiers of network-ipv4's
:return: None
### Response:
def delete(self, ids):
"""
Method to delete network-ipv4's by their ids
:param ids: Identifie... |
def mark_parent_tasks_as_failed(self, task_name, flush_logs=False):
"""
Marks all the parent tasks as failed
Args:
task_name (str): Name of the child task
flush_logs (bool): If ``True`` will discard all the logs form
parent tasks
Returns:
... | Marks all the parent tasks as failed
Args:
task_name (str): Name of the child task
flush_logs (bool): If ``True`` will discard all the logs form
parent tasks
Returns:
None | Below is the the instruction that describes the task:
### Input:
Marks all the parent tasks as failed
Args:
task_name (str): Name of the child task
flush_logs (bool): If ``True`` will discard all the logs form
parent tasks
Returns:
None
### Respo... |
def policy_and_value_net(rng_key,
batch_observations_shape,
num_actions,
bottom_layers=None):
"""A policy and value net function."""
# Layers.
cur_layers = []
if bottom_layers is not None:
cur_layers.extend(bottom_layers)
# Now, ... | A policy and value net function. | Below is the the instruction that describes the task:
### Input:
A policy and value net function.
### Response:
def policy_and_value_net(rng_key,
batch_observations_shape,
num_actions,
bottom_layers=None):
"""A policy and value net functi... |
def update_path(self, board, color, path):
""" update win/loss count along path """
wins = board.score(BLACK) >= board.score(WHITE)
for node in path:
if color == BLACK:
color = WHITE
else:
color = BLACK
if wins == (color == BLAC... | update win/loss count along path | Below is the the instruction that describes the task:
### Input:
update win/loss count along path
### Response:
def update_path(self, board, color, path):
""" update win/loss count along path """
wins = board.score(BLACK) >= board.score(WHITE)
for node in path:
if color == BLACK... |
def _ConvertAnyMessage(self, value, message):
"""Convert a JSON representation into Any message."""
if isinstance(value, dict) and not value:
return
try:
type_url = value['@type']
except KeyError:
raise ParseError('@type is missing when parsing any message.')
sub_message = _Create... | Convert a JSON representation into Any message. | Below is the the instruction that describes the task:
### Input:
Convert a JSON representation into Any message.
### Response:
def _ConvertAnyMessage(self, value, message):
"""Convert a JSON representation into Any message."""
if isinstance(value, dict) and not value:
return
try:
type_url =... |
def _get_fields_by_mro(klass, field_class, ordered=False):
"""Collect fields from a class, following its method resolution order. The
class itself is excluded from the search; only its parents are checked. Get
fields from ``_declared_fields`` if available, else use ``__dict__``.
:param type klass: Clas... | Collect fields from a class, following its method resolution order. The
class itself is excluded from the search; only its parents are checked. Get
fields from ``_declared_fields`` if available, else use ``__dict__``.
:param type klass: Class whose fields to retrieve
:param type field_class: Base field... | Below is the the instruction that describes the task:
### Input:
Collect fields from a class, following its method resolution order. The
class itself is excluded from the search; only its parents are checked. Get
fields from ``_declared_fields`` if available, else use ``__dict__``.
:param type klass: C... |
def step(self, action):
"""Forward action to the wrapped environment.
Args:
action: Action to apply to the environment.
Raises:
ValueError: Invalid action.
Returns:
Converted observation, converted reward, done flag, and info object.
"""
observ, reward, done, info = self._en... | Forward action to the wrapped environment.
Args:
action: Action to apply to the environment.
Raises:
ValueError: Invalid action.
Returns:
Converted observation, converted reward, done flag, and info object. | Below is the the instruction that describes the task:
### Input:
Forward action to the wrapped environment.
Args:
action: Action to apply to the environment.
Raises:
ValueError: Invalid action.
Returns:
Converted observation, converted reward, done flag, and info object.
### Respons... |
def get_help(self):
"""
Gets the help text for the command. If its not supplied the doc string is used.
"""
if self.help:
return self.help
elif self.__doc__ and self.__doc__.strip():
return self.__doc__.strip()
else:
return '' | Gets the help text for the command. If its not supplied the doc string is used. | Below is the the instruction that describes the task:
### Input:
Gets the help text for the command. If its not supplied the doc string is used.
### Response:
def get_help(self):
"""
Gets the help text for the command. If its not supplied the doc string is used.
"""
if self.help:
... |
def get_canonical_key(self, key_type, key_id):
"""
get_canonical_key returns the canonical form of a key given a key id.
For example, '12345' maps to shard 6. The canonical key at index 6
(say '12') is the canonical key id given the key id of '12345'. This
is useful for sets that... | get_canonical_key returns the canonical form of a key given a key id.
For example, '12345' maps to shard 6. The canonical key at index 6
(say '12') is the canonical key id given the key id of '12345'. This
is useful for sets that need to exist on all shards. See
compute_canonical_key_ids... | Below is the the instruction that describes the task:
### Input:
get_canonical_key returns the canonical form of a key given a key id.
For example, '12345' maps to shard 6. The canonical key at index 6
(say '12') is the canonical key id given the key id of '12345'. This
is useful for sets th... |
def hexblock_cb(cls, callback, data, address = None,
bits = None,
width = 16,
cb_args = (),
... | Dump a block of binary data using a callback function to convert each
line of text.
@type callback: function
@param callback: Callback function to convert each line of data.
@type data: str
@param data: Binary data.
@type address: str
@param address:
... | Below is the the instruction that describes the task:
### Input:
Dump a block of binary data using a callback function to convert each
line of text.
@type callback: function
@param callback: Callback function to convert each line of data.
@type data: str
@param data: Bina... |
def loadrecords(sources, source_type, recid):
"""Load records migration dump."""
# Load all record dumps up-front and find the specific JSON
if recid is not None:
for source in sources:
records = json.load(source)
for item in records:
if str(item['recid']) == ... | Load records migration dump. | Below is the the instruction that describes the task:
### Input:
Load records migration dump.
### Response:
def loadrecords(sources, source_type, recid):
"""Load records migration dump."""
# Load all record dumps up-front and find the specific JSON
if recid is not None:
for source in sources:
... |
def item_link(self, item):
""" Generates a link for a specific item of the feed. """
return reverse_lazy(
'forum_conversation:topic',
kwargs={
'forum_slug': item.forum.slug,
'forum_pk': item.forum.pk,
'slug': item.slug,
... | Generates a link for a specific item of the feed. | Below is the the instruction that describes the task:
### Input:
Generates a link for a specific item of the feed.
### Response:
def item_link(self, item):
""" Generates a link for a specific item of the feed. """
return reverse_lazy(
'forum_conversation:topic',
kwargs={
... |
def get_or_create_ap_election_meta(self, row, election):
"""
Gets or creates the APElectionMeta object for the given row of
AP data.
"""
APElectionMeta.objects.get_or_create(
ap_election_id=row["raceid"], election=election
) | Gets or creates the APElectionMeta object for the given row of
AP data. | Below is the the instruction that describes the task:
### Input:
Gets or creates the APElectionMeta object for the given row of
AP data.
### Response:
def get_or_create_ap_election_meta(self, row, election):
"""
Gets or creates the APElectionMeta object for the given row of
AP data.... |
def move(self, dest, isabspath=False):
"""
Recursively move self.workdir to another location. This is similar to the Unix "mv" command.
The destination path must not already exist. If the destination already exists
but is not a directory, it may be overwritten depending on os.rename() se... | Recursively move self.workdir to another location. This is similar to the Unix "mv" command.
The destination path must not already exist. If the destination already exists
but is not a directory, it may be overwritten depending on os.rename() semantics.
Be default, dest is located in the parent... | Below is the the instruction that describes the task:
### Input:
Recursively move self.workdir to another location. This is similar to the Unix "mv" command.
The destination path must not already exist. If the destination already exists
but is not a directory, it may be overwritten depending on os.r... |
def check_xups_bat_capacity(the_session, the_helper, the_snmp_value):
"""
OID .1.3.6.1.4.1.534.1.2.4.0
MIB Excerpt
Battery percent charge.
"""
the_helper.add_metric(
label=the_helper.options.type,
value=a_snmp_value,
uom='%')
the_helper.set_summary("Remaining Batter... | OID .1.3.6.1.4.1.534.1.2.4.0
MIB Excerpt
Battery percent charge. | Below is the the instruction that describes the task:
### Input:
OID .1.3.6.1.4.1.534.1.2.4.0
MIB Excerpt
Battery percent charge.
### Response:
def check_xups_bat_capacity(the_session, the_helper, the_snmp_value):
"""
OID .1.3.6.1.4.1.534.1.2.4.0
MIB Excerpt
Battery percent charge.
"""
... |
def is_timeout(self):
'''
Check if the lapse between initialization and now is more than ``self.timeout``.
'''
lapse = datetime.datetime.now() - self.init_time
return lapse > datetime.timedelta(seconds=self.timeout) | Check if the lapse between initialization and now is more than ``self.timeout``. | Below is the the instruction that describes the task:
### Input:
Check if the lapse between initialization and now is more than ``self.timeout``.
### Response:
def is_timeout(self):
'''
Check if the lapse between initialization and now is more than ``self.timeout``.
'''
lapse = date... |
def get_conda_env_data(mgr):
"""Finds kernel specs from conda environments
env_data is a structure {name -> (resourcedir, kernel spec)}
"""
if not mgr.find_conda_envs:
return {}
mgr.log.debug("Looking for conda environments in %s...", mgr.conda_env_dirs)
# find all potential env paths... | Finds kernel specs from conda environments
env_data is a structure {name -> (resourcedir, kernel spec)} | Below is the the instruction that describes the task:
### Input:
Finds kernel specs from conda environments
env_data is a structure {name -> (resourcedir, kernel spec)}
### Response:
def get_conda_env_data(mgr):
"""Finds kernel specs from conda environments
env_data is a structure {name -> (resourced... |
def scale_rows_by_largest_entry(S):
"""Scale each row in S by it's largest in magnitude entry.
Parameters
----------
S : csr_matrix
Returns
-------
S : csr_matrix
Each row has been scaled by it's largest in magnitude entry
Examples
--------
>>> from pyamg.gallery impor... | Scale each row in S by it's largest in magnitude entry.
Parameters
----------
S : csr_matrix
Returns
-------
S : csr_matrix
Each row has been scaled by it's largest in magnitude entry
Examples
--------
>>> from pyamg.gallery import poisson
>>> from pyamg.util.utils imp... | Below is the the instruction that describes the task:
### Input:
Scale each row in S by it's largest in magnitude entry.
Parameters
----------
S : csr_matrix
Returns
-------
S : csr_matrix
Each row has been scaled by it's largest in magnitude entry
Examples
--------
>>... |
def mavlink_packet(self, m):
"""handle an incoming mavlink packet"""
mtype = m.get_type()
if mtype == 'GPS_RAW':
(self.lat, self.lon) = (m.lat, m.lon)
elif mtype == 'GPS_RAW_INT':
(self.lat, self.lon) = (m.lat / 1.0e7, m.lon / 1.0e7)
elif mtype == "VFR_HUD... | handle an incoming mavlink packet | Below is the the instruction that describes the task:
### Input:
handle an incoming mavlink packet
### Response:
def mavlink_packet(self, m):
"""handle an incoming mavlink packet"""
mtype = m.get_type()
if mtype == 'GPS_RAW':
(self.lat, self.lon) = (m.lat, m.lon)
elif mt... |
def _write_attributes(self, attributes_dict, **args):
"""write graph, node or edge attributes
"""
for key, value in args.items():
try:
_type = attributes_dict[key]
except KeyError:
raise Exception(
"""no such attribute %... | write graph, node or edge attributes | Below is the the instruction that describes the task:
### Input:
write graph, node or edge attributes
### Response:
def _write_attributes(self, attributes_dict, **args):
"""write graph, node or edge attributes
"""
for key, value in args.items():
try:
_type = attr... |
def get_prepared_include_exclude(attributes):
"""Return tuple with prepared __include__ and __exclude__ attributes.
:type attributes: dict
:rtype: tuple
"""
attrs = dict()
for attr in ('__include__', '__exclude__'):
attrs[attr] = tuple([item.name for item in
... | Return tuple with prepared __include__ and __exclude__ attributes.
:type attributes: dict
:rtype: tuple | Below is the the instruction that describes the task:
### Input:
Return tuple with prepared __include__ and __exclude__ attributes.
:type attributes: dict
:rtype: tuple
### Response:
def get_prepared_include_exclude(attributes):
"""Return tuple with prepared __include__ and __exclude__ att... |
def mount_share(share_path):
"""Mounts a share at /Volumes
Args:
share_path: String URL with all auth info to connect to file share.
Returns:
The mount point or raises an error.
"""
sh_url = CFURLCreateWithString(None, share_path, None)
# Set UI to reduced interaction
open_... | Mounts a share at /Volumes
Args:
share_path: String URL with all auth info to connect to file share.
Returns:
The mount point or raises an error. | Below is the the instruction that describes the task:
### Input:
Mounts a share at /Volumes
Args:
share_path: String URL with all auth info to connect to file share.
Returns:
The mount point or raises an error.
### Response:
def mount_share(share_path):
"""Mounts a share at /Volumes
... |
def _path_components(self, path):
"""Breaks the path into a list of component names.
Does not include the root directory as a component, as all paths
are considered relative to the root directory for the FakeFilesystem.
Callers should basically follow this pattern:
.. code:: py... | Breaks the path into a list of component names.
Does not include the root directory as a component, as all paths
are considered relative to the root directory for the FakeFilesystem.
Callers should basically follow this pattern:
.. code:: python
file_path = self.absnormpat... | Below is the the instruction that describes the task:
### Input:
Breaks the path into a list of component names.
Does not include the root directory as a component, as all paths
are considered relative to the root directory for the FakeFilesystem.
Callers should basically follow this patter... |
def start_flask_service(self):
"""Define Flask parameter server service.
This HTTP server can do two things: get the current model
parameters and update model parameters. After registering
the `parameters` and `update` routes, the service will
get started.
"""
a... | Define Flask parameter server service.
This HTTP server can do two things: get the current model
parameters and update model parameters. After registering
the `parameters` and `update` routes, the service will
get started. | Below is the the instruction that describes the task:
### Input:
Define Flask parameter server service.
This HTTP server can do two things: get the current model
parameters and update model parameters. After registering
the `parameters` and `update` routes, the service will
get star... |
def getInterfaceAddresses(self, node, interface):
'''
Return the Ethernet and IP+mask addresses assigned to a
given interface on a node.
'''
intf = self.getNode(node)['nodeobj'].getInterface(interface)
return intf.ethaddr,intf.ipaddr,intf.netmask | Return the Ethernet and IP+mask addresses assigned to a
given interface on a node. | Below is the the instruction that describes the task:
### Input:
Return the Ethernet and IP+mask addresses assigned to a
given interface on a node.
### Response:
def getInterfaceAddresses(self, node, interface):
'''
Return the Ethernet and IP+mask addresses assigned to a
given inter... |
def adaptive_card(card: dict) -> Attachment:
"""
Returns an attachment for an adaptive card. The attachment will contain the card and the
appropriate 'contentType'. Will raise a TypeError if the 'card' argument is not an
dict.
:param card:
:return:
"""
if ... | Returns an attachment for an adaptive card. The attachment will contain the card and the
appropriate 'contentType'. Will raise a TypeError if the 'card' argument is not an
dict.
:param card:
:return: | Below is the the instruction that describes the task:
### Input:
Returns an attachment for an adaptive card. The attachment will contain the card and the
appropriate 'contentType'. Will raise a TypeError if the 'card' argument is not an
dict.
:param card:
:return:
### Response:
def ... |
def apply_filters(df, filters):
"""Basic filtering for a dataframe."""
idx = pd.Series([True]*df.shape[0])
for k, v in list(filters.items()):
if k not in df.columns:
continue
idx &= (df[k] == v)
return df.loc[idx] | Basic filtering for a dataframe. | Below is the the instruction that describes the task:
### Input:
Basic filtering for a dataframe.
### Response:
def apply_filters(df, filters):
"""Basic filtering for a dataframe."""
idx = pd.Series([True]*df.shape[0])
for k, v in list(filters.items()):
if k not in df.columns:
... |
def generate_form(model, only=None, meta=None):
"""
Generate WTForm based on SQLAlchemy table
:param model: SQLAlchemy sa.Table
:param only: list or set of columns that should be used in final form
:param meta: Meta class with settings for form
:return: WTForm object
"""
fields = Ordered... | Generate WTForm based on SQLAlchemy table
:param model: SQLAlchemy sa.Table
:param only: list or set of columns that should be used in final form
:param meta: Meta class with settings for form
:return: WTForm object | Below is the the instruction that describes the task:
### Input:
Generate WTForm based on SQLAlchemy table
:param model: SQLAlchemy sa.Table
:param only: list or set of columns that should be used in final form
:param meta: Meta class with settings for form
:return: WTForm object
### Response:
def ... |
def list_clients(self, instance=None):
"""
Lists the clients.
:param Optional[str] instance: A Yamcs instance name.
:rtype: ~collections.Iterable[yamcs.model.Client]
"""
# Server does not do pagination on listings of this resource.
# Return an iterator anyway for... | Lists the clients.
:param Optional[str] instance: A Yamcs instance name.
:rtype: ~collections.Iterable[yamcs.model.Client] | Below is the the instruction that describes the task:
### Input:
Lists the clients.
:param Optional[str] instance: A Yamcs instance name.
:rtype: ~collections.Iterable[yamcs.model.Client]
### Response:
def list_clients(self, instance=None):
"""
Lists the clients.
:param Op... |
def _find_element(self, selector, selector_type, check_displayed=False):
"""
Return first matching displayed element of non-zero size
or None if nothing found
"""
if selector_type == 'css':
elements = self.driver.find_elements_by_css_selector(selector)
elif se... | Return first matching displayed element of non-zero size
or None if nothing found | Below is the the instruction that describes the task:
### Input:
Return first matching displayed element of non-zero size
or None if nothing found
### Response:
def _find_element(self, selector, selector_type, check_displayed=False):
"""
Return first matching displayed element of non-zero s... |
def get_a(name=None, ipv4addr=None, allow_array=True, **api_opts):
'''
Get A record
CLI Examples:
.. code-block:: bash
salt-call infoblox.get_a name=abc.example.com
salt-call infoblox.get_a ipv4addr=192.168.3.5
'''
data = {}
if name:
data['name'] = name
if ipv4... | Get A record
CLI Examples:
.. code-block:: bash
salt-call infoblox.get_a name=abc.example.com
salt-call infoblox.get_a ipv4addr=192.168.3.5 | Below is the the instruction that describes the task:
### Input:
Get A record
CLI Examples:
.. code-block:: bash
salt-call infoblox.get_a name=abc.example.com
salt-call infoblox.get_a ipv4addr=192.168.3.5
### Response:
def get_a(name=None, ipv4addr=None, allow_array=True, **api_opts):
... |
def unregister(self, model):
"""
Unregister a permission handler from the model
Parameters
----------
model : django model class
A django model class
Raises
------
KeyError
Raise when the model have not registered in registry yet.... | Unregister a permission handler from the model
Parameters
----------
model : django model class
A django model class
Raises
------
KeyError
Raise when the model have not registered in registry yet. | Below is the the instruction that describes the task:
### Input:
Unregister a permission handler from the model
Parameters
----------
model : django model class
A django model class
Raises
------
KeyError
Raise when the model have not registe... |
def run(program, *args, **kwargs):
"""Run 'program' with 'args'"""
args = flattened(args, split=SHELL)
full_path = which(program)
logger = kwargs.pop("logger", LOG.debug)
fatal = kwargs.pop("fatal", True)
dryrun = kwargs.pop("dryrun", is_dryrun())
include_error = kwargs.pop("include_error",... | Run 'program' with 'args | Below is the the instruction that describes the task:
### Input:
Run 'program' with 'args
### Response:
def run(program, *args, **kwargs):
"""Run 'program' with 'args'"""
args = flattened(args, split=SHELL)
full_path = which(program)
logger = kwargs.pop("logger", LOG.debug)
fatal = kwargs.pop(... |
def rewrite_links(self, link_repl_func, resolve_base_href=True,
base_href=None):
"""
Rewrite all the links in the document. For each link
``link_repl_func(link)`` will be called, and the return value
will replace the old link.
Note that links may not be ab... | Rewrite all the links in the document. For each link
``link_repl_func(link)`` will be called, and the return value
will replace the old link.
Note that links may not be absolute (unless you first called
``make_links_absolute()``), and may be internal (e.g.,
``'#anchor'``). The... | Below is the the instruction that describes the task:
### Input:
Rewrite all the links in the document. For each link
``link_repl_func(link)`` will be called, and the return value
will replace the old link.
Note that links may not be absolute (unless you first called
``make_links_a... |
def insert(self, loc, column, value):
"""Insert new column data.
Args:
loc: Insertion index.
column: Column labels to insert.
value: Dtype object values to insert.
Returns:
A new PandasQueryCompiler with new data inserted.
"""
if ... | Insert new column data.
Args:
loc: Insertion index.
column: Column labels to insert.
value: Dtype object values to insert.
Returns:
A new PandasQueryCompiler with new data inserted. | Below is the the instruction that describes the task:
### Input:
Insert new column data.
Args:
loc: Insertion index.
column: Column labels to insert.
value: Dtype object values to insert.
Returns:
A new PandasQueryCompiler with new data inserted.
###... |
def labels(self):
"""Named entity labels."""
if not self.is_tagged(LABEL):
self.tag_labels()
return [word[LABEL] for word in self.words] | Named entity labels. | Below is the the instruction that describes the task:
### Input:
Named entity labels.
### Response:
def labels(self):
"""Named entity labels."""
if not self.is_tagged(LABEL):
self.tag_labels()
return [word[LABEL] for word in self.words] |
def rotateX(self, angle, axis_point=(0, 0, 0), rad=False):
"""Rotate around x-axis. If angle is in radians set ``rad=True``."""
if rad:
angle *= 57.29578
self.RotateX(angle)
if self.trail:
self.updateTrail()
return self | Rotate around x-axis. If angle is in radians set ``rad=True``. | Below is the the instruction that describes the task:
### Input:
Rotate around x-axis. If angle is in radians set ``rad=True``.
### Response:
def rotateX(self, angle, axis_point=(0, 0, 0), rad=False):
"""Rotate around x-axis. If angle is in radians set ``rad=True``."""
if rad:
angle *= ... |
def parse_reports(self,
log_key='picard/markdups',
section_name='Mark Duplicates',
section_anchor='picard-markduplicates',
plot_title='Picard: Deduplication Stats',
plot_id='picard_deduplication',
data_filename='multiqc_picard_dups'):
""" Find Picard MarkDuplicates reports and parse their da... | Find Picard MarkDuplicates reports and parse their dataself.
This function is also used by the biobambam2 module, hence the parameters. | Below is the the instruction that describes the task:
### Input:
Find Picard MarkDuplicates reports and parse their dataself.
This function is also used by the biobambam2 module, hence the parameters.
### Response:
def parse_reports(self,
log_key='picard/markdups',
section_name='Mark Duplicates',
s... |
def _get_query(self, cursor):
'''
Query tempalte for source Solr, sorts by id by default.
'''
query = {'q':'*:*',
'sort':'id desc',
'rows':self._rows,
'cursorMark':cursor}
if self._date_field:
query['sort'] = "{... | Query tempalte for source Solr, sorts by id by default. | Below is the the instruction that describes the task:
### Input:
Query tempalte for source Solr, sorts by id by default.
### Response:
def _get_query(self, cursor):
'''
Query tempalte for source Solr, sorts by id by default.
'''
query = {'q':'*:*',
'sort':'id de... |
def find_ge_index(self, k):
'Return first item with a key >= equal to k. Raise ValueError if not found'
i = bisect_left(self._keys, k)
if i != len(self):
return i
raise ValueError('No item found with key at or above: %r' % (k,)) | Return first item with a key >= equal to k. Raise ValueError if not found | Below is the the instruction that describes the task:
### Input:
Return first item with a key >= equal to k. Raise ValueError if not found
### Response:
def find_ge_index(self, k):
'Return first item with a key >= equal to k. Raise ValueError if not found'
i = bisect_left(self._keys, k)
i... |
def tail(filename, n):
"""Returns last n lines from the filename. No exception handling"""
size = os.path.getsize(filename)
with open(filename, "rb") as f:
fm = mmap.mmap(f.fileno(), 0, mmap.MAP_SHARED, mmap.PROT_READ)
try:
for i in xrange(size - 1, -1, -1):
if fm[i] == '\n':
n ... | Returns last n lines from the filename. No exception handling | Below is the the instruction that describes the task:
### Input:
Returns last n lines from the filename. No exception handling
### Response:
def tail(filename, n):
"""Returns last n lines from the filename. No exception handling"""
size = os.path.getsize(filename)
with open(filename, "rb") as f:
fm = mmap... |
def get_schema_func(self):
"""The get_schema function is set by a few different things:
- if there is a 'generate_schema_name' macro in the root project,
it will be used.
- if that does not exist but there is a 'generate_schema_name'
macro in the 'dbt' int... | The get_schema function is set by a few different things:
- if there is a 'generate_schema_name' macro in the root project,
it will be used.
- if that does not exist but there is a 'generate_schema_name'
macro in the 'dbt' internal project, that will be used
... | Below is the the instruction that describes the task:
### Input:
The get_schema function is set by a few different things:
- if there is a 'generate_schema_name' macro in the root project,
it will be used.
- if that does not exist but there is a 'generate_schema_name'
... |
def play(self, url=None, loop=None, digits=None, **kwargs):
"""
Create a <Play> element
:param url: Media URL
:param loop: Times to loop media
:param digits: Play DTMF tones for digits
:param kwargs: additional attributes
:returns: <Play> element
"""
... | Create a <Play> element
:param url: Media URL
:param loop: Times to loop media
:param digits: Play DTMF tones for digits
:param kwargs: additional attributes
:returns: <Play> element | Below is the the instruction that describes the task:
### Input:
Create a <Play> element
:param url: Media URL
:param loop: Times to loop media
:param digits: Play DTMF tones for digits
:param kwargs: additional attributes
:returns: <Play> element
### Response:
def play(se... |
def Trim(self):
"""
Returns a byte array that contains only the block header and transaction hash.
Returns:
bytes:
"""
ms = StreamManager.GetStream()
writer = BinaryWriter(ms)
self.SerializeUnsigned(writer)
writer.WriteByte(1)
self.Scr... | Returns a byte array that contains only the block header and transaction hash.
Returns:
bytes: | Below is the the instruction that describes the task:
### Input:
Returns a byte array that contains only the block header and transaction hash.
Returns:
bytes:
### Response:
def Trim(self):
"""
Returns a byte array that contains only the block header and transaction hash.
... |
def countedArray( expr ):
"""Helper to define a counted list of expressions.
This helper defines a pattern of the form::
integer expr expr expr...
where the leading integer tells how many expr expressions follow.
The matched tokens returns the array of expr tokens as a list - the lea... | Helper to define a counted list of expressions.
This helper defines a pattern of the form::
integer expr expr expr...
where the leading integer tells how many expr expressions follow.
The matched tokens returns the array of expr tokens as a list - the leading count token is suppressed. | Below is the the instruction that describes the task:
### Input:
Helper to define a counted list of expressions.
This helper defines a pattern of the form::
integer expr expr expr...
where the leading integer tells how many expr expressions follow.
The matched tokens returns the arra... |
def set_deplyment_vcenter_params(vcenter_resource_model, deploy_params):
"""
Sets the vcenter parameters if not already set at the deployment option
:param deploy_params: vCenterVMFromTemplateResourceModel or vCenterVMFromImageResourceModel
:type vcenter_resource_model: VMwarevCenterRes... | Sets the vcenter parameters if not already set at the deployment option
:param deploy_params: vCenterVMFromTemplateResourceModel or vCenterVMFromImageResourceModel
:type vcenter_resource_model: VMwarevCenterResourceModel | Below is the the instruction that describes the task:
### Input:
Sets the vcenter parameters if not already set at the deployment option
:param deploy_params: vCenterVMFromTemplateResourceModel or vCenterVMFromImageResourceModel
:type vcenter_resource_model: VMwarevCenterResourceModel
### Response:... |
def module(self):
"""The name of the current module if the request was dispatched
to an actual module. This is deprecated functionality, use blueprints
instead.
"""
from warnings import warn
warn(DeprecationWarning('modules were deprecated in favor of '
... | The name of the current module if the request was dispatched
to an actual module. This is deprecated functionality, use blueprints
instead. | Below is the the instruction that describes the task:
### Input:
The name of the current module if the request was dispatched
to an actual module. This is deprecated functionality, use blueprints
instead.
### Response:
def module(self):
"""The name of the current module if the request was ... |
def get_win_color(color):
"""Convert a named color definition to Windows console color foreground,
background and style numbers."""
foreground = background = style = None
control = ''
if ";" in color:
control, color = color.split(";", 1)
if control == bold:
style = colora... | Convert a named color definition to Windows console color foreground,
background and style numbers. | Below is the the instruction that describes the task:
### Input:
Convert a named color definition to Windows console color foreground,
background and style numbers.
### Response:
def get_win_color(color):
"""Convert a named color definition to Windows console color foreground,
background and style numb... |
def as_dict(self):
""" returns a dictionary view of the option
:returns: the option converted in a dict
:rtype: dict
"""
info = {}
info["type"] = self.__class__.__name__
info["help"] = self.help
info["default"] = self.default
info["multi"]... | returns a dictionary view of the option
:returns: the option converted in a dict
:rtype: dict | Below is the the instruction that describes the task:
### Input:
returns a dictionary view of the option
:returns: the option converted in a dict
:rtype: dict
### Response:
def as_dict(self):
""" returns a dictionary view of the option
:returns: the option converte... |
def sample(reader, writer, n, start=None, stop=None, tsCol=None,
writeSampleOnly=True):
"""Samples n rows.
Args:
reader: A FileRecordStream object with input data.
writer: A FileRecordStream object to write output data to.
n: The number of elements to sample.
start: The first row in the ... | Samples n rows.
Args:
reader: A FileRecordStream object with input data.
writer: A FileRecordStream object to write output data to.
n: The number of elements to sample.
start: The first row in the range to sample from.
stop: The last row in the range to sample from.
tsCol: If specified, the t... | Below is the the instruction that describes the task:
### Input:
Samples n rows.
Args:
reader: A FileRecordStream object with input data.
writer: A FileRecordStream object to write output data to.
n: The number of elements to sample.
start: The first row in the range to sample from.
stop: The... |
def find_executable(executable, path=None):
'''Try to find 'executable' in the directories listed in 'path' (a
string listing directories separated by 'os.pathsep'; defaults to
os.environ['PATH']).'''
if path is None:
path = os.environ['PATH']
paths = path.split(os.pathsep)
extlist = [''... | Try to find 'executable' in the directories listed in 'path' (a
string listing directories separated by 'os.pathsep'; defaults to
os.environ['PATH']). | Below is the the instruction that describes the task:
### Input:
Try to find 'executable' in the directories listed in 'path' (a
string listing directories separated by 'os.pathsep'; defaults to
os.environ['PATH']).
### Response:
def find_executable(executable, path=None):
'''Try to find 'executable' i... |
def none(self):
"""
Returns an empty QuerySet.
"""
return EmptyQuerySet(model=self.model, using=self._using, connection=self._connection) | Returns an empty QuerySet. | Below is the the instruction that describes the task:
### Input:
Returns an empty QuerySet.
### Response:
def none(self):
"""
Returns an empty QuerySet.
"""
return EmptyQuerySet(model=self.model, using=self._using, connection=self._connection) |
def flip_constraint(self, twig=None, solve_for=None, **kwargs):
"""
Flip an existing constraint to solve for a different parameter
:parameter str twig: twig to filter the constraint
:parameter solve_for: twig or actual parameter object of the new
parameter which this constra... | Flip an existing constraint to solve for a different parameter
:parameter str twig: twig to filter the constraint
:parameter solve_for: twig or actual parameter object of the new
parameter which this constraint should constraint (solve for).
:type solve_for: str or :class:`phoebe.pa... | Below is the the instruction that describes the task:
### Input:
Flip an existing constraint to solve for a different parameter
:parameter str twig: twig to filter the constraint
:parameter solve_for: twig or actual parameter object of the new
parameter which this constraint should cons... |
def enable_cell_picking(self, mesh=None, callback=None):
"""
Enables picking of cells. Press r to enable retangle based
selection. Press "r" again to turn it off. Selection will be
saved to self.picked_cells.
Uses last input mesh for input
Parameters
--------... | Enables picking of cells. Press r to enable retangle based
selection. Press "r" again to turn it off. Selection will be
saved to self.picked_cells.
Uses last input mesh for input
Parameters
----------
mesh : vtk.UnstructuredGrid, optional
UnstructuredGrid... | Below is the the instruction that describes the task:
### Input:
Enables picking of cells. Press r to enable retangle based
selection. Press "r" again to turn it off. Selection will be
saved to self.picked_cells.
Uses last input mesh for input
Parameters
----------
... |
def remove_data_flow(self, data_flow_id, destroy=True):
""" Removes a data flow from the container state
:param int data_flow_id: the id of the data_flow to remove
:raises exceptions.AttributeError: if the data_flow_id does not exist
"""
if data_flow_id not in self._data_flows:
... | Removes a data flow from the container state
:param int data_flow_id: the id of the data_flow to remove
:raises exceptions.AttributeError: if the data_flow_id does not exist | Below is the the instruction that describes the task:
### Input:
Removes a data flow from the container state
:param int data_flow_id: the id of the data_flow to remove
:raises exceptions.AttributeError: if the data_flow_id does not exist
### Response:
def remove_data_flow(self, data_flow_id, dest... |
def update_event(self, id, **kwargs): # noqa: E501
"""Update a specific event # noqa: E501
The following fields are readonly and will be ignored when passed in the request: <code>id</code>, <code>isEphemeral</code>, <code>isUserEvent</code>, <code>runningState</code>, <code>canDelete</code>, <code>ca... | Update a specific event # noqa: E501
The following fields are readonly and will be ignored when passed in the request: <code>id</code>, <code>isEphemeral</code>, <code>isUserEvent</code>, <code>runningState</code>, <code>canDelete</code>, <code>canClose</code>, <code>creatorType</code>, <code>createdAt</code>... | Below is the the instruction that describes the task:
### Input:
Update a specific event # noqa: E501
The following fields are readonly and will be ignored when passed in the request: <code>id</code>, <code>isEphemeral</code>, <code>isUserEvent</code>, <code>runningState</code>, <code>canDelete</code>, <c... |
def __get_jp(self, extractor_processor, sub_output=None):
"""Tries to get name from ExtractorProcessor to filter on first.
Otherwise falls back to filtering based on its metadata"""
if sub_output is None and extractor_processor.output_field is None:
raise ValueError(
... | Tries to get name from ExtractorProcessor to filter on first.
Otherwise falls back to filtering based on its metadata | Below is the the instruction that describes the task:
### Input:
Tries to get name from ExtractorProcessor to filter on first.
Otherwise falls back to filtering based on its metadata
### Response:
def __get_jp(self, extractor_processor, sub_output=None):
"""Tries to get name from ExtractorProcessor... |
def _init_defaults(self):
"""Create a `dict` of default configurations."""
defaults = {
'build_dir': None,
'build_datetime': datetime.datetime.now(dateutil.tz.tzutc()),
'pdf_path': None,
'extra_downloads': list(),
'environment': None,
... | Create a `dict` of default configurations. | Below is the the instruction that describes the task:
### Input:
Create a `dict` of default configurations.
### Response:
def _init_defaults(self):
"""Create a `dict` of default configurations."""
defaults = {
'build_dir': None,
'build_datetime': datetime.datetime.now(dateut... |
def query_log_filename(self, idx):
"""Queries for the VM log file name of an given index. Returns an empty
string if a log file with that index doesn't exists.
in idx of type int
Which log file name to query. 0=current log file.
return filename of type str
On re... | Queries for the VM log file name of an given index. Returns an empty
string if a log file with that index doesn't exists.
in idx of type int
Which log file name to query. 0=current log file.
return filename of type str
On return the full path to the log file or an empty... | Below is the the instruction that describes the task:
### Input:
Queries for the VM log file name of an given index. Returns an empty
string if a log file with that index doesn't exists.
in idx of type int
Which log file name to query. 0=current log file.
return filename of typ... |
def html_report(self, file_path):
"""Generate and save HTML report."""
self.logger.debug('Generating HTML report')
report = self.zap.core.htmlreport()
self._write_report(report, file_path) | Generate and save HTML report. | Below is the the instruction that describes the task:
### Input:
Generate and save HTML report.
### Response:
def html_report(self, file_path):
"""Generate and save HTML report."""
self.logger.debug('Generating HTML report')
report = self.zap.core.htmlreport()
self._write_report(rep... |
def check_type(o, acceptable_types, may_be_none=True):
"""Object is an instance of one of the acceptable types or None.
Args:
o: The object to be inspected.
acceptable_types: A type or tuple of acceptable types.
may_be_none(bool): Whether or not the object may be None.
Raises:
... | Object is an instance of one of the acceptable types or None.
Args:
o: The object to be inspected.
acceptable_types: A type or tuple of acceptable types.
may_be_none(bool): Whether or not the object may be None.
Raises:
TypeError: If the object is None and may_be_none=False, or... | Below is the the instruction that describes the task:
### Input:
Object is an instance of one of the acceptable types or None.
Args:
o: The object to be inspected.
acceptable_types: A type or tuple of acceptable types.
may_be_none(bool): Whether or not the object may be None.
Raise... |
def _refresh_context(self):
"""
Get current facade segment. To prevent resource leaking in Lambda worker,
every time there is segment present, we compare its trace id to current
environment variables. If it is different we create a new facade segment
and clean up subsegments stor... | Get current facade segment. To prevent resource leaking in Lambda worker,
every time there is segment present, we compare its trace id to current
environment variables. If it is different we create a new facade segment
and clean up subsegments stored. | Below is the the instruction that describes the task:
### Input:
Get current facade segment. To prevent resource leaking in Lambda worker,
every time there is segment present, we compare its trace id to current
environment variables. If it is different we create a new facade segment
and clea... |
def _read_para_from(self, code, cbit, clen, *, desc, length, version):
"""Read HIP FROM parameter.
Structure of HIP FROM parameter [RFC 8004]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
... | Read HIP FROM parameter.
Structure of HIP FROM parameter [RFC 8004]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
... | Below is the the instruction that describes the task:
### Input:
Read HIP FROM parameter.
Structure of HIP FROM parameter [RFC 8004]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+... |
def _insert(self, bs, pos):
"""Insert bs at pos."""
assert 0 <= pos <= self.len
if pos > self.len // 2:
# Inserting nearer end, so cut off end.
end = self._slice(pos, self.len)
self._truncateend(self.len - pos)
self._append(bs)
self._ap... | Insert bs at pos. | Below is the the instruction that describes the task:
### Input:
Insert bs at pos.
### Response:
def _insert(self, bs, pos):
"""Insert bs at pos."""
assert 0 <= pos <= self.len
if pos > self.len // 2:
# Inserting nearer end, so cut off end.
end = self._slice(pos, sel... |
def time_report_item(self, label, message=None):
"""
This will return a dictionary for the given message based on timestamps
:param label:
:param message: str of the message to find the timestamp
:return: dict of times
"""
next_ = TIMESTAMPS_ORDER[TIMESTAMP... | This will return a dictionary for the given message based on timestamps
:param label:
:param message: str of the message to find the timestamp
:return: dict of times | Below is the the instruction that describes the task:
### Input:
This will return a dictionary for the given message based on timestamps
:param label:
:param message: str of the message to find the timestamp
:return: dict of times
### Response:
def time_report_item(self, label, messa... |
def authenticate_ldap(self, username, password):
"""Get user by username and password and their permissions.
:param username: Username. String with a minimum 3 and maximum of 45 characters
:param password: User password. String with a minimum 3 and maximum of 45 characters
:return: Fol... | Get user by username and password and their permissions.
:param username: Username. String with a minimum 3 and maximum of 45 characters
:param password: User password. String with a minimum 3 and maximum of 45 characters
:return: Following dictionary:
::
{'user': {'id': ... | Below is the the instruction that describes the task:
### Input:
Get user by username and password and their permissions.
:param username: Username. String with a minimum 3 and maximum of 45 characters
:param password: User password. String with a minimum 3 and maximum of 45 characters
:re... |
def HttpResponse401(request, template=KEY_AUTH_401_TEMPLATE,
content=KEY_AUTH_401_CONTENT, content_type=KEY_AUTH_401_CONTENT_TYPE):
"""
HTTP response for not-authorized access (status code 403)
"""
return AccessFailedResponse(request, template, content, content_type, status=401) | HTTP response for not-authorized access (status code 403) | Below is the the instruction that describes the task:
### Input:
HTTP response for not-authorized access (status code 403)
### Response:
def HttpResponse401(request, template=KEY_AUTH_401_TEMPLATE,
content=KEY_AUTH_401_CONTENT, content_type=KEY_AUTH_401_CONTENT_TYPE):
"""
HTTP response for not-authorized a... |
def matching_files(self):
"""
Find files.
Returns:
list: the list of matching files.
"""
matching = []
matcher = self.file_path_regex
pieces = self.file_path_regex.pattern.split(sep)
partial_matchers = list(map(re.compile, (
sep.jo... | Find files.
Returns:
list: the list of matching files. | Below is the the instruction that describes the task:
### Input:
Find files.
Returns:
list: the list of matching files.
### Response:
def matching_files(self):
"""
Find files.
Returns:
list: the list of matching files.
"""
matching = []
... |
def populate_entity_type(apps, schema_editor):
"""Populate entity type from attached descriptor schema."""
Entity = apps.get_model('flow', 'Entity')
for entity in Entity.objects.all():
if entity.descriptor_schema is not None:
entity.type = entity.descriptor_schema.slug
entit... | Populate entity type from attached descriptor schema. | Below is the the instruction that describes the task:
### Input:
Populate entity type from attached descriptor schema.
### Response:
def populate_entity_type(apps, schema_editor):
"""Populate entity type from attached descriptor schema."""
Entity = apps.get_model('flow', 'Entity')
for entity in Entity... |
def downgrade():
"""Downgrade database."""
# Remove 'created' and 'updated' columns
op.drop_column('oauthclient_remoteaccount', 'created')
op.drop_column('oauthclient_remoteaccount', 'updated')
op.drop_column('oauthclient_remotetoken', 'created')
op.drop_column('oauthclient_remotetoken', 'updat... | Downgrade database. | Below is the the instruction that describes the task:
### Input:
Downgrade database.
### Response:
def downgrade():
"""Downgrade database."""
# Remove 'created' and 'updated' columns
op.drop_column('oauthclient_remoteaccount', 'created')
op.drop_column('oauthclient_remoteaccount', 'updated')
o... |
def disassemble(self, data, start_address=0):
"""
Return a list containing the virtual memory address, instruction length
and disassembly code for the given binary buffer.
"""
return _opcodes.disassemble(self._ptr, data, start_address) | Return a list containing the virtual memory address, instruction length
and disassembly code for the given binary buffer. | Below is the the instruction that describes the task:
### Input:
Return a list containing the virtual memory address, instruction length
and disassembly code for the given binary buffer.
### Response:
def disassemble(self, data, start_address=0):
"""
Return a list containing the virtual mem... |
def __initialize_ui(self):
"""
Initializes the Widget ui.
"""
LOGGER.debug("> Initializing '{0}' Widget ui.".format(self.__class__.__name__))
self.__view = self.Reporter_webView
self.setWindowTitle("{0} - Reporter".format(Constants.application_name))
self.Foote... | Initializes the Widget ui. | Below is the the instruction that describes the task:
### Input:
Initializes the Widget ui.
### Response:
def __initialize_ui(self):
"""
Initializes the Widget ui.
"""
LOGGER.debug("> Initializing '{0}' Widget ui.".format(self.__class__.__name__))
self.__view = self.Report... |
def file_modified_time(file_name) -> pd.Timestamp:
"""
File modified time in python
Args:
file_name: file name
Returns:
pd.Timestamp
"""
return pd.to_datetime(time.ctime(os.path.getmtime(filename=file_name))) | File modified time in python
Args:
file_name: file name
Returns:
pd.Timestamp | Below is the the instruction that describes the task:
### Input:
File modified time in python
Args:
file_name: file name
Returns:
pd.Timestamp
### Response:
def file_modified_time(file_name) -> pd.Timestamp:
"""
File modified time in python
Args:
file_name: file name
... |
def _year_expand(s):
""" Parses a year or dash-delimeted year range
"""
regex = r"^((?:19|20)\d{2})?(\s*-\s*)?((?:19|20)\d{2})?$"
try:
start, dash, end = match(regex, ustr(s)).groups()
start = start or 1900
end = end or 2099
except AttributeErr... | Parses a year or dash-delimeted year range | Below is the the instruction that describes the task:
### Input:
Parses a year or dash-delimeted year range
### Response:
def _year_expand(s):
""" Parses a year or dash-delimeted year range
"""
regex = r"^((?:19|20)\d{2})?(\s*-\s*)?((?:19|20)\d{2})?$"
try:
start, dash, e... |
def _get_url_scheme_regexes():
"""
Get configured mercurial schemes and convert them to regexes
Returns:
tuple: (scheme_name, scheme_value, compiled scheme_regex)
"""
output = sh("hg showconfig | grep '^schemes.'", shell=True).split('\n')
log.debug(output)
... | Get configured mercurial schemes and convert them to regexes
Returns:
tuple: (scheme_name, scheme_value, compiled scheme_regex) | Below is the the instruction that describes the task:
### Input:
Get configured mercurial schemes and convert them to regexes
Returns:
tuple: (scheme_name, scheme_value, compiled scheme_regex)
### Response:
def _get_url_scheme_regexes():
"""
Get configured mercurial schemes and... |
def _add_stats_data(self, teams_list, team_data_dict):
"""
Add a team's stats row to a dictionary.
Pass table contents and a stats dictionary of all teams to accumulate
all stats for each team in a single variable.
Parameters
----------
teams_list : generator
... | Add a team's stats row to a dictionary.
Pass table contents and a stats dictionary of all teams to accumulate
all stats for each team in a single variable.
Parameters
----------
teams_list : generator
A generator of all row items in a given table.
team_data_... | Below is the the instruction that describes the task:
### Input:
Add a team's stats row to a dictionary.
Pass table contents and a stats dictionary of all teams to accumulate
all stats for each team in a single variable.
Parameters
----------
teams_list : generator
... |
def substitute(P, x0, x1, V=0):
"""
Substitute a variable in a polynomial array.
Args:
P (Poly) : Input data.
x0 (Poly, int) : The variable to substitute. Indicated with either unit
variable, e.g. `x`, `y`, `z`, etc. or through an integer
matching the unit va... | Substitute a variable in a polynomial array.
Args:
P (Poly) : Input data.
x0 (Poly, int) : The variable to substitute. Indicated with either unit
variable, e.g. `x`, `y`, `z`, etc. or through an integer
matching the unit variables dimension, e.g. `x==0`, `y==1`,
... | Below is the the instruction that describes the task:
### Input:
Substitute a variable in a polynomial array.
Args:
P (Poly) : Input data.
x0 (Poly, int) : The variable to substitute. Indicated with either unit
variable, e.g. `x`, `y`, `z`, etc. or through an integer
... |
def construct_wal_name(sysinfo):
"""Get wal file name out of something like this:
{'dbname': '', 'systemid': '6181331723016416192', 'timeline': '1', 'xlogpos': '0/90001B0'}
"""
log_hex, seg_hex = sysinfo["xlogpos"].split("/", 1)
# seg_hex's topmost 8 bits are filename, low 24 bits are position in
... | Get wal file name out of something like this:
{'dbname': '', 'systemid': '6181331723016416192', 'timeline': '1', 'xlogpos': '0/90001B0'} | Below is the the instruction that describes the task:
### Input:
Get wal file name out of something like this:
{'dbname': '', 'systemid': '6181331723016416192', 'timeline': '1', 'xlogpos': '0/90001B0'}
### Response:
def construct_wal_name(sysinfo):
"""Get wal file name out of something like this:
{'dbn... |
def convert_translations(self, dest_dir):
"""
Converts translations to the new format and stores at dest_dir.
"""
if not os.path.isdir(dest_dir):
os.makedirs(dest_dir)
total_translation_rows = 0
with open(os.path.join(dest_dir, 'translations.txt'),
... | Converts translations to the new format and stores at dest_dir. | Below is the the instruction that describes the task:
### Input:
Converts translations to the new format and stores at dest_dir.
### Response:
def convert_translations(self, dest_dir):
"""
Converts translations to the new format and stores at dest_dir.
"""
if not os.path.isdir(dest_... |
def get_group_for_activity(self, module=None, project=None, **kwargs):
"""Get groups for activity.
:param str module: Base module
:param str module: Project which contains the group requested
:return: JSON
"""
_module_id = kwargs.get('module', module)
_project_i... | Get groups for activity.
:param str module: Base module
:param str module: Project which contains the group requested
:return: JSON | Below is the the instruction that describes the task:
### Input:
Get groups for activity.
:param str module: Base module
:param str module: Project which contains the group requested
:return: JSON
### Response:
def get_group_for_activity(self, module=None, project=None, **kwargs):
... |
def run_once(function, state={}, errors={}):
"""A memoization decorator, whose purpose is to cache calls."""
@six.wraps(function)
def _wrapper(*args, **kwargs):
if function in errors:
# Deliberate use of LBYL.
six.reraise(*errors[function])
try:
return st... | A memoization decorator, whose purpose is to cache calls. | Below is the the instruction that describes the task:
### Input:
A memoization decorator, whose purpose is to cache calls.
### Response:
def run_once(function, state={}, errors={}):
"""A memoization decorator, whose purpose is to cache calls."""
@six.wraps(function)
def _wrapper(*args, **kwargs):
... |
def createCircle(self, cx, cy, r, strokewidth=1, stroke='black', fill='none'):
"""
Creates a circle
@type cx: string or int
@param cx: starting x-coordinate
@type cy: string or int
@param cy: starting y-coordinate
@type r: string or int
@param r: ... | Creates a circle
@type cx: string or int
@param cx: starting x-coordinate
@type cy: string or int
@param cy: starting y-coordinate
@type r: string or int
@param r: radius
@type strokewidth: string or int
@param strokewidth: width of the pen use... | Below is the the instruction that describes the task:
### Input:
Creates a circle
@type cx: string or int
@param cx: starting x-coordinate
@type cy: string or int
@param cy: starting y-coordinate
@type r: string or int
@param r: radius
@type strokew... |
def open_graph(self, **args):
"""open a vcg graph
"""
self._stream.write("%sgraph:{\n" % self._indent)
self._inc_indent()
self._write_attributes(GRAPH_ATTRS, **args) | open a vcg graph | Below is the the instruction that describes the task:
### Input:
open a vcg graph
### Response:
def open_graph(self, **args):
"""open a vcg graph
"""
self._stream.write("%sgraph:{\n" % self._indent)
self._inc_indent()
self._write_attributes(GRAPH_ATTRS, **args) |
def _repo(self, args):
'''
Process repo commands
'''
args.pop(0)
command = args[0]
if command == 'list':
self._repo_list(args)
elif command == 'packages':
self._repo_packages(args)
elif command == 'search':
self._repo_pa... | Process repo commands | Below is the the instruction that describes the task:
### Input:
Process repo commands
### Response:
def _repo(self, args):
'''
Process repo commands
'''
args.pop(0)
command = args[0]
if command == 'list':
self._repo_list(args)
elif command == 'pa... |
def consume_value(self, ctx, opts):
""" Retrieve default value and display it when prompt is disabled. """
value = click.Option.consume_value(self, ctx, opts)
if not value:
# value not found by click on command line
# now check using our context helper in order into
... | Retrieve default value and display it when prompt is disabled. | Below is the the instruction that describes the task:
### Input:
Retrieve default value and display it when prompt is disabled.
### Response:
def consume_value(self, ctx, opts):
""" Retrieve default value and display it when prompt is disabled. """
value = click.Option.consume_value(self, ctx, opts... |
def token(ctx, opts, login, password):
"""Retrieve your API authentication token/key."""
click.echo(
"Retrieving API token for %(login)s ... "
% {"login": click.style(login, bold=True)},
nl=False,
)
context_msg = "Failed to retrieve the API token!"
with handle_api_exceptions... | Retrieve your API authentication token/key. | Below is the the instruction that describes the task:
### Input:
Retrieve your API authentication token/key.
### Response:
def token(ctx, opts, login, password):
"""Retrieve your API authentication token/key."""
click.echo(
"Retrieving API token for %(login)s ... "
% {"login": click.style(l... |
def mBank_set_iph_id(transactions, tag, tag_dict, *args):
"""
mBank Collect uses ID IPH to distinguish between virtual accounts,
adding iph_id may be helpful in further processing
"""
matches = iph_id_re.search(tag_dict[tag.slug])
if matches: # pragma no branch
tag_dict['iph_id'] = mat... | mBank Collect uses ID IPH to distinguish between virtual accounts,
adding iph_id may be helpful in further processing | Below is the the instruction that describes the task:
### Input:
mBank Collect uses ID IPH to distinguish between virtual accounts,
adding iph_id may be helpful in further processing
### Response:
def mBank_set_iph_id(transactions, tag, tag_dict, *args):
"""
mBank Collect uses ID IPH to distinguish bet... |
def sensor_offsets_encode(self, mag_ofs_x, mag_ofs_y, mag_ofs_z, mag_declination, raw_press, raw_temp, gyro_cal_x, gyro_cal_y, gyro_cal_z, accel_cal_x, accel_cal_y, accel_cal_z):
'''
Offsets and calibrations values for hardware sensors. This makes it
easier to debug the c... | Offsets and calibrations values for hardware sensors. This makes it
easier to debug the calibration process.
mag_ofs_x : magnetometer X offset (int16_t)
mag_ofs_y : magnetometer Y offset (int16_t)
mag_ofs_z ... | Below is the the instruction that describes the task:
### Input:
Offsets and calibrations values for hardware sensors. This makes it
easier to debug the calibration process.
mag_ofs_x : magnetometer X offset (int16_t)
mag_ofs_y : magne... |
def _remove_unused_wires(block, keep_inputs=True):
""" Removes all unconnected wires from a block"""
valid_wires = set()
for logic_net in block.logic:
valid_wires.update(logic_net.args, logic_net.dests)
wire_removal_set = block.wirevector_set.difference(valid_wires)
for removed_wire in wire... | Removes all unconnected wires from a block | Below is the the instruction that describes the task:
### Input:
Removes all unconnected wires from a block
### Response:
def _remove_unused_wires(block, keep_inputs=True):
""" Removes all unconnected wires from a block"""
valid_wires = set()
for logic_net in block.logic:
valid_wires.update(log... |
def negative_gradient(self, y, y_pred, sample_weight=None, **kwargs):
"""Negative gradient of partial likelihood
Parameters
---------
y : tuple, len = 2
First element is boolean event indicator and second element survival/censoring time.
y_pred : np.ndarray, shape=(n... | Negative gradient of partial likelihood
Parameters
---------
y : tuple, len = 2
First element is boolean event indicator and second element survival/censoring time.
y_pred : np.ndarray, shape=(n,):
The predictions. | Below is the the instruction that describes the task:
### Input:
Negative gradient of partial likelihood
Parameters
---------
y : tuple, len = 2
First element is boolean event indicator and second element survival/censoring time.
y_pred : np.ndarray, shape=(n,):
... |
def calc_z0_and_conv_factor_from_ratio_of_harmonics(z, z2, NA=0.999):
"""
Calculates the Conversion Factor and physical amplitude of motion in nms
by comparison of the ratio of the heights of the z signal and
second harmonic of z.
Parameters
----------
z : ndarray
array containing... | Calculates the Conversion Factor and physical amplitude of motion in nms
by comparison of the ratio of the heights of the z signal and
second harmonic of z.
Parameters
----------
z : ndarray
array containing z signal in volts
z2 : ndarray
array containing second harmonic of z ... | Below is the the instruction that describes the task:
### Input:
Calculates the Conversion Factor and physical amplitude of motion in nms
by comparison of the ratio of the heights of the z signal and
second harmonic of z.
Parameters
----------
z : ndarray
array containing z signal in ... |
def get(cls, id, automation, api=None):
"""
Fetches the resource from the server.
:param id: Automation member username
:param automation: Automation id or object
:param api: sevenbridges Api instance.
:return: AutomationMember object.
"""
username = Trans... | Fetches the resource from the server.
:param id: Automation member username
:param automation: Automation id or object
:param api: sevenbridges Api instance.
:return: AutomationMember object. | Below is the the instruction that describes the task:
### Input:
Fetches the resource from the server.
:param id: Automation member username
:param automation: Automation id or object
:param api: sevenbridges Api instance.
:return: AutomationMember object.
### Response:
def get(cls,... |
def draw_screen(self, size):
"""Render curses screen
"""
self.tui.clear()
canvas = self.top.render(size, focus=True)
self.tui.draw_screen(size, canvas) | Render curses screen | Below is the the instruction that describes the task:
### Input:
Render curses screen
### Response:
def draw_screen(self, size):
"""Render curses screen
"""
self.tui.clear()
canvas = self.top.render(size, focus=True)
self.tui.draw_screen(size, canvas) |
def update_views(self):
"""Update stats views."""
# Call the father's method
super(Plugin, self).update_views()
# Add specifics informations
# Alert and log
for key in ['user', 'system', 'iowait']:
if key in self.stats:
self.views[key]['decora... | Update stats views. | Below is the the instruction that describes the task:
### Input:
Update stats views.
### Response:
def update_views(self):
"""Update stats views."""
# Call the father's method
super(Plugin, self).update_views()
# Add specifics informations
# Alert and log
for key in... |
def X_more(self):
"""Zoom in on the x-axis."""
if self.parent.value('window_length') < 0.3:
return
self.parent.value('window_length',
self.parent.value('window_length') * 2)
self.parent.overview.update_position() | Zoom in on the x-axis. | Below is the the instruction that describes the task:
### Input:
Zoom in on the x-axis.
### Response:
def X_more(self):
"""Zoom in on the x-axis."""
if self.parent.value('window_length') < 0.3:
return
self.parent.value('window_length',
self.parent.value... |
def init_params(self, initializer=mx.init.Uniform(0.01), **kwargs):
"""Initializes the parameters and auxiliary states.
"""
self._module.init_params(initializer=initializer, **kwargs) | Initializes the parameters and auxiliary states. | Below is the the instruction that describes the task:
### Input:
Initializes the parameters and auxiliary states.
### Response:
def init_params(self, initializer=mx.init.Uniform(0.01), **kwargs):
"""Initializes the parameters and auxiliary states.
"""
self._module.init_params(initializer=in... |
def create_token_role(self, role,
allowed_policies=None, disallowed_policies=None,
orphan=None, period=None, renewable=None,
path_suffix=None, explicit_max_ttl=None):
"""POST /auth/token/roles/<role>
:param role:
:typ... | POST /auth/token/roles/<role>
:param role:
:type role:
:param allowed_policies:
:type allowed_policies:
:param disallowed_policies:
:type disallowed_policies:
:param orphan:
:type orphan:
:param period:
:type period:
:param renewab... | Below is the the instruction that describes the task:
### Input:
POST /auth/token/roles/<role>
:param role:
:type role:
:param allowed_policies:
:type allowed_policies:
:param disallowed_policies:
:type disallowed_policies:
:param orphan:
:type orphan... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.