code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def get_plist_data_from_string (data):
"""Parse plist data for a string. Tries biplist, falling back to
plistlib."""
if has_biplist:
return biplist.readPlistFromString(data)
# fall back to normal plistlist
try:
return plistlib.readPlistFromString(data)
except Exception:
#... | Parse plist data for a string. Tries biplist, falling back to
plistlib. | Below is the the instruction that describes the task:
### Input:
Parse plist data for a string. Tries biplist, falling back to
plistlib.
### Response:
def get_plist_data_from_string (data):
"""Parse plist data for a string. Tries biplist, falling back to
plistlib."""
if has_biplist:
return ... |
def file_should_be_skipped(
filename: str,
config: Mapping[str, Any],
path: str = ''
) -> bool:
"""Returns True if the file and/or folder should be skipped based on the passed in settings."""
os_path = os.path.join(path, filename)
normalized_path = os_path.replace('\\', '/')
if normalized_p... | Returns True if the file and/or folder should be skipped based on the passed in settings. | Below is the the instruction that describes the task:
### Input:
Returns True if the file and/or folder should be skipped based on the passed in settings.
### Response:
def file_should_be_skipped(
filename: str,
config: Mapping[str, Any],
path: str = ''
) -> bool:
"""Returns True if the file and/or... |
def delete_vnic_template_for_vlan(self, vlan_id):
"""Deletes VNIC Template for a vlan_id and physnet if it exists."""
with self.session.begin(subtransactions=True):
try:
self.session.query(ucsm_model.VnicTemplate).filter_by(
vlan_id=vlan_id).delete()
... | Deletes VNIC Template for a vlan_id and physnet if it exists. | Below is the the instruction that describes the task:
### Input:
Deletes VNIC Template for a vlan_id and physnet if it exists.
### Response:
def delete_vnic_template_for_vlan(self, vlan_id):
"""Deletes VNIC Template for a vlan_id and physnet if it exists."""
with self.session.begin(subtransactions=... |
def get_position(directory, identifier):
"""
Extracts the position of a paragraph from the identifier, and the parent directory of the
paragraph.
Parameters
----------
directory : Path
A parent directory of a paragraph.
identifier : str
An identifier of a paragraph.
Ret... | Extracts the position of a paragraph from the identifier, and the parent directory of the
paragraph.
Parameters
----------
directory : Path
A parent directory of a paragraph.
identifier : str
An identifier of a paragraph.
Returns
-------
float
The estimated posi... | Below is the the instruction that describes the task:
### Input:
Extracts the position of a paragraph from the identifier, and the parent directory of the
paragraph.
Parameters
----------
directory : Path
A parent directory of a paragraph.
identifier : str
An identifier of a par... |
async def setup(self):
"""Set up the connection with automatic retry."""
while True:
fut = self.loop.create_connection(
lambda: SW16Protocol(
self,
disconnect_callback=self.handle_disconnect_callback,
loop=self.loop,... | Set up the connection with automatic retry. | Below is the the instruction that describes the task:
### Input:
Set up the connection with automatic retry.
### Response:
async def setup(self):
"""Set up the connection with automatic retry."""
while True:
fut = self.loop.create_connection(
lambda: SW16Protocol(
... |
def _init_glyph(self, plot, mapping, properties, key):
"""
Returns a Bokeh glyph object.
"""
properties.pop('legend', None)
if key == 'arrow':
properties.pop('source')
arrow_end = mapping.pop('arrow_end')
arrow_start = mapping.pop('arrow_start'... | Returns a Bokeh glyph object. | Below is the the instruction that describes the task:
### Input:
Returns a Bokeh glyph object.
### Response:
def _init_glyph(self, plot, mapping, properties, key):
"""
Returns a Bokeh glyph object.
"""
properties.pop('legend', None)
if key == 'arrow':
properties.... |
def consume_input(self, mystr, stack=[], state=1, curchar=0, depth=0):
"""
Consumes an input and validates if it is accepted
Args:
mystr (str): the input string to be consumes
stack (list): the stack of symbols
state (int): the current state of the PDA
... | Consumes an input and validates if it is accepted
Args:
mystr (str): the input string to be consumes
stack (list): the stack of symbols
state (int): the current state of the PDA
curchar (int): the index of the consumed character
depth (int): the depth ... | Below is the the instruction that describes the task:
### Input:
Consumes an input and validates if it is accepted
Args:
mystr (str): the input string to be consumes
stack (list): the stack of symbols
state (int): the current state of the PDA
curchar (int): th... |
def export_project(self):
""" Processes misc options specific for GCC ARM, and run generator """
generated_projects = deepcopy(self.generated_projects)
self.process_data_for_makefile(self.workspace)
generated_projects['path'], generated_projects['files']['makefile'] = self.gen_file_jinja... | Processes misc options specific for GCC ARM, and run generator | Below is the the instruction that describes the task:
### Input:
Processes misc options specific for GCC ARM, and run generator
### Response:
def export_project(self):
""" Processes misc options specific for GCC ARM, and run generator """
generated_projects = deepcopy(self.generated_projects)
... |
def rows(self):
"""Yield rows for the term, for writing terms to a CSV file. """
# Translate the term value name so it can be assigned to a parameter.
tvm = self.section.doc.decl_terms.get(self.qualified_term, {}).get('termvaluename', '@value')
assert tvm
# Terminal children hav... | Yield rows for the term, for writing terms to a CSV file. | Below is the the instruction that describes the task:
### Input:
Yield rows for the term, for writing terms to a CSV file.
### Response:
def rows(self):
"""Yield rows for the term, for writing terms to a CSV file. """
# Translate the term value name so it can be assigned to a parameter.
tv... |
def group_route(self) -> 'Group.Route':
"""
Returns: route of this group
"""
# TODO
if self.__group_route is None:
self.__group_route = Group.Route(self)
return self.__group_route | Returns: route of this group | Below is the the instruction that describes the task:
### Input:
Returns: route of this group
### Response:
def group_route(self) -> 'Group.Route':
"""
Returns: route of this group
"""
# TODO
if self.__group_route is None:
self.__group_route = Group.Route(self)
... |
def check_power_unit_redundancy(power_unit_name_data, power_unit_redundancy_data):
""" check the status of the power units """
return (POWER_UNIT_REDUNDANCY_STATE[int(power_unit_redundancy_data)]["icingastatus"],
"Power unit '{}' redundancy: {}".format(power_unit_name_data,
... | check the status of the power units | Below is the the instruction that describes the task:
### Input:
check the status of the power units
### Response:
def check_power_unit_redundancy(power_unit_name_data, power_unit_redundancy_data):
""" check the status of the power units """
return (POWER_UNIT_REDUNDANCY_STATE[int(power_unit_redund... |
def chi_perp_from_mass1_mass2_xi2(mass1, mass2, xi2):
"""Returns the in-plane spin from mass1, mass2, and xi2 for the
secondary mass.
"""
q = q_from_mass1_mass2(mass1, mass2)
a1 = 2 + 3 * q / 2
a2 = 2 + 3 / (2 * q)
return q**2 * a2 / a1 * xi2 | Returns the in-plane spin from mass1, mass2, and xi2 for the
secondary mass. | Below is the the instruction that describes the task:
### Input:
Returns the in-plane spin from mass1, mass2, and xi2 for the
secondary mass.
### Response:
def chi_perp_from_mass1_mass2_xi2(mass1, mass2, xi2):
"""Returns the in-plane spin from mass1, mass2, and xi2 for the
secondary mass.
"""
q... |
def count_features_of_type(self, featuretype=None):
"""
Simple count of features.
Can be faster than "grep", and is faster than checking the length of
results from :meth:`gffutils.FeatureDB.features_of_type`.
Parameters
----------
featuretype : string
... | Simple count of features.
Can be faster than "grep", and is faster than checking the length of
results from :meth:`gffutils.FeatureDB.features_of_type`.
Parameters
----------
featuretype : string
Feature type (e.g., "gene") to count. If None, then count *all*
... | Below is the the instruction that describes the task:
### Input:
Simple count of features.
Can be faster than "grep", and is faster than checking the length of
results from :meth:`gffutils.FeatureDB.features_of_type`.
Parameters
----------
featuretype : string
... |
def map_team_id(code):
"""Take in team ID, read JSON file to map ID to name"""
for team in TEAM_DATA:
if team["code"] == code:
click.secho(team["name"], fg="green")
break
else:
click.secho("No team found for this code", fg="red", bold=True) | Take in team ID, read JSON file to map ID to name | Below is the the instruction that describes the task:
### Input:
Take in team ID, read JSON file to map ID to name
### Response:
def map_team_id(code):
"""Take in team ID, read JSON file to map ID to name"""
for team in TEAM_DATA:
if team["code"] == code:
click.secho(team["name"], fg="g... |
def sanitize(self):
'''
Check if the current settings conform to the LISP specifications and
fix them where possible.
'''
super(MapReplyMessage, self).sanitize()
# P: This is the probe-bit which indicates that the Map-Reply is in
# response to a locator reachabil... | Check if the current settings conform to the LISP specifications and
fix them where possible. | Below is the the instruction that describes the task:
### Input:
Check if the current settings conform to the LISP specifications and
fix them where possible.
### Response:
def sanitize(self):
'''
Check if the current settings conform to the LISP specifications and
fix them where po... |
def time(value,
allow_empty = False,
minimum = None,
maximum = None,
coerce_value = True,
**kwargs):
"""Validate that ``value`` is a valid :class:`time <python:datetime.time>`.
.. caution::
This validator will **always** return the time as timezone naive (eff... | Validate that ``value`` is a valid :class:`time <python:datetime.time>`.
.. caution::
This validator will **always** return the time as timezone naive (effectively
UTC). If ``value`` has a timezone / UTC offset applied, the validator will
coerce the value returned back to UTC.
:param value:... | Below is the the instruction that describes the task:
### Input:
Validate that ``value`` is a valid :class:`time <python:datetime.time>`.
.. caution::
This validator will **always** return the time as timezone naive (effectively
UTC). If ``value`` has a timezone / UTC offset applied, the validator... |
def set_logger(name,
level='INFO',
fmt=None,
datefmt=None,
propagate=1,
remove_handlers=False):
"""
This function will clear the previous handlers and set only one handler,
which will only be StreamHandler for the logger.
This f... | This function will clear the previous handlers and set only one handler,
which will only be StreamHandler for the logger.
This function is designed to be able to called multiple times in a context.
Note that if a logger has no handlers, it will be added a handler automatically when it is used. | Below is the the instruction that describes the task:
### Input:
This function will clear the previous handlers and set only one handler,
which will only be StreamHandler for the logger.
This function is designed to be able to called multiple times in a context.
Note that if a logger has no handlers, ... |
def from_schema(cls, schema, handlers={}, **kwargs):
"""
Construct a resolver from a JSON schema object.
"""
return cls(
schema.get('$id', schema.get('id', '')) if isinstance(schema, dict) else '',
schema,
handlers=handlers,
**kwarg... | Construct a resolver from a JSON schema object. | Below is the the instruction that describes the task:
### Input:
Construct a resolver from a JSON schema object.
### Response:
def from_schema(cls, schema, handlers={}, **kwargs):
"""
Construct a resolver from a JSON schema object.
"""
return cls(
schema.get('$id', ... |
def apply(
self,
query: BaseQuery,
func: Callable) -> BaseQuery:
"""
Filter queries to only those owned by current user if
can_only_access_owned_queries permission is set.
:returns: query
"""
if security_manager.can_only_access_owned_q... | Filter queries to only those owned by current user if
can_only_access_owned_queries permission is set.
:returns: query | Below is the the instruction that describes the task:
### Input:
Filter queries to only those owned by current user if
can_only_access_owned_queries permission is set.
:returns: query
### Response:
def apply(
self,
query: BaseQuery,
func: Callable) -> BaseQuery:... |
def pop(key, default=None):
'''
Pop (return & delete) a value from the minion datastore
.. versionadded:: 2015.5.2
CLI Example:
.. code-block:: bash
salt '*' data.pop <key> "there was no val"
'''
store = load()
val = store.pop(key, default)
dump(store)
return val | Pop (return & delete) a value from the minion datastore
.. versionadded:: 2015.5.2
CLI Example:
.. code-block:: bash
salt '*' data.pop <key> "there was no val" | Below is the the instruction that describes the task:
### Input:
Pop (return & delete) a value from the minion datastore
.. versionadded:: 2015.5.2
CLI Example:
.. code-block:: bash
salt '*' data.pop <key> "there was no val"
### Response:
def pop(key, default=None):
'''
Pop (return ... |
def setCurrentNode(self, node):
"""
Sets the currently selected node in the scene. If \
multiple nodes are selected, then the last one selected \
will be considered the current one.
:param node | <XNode> || None
"""
self.blockSignals(True)
... | Sets the currently selected node in the scene. If \
multiple nodes are selected, then the last one selected \
will be considered the current one.
:param node | <XNode> || None | Below is the the instruction that describes the task:
### Input:
Sets the currently selected node in the scene. If \
multiple nodes are selected, then the last one selected \
will be considered the current one.
:param node | <XNode> || None
### Response:
def setCurrentNode(s... |
def fields(cls):
"""Get the names of all writable properties that reflect
metadata tags (i.e., those that are instances of
:class:`MediaField`).
"""
for property, descriptor in cls.__dict__.items():
if isinstance(descriptor, MediaField):
if isinstance(... | Get the names of all writable properties that reflect
metadata tags (i.e., those that are instances of
:class:`MediaField`). | Below is the the instruction that describes the task:
### Input:
Get the names of all writable properties that reflect
metadata tags (i.e., those that are instances of
:class:`MediaField`).
### Response:
def fields(cls):
"""Get the names of all writable properties that reflect
metad... |
def validate(datapackage, schema='base'):
'''Validate Data Package datapackage.json files against a jsonschema.
Args:
datapackage (str or dict): The Data Package descriptor file (i.e.
datapackage.json) as a dict or its contents in a string.
schema (str or dict): If a string, it can ... | Validate Data Package datapackage.json files against a jsonschema.
Args:
datapackage (str or dict): The Data Package descriptor file (i.e.
datapackage.json) as a dict or its contents in a string.
schema (str or dict): If a string, it can be the schema ID in the
registry, a l... | Below is the the instruction that describes the task:
### Input:
Validate Data Package datapackage.json files against a jsonschema.
Args:
datapackage (str or dict): The Data Package descriptor file (i.e.
datapackage.json) as a dict or its contents in a string.
schema (str or dict): ... |
def _set_cluster_id(self, v, load=False):
"""
Setter method for cluster_id, mapped from YANG variable /routing_system/router/router_bgp/router_bgp_attributes/cluster_id (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_cluster_id is considered as a private
... | Setter method for cluster_id, mapped from YANG variable /routing_system/router/router_bgp/router_bgp_attributes/cluster_id (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_cluster_id is considered as a private
method. Backends looking to populate this variable sho... | Below is the the instruction that describes the task:
### Input:
Setter method for cluster_id, mapped from YANG variable /routing_system/router/router_bgp/router_bgp_attributes/cluster_id (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_cluster_id is considered as... |
def lfqFeatureGrouping(fiContainer, timeLimit=40, massLimit=10*1e-6,
eucLimit=None, timeKey='rt', massKey='mz',
massScalingFactor=None, categoryKey='specfile',
charges=None, matchArraySelector=None, specfiles=None):
""" #TODO: docstring
:para... | #TODO: docstring
:param fiContainer: #TODO: docstring
:param timeLimit: #TODO: docstring
:param massLimit: #TODO: docstring
:param eucLimit: #TODO: docstring
:param timeKey: #TODO: docstring
:param massKey: #TODO: docstring
:param massScalingFactor: #TODO: docstring
:param categoryKey: ... | Below is the the instruction that describes the task:
### Input:
#TODO: docstring
:param fiContainer: #TODO: docstring
:param timeLimit: #TODO: docstring
:param massLimit: #TODO: docstring
:param eucLimit: #TODO: docstring
:param timeKey: #TODO: docstring
:param massKey: #TODO: docstring
... |
def get_all_items_of_invoice(self, invoice_id):
"""
Get all items of invoice
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param invoice_id: the invoice id
:return: list
... | Get all items of invoice
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param invoice_id: the invoice id
:return: list | Below is the the instruction that describes the task:
### Input:
Get all items of invoice
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param invoice_id: the invoice id
:return: list
##... |
def median(items):
"""Note: modifies the input list!"""
items.sort()
k = len(items)//2
if len(items) % 2 == 0:
return (items[k] + items[k - 1]) / 2
else:
return items[k] | Note: modifies the input list! | Below is the the instruction that describes the task:
### Input:
Note: modifies the input list!
### Response:
def median(items):
"""Note: modifies the input list!"""
items.sort()
k = len(items)//2
if len(items) % 2 == 0:
return (items[k] + items[k - 1]) / 2
else:
return items[k] |
def ingest(self):
"""*Perform conesearches of the online NED database and import the results into a the sherlock-database*
The code:
1. uses the list of transient coordinates and queries NED for the results within the given search radius
2. Creates the `tcs_cat_ned_stream` tabl... | *Perform conesearches of the online NED database and import the results into a the sherlock-database*
The code:
1. uses the list of transient coordinates and queries NED for the results within the given search radius
2. Creates the `tcs_cat_ned_stream` table if it doesn't exist
... | Below is the the instruction that describes the task:
### Input:
*Perform conesearches of the online NED database and import the results into a the sherlock-database*
The code:
1. uses the list of transient coordinates and queries NED for the results within the given search radius
... |
def find_modules(rootpath, skip):
"""
Look for every file in the directory tree and return a dict
Hacked from sphinx.autodoc
"""
INITPY = '__init__.py'
rootpath = os.path.normpath(os.path.abspath(rootpath))
if INITPY in os.listdir(rootpath):
root_package = rootpath.split(... | Look for every file in the directory tree and return a dict
Hacked from sphinx.autodoc | Below is the the instruction that describes the task:
### Input:
Look for every file in the directory tree and return a dict
Hacked from sphinx.autodoc
### Response:
def find_modules(rootpath, skip):
"""
Look for every file in the directory tree and return a dict
Hacked from sphinx.autodoc
... |
def reweight(self, data):
r"""Reweight
This method implements the reweighting from section 4 in [CWB2007]_
Notes
-----
Reweighting implemented as:
.. math::
w = w \left( \frac{1}{1 + \frac{|x^w|}{n \sigma}} \right)
"""
print(' - Reweight... | r"""Reweight
This method implements the reweighting from section 4 in [CWB2007]_
Notes
-----
Reweighting implemented as:
.. math::
w = w \left( \frac{1}{1 + \frac{|x^w|}{n \sigma}} \right) | Below is the the instruction that describes the task:
### Input:
r"""Reweight
This method implements the reweighting from section 4 in [CWB2007]_
Notes
-----
Reweighting implemented as:
.. math::
w = w \left( \frac{1}{1 + \frac{|x^w|}{n \sigma}} \right)
### R... |
def plot_np(fignum, indata, s, units):
"""
makes plot of de(re)magnetization data for Thellier-Thellier type experiment
Parameters
__________
fignum : matplotlib figure number
indata : araiblock from, e.g., pmag.sortarai()
s : specimen name
units : [K, J, ""] (kelvin, joules, unknown)
... | makes plot of de(re)magnetization data for Thellier-Thellier type experiment
Parameters
__________
fignum : matplotlib figure number
indata : araiblock from, e.g., pmag.sortarai()
s : specimen name
units : [K, J, ""] (kelvin, joules, unknown)
Effect
_______
Makes a plot | Below is the the instruction that describes the task:
### Input:
makes plot of de(re)magnetization data for Thellier-Thellier type experiment
Parameters
__________
fignum : matplotlib figure number
indata : araiblock from, e.g., pmag.sortarai()
s : specimen name
units : [K, J, ""] (kelvin,... |
def load_keys(self, issuer, jwks_uri='', jwks=None, replace=False):
"""
Fetch keys from another server
:param jwks_uri: A URL pointing to a site that will return a JWKS
:param jwks: A dictionary representation of a JWKS
:param issuer: The provider URL
:param replace: If ... | Fetch keys from another server
:param jwks_uri: A URL pointing to a site that will return a JWKS
:param jwks: A dictionary representation of a JWKS
:param issuer: The provider URL
:param replace: If all previously gathered keys from this provider
should be replace.
:... | Below is the the instruction that describes the task:
### Input:
Fetch keys from another server
:param jwks_uri: A URL pointing to a site that will return a JWKS
:param jwks: A dictionary representation of a JWKS
:param issuer: The provider URL
:param replace: If all previously gath... |
def add_haproxy_checks(nrpe, unit_name):
"""
Add checks for each service in list
:param NRPE nrpe: NRPE object to add check to
:param str unit_name: Unit name to use in check description
"""
nrpe.add_check(
shortname='haproxy_servers',
description='Check HAProxy {%s}' % unit_nam... | Add checks for each service in list
:param NRPE nrpe: NRPE object to add check to
:param str unit_name: Unit name to use in check description | Below is the the instruction that describes the task:
### Input:
Add checks for each service in list
:param NRPE nrpe: NRPE object to add check to
:param str unit_name: Unit name to use in check description
### Response:
def add_haproxy_checks(nrpe, unit_name):
"""
Add checks for each service in l... |
def get_language_from_json(language, key):
"""Finds the given language in a json file."""
file_name = os.path.join(
os.path.dirname(__file__),
'languages',
'{0}.json').format(key.lower())
if os.path.exists(file_name):
try:
with open(file_name, 'r', encoding='utf... | Finds the given language in a json file. | Below is the the instruction that describes the task:
### Input:
Finds the given language in a json file.
### Response:
def get_language_from_json(language, key):
"""Finds the given language in a json file."""
file_name = os.path.join(
os.path.dirname(__file__),
'languages',
'{0}.j... |
def _is_noop_insn(insn):
"""
Check if the instruction does nothing.
:param insn: The capstone insn object.
:return: True if the instruction does no-op, False otherwise.
"""
if insn.insn_name() == 'nop':
# nops
return True
if insn.insn_nam... | Check if the instruction does nothing.
:param insn: The capstone insn object.
:return: True if the instruction does no-op, False otherwise. | Below is the the instruction that describes the task:
### Input:
Check if the instruction does nothing.
:param insn: The capstone insn object.
:return: True if the instruction does no-op, False otherwise.
### Response:
def _is_noop_insn(insn):
"""
Check if the instruction does noth... |
def _GetPluginData(self):
"""Retrieves the version and various plugin information.
Returns:
dict[str, list[str]]: available parsers and plugins.
"""
return_dict = {}
return_dict['Versions'] = [
('plaso engine', plaso.__version__),
('python', sys.version)]
hashers_informa... | Retrieves the version and various plugin information.
Returns:
dict[str, list[str]]: available parsers and plugins. | Below is the the instruction that describes the task:
### Input:
Retrieves the version and various plugin information.
Returns:
dict[str, list[str]]: available parsers and plugins.
### Response:
def _GetPluginData(self):
"""Retrieves the version and various plugin information.
Returns:
di... |
def maybedotted(name):
"""Resolve dotted names:
.. code-block:: python
>>> maybedotted('irc3.config')
<module 'irc3.config' from '...'>
>>> maybedotted('irc3.utils.IrcString')
<class 'irc3.utils.IrcString'>
..
"""
if not name:
raise LookupError(
... | Resolve dotted names:
.. code-block:: python
>>> maybedotted('irc3.config')
<module 'irc3.config' from '...'>
>>> maybedotted('irc3.utils.IrcString')
<class 'irc3.utils.IrcString'>
.. | Below is the the instruction that describes the task:
### Input:
Resolve dotted names:
.. code-block:: python
>>> maybedotted('irc3.config')
<module 'irc3.config' from '...'>
>>> maybedotted('irc3.utils.IrcString')
<class 'irc3.utils.IrcString'>
..
### Response:
def maybe... |
def reset_indentation(self, amount):
"""Replace previous indentation with desired amount"""
while self.result and self.result[-1][0] == INDENT:
self.result.pop()
self.result.append((INDENT, amount)) | Replace previous indentation with desired amount | Below is the the instruction that describes the task:
### Input:
Replace previous indentation with desired amount
### Response:
def reset_indentation(self, amount):
"""Replace previous indentation with desired amount"""
while self.result and self.result[-1][0] == INDENT:
self.result.pop... |
def set_cl_multibox(self, creg, label, top_connect='┴'):
"""
Sets the multi clbit box.
Args:
creg (string): The affected classical register.
label (string): The label for the multi clbit box.
top_connect (char): The char to connect the box on the top.
... | Sets the multi clbit box.
Args:
creg (string): The affected classical register.
label (string): The label for the multi clbit box.
top_connect (char): The char to connect the box on the top. | Below is the the instruction that describes the task:
### Input:
Sets the multi clbit box.
Args:
creg (string): The affected classical register.
label (string): The label for the multi clbit box.
top_connect (char): The char to connect the box on the top.
### Response:
d... |
def create_config_files(directory):
"""
Initialize directory ready for vpn walker
:param directory: the path where you want this to happen
:return:
"""
# Some constant strings
vpn_gate_url = "http://www.vpngate.net/api/iphone/"
if not os.path.exists(directory):
os.makedirs(direc... | Initialize directory ready for vpn walker
:param directory: the path where you want this to happen
:return: | Below is the the instruction that describes the task:
### Input:
Initialize directory ready for vpn walker
:param directory: the path where you want this to happen
:return:
### Response:
def create_config_files(directory):
"""
Initialize directory ready for vpn walker
:param directory: the path... |
def pull_params(voevent):
"""
Attempts to load the `What` section of a voevent as a nested dictionary.
.. warning:: Deprecated due to `Missing name attributes` issues.
`Param` or `Group` entries which are missing the `name` attribute
will be entered under a dictionary key of ``None``. This... | Attempts to load the `What` section of a voevent as a nested dictionary.
.. warning:: Deprecated due to `Missing name attributes` issues.
`Param` or `Group` entries which are missing the `name` attribute
will be entered under a dictionary key of ``None``. This means that if
there are multi... | Below is the the instruction that describes the task:
### Input:
Attempts to load the `What` section of a voevent as a nested dictionary.
.. warning:: Deprecated due to `Missing name attributes` issues.
`Param` or `Group` entries which are missing the `name` attribute
will be entered under a d... |
def get_seconds_until_next_quarter(now=None):
"""
Returns the number of seconds until the next quarter of an hour. This is the short-term rate limit used by Strava.
:param now: A (utc) timestamp
:type now: arrow.arrow.Arrow
:return: the number of seconds until the next quarter, as int
"""
if... | Returns the number of seconds until the next quarter of an hour. This is the short-term rate limit used by Strava.
:param now: A (utc) timestamp
:type now: arrow.arrow.Arrow
:return: the number of seconds until the next quarter, as int | Below is the the instruction that describes the task:
### Input:
Returns the number of seconds until the next quarter of an hour. This is the short-term rate limit used by Strava.
:param now: A (utc) timestamp
:type now: arrow.arrow.Arrow
:return: the number of seconds until the next quarter, as int
###... |
def rts_smoother(self, Xs, Ps, Qs=None, dts=None, UT=None):
"""
Runs the Rauch-Tung-Striebal Kalman smoother on a set of
means and covariances computed by the UKF. The usual input
would come from the output of `batch_filter()`.
Parameters
----------
Xs : numpy.a... | Runs the Rauch-Tung-Striebal Kalman smoother on a set of
means and covariances computed by the UKF. The usual input
would come from the output of `batch_filter()`.
Parameters
----------
Xs : numpy.array
array of the means (state variable x) of the output of a Kalman
... | Below is the the instruction that describes the task:
### Input:
Runs the Rauch-Tung-Striebal Kalman smoother on a set of
means and covariances computed by the UKF. The usual input
would come from the output of `batch_filter()`.
Parameters
----------
Xs : numpy.array
... |
def create(cls, name, cluster_virtual, network_value, macaddress,
interface_id, nodes, vlan_id=None, cluster_mode='balancing',
backup_mgt=None, primary_heartbeat=None, log_server_ref=None,
domain_server_address=None, location_ref=None, zone_ref=None,
default_n... | Create a layer 3 firewall cluster with management interface and any number
of nodes. If providing keyword arguments to create additional interfaces,
use the same constructor arguments and pass an `interfaces` keyword argument.
The constructor defined interface will be assigned as the primary
... | Below is the the instruction that describes the task:
### Input:
Create a layer 3 firewall cluster with management interface and any number
of nodes. If providing keyword arguments to create additional interfaces,
use the same constructor arguments and pass an `interfaces` keyword argument.
... |
def to_map_projection(arg, hemi=Ellipsis, chirality=Ellipsis,
center=Ellipsis, center_right=Ellipsis, radius=Ellipsis,
method=Ellipsis, registration=Ellipsis, sphere_radius=Ellipsis,
pre_affine=Ellipsis, post_affine=Ellipsis, meta_data=Ellipsis):
'''... | to_map_projection(mp) yields mp if mp is a map projection object.
to_map_projection((name, hemi)) is equivalent to map_projection(name, chirality=hemi).
to_map_projection((name, opts)) uses the given options dictionary as options to map_projection;
(name, hemi, opts) is also allowed as input.
to_map_p... | Below is the the instruction that describes the task:
### Input:
to_map_projection(mp) yields mp if mp is a map projection object.
to_map_projection((name, hemi)) is equivalent to map_projection(name, chirality=hemi).
to_map_projection((name, opts)) uses the given options dictionary as options to map_projec... |
def gen_file_jinja(self, template_file, data, output, dest_path):
if not os.path.exists(dest_path):
os.makedirs(dest_path)
output = join(dest_path, output)
logger.debug("Generating: %s" % output)
""" Fills data to the project template, using jinja2. """
env = Environ... | Fills data to the project template, using jinja2. | Below is the the instruction that describes the task:
### Input:
Fills data to the project template, using jinja2.
### Response:
def gen_file_jinja(self, template_file, data, output, dest_path):
if not os.path.exists(dest_path):
os.makedirs(dest_path)
output = join(dest_path, output)
... |
def detach_volume(volume_id, instance_id=None, device=None, force=False,
wait_for_detachement=False, region=None, key=None, keyid=None, profile=None):
'''
Detach an EBS volume from an EC2 instance.
.. versionadded:: 2016.11.0
volume_id
(string) – The ID of the EBS volume to b... | Detach an EBS volume from an EC2 instance.
.. versionadded:: 2016.11.0
volume_id
(string) – The ID of the EBS volume to be detached.
instance_id
(string) – The ID of the EC2 instance from which it will be detached.
device
(string) – The device on the instance through which the ... | Below is the the instruction that describes the task:
### Input:
Detach an EBS volume from an EC2 instance.
.. versionadded:: 2016.11.0
volume_id
(string) – The ID of the EBS volume to be detached.
instance_id
(string) – The ID of the EC2 instance from which it will be detached.
de... |
def set_params(self, arg_params, aux_params, allow_missing=False, force_init=True,
allow_extra=False):
"""Assigns parameter and aux state values.
Parameters
----------
arg_params : dict
Dictionary of name to `NDArray`.
aux_params : dict
... | Assigns parameter and aux state values.
Parameters
----------
arg_params : dict
Dictionary of name to `NDArray`.
aux_params : dict
Dictionary of name to `NDArray`.
allow_missing : bool
If ``True``, params could contain missing values, and the ... | Below is the the instruction that describes the task:
### Input:
Assigns parameter and aux state values.
Parameters
----------
arg_params : dict
Dictionary of name to `NDArray`.
aux_params : dict
Dictionary of name to `NDArray`.
allow_missing : bool
... |
def mean_subtraction(inp, base_axis=1, update_running_mean=True, fix_parameters=False):
"""
Mean subtraction layer.
It subtracts the mean of the elements of the input array,
and normalizes it to :math:`0`. Preprocessing arrays with this function has the effect of improving accuracy
in various tasks... | Mean subtraction layer.
It subtracts the mean of the elements of the input array,
and normalizes it to :math:`0`. Preprocessing arrays with this function has the effect of improving accuracy
in various tasks such as image classification.
At training time, this function is defined as
.. math::
... | Below is the the instruction that describes the task:
### Input:
Mean subtraction layer.
It subtracts the mean of the elements of the input array,
and normalizes it to :math:`0`. Preprocessing arrays with this function has the effect of improving accuracy
in various tasks such as image classification.
... |
def sec_to_public_pair(pubkey):
"""Convert a public key in sec binary format to a public pair."""
x = string_to_number(pubkey[1:33])
sec0 = pubkey[:1]
if sec0 not in (b'\2', b'\3'):
raise Exception("Compressed pubkey expected")
def public_pair_for_x(generator, x, is_even):
curve = g... | Convert a public key in sec binary format to a public pair. | Below is the the instruction that describes the task:
### Input:
Convert a public key in sec binary format to a public pair.
### Response:
def sec_to_public_pair(pubkey):
"""Convert a public key in sec binary format to a public pair."""
x = string_to_number(pubkey[1:33])
sec0 = pubkey[:1]
if sec0 n... |
def preferred_width(self, cli, max_available_width):
"""
Return the preferred width for this control.
That is the width of the longest line.
"""
text = token_list_to_text(self._get_tokens_cached(cli))
line_lengths = [get_cwidth(l) for l in text.split('\n')]
return... | Return the preferred width for this control.
That is the width of the longest line. | Below is the the instruction that describes the task:
### Input:
Return the preferred width for this control.
That is the width of the longest line.
### Response:
def preferred_width(self, cli, max_available_width):
"""
Return the preferred width for this control.
That is the width ... |
def up_ec2(connection,
region,
instance_id,
wait_for_ssh_available=True,
log=False,
timeout=600):
""" boots an existing ec2_instance """
# boot the ec2 instance
instance = connection.start_instances(instance_ids=instance_id)[0]
instance.update()
... | boots an existing ec2_instance | Below is the the instruction that describes the task:
### Input:
boots an existing ec2_instance
### Response:
def up_ec2(connection,
region,
instance_id,
wait_for_ssh_available=True,
log=False,
timeout=600):
""" boots an existing ec2_instance """
# bo... |
async def add(request: web.Request) -> web.Response:
""" Add a public key to the authorized_keys file.
POST /server/ssh_keys {"key": key string}
-> 201 Created
If the key string doesn't look like an openssh public key, rejects with 400
"""
body = await request.json()
if 'key' not in body o... | Add a public key to the authorized_keys file.
POST /server/ssh_keys {"key": key string}
-> 201 Created
If the key string doesn't look like an openssh public key, rejects with 400 | Below is the the instruction that describes the task:
### Input:
Add a public key to the authorized_keys file.
POST /server/ssh_keys {"key": key string}
-> 201 Created
If the key string doesn't look like an openssh public key, rejects with 400
### Response:
async def add(request: web.Request) -> web.... |
def collection_to_df(collection):
'''
Converts a collection back into a pandas DataFrame
parameters
----------
collection : list
list of Record objects where each Record represents one row from a dataframe
Returns
-------
df : pandas.DataFrame
DataFrame of length=len(c... | Converts a collection back into a pandas DataFrame
parameters
----------
collection : list
list of Record objects where each Record represents one row from a dataframe
Returns
-------
df : pandas.DataFrame
DataFrame of length=len(collection) where each row represents one Record | Below is the the instruction that describes the task:
### Input:
Converts a collection back into a pandas DataFrame
parameters
----------
collection : list
list of Record objects where each Record represents one row from a dataframe
Returns
-------
df : pandas.DataFrame
Dat... |
def edit(self, request, id):
"""Edit a gist
The files in the gist a cloned to a temporary directory and passed to
the default editor (defined by the EDITOR environmental variable). When
the user exits the editor, they will be provided with a prompt to
commit the changes, which w... | Edit a gist
The files in the gist a cloned to a temporary directory and passed to
the default editor (defined by the EDITOR environmental variable). When
the user exits the editor, they will be provided with a prompt to
commit the changes, which will then be pushed to the remote.
... | Below is the the instruction that describes the task:
### Input:
Edit a gist
The files in the gist a cloned to a temporary directory and passed to
the default editor (defined by the EDITOR environmental variable). When
the user exits the editor, they will be provided with a prompt to
... |
def clear_widget(self):
"""
Clears the thumbnail display widget of all thumbnails, but does
not remove them from the thumb_dict or thumb_list.
"""
if not self.gui_up:
return
canvas = self.c_view.get_canvas()
canvas.delete_all_objects()
self.c_v... | Clears the thumbnail display widget of all thumbnails, but does
not remove them from the thumb_dict or thumb_list. | Below is the the instruction that describes the task:
### Input:
Clears the thumbnail display widget of all thumbnails, but does
not remove them from the thumb_dict or thumb_list.
### Response:
def clear_widget(self):
"""
Clears the thumbnail display widget of all thumbnails, but does
... |
def run(self):
"""Executed on startup of application"""
for wsock in self.wsocks:
wsock.run()
for api in self.apis:
api.run() | Executed on startup of application | Below is the the instruction that describes the task:
### Input:
Executed on startup of application
### Response:
def run(self):
"""Executed on startup of application"""
for wsock in self.wsocks:
wsock.run()
for api in self.apis:
api.run() |
def watch(name, timespec, tag=None, user=None, job=None, unique_tag=False):
'''
.. versionadded:: 2017.7.0
Add an at job if trigger by watch
job : string
Command to run.
timespec : string
The 'timespec' follows the format documented in the at(1) manpage.
tag : string
... | .. versionadded:: 2017.7.0
Add an at job if trigger by watch
job : string
Command to run.
timespec : string
The 'timespec' follows the format documented in the at(1) manpage.
tag : string
Make a tag for the job.
user : string
The user to run the at job
..... | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 2017.7.0
Add an at job if trigger by watch
job : string
Command to run.
timespec : string
The 'timespec' follows the format documented in the at(1) manpage.
tag : string
Make a tag for the ... |
def sheetToHTML(sheet):
"""
Put 2d numpy data into a temporary HTML file.
This is a hack, copy/pasted from an earlier version of this software.
It is very messy, but works great! Good enough for me.
"""
assert "SHEET" in str(type(sheet))
#data,names=None,units=None,bookName=None,sheetName=N... | Put 2d numpy data into a temporary HTML file.
This is a hack, copy/pasted from an earlier version of this software.
It is very messy, but works great! Good enough for me. | Below is the the instruction that describes the task:
### Input:
Put 2d numpy data into a temporary HTML file.
This is a hack, copy/pasted from an earlier version of this software.
It is very messy, but works great! Good enough for me.
### Response:
def sheetToHTML(sheet):
"""
Put 2d numpy data int... |
def version(package, encoding='utf-8'):
"""Obtain the packge version from a python file e.g. pkg/__init__.py
See <https://packaging.python.org/en/latest/single_source_version.html>.
"""
path = os.path.join(os.path.dirname(__file__), package, '__init__.py')
with io.open(path, encoding=encoding) as fp... | Obtain the packge version from a python file e.g. pkg/__init__.py
See <https://packaging.python.org/en/latest/single_source_version.html>. | Below is the the instruction that describes the task:
### Input:
Obtain the packge version from a python file e.g. pkg/__init__.py
See <https://packaging.python.org/en/latest/single_source_version.html>.
### Response:
def version(package, encoding='utf-8'):
"""Obtain the packge version from a python file e... |
def add_access_control_headers(self, env=None):
"""Adds Access-Control* HTTP headers to this WbResponse's HTTP headers.
:param dict env: The WSGI environment dictionary
:return: The same WbResponse but with the values for the Access-Control* HTTP header added
:rtype: WbResponse
... | Adds Access-Control* HTTP headers to this WbResponse's HTTP headers.
:param dict env: The WSGI environment dictionary
:return: The same WbResponse but with the values for the Access-Control* HTTP header added
:rtype: WbResponse | Below is the the instruction that describes the task:
### Input:
Adds Access-Control* HTTP headers to this WbResponse's HTTP headers.
:param dict env: The WSGI environment dictionary
:return: The same WbResponse but with the values for the Access-Control* HTTP header added
:rtype: WbRespons... |
def external_commands(self):
"""Get the external commands from the daemon
Use a lock for this function to protect
:return: serialized external command list
:rtype: str
"""
res = []
with self.app.external_commands_lock:
for cmd in self.app.get_externa... | Get the external commands from the daemon
Use a lock for this function to protect
:return: serialized external command list
:rtype: str | Below is the the instruction that describes the task:
### Input:
Get the external commands from the daemon
Use a lock for this function to protect
:return: serialized external command list
:rtype: str
### Response:
def external_commands(self):
"""Get the external commands from the... |
def approve(self):
"""Approve object.
This reverts a removal, resets the report counter, marks it with a
green check mark (only visible to other moderators) on the website view
and sets the approved_by attribute to the logged in user.
:returns: The json response from the server... | Approve object.
This reverts a removal, resets the report counter, marks it with a
green check mark (only visible to other moderators) on the website view
and sets the approved_by attribute to the logged in user.
:returns: The json response from the server. | Below is the the instruction that describes the task:
### Input:
Approve object.
This reverts a removal, resets the report counter, marks it with a
green check mark (only visible to other moderators) on the website view
and sets the approved_by attribute to the logged in user.
:ret... |
def create_new(cls, oldvalue, *args):
"Raise if the old value already exists"
if oldvalue is not None:
raise AlreadyExistsException('%r already exists' % (oldvalue,))
return cls.create_instance(*args) | Raise if the old value already exists | Below is the the instruction that describes the task:
### Input:
Raise if the old value already exists
### Response:
def create_new(cls, oldvalue, *args):
"Raise if the old value already exists"
if oldvalue is not None:
raise AlreadyExistsException('%r already exists' % (oldvalue,))
return cl... |
def _update_console(self, value=None):
"""
Update the progress bar to the given value (out of the total
given to the constructor).
"""
if self._total == 0:
frac = 1.0
else:
frac = float(value) / float(self._total)
file = self._file
... | Update the progress bar to the given value (out of the total
given to the constructor). | Below is the the instruction that describes the task:
### Input:
Update the progress bar to the given value (out of the total
given to the constructor).
### Response:
def _update_console(self, value=None):
"""
Update the progress bar to the given value (out of the total
given to the... |
def AsHandler(request=None, modules=None, **kw):
'''Dispatch from within ModPython.'''
ps = ParsedSoap(request)
kw['request'] = request
_Dispatch(ps, modules, _ModPythonSendXML, _ModPythonSendFault, **kw) | Dispatch from within ModPython. | Below is the the instruction that describes the task:
### Input:
Dispatch from within ModPython.
### Response:
def AsHandler(request=None, modules=None, **kw):
'''Dispatch from within ModPython.'''
ps = ParsedSoap(request)
kw['request'] = request
_Dispatch(ps, modules, _ModPythonSendXML, _ModPython... |
def Open(self, file_object):
"""Opens the database file object.
Args:
file_object (FileIO): file-like object.
Raises:
IOError: if the SQLite database signature does not match.
OSError: if the SQLite database signature does not match.
ValueError: if the file-like object is invalid.
... | Opens the database file object.
Args:
file_object (FileIO): file-like object.
Raises:
IOError: if the SQLite database signature does not match.
OSError: if the SQLite database signature does not match.
ValueError: if the file-like object is invalid. | Below is the the instruction that describes the task:
### Input:
Opens the database file object.
Args:
file_object (FileIO): file-like object.
Raises:
IOError: if the SQLite database signature does not match.
OSError: if the SQLite database signature does not match.
ValueError: if ... |
def snapshot(self, name):
"""
Create a snapshot of the volume.
Args:
name: string - a human-readable name for the snapshot
"""
return self.get_data(
"volumes/%s/snapshots/" % self.id,
type=POST,
params={"name": name}
) | Create a snapshot of the volume.
Args:
name: string - a human-readable name for the snapshot | Below is the the instruction that describes the task:
### Input:
Create a snapshot of the volume.
Args:
name: string - a human-readable name for the snapshot
### Response:
def snapshot(self, name):
"""
Create a snapshot of the volume.
Args:
name: string - a... |
def _single_quote_handler_factory(on_single_quote, on_other):
"""Generates handlers used for classifying tokens that begin with one or more single quotes.
Args:
on_single_quote (callable): Called when another single quote is found. Accepts the current character's ordinal,
the current contex... | Generates handlers used for classifying tokens that begin with one or more single quotes.
Args:
on_single_quote (callable): Called when another single quote is found. Accepts the current character's ordinal,
the current context, and True if the token is a field name; returns a Transition.
... | Below is the the instruction that describes the task:
### Input:
Generates handlers used for classifying tokens that begin with one or more single quotes.
Args:
on_single_quote (callable): Called when another single quote is found. Accepts the current character's ordinal,
the current contex... |
def is_geophysical(ds, variable):
'''
Returns true if the dataset's variable is likely a geophysical variable
'''
ncvar = ds.variables[variable]
# Does it have a standard name and units?
standard_name = getattr(ncvar, 'standard_name', '')
if not standard_name:
return False
if sta... | Returns true if the dataset's variable is likely a geophysical variable | Below is the the instruction that describes the task:
### Input:
Returns true if the dataset's variable is likely a geophysical variable
### Response:
def is_geophysical(ds, variable):
'''
Returns true if the dataset's variable is likely a geophysical variable
'''
ncvar = ds.variables[variable]
... |
def external(self, external_id, include=None):
"""
Locate an Organization by it's external_id attribute.
:param include: list of objects to sideload. `Side-loading API Docs
<https://developer.zendesk.com/rest_api/docs/core/side_loading>`__.
:param external_id: external id o... | Locate an Organization by it's external_id attribute.
:param include: list of objects to sideload. `Side-loading API Docs
<https://developer.zendesk.com/rest_api/docs/core/side_loading>`__.
:param external_id: external id of organization | Below is the the instruction that describes the task:
### Input:
Locate an Organization by it's external_id attribute.
:param include: list of objects to sideload. `Side-loading API Docs
<https://developer.zendesk.com/rest_api/docs/core/side_loading>`__.
:param external_id: external id... |
def evrs(self):
"""Getter EVRs dictionary"""
if self._evrs is None:
import ait.core.evr as evr
self._evrs = evr.getDefaultDict()
return self._evrs | Getter EVRs dictionary | Below is the the instruction that describes the task:
### Input:
Getter EVRs dictionary
### Response:
def evrs(self):
"""Getter EVRs dictionary"""
if self._evrs is None:
import ait.core.evr as evr
self._evrs = evr.getDefaultDict()
return self._evrs |
def distinct(self, *columns, **_filter):
"""
Returns all rows of a table, but removes rows in with duplicate values in ``columns``.
Interally this creates a `DISTINCT statement <http://www.w3schools.com/sql/sql_distinct.asp>`_.
::
# returns only one row per year, ignoring th... | Returns all rows of a table, but removes rows in with duplicate values in ``columns``.
Interally this creates a `DISTINCT statement <http://www.w3schools.com/sql/sql_distinct.asp>`_.
::
# returns only one row per year, ignoring the rest
table.distinct('year')
# works... | Below is the the instruction that describes the task:
### Input:
Returns all rows of a table, but removes rows in with duplicate values in ``columns``.
Interally this creates a `DISTINCT statement <http://www.w3schools.com/sql/sql_distinct.asp>`_.
::
# returns only one row per year, ign... |
def meta_changed(self, model, prop_name, info):
"""When the meta was changed, we have to set the dirty flag, as the changes are unsaved"""
self.state_machine.marked_dirty = True
msg = info.arg
if model is not self and msg.change.startswith('sm_notification_'): # Signal was caused by the... | When the meta was changed, we have to set the dirty flag, as the changes are unsaved | Below is the the instruction that describes the task:
### Input:
When the meta was changed, we have to set the dirty flag, as the changes are unsaved
### Response:
def meta_changed(self, model, prop_name, info):
"""When the meta was changed, we have to set the dirty flag, as the changes are unsaved"""
... |
def dt_year(x):
"""Extracts the year out of a datetime sample.
:returns: an expression containing the year extracted from a datetime column.
Example:
>>> import vaex
>>> import numpy as np
>>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:34:22'], dtype=np.date... | Extracts the year out of a datetime sample.
:returns: an expression containing the year extracted from a datetime column.
Example:
>>> import vaex
>>> import numpy as np
>>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:34:22'], dtype=np.datetime64)
>>> df = va... | Below is the the instruction that describes the task:
### Input:
Extracts the year out of a datetime sample.
:returns: an expression containing the year extracted from a datetime column.
Example:
>>> import vaex
>>> import numpy as np
>>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10... |
def get_first_and_last(year, month):
"""Returns two datetimes: first day and last day of given year&month"""
ym_first = make_aware(
datetime.datetime(year, month, 1),
get_default_timezone()
)
ym_last = make_aware(
datetime.datetime(year, month, monthra... | Returns two datetimes: first day and last day of given year&month | Below is the the instruction that describes the task:
### Input:
Returns two datetimes: first day and last day of given year&month
### Response:
def get_first_and_last(year, month):
"""Returns two datetimes: first day and last day of given year&month"""
ym_first = make_aware(
datetime.d... |
def inet_pton(af, addr):
"""Convert an IP address from text representation into binary form"""
print('hello')
if af == socket.AF_INET:
return inet_aton(addr)
elif af == socket.AF_INET6:
# IPv6: The use of "::" indicates one or more groups of 16 bits of zeros.
# We deal with this ... | Convert an IP address from text representation into binary form | Below is the the instruction that describes the task:
### Input:
Convert an IP address from text representation into binary form
### Response:
def inet_pton(af, addr):
"""Convert an IP address from text representation into binary form"""
print('hello')
if af == socket.AF_INET:
return inet_aton(... |
def collect_consequences(self):
"""Recursively collect a set of _ReferenceKeys that would
consequentially get dropped if this were dropped via
"drop ... cascade".
:return Set[_ReferenceKey]: All the relations that would be dropped
"""
consequences = {self.key()}
... | Recursively collect a set of _ReferenceKeys that would
consequentially get dropped if this were dropped via
"drop ... cascade".
:return Set[_ReferenceKey]: All the relations that would be dropped | Below is the the instruction that describes the task:
### Input:
Recursively collect a set of _ReferenceKeys that would
consequentially get dropped if this were dropped via
"drop ... cascade".
:return Set[_ReferenceKey]: All the relations that would be dropped
### Response:
def collect_con... |
def _setup(self, delete=True):
"""Create a function instance and execute setup.
Args:
delete (bool): Delete buffered variables.
"""
if delete:
self.clear()
with nn.context_scope(self.ctx):
outputs = self.func(
*(self.inputs_f ... | Create a function instance and execute setup.
Args:
delete (bool): Delete buffered variables. | Below is the the instruction that describes the task:
### Input:
Create a function instance and execute setup.
Args:
delete (bool): Delete buffered variables.
### Response:
def _setup(self, delete=True):
"""Create a function instance and execute setup.
Args:
delete... |
def use_device(cls, device):
"""Change the device to execute on for the scope of the block."""
if device == cls.ops.device:
yield
else:
curr_Ops, curr_ops = (cls.Ops, cls.ops)
cls.Ops = get_ops(device)
cls.ops = cls.Ops()
yield
... | Change the device to execute on for the scope of the block. | Below is the the instruction that describes the task:
### Input:
Change the device to execute on for the scope of the block.
### Response:
def use_device(cls, device):
"""Change the device to execute on for the scope of the block."""
if device == cls.ops.device:
yield
else:
... |
def update_configuration(self, did, wid, eid, payload):
'''
Update the configuration specified in the payload
Args:
- did (str): Document ID
- eid (str): Element ID
- payload (json): the request body
Returns:
- configuration (str): the url... | Update the configuration specified in the payload
Args:
- did (str): Document ID
- eid (str): Element ID
- payload (json): the request body
Returns:
- configuration (str): the url-ready configuration string. | Below is the the instruction that describes the task:
### Input:
Update the configuration specified in the payload
Args:
- did (str): Document ID
- eid (str): Element ID
- payload (json): the request body
Returns:
- configuration (str): the url-ready ... |
def atomic_batch_mutate(self, mutation_map, consistency_level):
"""
Atomically mutate many columns or super columns for many row keys. See also: Mutation.
mutation_map maps key to column family to a list of Mutation objects to take place at that scope.
*
Parameters:
- mutation_map
- ... | Atomically mutate many columns or super columns for many row keys. See also: Mutation.
mutation_map maps key to column family to a list of Mutation objects to take place at that scope.
*
Parameters:
- mutation_map
- consistency_level | Below is the the instruction that describes the task:
### Input:
Atomically mutate many columns or super columns for many row keys. See also: Mutation.
mutation_map maps key to column family to a list of Mutation objects to take place at that scope.
*
Parameters:
- mutation_map
- consisten... |
def contents(self):
"""
A C{PMap}, the message contents without Eliot metadata.
"""
return self._logged_dict.discard(TIMESTAMP_FIELD).discard(
TASK_UUID_FIELD
).discard(TASK_LEVEL_FIELD) | A C{PMap}, the message contents without Eliot metadata. | Below is the the instruction that describes the task:
### Input:
A C{PMap}, the message contents without Eliot metadata.
### Response:
def contents(self):
"""
A C{PMap}, the message contents without Eliot metadata.
"""
return self._logged_dict.discard(TIMESTAMP_FIELD).discard(
... |
def cross(self, vec):
"""Cross product with another Vector3Array"""
if not isinstance(vec, Vector3Array):
raise TypeError('Cross product operand must be a Vector3Array')
if self.nV != 1 and vec.nV != 1 and self.nV != vec.nV:
raise ValueError('Cross product operands must h... | Cross product with another Vector3Array | Below is the the instruction that describes the task:
### Input:
Cross product with another Vector3Array
### Response:
def cross(self, vec):
"""Cross product with another Vector3Array"""
if not isinstance(vec, Vector3Array):
raise TypeError('Cross product operand must be a Vector3Array'... |
def get_student_assignments_for_sis_course_id_and_canvas_user_id(
self, sis_course_id, user_id):
"""
Returns student assignment data for the given user_id and course_id.
https://canvas.instructure.com/doc/api/analytics.html#method.analytics_api.student_in_course_assignments
... | Returns student assignment data for the given user_id and course_id.
https://canvas.instructure.com/doc/api/analytics.html#method.analytics_api.student_in_course_assignments | Below is the the instruction that describes the task:
### Input:
Returns student assignment data for the given user_id and course_id.
https://canvas.instructure.com/doc/api/analytics.html#method.analytics_api.student_in_course_assignments
### Response:
def get_student_assignments_for_sis_course_id_and_can... |
def to_underscore(string):
"""Converts a given string from CamelCase to under_score.
>>> to_underscore('FooBar')
'foo_bar'
"""
new_string = re.sub(r'([A-Z]+)([A-Z][a-z])', r'\1_\2', string)
new_string = re.sub(r'([a-z\d])([A-Z])', r'\1_\2', new_string)
return new_string.lower() | Converts a given string from CamelCase to under_score.
>>> to_underscore('FooBar')
'foo_bar' | Below is the the instruction that describes the task:
### Input:
Converts a given string from CamelCase to under_score.
>>> to_underscore('FooBar')
'foo_bar'
### Response:
def to_underscore(string):
"""Converts a given string from CamelCase to under_score.
>>> to_underscore('FooBar')
'foo_bar... |
def create_lzma(archive, compression, cmd, verbosity, interactive, filenames):
"""Create an LZMA archive with the lzma Python module."""
return _create(archive, compression, cmd, 'alone', verbosity, filenames) | Create an LZMA archive with the lzma Python module. | Below is the the instruction that describes the task:
### Input:
Create an LZMA archive with the lzma Python module.
### Response:
def create_lzma(archive, compression, cmd, verbosity, interactive, filenames):
"""Create an LZMA archive with the lzma Python module."""
return _create(archive, compression, cm... |
def handle_label(self, label, **options):
"""
Command handler.
"""
if not hasattr(commands, 'sync_%s' % label):
raise CommandError('"%s" is not a valid command.' % label)
getattr(commands, 'sync_%s' % label)(**sanitize_command_options(options)) | Command handler. | Below is the the instruction that describes the task:
### Input:
Command handler.
### Response:
def handle_label(self, label, **options):
"""
Command handler.
"""
if not hasattr(commands, 'sync_%s' % label):
raise CommandError('"%s" is not a valid command.' % label)
... |
def sort_index(self, axis=0, level=None, ascending=True, inplace=False,
kind='quicksort', na_position='last', sort_remaining=True):
"""
Sort Series by index labels.
Returns a new Series sorted by label if `inplace` argument is
``False``, otherwise updates the original... | Sort Series by index labels.
Returns a new Series sorted by label if `inplace` argument is
``False``, otherwise updates the original series and returns None.
Parameters
----------
axis : int, default 0
Axis to direct sorting. This can only be 0 for Series.
l... | Below is the the instruction that describes the task:
### Input:
Sort Series by index labels.
Returns a new Series sorted by label if `inplace` argument is
``False``, otherwise updates the original series and returns None.
Parameters
----------
axis : int, default 0
... |
def set_style(primary=None, secondary=None):
""" Sets primary and secondary component styles.
"""
global _primary_style, _secondary_style
if primary:
_primary_style = primary
if secondary:
_secondary_style = secondary | Sets primary and secondary component styles. | Below is the the instruction that describes the task:
### Input:
Sets primary and secondary component styles.
### Response:
def set_style(primary=None, secondary=None):
""" Sets primary and secondary component styles.
"""
global _primary_style, _secondary_style
if primary:
_primary_style = ... |
def _handle_report(self, report):
"""Try to emit a report and possibly keep a copy of it"""
keep_report = True
if self.report_callback is not None:
keep_report = self.report_callback(report, self.context)
if keep_report:
self.reports.append(report) | Try to emit a report and possibly keep a copy of it | Below is the the instruction that describes the task:
### Input:
Try to emit a report and possibly keep a copy of it
### Response:
def _handle_report(self, report):
"""Try to emit a report and possibly keep a copy of it"""
keep_report = True
if self.report_callback is not None:
... |
def build_response(
self, data: AwaitableOrValue[Optional[Dict[str, Any]]]
) -> AwaitableOrValue[ExecutionResult]:
"""Build response.
Given a completed execution context and data, build the (data, errors) response
defined by the "Response" section of the GraphQL spec.
"""
... | Build response.
Given a completed execution context and data, build the (data, errors) response
defined by the "Response" section of the GraphQL spec. | Below is the the instruction that describes the task:
### Input:
Build response.
Given a completed execution context and data, build the (data, errors) response
defined by the "Response" section of the GraphQL spec.
### Response:
def build_response(
self, data: AwaitableOrValue[Optional[Di... |
def remove():
"""Function executed when running the script with the -remove switch"""
current = True # only affects current user
root = winreg.HKEY_CURRENT_USER if current else winreg.HKEY_LOCAL_MACHINE
for key in (KEY_C1 % ("", EWS), KEY_C1 % ("NoCon", EWS),
KEY_C0 % ("", EWS), KE... | Function executed when running the script with the -remove switch | Below is the the instruction that describes the task:
### Input:
Function executed when running the script with the -remove switch
### Response:
def remove():
"""Function executed when running the script with the -remove switch"""
current = True # only affects current user
root = winreg.HKEY_CURREN... |
def get_version(extension, workflow_file):
'''Determines the version of a .py, .wdl, or .cwl file.'''
if extension == 'py' and two_seven_compatible(workflow_file):
return '2.7'
elif extension == 'cwl':
return yaml.load(open(workflow_file))['cwlVersion']
else: # Must be a wdl file.
... | Determines the version of a .py, .wdl, or .cwl file. | Below is the the instruction that describes the task:
### Input:
Determines the version of a .py, .wdl, or .cwl file.
### Response:
def get_version(extension, workflow_file):
'''Determines the version of a .py, .wdl, or .cwl file.'''
if extension == 'py' and two_seven_compatible(workflow_file):
ret... |
def percussive(y, **kwargs):
'''Extract percussive elements from an audio time-series.
Parameters
----------
y : np.ndarray [shape=(n,)]
audio time series
kwargs : additional keyword arguments.
See `librosa.decompose.hpss` for details.
Returns
-------
y_percussive : np.... | Extract percussive elements from an audio time-series.
Parameters
----------
y : np.ndarray [shape=(n,)]
audio time series
kwargs : additional keyword arguments.
See `librosa.decompose.hpss` for details.
Returns
-------
y_percussive : np.ndarray [shape=(n,)]
audio t... | Below is the the instruction that describes the task:
### Input:
Extract percussive elements from an audio time-series.
Parameters
----------
y : np.ndarray [shape=(n,)]
audio time series
kwargs : additional keyword arguments.
See `librosa.decompose.hpss` for details.
Returns
... |
def clientConnectionFailed(self, connector, reason):
"""Called when the client has failed to connect to the broker.
See the documentation of
`twisted.internet.protocol.ReconnectingClientFactory` for details.
"""
_legacy_twisted_log.msg(
"Connection to the AMQP broker... | Called when the client has failed to connect to the broker.
See the documentation of
`twisted.internet.protocol.ReconnectingClientFactory` for details. | Below is the the instruction that describes the task:
### Input:
Called when the client has failed to connect to the broker.
See the documentation of
`twisted.internet.protocol.ReconnectingClientFactory` for details.
### Response:
def clientConnectionFailed(self, connector, reason):
"""Cal... |
def mount(self, volume):
"""Command that is an alternative to the :func:`mount` command that opens a LUKS container. The opened volume is
added to the subvolume set of this volume. Requires the user to enter the key manually.
TODO: add support for :attr:`keys`
:return: the Volume conta... | Command that is an alternative to the :func:`mount` command that opens a LUKS container. The opened volume is
added to the subvolume set of this volume. Requires the user to enter the key manually.
TODO: add support for :attr:`keys`
:return: the Volume contained in the LUKS container, or None ... | Below is the the instruction that describes the task:
### Input:
Command that is an alternative to the :func:`mount` command that opens a LUKS container. The opened volume is
added to the subvolume set of this volume. Requires the user to enter the key manually.
TODO: add support for :attr:`keys`
... |
def delete(self, organization, domain=None):
"""Remove organizations and domains from the registry.
The method removes the given 'organization' or 'domain' from the registry,
but not both at the same time.
When 'organization' is the only parameter given, it will be removed from
... | Remove organizations and domains from the registry.
The method removes the given 'organization' or 'domain' from the registry,
but not both at the same time.
When 'organization' is the only parameter given, it will be removed from
the registry, including those domains related to it. Wh... | Below is the the instruction that describes the task:
### Input:
Remove organizations and domains from the registry.
The method removes the given 'organization' or 'domain' from the registry,
but not both at the same time.
When 'organization' is the only parameter given, it will be removed... |
def Rz_to_lambdanu_hess(R,z,Delta=1.):
"""
NAME:
Rz_to_lambdanu_hess
PURPOSE:
calculate the Hessian of the cylindrical (R,z) to prolate spheroidal
(lambda,nu) conversion
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
Delta - foc... | NAME:
Rz_to_lambdanu_hess
PURPOSE:
calculate the Hessian of the cylindrical (R,z) to prolate spheroidal
(lambda,nu) conversion
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
Delta - focal distance that defines the spheroidal coordinate ... | Below is the the instruction that describes the task:
### Input:
NAME:
Rz_to_lambdanu_hess
PURPOSE:
calculate the Hessian of the cylindrical (R,z) to prolate spheroidal
(lambda,nu) conversion
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
... |
def ciphertext(self, be_secure=True):
"""Return the ciphertext of the EncryptedNumber.
Choosing a random number is slow. Therefore, methods like
:meth:`__add__` and :meth:`__mul__` take a shortcut and do not
follow Paillier encryption fully - every encrypted sum or
product shoul... | Return the ciphertext of the EncryptedNumber.
Choosing a random number is slow. Therefore, methods like
:meth:`__add__` and :meth:`__mul__` take a shortcut and do not
follow Paillier encryption fully - every encrypted sum or
product should be multiplied by r **
:attr:`~PaillierP... | Below is the the instruction that describes the task:
### Input:
Return the ciphertext of the EncryptedNumber.
Choosing a random number is slow. Therefore, methods like
:meth:`__add__` and :meth:`__mul__` take a shortcut and do not
follow Paillier encryption fully - every encrypted sum or
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.