code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def rm_first_of_dup_args(self) -> None:
"""Eliminate duplicate arguments by removing the first occurrences.
Remove the first occurrences of duplicate arguments, regardless of
their value. Result of the rendered wikitext should remain the same.
Warning: Some meaningful data may be remove... | Eliminate duplicate arguments by removing the first occurrences.
Remove the first occurrences of duplicate arguments, regardless of
their value. Result of the rendered wikitext should remain the same.
Warning: Some meaningful data may be removed from wikitext.
Also see `rm_dup_args_saf... | Below is the the instruction that describes the task:
### Input:
Eliminate duplicate arguments by removing the first occurrences.
Remove the first occurrences of duplicate arguments, regardless of
their value. Result of the rendered wikitext should remain the same.
Warning: Some meaningful ... |
def bool(cls, must=None, should=None, must_not=None, minimum_number_should_match=None, boost=None):
'''
http://www.elasticsearch.org/guide/reference/query-dsl/bool-query.html
A query that matches documents matching boolean combinations of other queris. The bool query maps to Lucene BooleanQuery.... | http://www.elasticsearch.org/guide/reference/query-dsl/bool-query.html
A query that matches documents matching boolean combinations of other queris. The bool query maps to Lucene BooleanQuery. It is built using one of more boolean clauses, each clause with a typed occurrence. The occurrence types are:
'... | Below is the the instruction that describes the task:
### Input:
http://www.elasticsearch.org/guide/reference/query-dsl/bool-query.html
A query that matches documents matching boolean combinations of other queris. The bool query maps to Lucene BooleanQuery. It is built using one of more boolean clauses, eac... |
def copy(self, klass=_x):
"""A new chain beginning with the current chain tokens and argument.
"""
chain = super().copy()
new_chain = klass(chain._args[0])
new_chain._tokens = [[
chain.compose, [], {},
]]
return new_chain | A new chain beginning with the current chain tokens and argument. | Below is the the instruction that describes the task:
### Input:
A new chain beginning with the current chain tokens and argument.
### Response:
def copy(self, klass=_x):
"""A new chain beginning with the current chain tokens and argument.
"""
chain = super().copy()
new_chain = klas... |
def cql_query_with_prepare(query, statement_name, statement_arguments, callback_errors=None, contact_points=None,
port=None, cql_user=None, cql_pass=None, **kwargs):
'''
Run a query on a Cassandra cluster and return a dictionary.
This function should not be used asynchronously fo... | Run a query on a Cassandra cluster and return a dictionary.
This function should not be used asynchronously for SELECTs -- it will not
return anything and we don't currently have a mechanism for handling a future
that will return results.
:param query: The query to execute.
:type query: ... | Below is the the instruction that describes the task:
### Input:
Run a query on a Cassandra cluster and return a dictionary.
This function should not be used asynchronously for SELECTs -- it will not
return anything and we don't currently have a mechanism for handling a future
that will return results.... |
def read_xref_from(self, parser, start, xrefs):
"""Reads XRefs from the given location."""
parser.seek(start)
parser.reset()
try:
(pos, token) = parser.nexttoken()
except PSEOF:
raise PDFNoValidXRef('Unexpected EOF')
if self.debug:
logg... | Reads XRefs from the given location. | Below is the the instruction that describes the task:
### Input:
Reads XRefs from the given location.
### Response:
def read_xref_from(self, parser, start, xrefs):
"""Reads XRefs from the given location."""
parser.seek(start)
parser.reset()
try:
(pos, token) = parser.nex... |
def _add_id_column(layer):
"""Add an ID column if it's not present in the attribute table.
:param layer: The vector layer.
:type layer: QgsVectorLayer
"""
layer_purpose = layer.keywords['layer_purpose']
mapping = {
layer_purpose_exposure['key']: exposure_id_field,
layer_purpose_... | Add an ID column if it's not present in the attribute table.
:param layer: The vector layer.
:type layer: QgsVectorLayer | Below is the the instruction that describes the task:
### Input:
Add an ID column if it's not present in the attribute table.
:param layer: The vector layer.
:type layer: QgsVectorLayer
### Response:
def _add_id_column(layer):
"""Add an ID column if it's not present in the attribute table.
:param... |
def simulate_system(self, parameters, initial_conditions, timepoints):
"""
Simulates the system for each of the timepoints, starting at initial_constants and initial_values values
:param parameters: list of the initial values for the constants in the model.
Mus... | Simulates the system for each of the timepoints, starting at initial_constants and initial_values values
:param parameters: list of the initial values for the constants in the model.
Must be in the same order as in the model
:param initial_conditions: List of the initi... | Below is the the instruction that describes the task:
### Input:
Simulates the system for each of the timepoints, starting at initial_constants and initial_values values
:param parameters: list of the initial values for the constants in the model.
Must be in the same order... |
def list_books(self):
''' Return the list of book names '''
names = []
try:
for n in self.cur.execute("SELECT name FROM book;").fetchall():
names.extend(n)
except:
self.error("ERROR: cannot find database table 'book'")
return(names) | Return the list of book names | Below is the the instruction that describes the task:
### Input:
Return the list of book names
### Response:
def list_books(self):
''' Return the list of book names '''
names = []
try:
for n in self.cur.execute("SELECT name FROM book;").fetchall():
names.extend(n... |
def forward(
self,
chat_id: Union[int, str],
disable_notification: bool = None,
as_copy: bool = False,
remove_caption: bool = False
):
"""Bound method *forward* of :obj:`Message <pyrogram.Messages>`.
Args:
chat_id (``int`` | ``str``):
... | Bound method *forward* of :obj:`Message <pyrogram.Messages>`.
Args:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
For your personal cloud (Saved Messages) you can simply use "me" or "self".
For a contact th... | Below is the the instruction that describes the task:
### Input:
Bound method *forward* of :obj:`Message <pyrogram.Messages>`.
Args:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
For your personal cloud (Saved Messages... |
def get_fd_from_final_mass_spin(template=None, distance=None, **kwargs):
"""Return frequency domain ringdown with all the modes specified.
Parameters
----------
template: object
An object that has attached properties. This can be used to substitute
for keyword arguments. A common exampl... | Return frequency domain ringdown with all the modes specified.
Parameters
----------
template: object
An object that has attached properties. This can be used to substitute
for keyword arguments. A common example would be a row in an xml table.
distance : {None, float}, optional
... | Below is the the instruction that describes the task:
### Input:
Return frequency domain ringdown with all the modes specified.
Parameters
----------
template: object
An object that has attached properties. This can be used to substitute
for keyword arguments. A common example would be ... |
def declare_alias(self, name):
"""Insert a Python function into this Namespace with an
explicitly-given name, but detect its argument count automatically.
"""
def decorator(f):
self._auto_register_function(f, name)
return f
return decorator | Insert a Python function into this Namespace with an
explicitly-given name, but detect its argument count automatically. | Below is the the instruction that describes the task:
### Input:
Insert a Python function into this Namespace with an
explicitly-given name, but detect its argument count automatically.
### Response:
def declare_alias(self, name):
"""Insert a Python function into this Namespace with an
expl... |
def set_hooks(cls, hooks: dict) -> bool:
"""
Merge internal hooks set with the given hooks
"""
cls._hooks = cls._hooks.new_child()
for hook_name, hook_pt in hooks.items():
if '.' not in hook_name:
hook_name = cls.__module__ \
+ '.' ... | Merge internal hooks set with the given hooks | Below is the the instruction that describes the task:
### Input:
Merge internal hooks set with the given hooks
### Response:
def set_hooks(cls, hooks: dict) -> bool:
"""
Merge internal hooks set with the given hooks
"""
cls._hooks = cls._hooks.new_child()
for hook_name, hook... |
def namedtuple_with_defaults(typename: str, field_names: Union[str, List[str]],
default_values: collections.Iterable = ()):
"""
Convenience function for defining a namedtuple with default values
From: https://stackoverflow.com/questions/11351032/namedtuple-and-default-values-fo... | Convenience function for defining a namedtuple with default values
From: https://stackoverflow.com/questions/11351032/namedtuple-and-default-values-for-optional-keyword-arguments
Examples:
>>> Node = namedtuple_with_defaults('Node', 'val left right')
>>> Node()
Node(val=None, left=None... | Below is the the instruction that describes the task:
### Input:
Convenience function for defining a namedtuple with default values
From: https://stackoverflow.com/questions/11351032/namedtuple-and-default-values-for-optional-keyword-arguments
Examples:
>>> Node = namedtuple_with_defaults('Node', ... |
def download(self, filename, format='sdf', overwrite=False, resolvers=None, **kwargs):
""" Download the resolved structure as a file """
download(self.input, filename, format, overwrite, resolvers, **kwargs) | Download the resolved structure as a file | Below is the the instruction that describes the task:
### Input:
Download the resolved structure as a file
### Response:
def download(self, filename, format='sdf', overwrite=False, resolvers=None, **kwargs):
""" Download the resolved structure as a file """
download(self.input, filename, format, ov... |
def do_save(self, line):
"""save [config_file] Save session variables to file save (without parameters):
Save session to default file ~/.dataone_cli.conf save.
<file>: Save session to specified file.
"""
config_file = self._split_args(line, 0, 1)[0]
self._command_proces... | save [config_file] Save session variables to file save (without parameters):
Save session to default file ~/.dataone_cli.conf save.
<file>: Save session to specified file. | Below is the the instruction that describes the task:
### Input:
save [config_file] Save session variables to file save (without parameters):
Save session to default file ~/.dataone_cli.conf save.
<file>: Save session to specified file.
### Response:
def do_save(self, line):
"""save [confi... |
def read(self, data):
"""Handles incoming raw sensor data and broadcasts it to specified
udp servers and connected tcp clients
:param data: NMEA raw sentences incoming data
"""
self.log('Received NMEA data:', data, lvl=debug)
# self.log(data, pretty=True)
if sel... | Handles incoming raw sensor data and broadcasts it to specified
udp servers and connected tcp clients
:param data: NMEA raw sentences incoming data | Below is the the instruction that describes the task:
### Input:
Handles incoming raw sensor data and broadcasts it to specified
udp servers and connected tcp clients
:param data: NMEA raw sentences incoming data
### Response:
def read(self, data):
"""Handles incoming raw sensor data and br... |
def _get_choices(self):
"""
Returns menus specified in ``PAGE_MENU_TEMPLATES`` unless you provide
some custom choices in the field definition.
"""
if self._overridden_choices:
# Note: choices is a property on Field bound to _get_choices().
return self._cho... | Returns menus specified in ``PAGE_MENU_TEMPLATES`` unless you provide
some custom choices in the field definition. | Below is the the instruction that describes the task:
### Input:
Returns menus specified in ``PAGE_MENU_TEMPLATES`` unless you provide
some custom choices in the field definition.
### Response:
def _get_choices(self):
"""
Returns menus specified in ``PAGE_MENU_TEMPLATES`` unless you provide... |
def custom(self, ref, context=None):
"""
Get whether the specified reference is B{not} an (xs) builtin.
@param ref: A str or qref.
@type ref: (str|qref)
@return: True if B{not} a builtin, else False.
@rtype: bool
"""
if ref is None:
return True... | Get whether the specified reference is B{not} an (xs) builtin.
@param ref: A str or qref.
@type ref: (str|qref)
@return: True if B{not} a builtin, else False.
@rtype: bool | Below is the the instruction that describes the task:
### Input:
Get whether the specified reference is B{not} an (xs) builtin.
@param ref: A str or qref.
@type ref: (str|qref)
@return: True if B{not} a builtin, else False.
@rtype: bool
### Response:
def custom(self, ref, context=No... |
def zap(input_url, archive, domain, host, internal, robots, proxies):
"""Extract links from robots.txt and sitemap.xml."""
if archive:
print('%s Fetching URLs from archive.org' % run)
if False:
archived_urls = time_machine(domain, 'domain')
else:
archived_urls = t... | Extract links from robots.txt and sitemap.xml. | Below is the the instruction that describes the task:
### Input:
Extract links from robots.txt and sitemap.xml.
### Response:
def zap(input_url, archive, domain, host, internal, robots, proxies):
"""Extract links from robots.txt and sitemap.xml."""
if archive:
print('%s Fetching URLs from archive.o... |
def tell(self):
"""Return the file's current position.
Returns:
int, file's current position in bytes.
"""
self._check_open_file()
if self._flushes_after_tell():
self.flush()
if not self._append:
return self._io.tell()
if self._... | Return the file's current position.
Returns:
int, file's current position in bytes. | Below is the the instruction that describes the task:
### Input:
Return the file's current position.
Returns:
int, file's current position in bytes.
### Response:
def tell(self):
"""Return the file's current position.
Returns:
int, file's current position in bytes.
... |
def get_queues(*queue_names, **kwargs):
"""
Return queue instances from specified queue names.
All instances must use the same Redis connection.
"""
from .settings import QUEUES
if len(queue_names) <= 1:
# Return "default" queue if no queue name is specified
# or one queue with ... | Return queue instances from specified queue names.
All instances must use the same Redis connection. | Below is the the instruction that describes the task:
### Input:
Return queue instances from specified queue names.
All instances must use the same Redis connection.
### Response:
def get_queues(*queue_names, **kwargs):
"""
Return queue instances from specified queue names.
All instances must use t... |
def zoom_out(self):
"""Scale the image down by one scale step."""
if self._scalefactor >= self._sfmin:
self._scalefactor -= 1
self.scale_image()
self._adjust_scrollbar(1/self._scalestep)
self.sig_zoom_changed.emit(self.get_scaling()) | Scale the image down by one scale step. | Below is the the instruction that describes the task:
### Input:
Scale the image down by one scale step.
### Response:
def zoom_out(self):
"""Scale the image down by one scale step."""
if self._scalefactor >= self._sfmin:
self._scalefactor -= 1
self.scale_image()
... |
def handle_command(self, master, mpstate, args):
'''handle parameter commands'''
param_wildcard = "*"
usage="Usage: param <fetch|save|set|show|load|preload|forceload|diff|download|help>"
if len(args) < 1:
print(usage)
return
if args[0] == "fetch":
... | handle parameter commands | Below is the the instruction that describes the task:
### Input:
handle parameter commands
### Response:
def handle_command(self, master, mpstate, args):
'''handle parameter commands'''
param_wildcard = "*"
usage="Usage: param <fetch|save|set|show|load|preload|forceload|diff|download|help>"... |
def rename(self, new_dirname=None, new_basename=None):
"""Rename the dirname, basename or their combinations.
**中文文档**
对文件的目录名, 文件夹名, 或它们的组合进行修改。
"""
if not new_basename:
new_basename = self.new_basename
if not new_dirname:
new_di... | Rename the dirname, basename or their combinations.
**中文文档**
对文件的目录名, 文件夹名, 或它们的组合进行修改。 | Below is the the instruction that describes the task:
### Input:
Rename the dirname, basename or their combinations.
**中文文档**
对文件的目录名, 文件夹名, 或它们的组合进行修改。
### Response:
def rename(self, new_dirname=None, new_basename=None):
"""Rename the dirname, basename or their combinatio... |
def to_identifier(string):
"""Makes a python identifier (perhaps an ugly one) out of any string.
This isn't an isomorphic change, the original name can't be recovered
from the change in all cases, so it must be stored separately.
Examples:
>>> to_identifier('Alice\'s Restaurant') -> 'Alice_s_Resta... | Makes a python identifier (perhaps an ugly one) out of any string.
This isn't an isomorphic change, the original name can't be recovered
from the change in all cases, so it must be stored separately.
Examples:
>>> to_identifier('Alice\'s Restaurant') -> 'Alice_s_Restaurant'
>>> to_identifier('#if'... | Below is the the instruction that describes the task:
### Input:
Makes a python identifier (perhaps an ugly one) out of any string.
This isn't an isomorphic change, the original name can't be recovered
from the change in all cases, so it must be stored separately.
Examples:
>>> to_identifier('Alic... |
def get_opt_add_remove_edges_greedy(instance):
'''
only apply with elementary path consistency notion
'''
sem = [sign_cons_prg, elem_path_prg, fwd_prop_prg, bwd_prop_prg]
inst = instance.to_file()
prg = [ inst, remove_edges_prg,
min_repairs_prg, show_rep_prg
... | only apply with elementary path consistency notion | Below is the the instruction that describes the task:
### Input:
only apply with elementary path consistency notion
### Response:
def get_opt_add_remove_edges_greedy(instance):
'''
only apply with elementary path consistency notion
'''
sem = [sign_cons_prg, elem_path_prg, fwd_prop_prg, bwd_prop_prg... |
def _read_blob_in_tree(tree, components):
"""Recursively open trees to ultimately read a blob"""
if len(components) == 1:
# Tree is direct parent of blob
return _read_blob(tree, components[0])
else:
# Still trees to open
dirname = components.pop(0)
for t in tree.trave... | Recursively open trees to ultimately read a blob | Below is the the instruction that describes the task:
### Input:
Recursively open trees to ultimately read a blob
### Response:
def _read_blob_in_tree(tree, components):
"""Recursively open trees to ultimately read a blob"""
if len(components) == 1:
# Tree is direct parent of blob
return _r... |
def download_member_shared(cls, member_data, target_member_dir, source=None,
max_size=MAX_SIZE_DEFAULT, id_filename=False):
"""
Download files to sync a local dir to match OH member shared data.
Files are downloaded to match their "basename" on Open Humans.
... | Download files to sync a local dir to match OH member shared data.
Files are downloaded to match their "basename" on Open Humans.
If there are multiple files with the same name, the most recent is
downloaded.
:param member_data: This field is data related to member in a project.
... | Below is the the instruction that describes the task:
### Input:
Download files to sync a local dir to match OH member shared data.
Files are downloaded to match their "basename" on Open Humans.
If there are multiple files with the same name, the most recent is
downloaded.
:param m... |
def _calc_resp(password_hash, server_challenge):
"""
Generate the LM response given a 16-byte password hash and the
challenge from the CHALLENGE_MESSAGE
:param password_hash: A 16-byte password hash
:param server_challenge: A random 8-byte response generated by the
s... | Generate the LM response given a 16-byte password hash and the
challenge from the CHALLENGE_MESSAGE
:param password_hash: A 16-byte password hash
:param server_challenge: A random 8-byte response generated by the
server in the CHALLENGE_MESSAGE
:return res: A 24-byte buffer ... | Below is the the instruction that describes the task:
### Input:
Generate the LM response given a 16-byte password hash and the
challenge from the CHALLENGE_MESSAGE
:param password_hash: A 16-byte password hash
:param server_challenge: A random 8-byte response generated by the
s... |
def _re_pattern_pprint(obj, p, cycle):
"""The pprint function for regular expression patterns."""
p.text('re.compile(')
pattern = repr(obj.pattern)
if pattern[:1] in 'uU':
pattern = pattern[1:]
prefix = 'ur'
else:
prefix = 'r'
pattern = prefix + pattern.replace('\\\\', '\... | The pprint function for regular expression patterns. | Below is the the instruction that describes the task:
### Input:
The pprint function for regular expression patterns.
### Response:
def _re_pattern_pprint(obj, p, cycle):
"""The pprint function for regular expression patterns."""
p.text('re.compile(')
pattern = repr(obj.pattern)
if pattern[:1] in '... |
def to_index(self):
"""Convert this variable to a pandas.Index"""
# n.b. creating a new pandas.Index from an old pandas.Index is
# basically free as pandas.Index objects are immutable
assert self.ndim == 1
index = self._data.array
if isinstance(index, pd.MultiIndex):
... | Convert this variable to a pandas.Index | Below is the the instruction that describes the task:
### Input:
Convert this variable to a pandas.Index
### Response:
def to_index(self):
"""Convert this variable to a pandas.Index"""
# n.b. creating a new pandas.Index from an old pandas.Index is
# basically free as pandas.Index objects ar... |
def draw_img_button(width=200, height=50, text='This is a button', color=rgb(200,100,50)):
""" Draws a simple image button. """
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
ctx = cairo.Context(surface)
ctx.rectangle(0, 0, width - 1, height - 1)
ctx.set_source_rgb(color.red/... | Draws a simple image button. | Below is the the instruction that describes the task:
### Input:
Draws a simple image button.
### Response:
def draw_img_button(width=200, height=50, text='This is a button', color=rgb(200,100,50)):
""" Draws a simple image button. """
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
... |
def _find_field_generator_templates(self):
"""
Return a dictionary of the form {name: field_generator} containing
all tohu generators defined in the class and instance namespace
of this custom generator.
"""
field_gen_templates = {}
# Extract field generators fro... | Return a dictionary of the form {name: field_generator} containing
all tohu generators defined in the class and instance namespace
of this custom generator. | Below is the the instruction that describes the task:
### Input:
Return a dictionary of the form {name: field_generator} containing
all tohu generators defined in the class and instance namespace
of this custom generator.
### Response:
def _find_field_generator_templates(self):
"""
... |
def _connect_lxd(spec):
"""
Return ContextService arguments for an LXD container connection.
"""
return {
'method': 'lxd',
'kwargs': {
'container': spec.remote_addr(),
'python_path': spec.python_path(),
'lxc_path': spec.mitogen_lxc_path(),
... | Return ContextService arguments for an LXD container connection. | Below is the the instruction that describes the task:
### Input:
Return ContextService arguments for an LXD container connection.
### Response:
def _connect_lxd(spec):
"""
Return ContextService arguments for an LXD container connection.
"""
return {
'method': 'lxd',
'kwargs': {
... |
def pg_isready(self):
"""Runs pg_isready to see if PostgreSQL is accepting connections.
:returns: 'ok' if PostgreSQL is up, 'reject' if starting up, 'no_resopnse' if not up."""
cmd = [self._pgcommand('pg_isready'), '-p', self._local_address['port'], '-d', self._database]
# Host is not... | Runs pg_isready to see if PostgreSQL is accepting connections.
:returns: 'ok' if PostgreSQL is up, 'reject' if starting up, 'no_resopnse' if not up. | Below is the the instruction that describes the task:
### Input:
Runs pg_isready to see if PostgreSQL is accepting connections.
:returns: 'ok' if PostgreSQL is up, 'reject' if starting up, 'no_resopnse' if not up.
### Response:
def pg_isready(self):
"""Runs pg_isready to see if PostgreSQL is accep... |
def set_scope(self, http_method, scope):
"""Set a scope condition for the resource for a http_method
Parameters:
* **http_method (str):** HTTP method like GET, POST, PUT, DELETE
* **scope (str, list):** the scope of access control as str if single, or as a list of strings if mul... | Set a scope condition for the resource for a http_method
Parameters:
* **http_method (str):** HTTP method like GET, POST, PUT, DELETE
* **scope (str, list):** the scope of access control as str if single, or as a list of strings if multiple scopes are to be set | Below is the the instruction that describes the task:
### Input:
Set a scope condition for the resource for a http_method
Parameters:
* **http_method (str):** HTTP method like GET, POST, PUT, DELETE
* **scope (str, list):** the scope of access control as str if single, or as a list ... |
def on_menu_make_MagIC_results_tables(self, event):
"""
Creates or Updates Specimens or Pmag Specimens MagIC table,
overwrites .redo file for safety, and starts User dialog to
generate other MagIC tables for later contribution to the MagIC
database. The following describes th... | Creates or Updates Specimens or Pmag Specimens MagIC table,
overwrites .redo file for safety, and starts User dialog to
generate other MagIC tables for later contribution to the MagIC
database. The following describes the steps used in the 2.5 data
format to do this:
1. rea... | Below is the the instruction that describes the task:
### Input:
Creates or Updates Specimens or Pmag Specimens MagIC table,
overwrites .redo file for safety, and starts User dialog to
generate other MagIC tables for later contribution to the MagIC
database. The following describes the st... |
def get_sla_template_path(service_type=ServiceTypes.ASSET_ACCESS):
"""
Get the template for a ServiceType.
:param service_type: ServiceTypes
:return: Path of the template, str
"""
if service_type == ServiceTypes.ASSET_ACCESS:
name = 'access_sla_template.json'
elif service_type == Se... | Get the template for a ServiceType.
:param service_type: ServiceTypes
:return: Path of the template, str | Below is the the instruction that describes the task:
### Input:
Get the template for a ServiceType.
:param service_type: ServiceTypes
:return: Path of the template, str
### Response:
def get_sla_template_path(service_type=ServiceTypes.ASSET_ACCESS):
"""
Get the template for a ServiceType.
:p... |
def delete_route_table(route_table_id=None, route_table_name=None,
region=None, key=None, keyid=None, profile=None):
'''
Deletes a route table.
CLI Examples:
.. code-block:: bash
salt myminion boto_vpc.delete_route_table route_table_id='rtb-1f382e7d'
salt mymini... | Deletes a route table.
CLI Examples:
.. code-block:: bash
salt myminion boto_vpc.delete_route_table route_table_id='rtb-1f382e7d'
salt myminion boto_vpc.delete_route_table route_table_name='myroutetable' | Below is the the instruction that describes the task:
### Input:
Deletes a route table.
CLI Examples:
.. code-block:: bash
salt myminion boto_vpc.delete_route_table route_table_id='rtb-1f382e7d'
salt myminion boto_vpc.delete_route_table route_table_name='myroutetable'
### Response:
def d... |
def get_sentry(self, username):
"""
Returns contents of sentry file for the given username
.. note::
returns ``None`` if :attr:`credential_location` is not set, or file is not found/inaccessible
:param username: username
:type username: :class:`str`
:return:... | Returns contents of sentry file for the given username
.. note::
returns ``None`` if :attr:`credential_location` is not set, or file is not found/inaccessible
:param username: username
:type username: :class:`str`
:return: sentry file contents, or ``None``
:rtype: :... | Below is the the instruction that describes the task:
### Input:
Returns contents of sentry file for the given username
.. note::
returns ``None`` if :attr:`credential_location` is not set, or file is not found/inaccessible
:param username: username
:type username: :class:`str`... |
def monte_carlo_csiszar_f_divergence(
f,
p_log_prob,
q,
num_draws,
use_reparametrization=None,
seed=None,
name=None):
"""Monte-Carlo approximation of the Csiszar f-Divergence.
A Csiszar-function is a member of,
```none
F = { f:R_+ to R : f convex }.
```
The Csiszar f-Divergenc... | Monte-Carlo approximation of the Csiszar f-Divergence.
A Csiszar-function is a member of,
```none
F = { f:R_+ to R : f convex }.
```
The Csiszar f-Divergence for Csiszar-function f is given by:
```none
D_f[p(X), q(X)] := E_{q(X)}[ f( p(X) / q(X) ) ]
~= m**-1 sum_j^m f( p(x_j) / q(x_j... | Below is the the instruction that describes the task:
### Input:
Monte-Carlo approximation of the Csiszar f-Divergence.
A Csiszar-function is a member of,
```none
F = { f:R_+ to R : f convex }.
```
The Csiszar f-Divergence for Csiszar-function f is given by:
```none
D_f[p(X), q(X)] := E_{q(X)}[ f(... |
def process_result(transmute_func, context, result, exc, content_type):
"""
process a result:
transmute_func: the transmute_func function that returned the response.
context: the transmute_context to use.
result: the return value of the function, which will be serialized and
returned ... | process a result:
transmute_func: the transmute_func function that returned the response.
context: the transmute_context to use.
result: the return value of the function, which will be serialized and
returned back in the API.
exc: the exception object. For Python 2, the traceback should
... | Below is the the instruction that describes the task:
### Input:
process a result:
transmute_func: the transmute_func function that returned the response.
context: the transmute_context to use.
result: the return value of the function, which will be serialized and
returned back in the API... |
def parseURIRaw(str, raw):
"""Parse an URI but allows to keep intact the original
fragments. URI-reference = URI / relative-ref """
ret = libxml2mod.xmlParseURIRaw(str, raw)
if ret is None:raise uriError('xmlParseURIRaw() failed')
return URI(_obj=ret) | Parse an URI but allows to keep intact the original
fragments. URI-reference = URI / relative-ref | Below is the the instruction that describes the task:
### Input:
Parse an URI but allows to keep intact the original
fragments. URI-reference = URI / relative-ref
### Response:
def parseURIRaw(str, raw):
"""Parse an URI but allows to keep intact the original
fragments. URI-reference = URI / rel... |
def get_pipe_series_output(commands: Sequence[str],
stdinput: BinaryIO = None) -> bytes:
"""
Get the output from a piped series of commands.
Args:
commands: sequence of command strings
stdinput: optional ``stdin`` data to feed into the start of the pipe
Retur... | Get the output from a piped series of commands.
Args:
commands: sequence of command strings
stdinput: optional ``stdin`` data to feed into the start of the pipe
Returns:
``stdout`` from the end of the pipe | Below is the the instruction that describes the task:
### Input:
Get the output from a piped series of commands.
Args:
commands: sequence of command strings
stdinput: optional ``stdin`` data to feed into the start of the pipe
Returns:
``stdout`` from the end of the pipe
### Respons... |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'id') and self.id is not None:
_dict['id'] = self.id
return _dict | 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, 'id') and self.id is not None:
_dict['id'] = s... |
def load_etext(etextno, refresh_cache=False, mirror=None, prefer_ascii=False):
"""Returns a unicode representation of the full body of a Project Gutenberg
text. After making an initial remote call to Project Gutenberg's servers,
the text is persisted locally.
"""
etextno = validate_etextno(etextno)... | Returns a unicode representation of the full body of a Project Gutenberg
text. After making an initial remote call to Project Gutenberg's servers,
the text is persisted locally. | Below is the the instruction that describes the task:
### Input:
Returns a unicode representation of the full body of a Project Gutenberg
text. After making an initial remote call to Project Gutenberg's servers,
the text is persisted locally.
### Response:
def load_etext(etextno, refresh_cache=False, mirro... |
def disable(self):
"""Disables the entity at this endpoint."""
self.post("disable")
if self.service.restart_required:
self.service.restart(120)
return self | Disables the entity at this endpoint. | Below is the the instruction that describes the task:
### Input:
Disables the entity at this endpoint.
### Response:
def disable(self):
"""Disables the entity at this endpoint."""
self.post("disable")
if self.service.restart_required:
self.service.restart(120)
return sel... |
def _software(self, *args, **kwargs):
'''
Return installed software.
'''
data = dict()
if 'exclude' in kwargs:
excludes = kwargs['exclude'].split(",")
else:
excludes = list()
os_family = __grains__.get("os_family").lower()
# Get l... | Return installed software. | Below is the the instruction that describes the task:
### Input:
Return installed software.
### Response:
def _software(self, *args, **kwargs):
'''
Return installed software.
'''
data = dict()
if 'exclude' in kwargs:
excludes = kwargs['exclude'].split(",")
... |
def add_preset(self, name=None, desc=None, note=None, opts=SoSOptions()):
"""Add a new on-disk preset and write it to the configured
presets path.
:param preset: the new PresetDefaults to add
"""
presets_path = self.presets_path
if not name:
raise Va... | Add a new on-disk preset and write it to the configured
presets path.
:param preset: the new PresetDefaults to add | Below is the the instruction that describes the task:
### Input:
Add a new on-disk preset and write it to the configured
presets path.
:param preset: the new PresetDefaults to add
### Response:
def add_preset(self, name=None, desc=None, note=None, opts=SoSOptions()):
"""Add a new o... |
def transformer_librispeech_v2():
"""HParams for training ASR model on LibriSpeech V2."""
hparams = transformer_base()
hparams.max_length = 1240000
hparams.max_input_seq_length = 1550
hparams.max_target_seq_length = 350
hparams.batch_size = 16
hparams.num_decoder_layers = 4
hparams.num_encoder_layers =... | HParams for training ASR model on LibriSpeech V2. | Below is the the instruction that describes the task:
### Input:
HParams for training ASR model on LibriSpeech V2.
### Response:
def transformer_librispeech_v2():
"""HParams for training ASR model on LibriSpeech V2."""
hparams = transformer_base()
hparams.max_length = 1240000
hparams.max_input_seq_length ... |
def paintMilestone( self, painter ):
"""
Paints this item as the milestone look.
:param painter | <QPainter>
"""
# generate the rect
rect = self.rect()
padding = self.padding()
gantt = self.scene().ganttWidget()
cell_w... | Paints this item as the milestone look.
:param painter | <QPainter> | Below is the the instruction that describes the task:
### Input:
Paints this item as the milestone look.
:param painter | <QPainter>
### Response:
def paintMilestone( self, painter ):
"""
Paints this item as the milestone look.
:param painter | <QPainter>... |
def bbox(self):
"""(left, top, right, bottom) tuple."""
if not hasattr(self, '_bbox'):
self._bbox = extract_bbox(self)
return self._bbox | (left, top, right, bottom) tuple. | Below is the the instruction that describes the task:
### Input:
(left, top, right, bottom) tuple.
### Response:
def bbox(self):
"""(left, top, right, bottom) tuple."""
if not hasattr(self, '_bbox'):
self._bbox = extract_bbox(self)
return self._bbox |
def _postprocess_data(self, data):
"""
Applies necessary type transformation to the data before
it is set on a ColumnDataSource.
"""
new_data = {}
for k, values in data.items():
values = decode_bytes(values) # Bytes need decoding to strings
# Cert... | Applies necessary type transformation to the data before
it is set on a ColumnDataSource. | Below is the the instruction that describes the task:
### Input:
Applies necessary type transformation to the data before
it is set on a ColumnDataSource.
### Response:
def _postprocess_data(self, data):
"""
Applies necessary type transformation to the data before
it is set on a Col... |
def addSkip(self, test, reason):
"""Register that a test that was skipped.
Parameters
----------
test : unittest.TestCase
The test that has completed.
reason : str
The reason the test was skipped.
"""
result = self._handle_result(
... | Register that a test that was skipped.
Parameters
----------
test : unittest.TestCase
The test that has completed.
reason : str
The reason the test was skipped. | Below is the the instruction that describes the task:
### Input:
Register that a test that was skipped.
Parameters
----------
test : unittest.TestCase
The test that has completed.
reason : str
The reason the test was skipped.
### Response:
def addSkip(self, ... |
def sixteen_oscillator_two_stimulated_ensembles_grid():
"Not accurate false due to spikes are observed"
parameters = legion_parameters();
parameters.teta_x = -1.1;
template_dynamic_legion(16, 2000, 1500, conn_type = conn_type.GRID_FOUR, params = parameters, stimulus = [1, 1, 1, 0,
... | Not accurate false due to spikes are observed | Below is the the instruction that describes the task:
### Input:
Not accurate false due to spikes are observed
### Response:
def sixteen_oscillator_two_stimulated_ensembles_grid():
"Not accurate false due to spikes are observed"
parameters = legion_parameters();
parameters.teta_x = -1.1;
templa... |
def starter(cls):
"""Get bounced start URL."""
data = cls.getPage(cls.url)
url1 = cls.fetchUrl(cls.url, data, cls.prevSearch)
data = cls.getPage(url1)
url2 = cls.fetchUrl(url1, data, cls.nextSearch)
return cls.prevUrlModifier(url2) | Get bounced start URL. | Below is the the instruction that describes the task:
### Input:
Get bounced start URL.
### Response:
def starter(cls):
"""Get bounced start URL."""
data = cls.getPage(cls.url)
url1 = cls.fetchUrl(cls.url, data, cls.prevSearch)
data = cls.getPage(url1)
url2 = cls.fetchUrl(ur... |
def hl_table2canvas(self, w, res_dict):
"""Highlight marking on canvas when user click on table."""
objlist = []
width = self.markwidth + self._dwidth
# Remove existing highlight
if self.markhltag:
try:
self.canvas.delete_object_by_tag(self.markhltag,... | Highlight marking on canvas when user click on table. | Below is the the instruction that describes the task:
### Input:
Highlight marking on canvas when user click on table.
### Response:
def hl_table2canvas(self, w, res_dict):
"""Highlight marking on canvas when user click on table."""
objlist = []
width = self.markwidth + self._dwidth
... |
def _edge_event(self, i, j):
"""
Force edge (i, j) to be present in mesh.
This works by removing intersected triangles and filling holes up to
the cutting edge.
"""
front_index = self._front.index(i)
#debug(" == edge event ==")
front = self._fro... | Force edge (i, j) to be present in mesh.
This works by removing intersected triangles and filling holes up to
the cutting edge. | Below is the the instruction that describes the task:
### Input:
Force edge (i, j) to be present in mesh.
This works by removing intersected triangles and filling holes up to
the cutting edge.
### Response:
def _edge_event(self, i, j):
"""
Force edge (i, j) to be present in mesh.
... |
def _union_copy(dict1, dict2):
"""
Internal wrapper to keep one level of copying out of play, for efficiency.
Only copies data on dict2, but will alter dict1.
"""
for key, value in dict2.items():
if key in dict1 and isinstance(value, dict):
dict1[key] = _union_copy(dict1[key], ... | Internal wrapper to keep one level of copying out of play, for efficiency.
Only copies data on dict2, but will alter dict1. | Below is the the instruction that describes the task:
### Input:
Internal wrapper to keep one level of copying out of play, for efficiency.
Only copies data on dict2, but will alter dict1.
### Response:
def _union_copy(dict1, dict2):
"""
Internal wrapper to keep one level of copying out of play, for e... |
def add_metaclass(metaclass):
"""
Class decorator for creating a class with a metaclass.
Adapted from the six project:
https://pythonhosted.org/six/
"""
vars_to_skip = ('__dict__', '__weakref__')
def wrapper(cls):
copied_dict = {
key: value
for key, value i... | Class decorator for creating a class with a metaclass.
Adapted from the six project:
https://pythonhosted.org/six/ | Below is the the instruction that describes the task:
### Input:
Class decorator for creating a class with a metaclass.
Adapted from the six project:
https://pythonhosted.org/six/
### Response:
def add_metaclass(metaclass):
"""
Class decorator for creating a class with a metaclass.
Adapted f... |
def get_components(self, uri):
"""
Get components from a component definition in order
"""
try:
component_definition = self._components[uri]
except KeyError:
return False
sorted_sequences = sorted(component_definition.sequence_annotations,
... | Get components from a component definition in order | Below is the the instruction that describes the task:
### Input:
Get components from a component definition in order
### Response:
def get_components(self, uri):
"""
Get components from a component definition in order
"""
try:
component_definition = self._components[uri]... |
def build(self):
"""
Create the current layer
:return: string of the packet with the payload
"""
p = self.do_build()
p += self.build_padding()
p = self.build_done(p)
return p | Create the current layer
:return: string of the packet with the payload | Below is the the instruction that describes the task:
### Input:
Create the current layer
:return: string of the packet with the payload
### Response:
def build(self):
"""
Create the current layer
:return: string of the packet with the payload
"""
p = self.do_build... |
def dist_is_editable(dist):
# type: (Distribution) -> bool
"""
Return True if given Distribution is an editable install.
"""
for path_item in sys.path:
egg_link = os.path.join(path_item, dist.project_name + '.egg-link')
if os.path.isfile(egg_link):
return True
return ... | Return True if given Distribution is an editable install. | Below is the the instruction that describes the task:
### Input:
Return True if given Distribution is an editable install.
### Response:
def dist_is_editable(dist):
# type: (Distribution) -> bool
"""
Return True if given Distribution is an editable install.
"""
for path_item in sys.path:
... |
def _parseWasbUrl(cls, url):
"""
:param urlparse.ParseResult url: x
:rtype: AzureJobStore.BlobInfo
"""
assert url.scheme in ('wasb', 'wasbs')
try:
container, account = url.netloc.split('@')
except ValueError:
raise InvalidImportExportUrlExc... | :param urlparse.ParseResult url: x
:rtype: AzureJobStore.BlobInfo | Below is the the instruction that describes the task:
### Input:
:param urlparse.ParseResult url: x
:rtype: AzureJobStore.BlobInfo
### Response:
def _parseWasbUrl(cls, url):
"""
:param urlparse.ParseResult url: x
:rtype: AzureJobStore.BlobInfo
"""
assert url.scheme i... |
def _get_time_at_progress(self, x_target):
"""
Return the projected time when progress level `x_target` will be reached.
Since the underlying progress model is nonlinear, we need to do use Newton method to find a numerical solution
to the equation x(t) = x_target.
"""
t,... | Return the projected time when progress level `x_target` will be reached.
Since the underlying progress model is nonlinear, we need to do use Newton method to find a numerical solution
to the equation x(t) = x_target. | Below is the the instruction that describes the task:
### Input:
Return the projected time when progress level `x_target` will be reached.
Since the underlying progress model is nonlinear, we need to do use Newton method to find a numerical solution
to the equation x(t) = x_target.
### Response:
d... |
def get_ssh_key(host,
username,
password,
protocol=None,
port=None,
certificate_verify=False):
'''
Retrieve the authorized_keys entry for root.
This function only works for ESXi, not vCenter.
:param host: The location of th... | Retrieve the authorized_keys entry for root.
This function only works for ESXi, not vCenter.
:param host: The location of the ESXi Host
:param username: Username to connect as
:param password: Password for the ESXi web endpoint
:param protocol: defaults to https, can be http if ssl is disabled on E... | Below is the the instruction that describes the task:
### Input:
Retrieve the authorized_keys entry for root.
This function only works for ESXi, not vCenter.
:param host: The location of the ESXi Host
:param username: Username to connect as
:param password: Password for the ESXi web endpoint
:p... |
def int_to_bytes(i, minlen=1, order='big'): # pragma: no cover
"""convert integer to bytes"""
blen = max(minlen, PGPObject.int_byte_len(i), 1)
if six.PY2:
r = iter(_ * 8 for _ in (range(blen) if order == 'little' else range(blen - 1, -1, -1)))
return bytes(bytearray((i ... | convert integer to bytes | Below is the the instruction that describes the task:
### Input:
convert integer to bytes
### Response:
def int_to_bytes(i, minlen=1, order='big'): # pragma: no cover
"""convert integer to bytes"""
blen = max(minlen, PGPObject.int_byte_len(i), 1)
if six.PY2:
r = iter(_ * 8 for... |
def _check_for_duplicates(durations, events):
"""Checks for duplicated event times in the data set. This is narrowed to detecting duplicated event times
where the events are of different types
"""
# Setting up DataFrame to detect duplicates
df = pd.DataFrame({"t": durations, "e":... | Checks for duplicated event times in the data set. This is narrowed to detecting duplicated event times
where the events are of different types | Below is the the instruction that describes the task:
### Input:
Checks for duplicated event times in the data set. This is narrowed to detecting duplicated event times
where the events are of different types
### Response:
def _check_for_duplicates(durations, events):
"""Checks for duplicated event... |
def main(argv): # pylint: disable=W0613
'''
Main program body
'''
thin_path = os.path.join(OPTIONS.saltdir, THIN_ARCHIVE)
if os.path.isfile(thin_path):
if OPTIONS.checksum != get_hash(thin_path, OPTIONS.hashfunc):
need_deployment()
unpack_thin(thin_path)
# Salt t... | Main program body | Below is the the instruction that describes the task:
### Input:
Main program body
### Response:
def main(argv): # pylint: disable=W0613
'''
Main program body
'''
thin_path = os.path.join(OPTIONS.saltdir, THIN_ARCHIVE)
if os.path.isfile(thin_path):
if OPTIONS.checksum != get_hash(thin_... |
def get_enabled_browsers():
"""
Check the ADMINFILES_BROWSER_VIEWS setting and return a list of
instantiated browser views that have the necessary
dependencies/configuration to run.
"""
global _enabled_browsers_cache
if _enabled_browsers_cache is not None:
return _enabled_browsers_c... | Check the ADMINFILES_BROWSER_VIEWS setting and return a list of
instantiated browser views that have the necessary
dependencies/configuration to run. | Below is the the instruction that describes the task:
### Input:
Check the ADMINFILES_BROWSER_VIEWS setting and return a list of
instantiated browser views that have the necessary
dependencies/configuration to run.
### Response:
def get_enabled_browsers():
"""
Check the ADMINFILES_BROWSER_VIEWS set... |
def explode_azure_storage_url(url):
# type: (str) -> Tuple[str, str, str, str, str]
"""Explode Azure Storage URL into parts
:param url str: storage url
:rtype: tuple
:return: (sa, mode, ep, rpath, sas)
"""
tmp = url.split('/')
host = tmp[2].split('.')
sa = host[0]
mode = host[1].... | Explode Azure Storage URL into parts
:param url str: storage url
:rtype: tuple
:return: (sa, mode, ep, rpath, sas) | Below is the the instruction that describes the task:
### Input:
Explode Azure Storage URL into parts
:param url str: storage url
:rtype: tuple
:return: (sa, mode, ep, rpath, sas)
### Response:
def explode_azure_storage_url(url):
# type: (str) -> Tuple[str, str, str, str, str]
"""Explode Azure ... |
def _configure_send(self, request, **kwargs):
# type: (ClientRequest, Any) -> Dict[str, str]
"""Configure the kwargs to use with requests.
See "send" for kwargs details.
:param ClientRequest request: The request object to be sent.
:returns: The requests.Session.request kwargs
... | Configure the kwargs to use with requests.
See "send" for kwargs details.
:param ClientRequest request: The request object to be sent.
:returns: The requests.Session.request kwargs
:rtype: dict[str,str] | Below is the the instruction that describes the task:
### Input:
Configure the kwargs to use with requests.
See "send" for kwargs details.
:param ClientRequest request: The request object to be sent.
:returns: The requests.Session.request kwargs
:rtype: dict[str,str]
### Response: ... |
def aws(self):
"""
Access the aws
:returns: twilio.rest.accounts.v1.credential.aws.AwsList
:rtype: twilio.rest.accounts.v1.credential.aws.AwsList
"""
if self._aws is None:
self._aws = AwsList(self._version, )
return self._aws | Access the aws
:returns: twilio.rest.accounts.v1.credential.aws.AwsList
:rtype: twilio.rest.accounts.v1.credential.aws.AwsList | Below is the the instruction that describes the task:
### Input:
Access the aws
:returns: twilio.rest.accounts.v1.credential.aws.AwsList
:rtype: twilio.rest.accounts.v1.credential.aws.AwsList
### Response:
def aws(self):
"""
Access the aws
:returns: twilio.rest.accounts.v1... |
def get_coding_intervals(self, build='37', genes=None):
"""Return a dictionary with chromosomes as keys and interval trees as values
Each interval represents a coding region of overlapping genes.
Args:
build(str): The genome build
genes(iterable(scout.models.HgncGene)):... | Return a dictionary with chromosomes as keys and interval trees as values
Each interval represents a coding region of overlapping genes.
Args:
build(str): The genome build
genes(iterable(scout.models.HgncGene)):
Returns:
intervals(dict): A dictionary with c... | Below is the the instruction that describes the task:
### Input:
Return a dictionary with chromosomes as keys and interval trees as values
Each interval represents a coding region of overlapping genes.
Args:
build(str): The genome build
genes(iterable(scout.models.HgncGene)... |
def load_database(adapter, variant_file=None, sv_file=None, family_file=None,
family_type='ped', skip_case_id=False, gq_treshold=None,
case_id=None, max_window = 3000, profile_file=None,
hard_threshold=0.95, soft_threshold=0.9):
"""Load the database with a case ... | Load the database with a case and its variants
Args:
adapter: Connection to database
variant_file(str): Path to variant file
sv_file(str): Path to sv variant file
family_file(str): Path to family file
family_type(str): Format of family file
skip_case_id(b... | Below is the the instruction that describes the task:
### Input:
Load the database with a case and its variants
Args:
adapter: Connection to database
variant_file(str): Path to variant file
sv_file(str): Path to sv variant file
family_file(str): Path to family file
... |
def parse_portal_json():
""" Extract id, ip from https://www.meethue.com/api/nupnp
Note: the ip is only the base and needs xml file appended, and
the id is not exactly the same as the serial number in the xml
"""
try:
json_str = from_url('https://www.meethue.com/api/nupnp')
except urlli... | Extract id, ip from https://www.meethue.com/api/nupnp
Note: the ip is only the base and needs xml file appended, and
the id is not exactly the same as the serial number in the xml | Below is the the instruction that describes the task:
### Input:
Extract id, ip from https://www.meethue.com/api/nupnp
Note: the ip is only the base and needs xml file appended, and
the id is not exactly the same as the serial number in the xml
### Response:
def parse_portal_json():
""" Extract id, ip... |
def rpc_receiver_count(self, service, routing_id):
'''Get the number of peers that would handle a particular RPC
:param service: the service name
:type service: anything hash-able
:param routing_id:
the id used for narrowing within the service handlers
:type routing_... | Get the number of peers that would handle a particular RPC
:param service: the service name
:type service: anything hash-able
:param routing_id:
the id used for narrowing within the service handlers
:type routing_id: int
:returns:
the integer number of p... | Below is the the instruction that describes the task:
### Input:
Get the number of peers that would handle a particular RPC
:param service: the service name
:type service: anything hash-able
:param routing_id:
the id used for narrowing within the service handlers
:type r... |
def round_dict(dic, places):
"""
Rounds all values in a dict containing only numeric types to `places` decimal places.
If places is None, round to INT.
"""
if places is None:
for key, value in dic.items():
dic[key] = round(value)
else:
for key, value in dic.items():
... | Rounds all values in a dict containing only numeric types to `places` decimal places.
If places is None, round to INT. | Below is the the instruction that describes the task:
### Input:
Rounds all values in a dict containing only numeric types to `places` decimal places.
If places is None, round to INT.
### Response:
def round_dict(dic, places):
"""
Rounds all values in a dict containing only numeric types to `places` de... |
def to_array(self, channels=2):
"""Generate the array of volume multipliers for the dynamic"""
if self.fade_type == "linear":
return np.linspace(self.in_volume, self.out_volume,
self.duration * channels)\
.reshape(self.duration, channels)
elif self.fad... | Generate the array of volume multipliers for the dynamic | Below is the the instruction that describes the task:
### Input:
Generate the array of volume multipliers for the dynamic
### Response:
def to_array(self, channels=2):
"""Generate the array of volume multipliers for the dynamic"""
if self.fade_type == "linear":
return np.linspace(self.i... |
def _basis_spline_factory(coef, degree, knots, der, ext):
"""Return a B-Spline given some coefficients."""
return functools.partial(interpolate.splev, tck=(knots, coef, degree), der=der, ext=ext) | Return a B-Spline given some coefficients. | Below is the the instruction that describes the task:
### Input:
Return a B-Spline given some coefficients.
### Response:
def _basis_spline_factory(coef, degree, knots, der, ext):
"""Return a B-Spline given some coefficients."""
return functools.partial(interpolate.splev, tck=(knots, coef, degree),... |
def last(self, rows: List[Row]) -> List[Row]:
"""
Takes an expression that evaluates to a list of rows, and returns the last one in that
list.
"""
if not rows:
logger.warning("Trying to get last row from an empty list")
return []
return [rows[-1]] | Takes an expression that evaluates to a list of rows, and returns the last one in that
list. | Below is the the instruction that describes the task:
### Input:
Takes an expression that evaluates to a list of rows, and returns the last one in that
list.
### Response:
def last(self, rows: List[Row]) -> List[Row]:
"""
Takes an expression that evaluates to a list of rows, and returns the... |
def _find_project_config_file(user_config_file):
"""Find path to project-wide config file
Search from current working directory, and traverse path up to
directory with .versionner.rc file or root directory
:param user_config_file: instance with user-wide config path
:type: pathlib.Path
:rtype: ... | Find path to project-wide config file
Search from current working directory, and traverse path up to
directory with .versionner.rc file or root directory
:param user_config_file: instance with user-wide config path
:type: pathlib.Path
:rtype: pathlib.Path | Below is the the instruction that describes the task:
### Input:
Find path to project-wide config file
Search from current working directory, and traverse path up to
directory with .versionner.rc file or root directory
:param user_config_file: instance with user-wide config path
:type: pathlib.Path... |
def register_callback_renamed(self, func, serialised=True):
"""
Register a callback for resource rename. This will be called when any resource
is renamed within your agent.
If `serialised` is not set, the callbacks might arrive in a different order to they were requested.
The p... | Register a callback for resource rename. This will be called when any resource
is renamed within your agent.
If `serialised` is not set, the callbacks might arrive in a different order to they were requested.
The payload passed to your callback is an OrderedDict with the following keys
... | Below is the the instruction that describes the task:
### Input:
Register a callback for resource rename. This will be called when any resource
is renamed within your agent.
If `serialised` is not set, the callbacks might arrive in a different order to they were requested.
The payload pass... |
def _has_bcftools_germline_stats(data):
"""Check for the presence of a germline stats file, CWL compatible.
"""
stats_file = tz.get_in(["summary", "qc"], data)
if isinstance(stats_file, dict):
stats_file = tz.get_in(["variants", "base"], stats_file)
if not stats_file:
stats_file = ""... | Check for the presence of a germline stats file, CWL compatible. | Below is the the instruction that describes the task:
### Input:
Check for the presence of a germline stats file, CWL compatible.
### Response:
def _has_bcftools_germline_stats(data):
"""Check for the presence of a germline stats file, CWL compatible.
"""
stats_file = tz.get_in(["summary", "qc"], data)... |
def _field_value_text(self, field):
"""Return the html representation of the value of the given field"""
if field in self.fields:
return unicode(self.get(field))
else:
return self.get_timemachine_instance(field)._object_name_text() | Return the html representation of the value of the given field | Below is the the instruction that describes the task:
### Input:
Return the html representation of the value of the given field
### Response:
def _field_value_text(self, field):
"""Return the html representation of the value of the given field"""
if field in self.fields:
return unicode(... |
def prepread(sheet, header=True, startcell=None, stopcell=None):
"""Return four StartStop objects, defining the outer bounds of
header row and data range, respectively. If header is False, the
first two items will be None.
--> [headstart, headstop, datstart, datstop]
sheet: xlrd.sheet.Sheet instan... | Return four StartStop objects, defining the outer bounds of
header row and data range, respectively. If header is False, the
first two items will be None.
--> [headstart, headstop, datstart, datstop]
sheet: xlrd.sheet.Sheet instance
Ready for use.
header: bool or str
True if the d... | Below is the the instruction that describes the task:
### Input:
Return four StartStop objects, defining the outer bounds of
header row and data range, respectively. If header is False, the
first two items will be None.
--> [headstart, headstop, datstart, datstop]
sheet: xlrd.sheet.Sheet instance
... |
def list_balancers(profile, **libcloud_kwargs):
'''
Return a list of load balancers.
:param profile: The profile key
:type profile: ``str``
:param libcloud_kwargs: Extra arguments for the driver's list_balancers method
:type libcloud_kwargs: ``dict``
CLI Example:
.. code-block:: ba... | Return a list of load balancers.
:param profile: The profile key
:type profile: ``str``
:param libcloud_kwargs: Extra arguments for the driver's list_balancers method
:type libcloud_kwargs: ``dict``
CLI Example:
.. code-block:: bash
salt myminion libcloud_storage.list_balancers pr... | Below is the the instruction that describes the task:
### Input:
Return a list of load balancers.
:param profile: The profile key
:type profile: ``str``
:param libcloud_kwargs: Extra arguments for the driver's list_balancers method
:type libcloud_kwargs: ``dict``
CLI Example:
.. code-b... |
def clear(self, page_size=10, vtimeout=10):
"""Utility function to remove all messages from a queue"""
n = 0
l = self.get_messages(page_size, vtimeout)
while l:
for m in l:
self.delete_message(m)
n += 1
l = self.get_messages(page_si... | Utility function to remove all messages from a queue | Below is the the instruction that describes the task:
### Input:
Utility function to remove all messages from a queue
### Response:
def clear(self, page_size=10, vtimeout=10):
"""Utility function to remove all messages from a queue"""
n = 0
l = self.get_messages(page_size, vtimeout)
... |
def estimateabundance(self):
"""
Estimate the abundance of taxonomic groups
"""
logging.info('Estimating abundance of taxonomic groups')
# Create and start threads
for i in range(self.cpus):
# Send the threads to the appropriate destination function
... | Estimate the abundance of taxonomic groups | Below is the the instruction that describes the task:
### Input:
Estimate the abundance of taxonomic groups
### Response:
def estimateabundance(self):
"""
Estimate the abundance of taxonomic groups
"""
logging.info('Estimating abundance of taxonomic groups')
# Create and sta... |
def round(self, value_array):
"""
Rounds a categorical variable by setting to one the max of the given vector and to zero the rest of the entries.
Assumes an 1x[number of categories] array (due to one-hot encoding) as an input
"""
rounded_values = np.zeros(value_array.shape)
... | Rounds a categorical variable by setting to one the max of the given vector and to zero the rest of the entries.
Assumes an 1x[number of categories] array (due to one-hot encoding) as an input | Below is the the instruction that describes the task:
### Input:
Rounds a categorical variable by setting to one the max of the given vector and to zero the rest of the entries.
Assumes an 1x[number of categories] array (due to one-hot encoding) as an input
### Response:
def round(self, value_array):
... |
def _header(self, pam=False):
"""Return file header as byte string."""
if pam or self.magicnum == b'P7':
header = "\n".join((
"P7",
"HEIGHT %i" % self.height,
"WIDTH %i" % self.width,
"DEPTH %i" % self.depth,
"MA... | Return file header as byte string. | Below is the the instruction that describes the task:
### Input:
Return file header as byte string.
### Response:
def _header(self, pam=False):
"""Return file header as byte string."""
if pam or self.magicnum == b'P7':
header = "\n".join((
"P7",
"HEIGHT %... |
def _generate_message_error(cls, response_code, messages, response_id):
"""
:type response_code: int
:type messages: list[str]
:type response_id: str
:rtype: str
"""
line_response_code = cls._FORMAT_RESPONSE_CODE_LINE \
.format(response_code)
... | :type response_code: int
:type messages: list[str]
:type response_id: str
:rtype: str | Below is the the instruction that describes the task:
### Input:
:type response_code: int
:type messages: list[str]
:type response_id: str
:rtype: str
### Response:
def _generate_message_error(cls, response_code, messages, response_id):
"""
:type response_code: int
... |
def in_(self, qfield, *values):
''' Works the same as the query expression method ``in_``
'''
self.__query_obj.in_(qfield, *values)
return self | Works the same as the query expression method ``in_`` | Below is the the instruction that describes the task:
### Input:
Works the same as the query expression method ``in_``
### Response:
def in_(self, qfield, *values):
''' Works the same as the query expression method ``in_``
'''
self.__query_obj.in_(qfield, *values)
return self |
def add_to_batch(self, batch):
'''
Adds paths to the given batch object. They are all added as
GL_TRIANGLES, so the batch will aggregate them all into a single OpenGL
primitive.
'''
for name in self.paths:
svg_path = self.paths[name]
svg_path.add_t... | Adds paths to the given batch object. They are all added as
GL_TRIANGLES, so the batch will aggregate them all into a single OpenGL
primitive. | Below is the the instruction that describes the task:
### Input:
Adds paths to the given batch object. They are all added as
GL_TRIANGLES, so the batch will aggregate them all into a single OpenGL
primitive.
### Response:
def add_to_batch(self, batch):
'''
Adds paths to the given ba... |
def _validate_index_level(self, level):
"""
Validate index level.
For single-level Index getting level number is a no-op, but some
verification must be done like in MultiIndex.
"""
if isinstance(level, int):
if level < 0 and level != -1:
rais... | Validate index level.
For single-level Index getting level number is a no-op, but some
verification must be done like in MultiIndex. | Below is the the instruction that describes the task:
### Input:
Validate index level.
For single-level Index getting level number is a no-op, but some
verification must be done like in MultiIndex.
### Response:
def _validate_index_level(self, level):
"""
Validate index level.
... |
def agent_for_socks_port(reactor, torconfig, socks_config, pool=None):
"""
This returns a Deferred that fires with an object that implements
:class:`twisted.web.iweb.IAgent` and is thus suitable for passing
to ``treq`` as the ``agent=`` kwarg. Of course can be used
directly; see `using Twisted web c... | This returns a Deferred that fires with an object that implements
:class:`twisted.web.iweb.IAgent` and is thus suitable for passing
to ``treq`` as the ``agent=`` kwarg. Of course can be used
directly; see `using Twisted web cliet
<http://twistedmatrix.com/documents/current/web/howto/client.html>`_. If
... | Below is the the instruction that describes the task:
### Input:
This returns a Deferred that fires with an object that implements
:class:`twisted.web.iweb.IAgent` and is thus suitable for passing
to ``treq`` as the ``agent=`` kwarg. Of course can be used
directly; see `using Twisted web cliet
<http... |
def set_input_divide_by_period(holder, period, array):
"""
This function can be declared as a ``set_input`` attribute of a variable.
In this case, the variable will accept inputs on larger periods that its definition period, and the value for the larger period will be divided between its subperiods... | This function can be declared as a ``set_input`` attribute of a variable.
In this case, the variable will accept inputs on larger periods that its definition period, and the value for the larger period will be divided between its subperiods.
To read more about ``set_input`` attributes, check the `docu... | Below is the the instruction that describes the task:
### Input:
This function can be declared as a ``set_input`` attribute of a variable.
In this case, the variable will accept inputs on larger periods that its definition period, and the value for the larger period will be divided between its subperiods.
... |
def breadcrumb(self):
""" Get the category hierarchy leading up to this category, including
root and self.
For example, path/to/long/category will return a list containing
Category('path'), Category('path/to'), and Category('path/to/long').
"""
ret = []
here = se... | Get the category hierarchy leading up to this category, including
root and self.
For example, path/to/long/category will return a list containing
Category('path'), Category('path/to'), and Category('path/to/long'). | Below is the the instruction that describes the task:
### Input:
Get the category hierarchy leading up to this category, including
root and self.
For example, path/to/long/category will return a list containing
Category('path'), Category('path/to'), and Category('path/to/long').
### Respons... |
def qteSplitApplet(self, applet: (QtmacsApplet, str)=None,
splitHoriz: bool=True,
windowObj: QtmacsWindow=None):
"""
Reveal ``applet`` by splitting the space occupied by the
current applet.
If ``applet`` is already visible then the method do... | Reveal ``applet`` by splitting the space occupied by the
current applet.
If ``applet`` is already visible then the method does
nothing. Furthermore, this method does not change the focus,
ie. the currently active applet will remain active.
If ``applet`` is **None** then the nex... | Below is the the instruction that describes the task:
### Input:
Reveal ``applet`` by splitting the space occupied by the
current applet.
If ``applet`` is already visible then the method does
nothing. Furthermore, this method does not change the focus,
ie. the currently active apple... |
def first_derivative(f, **kwargs):
"""Calculate the first derivative of a grid of values.
Works for both regularly-spaced data and grids with varying spacing.
Either `x` or `delta` must be specified, or `f` must be given as an `xarray.DataArray` with
attached coordinate and projection information. If ... | Calculate the first derivative of a grid of values.
Works for both regularly-spaced data and grids with varying spacing.
Either `x` or `delta` must be specified, or `f` must be given as an `xarray.DataArray` with
attached coordinate and projection information. If `f` is an `xarray.DataArray`, and `x` or
... | Below is the the instruction that describes the task:
### Input:
Calculate the first derivative of a grid of values.
Works for both regularly-spaced data and grids with varying spacing.
Either `x` or `delta` must be specified, or `f` must be given as an `xarray.DataArray` with
attached coordinate and ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.