code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _adjusted_script_code(self, script):
'''
Checks if the script code pased in to the sighash function is already
length-prepended
This will break if there's a redeem script that's just a pushdata
That won't happen in practice
Args:
script (bytes): the spend... | Checks if the script code pased in to the sighash function is already
length-prepended
This will break if there's a redeem script that's just a pushdata
That won't happen in practice
Args:
script (bytes): the spend script
Returns:
(bytes): the length-prep... | Below is the the instruction that describes the task:
### Input:
Checks if the script code pased in to the sighash function is already
length-prepended
This will break if there's a redeem script that's just a pushdata
That won't happen in practice
Args:
script (bytes): t... |
def median_approx(self, expression, percentage=50., binby=[], limits=None, shape=default_shape, percentile_shape=256, percentile_limits="minmax", selection=False, delay=False):
"""Calculate the median , possibly on a grid defined by binby.
NOTE: this value is approximated by calculating the cumulative ... | Calculate the median , possibly on a grid defined by binby.
NOTE: this value is approximated by calculating the cumulative distribution on a grid defined by
percentile_shape and percentile_limits
:param expression: {expression}
:param binby: {binby}
:param limits: {limits}
... | Below is the the instruction that describes the task:
### Input:
Calculate the median , possibly on a grid defined by binby.
NOTE: this value is approximated by calculating the cumulative distribution on a grid defined by
percentile_shape and percentile_limits
:param expression: {expressi... |
async def unignore_all(self, ctx):
"""Unignores all channels in this server from being processed.
To use this command you must have the Manage Channels permission or have the
Bot Admin role.
"""
channels = [c for c in ctx.message.server.channels if c.type is discord.ChannelType.... | Unignores all channels in this server from being processed.
To use this command you must have the Manage Channels permission or have the
Bot Admin role. | Below is the the instruction that describes the task:
### Input:
Unignores all channels in this server from being processed.
To use this command you must have the Manage Channels permission or have the
Bot Admin role.
### Response:
async def unignore_all(self, ctx):
"""Unignores all channe... |
def user_has_reviewed(obj, user):
"""Returns True if the user has already reviewed the object."""
ctype = ContentType.objects.get_for_model(obj)
try:
models.Review.objects.get(user=user, content_type=ctype,
object_id=obj.id)
except models.Review.DoesNotExist:
... | Returns True if the user has already reviewed the object. | Below is the the instruction that describes the task:
### Input:
Returns True if the user has already reviewed the object.
### Response:
def user_has_reviewed(obj, user):
"""Returns True if the user has already reviewed the object."""
ctype = ContentType.objects.get_for_model(obj)
try:
models.R... |
def get_high_level_mean_pars(self, high_level_type, high_level_name, calculation_type, elements_type, mean_fit, dirtype):
"""
Gets the Parameters of a mean of lower level data such as a Site
level Fisher mean of Specimen interpretations
Parameters
----------
high_level_t... | Gets the Parameters of a mean of lower level data such as a Site
level Fisher mean of Specimen interpretations
Parameters
----------
high_level_type : 'samples','sites','locations','study'
high_level_name : sample, site, location, or study whose
data to which to appl... | Below is the the instruction that describes the task:
### Input:
Gets the Parameters of a mean of lower level data such as a Site
level Fisher mean of Specimen interpretations
Parameters
----------
high_level_type : 'samples','sites','locations','study'
high_level_name : sam... |
def set_header(self, name: str, value: _HeaderTypes) -> None:
"""Sets the given response header name and value.
All header values are converted to strings (`datetime` objects
are formatted according to the HTTP specification for the
``Date`` header).
"""
self._headers[n... | Sets the given response header name and value.
All header values are converted to strings (`datetime` objects
are formatted according to the HTTP specification for the
``Date`` header). | Below is the the instruction that describes the task:
### Input:
Sets the given response header name and value.
All header values are converted to strings (`datetime` objects
are formatted according to the HTTP specification for the
``Date`` header).
### Response:
def set_header(self, name... |
def path(self):
"""
Return the path to this directory.
"""
p = ''
if self._parent and self._parent.path:
p = os.path.join(p, self._parent.path)
if self._base:
p = os.path.join(p, self._base)
if self._path:
p = os.path.join(p, s... | Return the path to this directory. | Below is the the instruction that describes the task:
### Input:
Return the path to this directory.
### Response:
def path(self):
"""
Return the path to this directory.
"""
p = ''
if self._parent and self._parent.path:
p = os.path.join(p, self._parent.path)
... |
def _to_topology(self, atom_list, chains=None, residues=None):
"""Create a mdtraj.Topology from a Compound.
Parameters
----------
atom_list : list of mb.Compound
Atoms to include in the topology
chains : mb.Compound or list of mb.Compound
Chain types to a... | Create a mdtraj.Topology from a Compound.
Parameters
----------
atom_list : list of mb.Compound
Atoms to include in the topology
chains : mb.Compound or list of mb.Compound
Chain types to add to the topology
residues : str of list of str
Label... | Below is the the instruction that describes the task:
### Input:
Create a mdtraj.Topology from a Compound.
Parameters
----------
atom_list : list of mb.Compound
Atoms to include in the topology
chains : mb.Compound or list of mb.Compound
Chain types to add to... |
def is_smooth_from(self, previous, warning_on=True):
"""[Warning: The name of this method is somewhat misleading (yet kept
for compatibility with scripts created using svg.path 2.0). This
method is meant only for d string creation and should not be used to
check for kinks. To check a s... | [Warning: The name of this method is somewhat misleading (yet kept
for compatibility with scripts created using svg.path 2.0). This
method is meant only for d string creation and should not be used to
check for kinks. To check a segment for differentiability, use the
joins_smoothly_wit... | Below is the the instruction that describes the task:
### Input:
[Warning: The name of this method is somewhat misleading (yet kept
for compatibility with scripts created using svg.path 2.0). This
method is meant only for d string creation and should not be used to
check for kinks. To chec... |
def list_gemeenten(self, sort=1):
'''
List all `gemeenten` in Vlaanderen.
:param integer sort: What field to sort on.
:rtype: A :class:`list` of :class:`Gemeente`.
'''
def creator():
url = self.base_url + '/municipality'
h = self.base_headers
... | List all `gemeenten` in Vlaanderen.
:param integer sort: What field to sort on.
:rtype: A :class:`list` of :class:`Gemeente`. | Below is the the instruction that describes the task:
### Input:
List all `gemeenten` in Vlaanderen.
:param integer sort: What field to sort on.
:rtype: A :class:`list` of :class:`Gemeente`.
### Response:
def list_gemeenten(self, sort=1):
'''
List all `gemeenten` in Vlaanderen.
... |
def create(cls, title, conn=None, google_user=None,
google_password=None):
""" Create a new spreadsheet with the given ``title``. """
conn = Connection.connect(conn=conn, google_user=google_user,
google_password=google_password)
res = Resource(typ... | Create a new spreadsheet with the given ``title``. | Below is the the instruction that describes the task:
### Input:
Create a new spreadsheet with the given ``title``.
### Response:
def create(cls, title, conn=None, google_user=None,
google_password=None):
""" Create a new spreadsheet with the given ``title``. """
conn = Connection.co... |
def getLogicalInterfaces(self, draft=False, name=None, schemaId=None):
"""
Get all logical interfaces for an org.
Parameters: draft (boolean).
Returns:
- list of ids
- response object
Throws APIException on failure.
"""
if draft:
... | Get all logical interfaces for an org.
Parameters: draft (boolean).
Returns:
- list of ids
- response object
Throws APIException on failure. | Below is the the instruction that describes the task:
### Input:
Get all logical interfaces for an org.
Parameters: draft (boolean).
Returns:
- list of ids
- response object
Throws APIException on failure.
### Response:
def getLogicalInterfaces(self, draft=False, nam... |
def interval_cover(I):
"""Minimum interval cover
:param I: list of closed intervals
:returns: minimum list of points covering all intervals
:complexity: O(n log n)
"""
S = []
for start, end in sorted(I, key=lambda v: v[1]):
if not S or S[-1] < start:
S.append(end)
re... | Minimum interval cover
:param I: list of closed intervals
:returns: minimum list of points covering all intervals
:complexity: O(n log n) | Below is the the instruction that describes the task:
### Input:
Minimum interval cover
:param I: list of closed intervals
:returns: minimum list of points covering all intervals
:complexity: O(n log n)
### Response:
def interval_cover(I):
"""Minimum interval cover
:param I: list of closed in... |
def clean(self):
"""
Check format name uniqueness for sites
:return: cleaned_data
"""
data = self.cleaned_data
formats = Format.objects.filter(name=data['name'])
if self.instance:
formats = formats.exclude(pk=self.instance.pk)
exists_sites =... | Check format name uniqueness for sites
:return: cleaned_data | Below is the the instruction that describes the task:
### Input:
Check format name uniqueness for sites
:return: cleaned_data
### Response:
def clean(self):
"""
Check format name uniqueness for sites
:return: cleaned_data
"""
data = self.cleaned_data
forma... |
def less(a, b, *args):
"""Implements the '<' operator with JS-style type coertion."""
types = set([type(a), type(b)])
if float in types or int in types:
try:
a, b = float(a), float(b)
except TypeError:
# NaN
return False
return a < b and (not args or l... | Implements the '<' operator with JS-style type coertion. | Below is the the instruction that describes the task:
### Input:
Implements the '<' operator with JS-style type coertion.
### Response:
def less(a, b, *args):
"""Implements the '<' operator with JS-style type coertion."""
types = set([type(a), type(b)])
if float in types or int in types:
try:
... |
def _classes_default(self):
"""This has to be in a method, for TerminalIPythonApp to be available."""
return [
InteractiveShellApp, # ShellApp comes before TerminalApp, because
self.__class__, # it will also affect subclasses (e.g. QtConsole)
TerminalInteractiveS... | This has to be in a method, for TerminalIPythonApp to be available. | Below is the the instruction that describes the task:
### Input:
This has to be in a method, for TerminalIPythonApp to be available.
### Response:
def _classes_default(self):
"""This has to be in a method, for TerminalIPythonApp to be available."""
return [
InteractiveShellApp, # ShellA... |
def data_directory(self):
"""
The absolute pathname of the directory where pip-accel's data files are stored (a string).
- Environment variable: ``$PIP_ACCEL_CACHE``
- Configuration option: ``data-directory``
- Default: ``/var/cache/pip-accel`` if running as ``root``, ``~/.pip-a... | The absolute pathname of the directory where pip-accel's data files are stored (a string).
- Environment variable: ``$PIP_ACCEL_CACHE``
- Configuration option: ``data-directory``
- Default: ``/var/cache/pip-accel`` if running as ``root``, ``~/.pip-accel`` otherwise | Below is the the instruction that describes the task:
### Input:
The absolute pathname of the directory where pip-accel's data files are stored (a string).
- Environment variable: ``$PIP_ACCEL_CACHE``
- Configuration option: ``data-directory``
- Default: ``/var/cache/pip-accel`` if running ... |
def translations_generator_to_dataframe(translations_generator):
"""
Given a generator of (Variant, [Translation]) pairs,
returns a DataFrame of translated protein fragments with columns
for each field of a Translation object (and chr/pos/ref/alt per variant).
"""
return dataframe_from_generator... | Given a generator of (Variant, [Translation]) pairs,
returns a DataFrame of translated protein fragments with columns
for each field of a Translation object (and chr/pos/ref/alt per variant). | Below is the the instruction that describes the task:
### Input:
Given a generator of (Variant, [Translation]) pairs,
returns a DataFrame of translated protein fragments with columns
for each field of a Translation object (and chr/pos/ref/alt per variant).
### Response:
def translations_generator_to_datafr... |
def render_pulp_tag(self):
"""
Configure the pulp_tag plugin.
"""
if not self.dj.dock_json_has_plugin_conf('postbuild_plugins',
'pulp_tag'):
return
pulp_registry = self.spec.pulp_registry.value
if pulp_registry... | Configure the pulp_tag plugin. | Below is the the instruction that describes the task:
### Input:
Configure the pulp_tag plugin.
### Response:
def render_pulp_tag(self):
"""
Configure the pulp_tag plugin.
"""
if not self.dj.dock_json_has_plugin_conf('postbuild_plugins',
... |
def remove(name_or_path):
'''Remove an environment or module
:param name_or_path: name or path to environment or module
'''
r = resolve(name_or_path)
r.resolved[0].remove()
EnvironmentCache.discard(r.resolved[0])
EnvironmentCache.save() | Remove an environment or module
:param name_or_path: name or path to environment or module | Below is the the instruction that describes the task:
### Input:
Remove an environment or module
:param name_or_path: name or path to environment or module
### Response:
def remove(name_or_path):
'''Remove an environment or module
:param name_or_path: name or path to environment or module
'''
... |
def reduce_stock(self, product_id, sku_info, quantity):
"""
减少库存
:param product_id: 商品ID
:param sku_info: sku信息,格式"id1:vid1;id2:vid2",如商品为统一规格,则此处赋值为空字符串即可
:param quantity: 减少的库存数量
:return: 返回的 JSON 数据包
"""
return self._post(
'merchant/stock/r... | 减少库存
:param product_id: 商品ID
:param sku_info: sku信息,格式"id1:vid1;id2:vid2",如商品为统一规格,则此处赋值为空字符串即可
:param quantity: 减少的库存数量
:return: 返回的 JSON 数据包 | Below is the the instruction that describes the task:
### Input:
减少库存
:param product_id: 商品ID
:param sku_info: sku信息,格式"id1:vid1;id2:vid2",如商品为统一规格,则此处赋值为空字符串即可
:param quantity: 减少的库存数量
:return: 返回的 JSON 数据包
### Response:
def reduce_stock(self, product_id, sku_info, quantity):
... |
def slice_to(self, s):
'''
Copy the slice into the supplied StringBuffer
@type s: string
'''
result = ''
if self.slice_check():
result = self.current[self.bra:self.ket]
return result | Copy the slice into the supplied StringBuffer
@type s: string | Below is the the instruction that describes the task:
### Input:
Copy the slice into the supplied StringBuffer
@type s: string
### Response:
def slice_to(self, s):
'''
Copy the slice into the supplied StringBuffer
@type s: string
'''
result = ''
if self.sli... |
def add_time(data):
"""And a friendly update time to the supplied data.
Arguments:
data (:py:class:`dict`): The response data and its update time.
Returns:
:py:class:`dict`: The data with a friendly update time.
"""
payload = data['data']
updated = data['updated'].date()
if up... | And a friendly update time to the supplied data.
Arguments:
data (:py:class:`dict`): The response data and its update time.
Returns:
:py:class:`dict`: The data with a friendly update time. | Below is the the instruction that describes the task:
### Input:
And a friendly update time to the supplied data.
Arguments:
data (:py:class:`dict`): The response data and its update time.
Returns:
:py:class:`dict`: The data with a friendly update time.
### Response:
def add_time(data):
"... |
def get_job(self, job_id):
"""GetJob
https://apidocs.joyent.com/manta/api.html#GetJob
with the added sugar that it will retrieve the archived job if it has
been archived, per:
https://apidocs.joyent.com/manta/jobs-reference.html#job-completion-and-archival
"""
... | GetJob
https://apidocs.joyent.com/manta/api.html#GetJob
with the added sugar that it will retrieve the archived job if it has
been archived, per:
https://apidocs.joyent.com/manta/jobs-reference.html#job-completion-and-archival | Below is the the instruction that describes the task:
### Input:
GetJob
https://apidocs.joyent.com/manta/api.html#GetJob
with the added sugar that it will retrieve the archived job if it has
been archived, per:
https://apidocs.joyent.com/manta/jobs-reference.html#job-completi... |
def unpack(self, buff, offset=0):
"""Unpack a binary message into this object's attributes.
Unpack the binary value *buff* and update this object attributes based
on the results.
Args:
buff (bytes): Binary data package to be unpacked.
offset (int): Where to begi... | Unpack a binary message into this object's attributes.
Unpack the binary value *buff* and update this object attributes based
on the results.
Args:
buff (bytes): Binary data package to be unpacked.
offset (int): Where to begin unpacking.
Raises:
Exc... | Below is the the instruction that describes the task:
### Input:
Unpack a binary message into this object's attributes.
Unpack the binary value *buff* and update this object attributes based
on the results.
Args:
buff (bytes): Binary data package to be unpacked.
off... |
def prepare_env(app, env, docname):
"""
Prepares the sphinx environment to store sphinx-needs internal data.
"""
if not hasattr(env, 'needs_all_needs'):
# Used to store all needed information about all needs in document
env.needs_all_needs = {}
if not hasattr(env, 'needs_functions')... | Prepares the sphinx environment to store sphinx-needs internal data. | Below is the the instruction that describes the task:
### Input:
Prepares the sphinx environment to store sphinx-needs internal data.
### Response:
def prepare_env(app, env, docname):
"""
Prepares the sphinx environment to store sphinx-needs internal data.
"""
if not hasattr(env, 'needs_all_needs')... |
def to_mapping(self,**values):
"""
Create a JSON-serializable representation of the plane that is usable with the
javascript frontend
"""
strike, dip, rake = self.strike_dip_rake()
min, max = self.angular_errors()
try:
disabled = self.disabled
... | Create a JSON-serializable representation of the plane that is usable with the
javascript frontend | Below is the the instruction that describes the task:
### Input:
Create a JSON-serializable representation of the plane that is usable with the
javascript frontend
### Response:
def to_mapping(self,**values):
"""
Create a JSON-serializable representation of the plane that is usable with the... |
def guard_submit(analysis_request):
"""Return whether the transition "submit" can be performed or not.
Returns True if there is at least one analysis in a non-detached state and
all analyses in a non-detached analyses have been submitted.
"""
analyses_ready = False
for analysis in analysis_reque... | Return whether the transition "submit" can be performed or not.
Returns True if there is at least one analysis in a non-detached state and
all analyses in a non-detached analyses have been submitted. | Below is the the instruction that describes the task:
### Input:
Return whether the transition "submit" can be performed or not.
Returns True if there is at least one analysis in a non-detached state and
all analyses in a non-detached analyses have been submitted.
### Response:
def guard_submit(analysis_re... |
def from_array(array):
"""
Deserialize a new Sticker from a given dictionary.
:return: new Sticker instance.
:rtype: Sticker
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
... | Deserialize a new Sticker from a given dictionary.
:return: new Sticker instance.
:rtype: Sticker | Below is the the instruction that describes the task:
### Input:
Deserialize a new Sticker from a given dictionary.
:return: new Sticker instance.
:rtype: Sticker
### Response:
def from_array(array):
"""
Deserialize a new Sticker from a given dictionary.
:return: new Stick... |
def start_packet_groups(self, clear_time_stamps=True, *ports):
""" Start packet groups on ports.
:param clear_time_stamps: True - clear time stamps, False - don't.
:param ports: list of ports to start traffic on, if empty start on all ports.
"""
port_list = self.set_ports_list(*... | Start packet groups on ports.
:param clear_time_stamps: True - clear time stamps, False - don't.
:param ports: list of ports to start traffic on, if empty start on all ports. | Below is the the instruction that describes the task:
### Input:
Start packet groups on ports.
:param clear_time_stamps: True - clear time stamps, False - don't.
:param ports: list of ports to start traffic on, if empty start on all ports.
### Response:
def start_packet_groups(self, clear_time_sta... |
def get_leaves(self):
"""Get the deepest entries as a flat set."""
ret_set = set()
for val in self.values():
if isinstance(val, self.__class__):
ret_set |= val.get_leaves()
elif isinstance(val, dict):
ret_set |= set(val.values())
... | Get the deepest entries as a flat set. | Below is the the instruction that describes the task:
### Input:
Get the deepest entries as a flat set.
### Response:
def get_leaves(self):
"""Get the deepest entries as a flat set."""
ret_set = set()
for val in self.values():
if isinstance(val, self.__class__):
... |
def define_passive_branch_flows_with_kirchhoff(network,snapshots,skip_vars=False):
""" define passive branch flows with the kirchoff method """
for sub_network in network.sub_networks.obj:
find_tree(sub_network)
find_cycles(sub_network)
#following is necessary to calculate angles post-... | define passive branch flows with the kirchoff method | Below is the the instruction that describes the task:
### Input:
define passive branch flows with the kirchoff method
### Response:
def define_passive_branch_flows_with_kirchhoff(network,snapshots,skip_vars=False):
""" define passive branch flows with the kirchoff method """
for sub_network in network.sub... |
def rectify_ajax_form_data(self, data):
"""
If a widget was converted and the Form data was submitted through an Ajax request,
then these data fields must be converted to suit the Django Form validation
"""
for name, field in self.base_fields.items():
try:
... | If a widget was converted and the Form data was submitted through an Ajax request,
then these data fields must be converted to suit the Django Form validation | Below is the the instruction that describes the task:
### Input:
If a widget was converted and the Form data was submitted through an Ajax request,
then these data fields must be converted to suit the Django Form validation
### Response:
def rectify_ajax_form_data(self, data):
"""
If a widg... |
def ParseOptions(cls, options, analysis_plugin):
"""Parses and validates options.
Args:
options (argparse.Namespace): parser options.
analysis_plugin (AnalysisPlugin): analysis plugin to configure.
Raises:
BadConfigObject: when the output module object is of the wrong type.
BadConf... | Parses and validates options.
Args:
options (argparse.Namespace): parser options.
analysis_plugin (AnalysisPlugin): analysis plugin to configure.
Raises:
BadConfigObject: when the output module object is of the wrong type.
BadConfigOption: when a configuration parameter fails validatio... | Below is the the instruction that describes the task:
### Input:
Parses and validates options.
Args:
options (argparse.Namespace): parser options.
analysis_plugin (AnalysisPlugin): analysis plugin to configure.
Raises:
BadConfigObject: when the output module object is of the wrong type.
... |
def _computeOverlaps(data, selfOverlaps=False, dtype="int16"):
"""
Calculates all pairwise overlaps between the rows of the input. Returns an
array of all n(n-1)/2 values in the upper triangular portion of the
pairwise overlap matrix. Values are returned in row-major order.
@param data (scipy.spars... | Calculates all pairwise overlaps between the rows of the input. Returns an
array of all n(n-1)/2 values in the upper triangular portion of the
pairwise overlap matrix. Values are returned in row-major order.
@param data (scipy.sparse.csr_matrix) A CSR sparse matrix with one vector
per row. Any non-... | Below is the the instruction that describes the task:
### Input:
Calculates all pairwise overlaps between the rows of the input. Returns an
array of all n(n-1)/2 values in the upper triangular portion of the
pairwise overlap matrix. Values are returned in row-major order.
@param data (scipy.sparse.csr_... |
def get_ip(self, use_cached=True):
"""Get the last known IP of this device"""
device_json = self.get_device_json(use_cached)
return device_json.get("dpLastKnownIp") | Get the last known IP of this device | Below is the the instruction that describes the task:
### Input:
Get the last known IP of this device
### Response:
def get_ip(self, use_cached=True):
"""Get the last known IP of this device"""
device_json = self.get_device_json(use_cached)
return device_json.get("dpLastKnownIp") |
def get(self, url, name, params=None, headers=None, connection=None):
"""
Synchronous GET request.
"""
if name is None: name = ''
params = params or {}
headers = headers or {}
endpoint = self._build_endpoint_url(url, name)
self._authenticate(params, header... | Synchronous GET request. | Below is the the instruction that describes the task:
### Input:
Synchronous GET request.
### Response:
def get(self, url, name, params=None, headers=None, connection=None):
"""
Synchronous GET request.
"""
if name is None: name = ''
params = params or {}
headers = h... |
def contains(bank, key):
'''
Checks if the specified bank contains the specified key.
'''
_init_client()
etcd_key = '{0}/{1}/{2}'.format(path_prefix, bank, key)
try:
r = client.read(etcd_key)
# return True for keys, not dirs
return r.dir is False
except etcd.EtcdKeyNo... | Checks if the specified bank contains the specified key. | Below is the the instruction that describes the task:
### Input:
Checks if the specified bank contains the specified key.
### Response:
def contains(bank, key):
'''
Checks if the specified bank contains the specified key.
'''
_init_client()
etcd_key = '{0}/{1}/{2}'.format(path_prefix, bank, key... |
def expand_star(mod_name):
"""Expand something like 'unuk.tasks.*' into a list of all the modules
there.
"""
expanded = []
mod_dir = os.path.dirname(
__import__(mod_name[:-2], {}, {}, ['']).__file__)
for f in glob.glob1(mod_dir, "[!_]*.py"):
expanded.append('%s.%s' % (mod_name[:-... | Expand something like 'unuk.tasks.*' into a list of all the modules
there. | Below is the the instruction that describes the task:
### Input:
Expand something like 'unuk.tasks.*' into a list of all the modules
there.
### Response:
def expand_star(mod_name):
"""Expand something like 'unuk.tasks.*' into a list of all the modules
there.
"""
expanded = []
mod_dir = os.p... |
def split_func(string):
"""
Take a string like 'requiredIf("arg_name")'
return the function name and the argument:
(requiredIf, arg_name)
"""
ind = string.index("(")
return string[:ind], string[ind+1:-1].strip('"') | Take a string like 'requiredIf("arg_name")'
return the function name and the argument:
(requiredIf, arg_name) | Below is the the instruction that describes the task:
### Input:
Take a string like 'requiredIf("arg_name")'
return the function name and the argument:
(requiredIf, arg_name)
### Response:
def split_func(string):
"""
Take a string like 'requiredIf("arg_name")'
return the function name and the a... |
def bar_chart(data, bar_char='=', width=80):
"""Return an horizontal bar chart
>>> print bar_chart({
... 'one': '1',
... 'two': '2',
... 'three': '3',
... 'four': '4',
... 'five': '5',
... })
five =====
four ====
one =
three ===
two ==
>>> print bar_chart({
... '1/1': 1/1.... | Return an horizontal bar chart
>>> print bar_chart({
... 'one': '1',
... 'two': '2',
... 'three': '3',
... 'four': '4',
... 'five': '5',
... })
five =====
four ====
one =
three ===
two ==
>>> print bar_chart({
... '1/1': 1/1.0,
... '1/2': 1/2.0,
... '1/3': 1/3.0,
... | Below is the the instruction that describes the task:
### Input:
Return an horizontal bar chart
>>> print bar_chart({
... 'one': '1',
... 'two': '2',
... 'three': '3',
... 'four': '4',
... 'five': '5',
... })
five =====
four ====
one =
three ===
two ==
>>> print bar_chart({
... |
def handle(self):
"""
Handle a single message. SocketServer takes care of splitting out the messages.
Messages are JSON-encoded logging module records.
"""
# Unpack the data from the request
data, socket = self.request
try:
# Parse it... | Handle a single message. SocketServer takes care of splitting out the messages.
Messages are JSON-encoded logging module records. | Below is the the instruction that describes the task:
### Input:
Handle a single message. SocketServer takes care of splitting out the messages.
Messages are JSON-encoded logging module records.
### Response:
def handle(self):
"""
Handle a single message. SocketServer takes care of... |
def getConstants(ast):
'''
RAM: implemented magic method __lt__ for ASTNode to fix issues
#88 and #209. The following test code works now, as does the test suite.
import numexpr as ne
a = 1 + 3j; b = 5.0
ne.evaluate( 'a*2 + 15j - b' )
'''
constants_order = sorted( ast.allOf('constant') )... | RAM: implemented magic method __lt__ for ASTNode to fix issues
#88 and #209. The following test code works now, as does the test suite.
import numexpr as ne
a = 1 + 3j; b = 5.0
ne.evaluate( 'a*2 + 15j - b' ) | Below is the the instruction that describes the task:
### Input:
RAM: implemented magic method __lt__ for ASTNode to fix issues
#88 and #209. The following test code works now, as does the test suite.
import numexpr as ne
a = 1 + 3j; b = 5.0
ne.evaluate( 'a*2 + 15j - b' )
### Response:
def getConst... |
def volumes(self):
"""Returns all available volumes"""
if self._data is not None:
volumes = []
for volume in self._data["volumes"]:
volumes.append(volume["id"])
return volumes | Returns all available volumes | Below is the the instruction that describes the task:
### Input:
Returns all available volumes
### Response:
def volumes(self):
"""Returns all available volumes"""
if self._data is not None:
volumes = []
for volume in self._data["volumes"]:
volumes.appen... |
def visit_ImportFrom(self, node):
"""callback for 'import from' statement"""
self.imports.extend((node.module, n.name, n.asname, node.level)
for n in node.names)
ast.NodeVisitor.generic_visit(self, node) | callback for 'import from' statement | Below is the the instruction that describes the task:
### Input:
callback for 'import from' statement
### Response:
def visit_ImportFrom(self, node):
"""callback for 'import from' statement"""
self.imports.extend((node.module, n.name, n.asname, node.level)
for n in node.... |
def segment_file(self, value):
""" Setter for _segment_file attribute """
assert os.path.isfile(value), "%s is not a valid file" % value
self._segment_file = value | Setter for _segment_file attribute | Below is the the instruction that describes the task:
### Input:
Setter for _segment_file attribute
### Response:
def segment_file(self, value):
""" Setter for _segment_file attribute """
assert os.path.isfile(value), "%s is not a valid file" % value
self._segment_file = value |
def transform(self, Z):
"""Transform an ArrayRDD (or DictRDD with column 'X') containing
sequence of documents to a document-term matrix.
Parameters
----------
Z : ArrayRDD or DictRDD with raw text documents
Samples. Each sample must be a text document (either bytes ... | Transform an ArrayRDD (or DictRDD with column 'X') containing
sequence of documents to a document-term matrix.
Parameters
----------
Z : ArrayRDD or DictRDD with raw text documents
Samples. Each sample must be a text document (either bytes or
unicode strings) whi... | Below is the the instruction that describes the task:
### Input:
Transform an ArrayRDD (or DictRDD with column 'X') containing
sequence of documents to a document-term matrix.
Parameters
----------
Z : ArrayRDD or DictRDD with raw text documents
Samples. Each sample must... |
def _encode_telegram_base64(string):
"""
Inverse for `_decode_telegram_base64`.
"""
try:
return base64.urlsafe_b64encode(string).rstrip(b'=').decode('ascii')
except (binascii.Error, ValueError, TypeError):
return None | Inverse for `_decode_telegram_base64`. | Below is the the instruction that describes the task:
### Input:
Inverse for `_decode_telegram_base64`.
### Response:
def _encode_telegram_base64(string):
"""
Inverse for `_decode_telegram_base64`.
"""
try:
return base64.urlsafe_b64encode(string).rstrip(b'=').decode('ascii')
except (bin... |
def log_pdf(self, y, mu, weights=None):
"""
computes the log of the pdf or pmf of the values under the current distribution
Parameters
----------
y : array-like of length n
target values
mu : array-like of length n
expected values
weights ... | computes the log of the pdf or pmf of the values under the current distribution
Parameters
----------
y : array-like of length n
target values
mu : array-like of length n
expected values
weights : array-like shape (n,) or None, default: None
s... | Below is the the instruction that describes the task:
### Input:
computes the log of the pdf or pmf of the values under the current distribution
Parameters
----------
y : array-like of length n
target values
mu : array-like of length n
expected values
... |
def add_trial(self, trial):
"""Add trial to bracket assuming bracket is not filled.
At a later iteration, a newly added trial will be given equal
opportunity to catch up."""
assert not self.filled(), "Cannot add trial to filled bracket!"
self._live_trials[trial] = None
s... | Add trial to bracket assuming bracket is not filled.
At a later iteration, a newly added trial will be given equal
opportunity to catch up. | Below is the the instruction that describes the task:
### Input:
Add trial to bracket assuming bracket is not filled.
At a later iteration, a newly added trial will be given equal
opportunity to catch up.
### Response:
def add_trial(self, trial):
"""Add trial to bracket assuming bracket is... |
def timefrequency(data, method='morlet', time_skip=1, **options):
"""Compute the power spectrum over time.
Parameters
----------
data : instance of ChanTime
data to analyze
method : str
the method to compute the time-frequency representation, such as
'morlet' (wavelet using ... | Compute the power spectrum over time.
Parameters
----------
data : instance of ChanTime
data to analyze
method : str
the method to compute the time-frequency representation, such as
'morlet' (wavelet using complex morlet window),
'spectrogram' (corresponds to 'spectralde... | Below is the the instruction that describes the task:
### Input:
Compute the power spectrum over time.
Parameters
----------
data : instance of ChanTime
data to analyze
method : str
the method to compute the time-frequency representation, such as
'morlet' (wavelet using comp... |
def simulate_dynamic(self, order = 0.998, solution = solve_type.FAST, collect_dynamic = False, step = 0.1, int_step = 0.01, threshold_changes = 0.0000001):
"""!
@brief Performs dynamic simulation of the network until stop condition is not reached. Stop condition is defined by input argument 'order'.
... | !
@brief Performs dynamic simulation of the network until stop condition is not reached. Stop condition is defined by input argument 'order'.
@param[in] order (double): Order of process synchronization, distributed 0..1.
@param[in] solution (solve_type): Type of solution.
@... | Below is the the instruction that describes the task:
### Input:
!
@brief Performs dynamic simulation of the network until stop condition is not reached. Stop condition is defined by input argument 'order'.
@param[in] order (double): Order of process synchronization, distributed 0..1.
... |
def from_deformation(cls, deformation):
"""
Factory method that returns a Strain object from a deformation
gradient
Args:
deformation (3x3 array-like):
"""
dfm = Deformation(deformation)
return cls(0.5 * (np.dot(dfm.trans, dfm) - np.eye(3))) | Factory method that returns a Strain object from a deformation
gradient
Args:
deformation (3x3 array-like): | Below is the the instruction that describes the task:
### Input:
Factory method that returns a Strain object from a deformation
gradient
Args:
deformation (3x3 array-like):
### Response:
def from_deformation(cls, deformation):
"""
Factory method that returns a Strain ob... |
def context(name):
'''A decorator for theme context processors'''
def wrapper(func):
g.theme.context_processors[name] = func
return func
return wrapper | A decorator for theme context processors | Below is the the instruction that describes the task:
### Input:
A decorator for theme context processors
### Response:
def context(name):
'''A decorator for theme context processors'''
def wrapper(func):
g.theme.context_processors[name] = func
return func
return wrapper |
def add(self, other):
"""Return the QuantumChannel self + other.
Args:
other (QuantumChannel): a quantum channel.
Returns:
Chi: the linear addition self + other as a Chi object.
Raises:
QiskitError: if other is not a QuantumChannel subclass, or
... | Return the QuantumChannel self + other.
Args:
other (QuantumChannel): a quantum channel.
Returns:
Chi: the linear addition self + other as a Chi object.
Raises:
QiskitError: if other is not a QuantumChannel subclass, or
has incompatible dimensio... | Below is the the instruction that describes the task:
### Input:
Return the QuantumChannel self + other.
Args:
other (QuantumChannel): a quantum channel.
Returns:
Chi: the linear addition self + other as a Chi object.
Raises:
QiskitError: if other is no... |
def CreateNewZipWithSignedLibs(z_in,
z_out,
ignore_files=None,
signer=None,
skip_signing_files=None):
"""Copies files from one zip to another, signing all qualifying files."""
ignore_files = i... | Copies files from one zip to another, signing all qualifying files. | Below is the the instruction that describes the task:
### Input:
Copies files from one zip to another, signing all qualifying files.
### Response:
def CreateNewZipWithSignedLibs(z_in,
z_out,
ignore_files=None,
signer=None,... |
def start_web_rtc(self, ersip, ersport, roomId):
"""
Starts a WebRTC signalling client to an ERS (Evostream Rendezvous
Server).
:param ersip: IP address (xx.yy.zz.xx) of ERS.
:type ersip: str
:param ersport: IP port of ERS.
:type ersport: int
:param roo... | Starts a WebRTC signalling client to an ERS (Evostream Rendezvous
Server).
:param ersip: IP address (xx.yy.zz.xx) of ERS.
:type ersip: str
:param ersport: IP port of ERS.
:type ersport: int
:param roomId: Unique room Identifier within ERS that will be used by
... | Below is the the instruction that describes the task:
### Input:
Starts a WebRTC signalling client to an ERS (Evostream Rendezvous
Server).
:param ersip: IP address (xx.yy.zz.xx) of ERS.
:type ersip: str
:param ersport: IP port of ERS.
:type ersport: int
:param roo... |
def _start_member(self):
"""Starts writing a new member if required.
"""
if self._new_member:
self._init_write(self.name)
self._write_gzip_header()
self._new_member = False | Starts writing a new member if required. | Below is the the instruction that describes the task:
### Input:
Starts writing a new member if required.
### Response:
def _start_member(self):
"""Starts writing a new member if required.
"""
if self._new_member:
self._init_write(self.name)
self._write_gzip_header()... |
def _put_output(self, output: Optional[str]) -> None:
"""Put output string to ffmpeg command."""
if output is None:
self._argv.extend(["-f", "null", "-"])
return
output_cmd = shlex.split(str(output))
if len(output_cmd) > 1:
self._argv.extend(output_cm... | Put output string to ffmpeg command. | Below is the the instruction that describes the task:
### Input:
Put output string to ffmpeg command.
### Response:
def _put_output(self, output: Optional[str]) -> None:
"""Put output string to ffmpeg command."""
if output is None:
self._argv.extend(["-f", "null", "-"])
retu... |
def matchi(string, templ, wstr, wchr):
"""
Determine whether a string is matched by a template containing wild cards.
The pattern comparison is case-insensitive.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/matchi_c.html
:param string: String to be tested.
:type string: str
:par... | Determine whether a string is matched by a template containing wild cards.
The pattern comparison is case-insensitive.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/matchi_c.html
:param string: String to be tested.
:type string: str
:param templ: Template (with wild cards) to test agains... | Below is the the instruction that describes the task:
### Input:
Determine whether a string is matched by a template containing wild cards.
The pattern comparison is case-insensitive.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/matchi_c.html
:param string: String to be tested.
:type st... |
def format_relation_name(value, format_type=None):
"""
.. warning::
The 'format_relation_name' function has been renamed 'format_resource_type' and the
settings are now 'JSON_API_FORMAT_TYPES' and 'JSON_API_PLURALIZE_TYPES' instead of
'JSON_API_FORMAT_RELATION_KEYS' and 'JSON_API_PLURAL... | .. warning::
The 'format_relation_name' function has been renamed 'format_resource_type' and the
settings are now 'JSON_API_FORMAT_TYPES' and 'JSON_API_PLURALIZE_TYPES' instead of
'JSON_API_FORMAT_RELATION_KEYS' and 'JSON_API_PLURALIZE_RELATION_TYPE' | Below is the the instruction that describes the task:
### Input:
.. warning::
The 'format_relation_name' function has been renamed 'format_resource_type' and the
settings are now 'JSON_API_FORMAT_TYPES' and 'JSON_API_PLURALIZE_TYPES' instead of
'JSON_API_FORMAT_RELATION_KEYS' and 'JSON_API_... |
def minimise_tables(routing_tables, target_lengths,
methods=(remove_default_entries, ordered_covering)):
"""Utility function which attempts to minimises routing tables for multiple
chips.
For each routing table supplied, this function will attempt to use the
minimisation algorithms ... | Utility function which attempts to minimises routing tables for multiple
chips.
For each routing table supplied, this function will attempt to use the
minimisation algorithms given (or some sensible default algorithms), trying
each sequentially until a target number of routing entries has been
reac... | Below is the the instruction that describes the task:
### Input:
Utility function which attempts to minimises routing tables for multiple
chips.
For each routing table supplied, this function will attempt to use the
minimisation algorithms given (or some sensible default algorithms), trying
each se... |
def forward_complex(self, log_sigma):
"""Compute a model response, i.e. complex impedances
Parameters
----------
log_sigma : 1xN or 2xN numpy.ndarray
Model parameters log sigma, N the number of cells. If first
dimension is of length one, assume phase values to be... | Compute a model response, i.e. complex impedances
Parameters
----------
log_sigma : 1xN or 2xN numpy.ndarray
Model parameters log sigma, N the number of cells. If first
dimension is of length one, assume phase values to be zero
Returns
-------
me... | Below is the the instruction that describes the task:
### Input:
Compute a model response, i.e. complex impedances
Parameters
----------
log_sigma : 1xN or 2xN numpy.ndarray
Model parameters log sigma, N the number of cells. If first
dimension is of length one, assum... |
def handler(self, environ, start_response):
"""Proxy for requests to the actual http server"""
logger = logging.getLogger(__name__ + '.WSGIProxyApplication.handler')
url = urlparse(reconstruct_url(environ, self.port))
# Create connection object
try:
connection = self... | Proxy for requests to the actual http server | Below is the the instruction that describes the task:
### Input:
Proxy for requests to the actual http server
### Response:
def handler(self, environ, start_response):
"""Proxy for requests to the actual http server"""
logger = logging.getLogger(__name__ + '.WSGIProxyApplication.handler')
u... |
def sizeof(self, context=None) -> int:
"""
Return the size of the construct in bytes.
:param context: Optional context dictionary.
"""
if context is None:
context = Context()
if not isinstance(context, Context):
context = Context(context)
... | Return the size of the construct in bytes.
:param context: Optional context dictionary. | Below is the the instruction that describes the task:
### Input:
Return the size of the construct in bytes.
:param context: Optional context dictionary.
### Response:
def sizeof(self, context=None) -> int:
"""
Return the size of the construct in bytes.
:param context: Optional con... |
def create(python, env_dir, system, prompt, bare, virtualenv_py=None):
"""Main entry point to use this as a module.
"""
if not python or python == sys.executable:
_create_with_this(
env_dir=env_dir, system=system, prompt=prompt,
bare=bare, virtualenv_py=virtualenv_py,
... | Main entry point to use this as a module. | Below is the the instruction that describes the task:
### Input:
Main entry point to use this as a module.
### Response:
def create(python, env_dir, system, prompt, bare, virtualenv_py=None):
"""Main entry point to use this as a module.
"""
if not python or python == sys.executable:
_create_wit... |
def json_worker(self, mask, cache_id=None, cache_method="string",
cache_section="www"):
"""A function annotation that adds a worker request. A worker request
is a POST request that is computed asynchronously. That is, the
actual task is performed in a different thread a... | A function annotation that adds a worker request. A worker request
is a POST request that is computed asynchronously. That is, the
actual task is performed in a different thread and the network
request returns immediately. The client side uses polling to fetch
the result and ... | Below is the the instruction that describes the task:
### Input:
A function annotation that adds a worker request. A worker request
is a POST request that is computed asynchronously. That is, the
actual task is performed in a different thread and the network
request returns immediat... |
def get_season_player_stats(self, season_key, player_key):
"""
Calling Season Player Stats API.
Arg:
season_key: key of the season
player_key: key of the player
Return:
json data
"""
season_player_stats_url = self.api_path + "season/" + ... | Calling Season Player Stats API.
Arg:
season_key: key of the season
player_key: key of the player
Return:
json data | Below is the the instruction that describes the task:
### Input:
Calling Season Player Stats API.
Arg:
season_key: key of the season
player_key: key of the player
Return:
json data
### Response:
def get_season_player_stats(self, season_key, player_key):
"""... |
def index_bams(job, config):
"""
Convenience job for handling bam indexing to make the workflow declaration cleaner
:param JobFunctionWrappingJob job: passed automatically by Toil
:param Namespace config: Argparse Namespace object containing argument inputs
"""
job.fileStore.logToMaster('Indexe... | Convenience job for handling bam indexing to make the workflow declaration cleaner
:param JobFunctionWrappingJob job: passed automatically by Toil
:param Namespace config: Argparse Namespace object containing argument inputs | Below is the the instruction that describes the task:
### Input:
Convenience job for handling bam indexing to make the workflow declaration cleaner
:param JobFunctionWrappingJob job: passed automatically by Toil
:param Namespace config: Argparse Namespace object containing argument inputs
### Response:
de... |
def verify_compact_verbose(self, jws=None, keys=None, allow_none=False,
sigalg=None):
"""
Verify a JWT signature and return dict with validation results
:param jws: A signed JSON Web Token
:param keys: A list of keys that can possibly be used to verify the... | Verify a JWT signature and return dict with validation results
:param jws: A signed JSON Web Token
:param keys: A list of keys that can possibly be used to verify the
signature
:param allow_none: If signature algorithm 'none' is allowed
:param sigalg: Expected sigalg
... | Below is the the instruction that describes the task:
### Input:
Verify a JWT signature and return dict with validation results
:param jws: A signed JSON Web Token
:param keys: A list of keys that can possibly be used to verify the
signature
:param allow_none: If signature algor... |
def get_shape(self, prune=False, hs_dims=None):
"""Tuple of array dimensions' lengths.
It returns a tuple of ints, each representing the length of a cube
dimension, in the order those dimensions appear in the cube.
Pruning is supported. Dimensions that get reduced to a single element
... | Tuple of array dimensions' lengths.
It returns a tuple of ints, each representing the length of a cube
dimension, in the order those dimensions appear in the cube.
Pruning is supported. Dimensions that get reduced to a single element
(e.g. due to pruning) are removed from the returning ... | Below is the the instruction that describes the task:
### Input:
Tuple of array dimensions' lengths.
It returns a tuple of ints, each representing the length of a cube
dimension, in the order those dimensions appear in the cube.
Pruning is supported. Dimensions that get reduced to a single ... |
def walk(self, basedir):
"""Walk all the directories of basedir except hidden directories
:param basedir: string, the directory to walk
:returns: generator, same as os.walk
"""
system_d = SitePackagesDir()
filter_system_d = system_d and os.path.commonprefix([system_d, ba... | Walk all the directories of basedir except hidden directories
:param basedir: string, the directory to walk
:returns: generator, same as os.walk | Below is the the instruction that describes the task:
### Input:
Walk all the directories of basedir except hidden directories
:param basedir: string, the directory to walk
:returns: generator, same as os.walk
### Response:
def walk(self, basedir):
"""Walk all the directories of basedir ex... |
def add_generic_info_message_for_error(request):
"""
Add message to request indicating that there was an issue processing request.
Arguments:
request: The current request.
"""
messages.info(
request,
_(
'{strong_start}Something happened.{strong_end} '
... | Add message to request indicating that there was an issue processing request.
Arguments:
request: The current request. | Below is the the instruction that describes the task:
### Input:
Add message to request indicating that there was an issue processing request.
Arguments:
request: The current request.
### Response:
def add_generic_info_message_for_error(request):
"""
Add message to request indicating that ther... |
def get_plaintext_citations(arxiv_id):
"""
Get the citations of a given preprint, in plain text.
.. note::
Bulk download of sources from arXiv is not permitted by their API. \
You should have a look at http://arxiv.org/help/bulk_data_s3.
:param arxiv_id: The arXiv id (e.g. ``1... | Get the citations of a given preprint, in plain text.
.. note::
Bulk download of sources from arXiv is not permitted by their API. \
You should have a look at http://arxiv.org/help/bulk_data_s3.
:param arxiv_id: The arXiv id (e.g. ``1401.2910`` or ``1401.2910v1``) in \
a c... | Below is the the instruction that describes the task:
### Input:
Get the citations of a given preprint, in plain text.
.. note::
Bulk download of sources from arXiv is not permitted by their API. \
You should have a look at http://arxiv.org/help/bulk_data_s3.
:param arxiv_id: The ... |
def fit_transform(self, X, y=None):
'''
Flips the negative eigenvalues of X.
Parameters
----------
X : array, shape [n, n]
The *symmetric* input similarities. If X is asymmetric, it will be
treated as if it were symmetric based on its lower-triangular par... | Flips the negative eigenvalues of X.
Parameters
----------
X : array, shape [n, n]
The *symmetric* input similarities. If X is asymmetric, it will be
treated as if it were symmetric based on its lower-triangular part.
Returns
-------
Xt : array, ... | Below is the the instruction that describes the task:
### Input:
Flips the negative eigenvalues of X.
Parameters
----------
X : array, shape [n, n]
The *symmetric* input similarities. If X is asymmetric, it will be
treated as if it were symmetric based on its lower-t... |
def textContent(self, text: str) -> None: # type: ignore
"""Set textContent both on this node and related browser node."""
self._set_text_content(text)
if self.connected:
self._set_text_content_web(text) | Set textContent both on this node and related browser node. | Below is the the instruction that describes the task:
### Input:
Set textContent both on this node and related browser node.
### Response:
def textContent(self, text: str) -> None: # type: ignore
"""Set textContent both on this node and related browser node."""
self._set_text_content(text)
... |
def get_identifiers(source_code):
'''Split source code into python identifier-like tokens'''
tokens = set(re.split(r"[^0-9a-zA-Z_.]", source_code))
valid = re.compile(r'[a-zA-Z_]')
return [token for token in tokens if re.match(valid, token)] | Split source code into python identifier-like tokens | Below is the the instruction that describes the task:
### Input:
Split source code into python identifier-like tokens
### Response:
def get_identifiers(source_code):
'''Split source code into python identifier-like tokens'''
tokens = set(re.split(r"[^0-9a-zA-Z_.]", source_code))
valid = re.compile(r... |
async def registry_dump_handle(request):
'''
only read
:param request:
:return:
'''
registry = registry_dump_handle.registry
response_dict = {}
repo = registry._repository
response_dict['registered_services'] = repo._registered_services
response_dict['uptimes'] = repo._uptimes
... | only read
:param request:
:return: | Below is the the instruction that describes the task:
### Input:
only read
:param request:
:return:
### Response:
async def registry_dump_handle(request):
'''
only read
:param request:
:return:
'''
registry = registry_dump_handle.registry
response_dict = {}
repo = registry._... |
def long_click(self, duration=2.0):
"""
Perform the long click action on the UI element(s) represented by the UI proxy. If this UI proxy represents a
set of UI elements, the first one in the set is clicked and the anchor point of the UI element is used as the
default one. Similar to cl... | Perform the long click action on the UI element(s) represented by the UI proxy. If this UI proxy represents a
set of UI elements, the first one in the set is clicked and the anchor point of the UI element is used as the
default one. Similar to click but press the screen for the given time interval and... | Below is the the instruction that describes the task:
### Input:
Perform the long click action on the UI element(s) represented by the UI proxy. If this UI proxy represents a
set of UI elements, the first one in the set is clicked and the anchor point of the UI element is used as the
default one. ... |
def time_auth(self, load):
'''
Make sure that all failures happen in the same amount of time
'''
start = time.time()
ret = self.__auth_call(load)
if ret:
return ret
f_time = time.time() - start
if f_time > self.max_fail:
self.max_fa... | Make sure that all failures happen in the same amount of time | Below is the the instruction that describes the task:
### Input:
Make sure that all failures happen in the same amount of time
### Response:
def time_auth(self, load):
'''
Make sure that all failures happen in the same amount of time
'''
start = time.time()
ret = self.__auth... |
def intervalTrees(reffh, scoreType=int, verbose=False):
"""
Build a dictionary of interval trees indexed by chrom from a BED stream or
file
:param reffh: This can be either a string, or a stream-like object. In the
former case, it is treated as a filename. The format of the
file... | Build a dictionary of interval trees indexed by chrom from a BED stream or
file
:param reffh: This can be either a string, or a stream-like object. In the
former case, it is treated as a filename. The format of the
file/stream must be BED.
:param scoreType: The data type for score... | Below is the the instruction that describes the task:
### Input:
Build a dictionary of interval trees indexed by chrom from a BED stream or
file
:param reffh: This can be either a string, or a stream-like object. In the
former case, it is treated as a filename. The format of the
... |
def find_xy_peak(img, center=None, sigma=3.0):
""" Find the center of the peak of offsets """
# find level of noise in histogram
istats = imagestats.ImageStats(img.astype(np.float32), nclip=1,
fields='stddev,mode,mean,max,min')
if istats.stddev == 0.0:
istats =... | Find the center of the peak of offsets | Below is the the instruction that describes the task:
### Input:
Find the center of the peak of offsets
### Response:
def find_xy_peak(img, center=None, sigma=3.0):
""" Find the center of the peak of offsets """
# find level of noise in histogram
istats = imagestats.ImageStats(img.astype(np.float32), n... |
def kelly_kapowski(s, g, w, its=50, r=0.025, m=1.5, **kwargs):
"""
Compute cortical thickness using the DiReCT algorithm.
Diffeomorphic registration-based cortical thickness based on probabilistic
segmentation of an image. This is an optimization algorithm.
Arguments
---------
s : AN... | Compute cortical thickness using the DiReCT algorithm.
Diffeomorphic registration-based cortical thickness based on probabilistic
segmentation of an image. This is an optimization algorithm.
Arguments
---------
s : ANTsimage
segmentation image
g : ANTsImage
gray matt... | Below is the the instruction that describes the task:
### Input:
Compute cortical thickness using the DiReCT algorithm.
Diffeomorphic registration-based cortical thickness based on probabilistic
segmentation of an image. This is an optimization algorithm.
Arguments
---------
s : ANTsimag... |
def acknowledge_message(self):
"""Comment provided when acknowledging the alarm."""
if (self.is_acknowledged and
self._proto.acknowledgeInfo.HasField('acknowledgeMessage')):
return self._proto.acknowledgeInfo.acknowledgeMessage
return None | Comment provided when acknowledging the alarm. | Below is the the instruction that describes the task:
### Input:
Comment provided when acknowledging the alarm.
### Response:
def acknowledge_message(self):
"""Comment provided when acknowledging the alarm."""
if (self.is_acknowledged and
self._proto.acknowledgeInfo.HasField('acknow... |
def _asym_transform_deriv_shape(systematic_utilities,
alt_IDs,
rows_to_alts,
eta,
ref_position=None,
dh_dc_array=None,
fill_dc_d... | Parameters
----------
systematic_utilities : 1D ndarray.
Contains the systematic utilities for each each available alternative
for each observation. All elements should be ints, floats, or longs.
alt_IDs : 1D ndarray.
All elements should be ints. There should be one row per obervation... | Below is the the instruction that describes the task:
### Input:
Parameters
----------
systematic_utilities : 1D ndarray.
Contains the systematic utilities for each each available alternative
for each observation. All elements should be ints, floats, or longs.
alt_IDs : 1D ndarray.
... |
def bboxiter(tile_bounds, tiles_per_row_per_region=1):
"""
Iterate through a grid of regions defined by a TileBB.
Args:
tile_bounds (GridBB):
tiles_per_row_per_region: Combine multiple tiles in one region.
E.g. if set to two, four tiles will be combined in one region.
... | Iterate through a grid of regions defined by a TileBB.
Args:
tile_bounds (GridBB):
tiles_per_row_per_region: Combine multiple tiles in one region.
E.g. if set to two, four tiles will be combined in one region.
See `kml` module description for more details. Leaving the
... | Below is the the instruction that describes the task:
### Input:
Iterate through a grid of regions defined by a TileBB.
Args:
tile_bounds (GridBB):
tiles_per_row_per_region: Combine multiple tiles in one region.
E.g. if set to two, four tiles will be combined in one region.
... |
def get_next_step(self):
"""Find the proper step when user clicks the Next button.
:returns: The step to be switched to.
:rtype: WizardStep instance or None
"""
if self.layer_purpose != layer_purpose_aggregation:
subcategory = self.parent.step_kw_subcategory.\
... | Find the proper step when user clicks the Next button.
:returns: The step to be switched to.
:rtype: WizardStep instance or None | Below is the the instruction that describes the task:
### Input:
Find the proper step when user clicks the Next button.
:returns: The step to be switched to.
:rtype: WizardStep instance or None
### Response:
def get_next_step(self):
"""Find the proper step when user clicks the Next button.... |
def main(self, options, args):
"""
Main routine for running the reference viewer.
`options` is a OptionParser object that has been populated with
values from parsing the command line. It should at least include
the options from add_default_options()
`args` is a list of... | Main routine for running the reference viewer.
`options` is a OptionParser object that has been populated with
values from parsing the command line. It should at least include
the options from add_default_options()
`args` is a list of arguments to the viewer after parsing out
... | Below is the the instruction that describes the task:
### Input:
Main routine for running the reference viewer.
`options` is a OptionParser object that has been populated with
values from parsing the command line. It should at least include
the options from add_default_options()
`... |
def _resolve_shape(self, name, layers):
'''Given a list of layers, find the layer output with the given name.
Parameters
----------
name : str
Name of a layer to resolve.
layers : list of :class:`theanets.layers.base.Layer`
A list of layers to search in.
... | Given a list of layers, find the layer output with the given name.
Parameters
----------
name : str
Name of a layer to resolve.
layers : list of :class:`theanets.layers.base.Layer`
A list of layers to search in.
Raises
------
util.Configu... | Below is the the instruction that describes the task:
### Input:
Given a list of layers, find the layer output with the given name.
Parameters
----------
name : str
Name of a layer to resolve.
layers : list of :class:`theanets.layers.base.Layer`
A list of lay... |
def get_postadres_by_huisnummer(self, huisnummer):
'''
Get the `postadres` for a :class:`Huisnummer`.
:param huisnummer: The :class:`Huisnummer` for which the \
`postadres` is wanted. OR A huisnummer id.
:rtype: A :class:`str`.
'''
try:
id = huisn... | Get the `postadres` for a :class:`Huisnummer`.
:param huisnummer: The :class:`Huisnummer` for which the \
`postadres` is wanted. OR A huisnummer id.
:rtype: A :class:`str`. | Below is the the instruction that describes the task:
### Input:
Get the `postadres` for a :class:`Huisnummer`.
:param huisnummer: The :class:`Huisnummer` for which the \
`postadres` is wanted. OR A huisnummer id.
:rtype: A :class:`str`.
### Response:
def get_postadres_by_huisnummer(se... |
def warn_deprecated(since, message='', name='', alternative='', pending=False,
obj_type='attribute', addendum=''):
"""Display deprecation warning in a standard way.
Parameters
----------
since : str
The release at which this API became deprecated.
message : str, optiona... | Display deprecation warning in a standard way.
Parameters
----------
since : str
The release at which this API became deprecated.
message : str, optional
Override the default deprecation message. The format
specifier `%(name)s` may be used for the name of the function,
... | Below is the the instruction that describes the task:
### Input:
Display deprecation warning in a standard way.
Parameters
----------
since : str
The release at which this API became deprecated.
message : str, optional
Override the default deprecation message. The format
s... |
def surround_parse(self, node, pre_char, post_char):
"""Parse the subnodes of a given node. Subnodes with tags in the
`ignore` list are ignored. Prepend `pre_char` and append `post_char` to
the output in self.pieces."""
self.add_text(pre_char)
self.subnode_parse(node)
sel... | Parse the subnodes of a given node. Subnodes with tags in the
`ignore` list are ignored. Prepend `pre_char` and append `post_char` to
the output in self.pieces. | Below is the the instruction that describes the task:
### Input:
Parse the subnodes of a given node. Subnodes with tags in the
`ignore` list are ignored. Prepend `pre_char` and append `post_char` to
the output in self.pieces.
### Response:
def surround_parse(self, node, pre_char, post_char):
... |
async def delete(self, *args, **kwargs):
'''
Corresponds to DELETE request with a resource identifier, deleting a single document from the database
'''
pk = self.pk_type(kwargs['pk'])
result = await self._meta.object_class.delete_entries(db=self.db, query={self.pk: pk})
i... | Corresponds to DELETE request with a resource identifier, deleting a single document from the database | Below is the the instruction that describes the task:
### Input:
Corresponds to DELETE request with a resource identifier, deleting a single document from the database
### Response:
async def delete(self, *args, **kwargs):
'''
Corresponds to DELETE request with a resource identifier, deleting a sin... |
def _add_pos1(token):
"""
Adds a 'pos1' element to a frog token.
"""
result = token.copy()
result['pos1'] = _POSMAP[token['pos'].split("(")[0]]
return result | Adds a 'pos1' element to a frog token. | Below is the the instruction that describes the task:
### Input:
Adds a 'pos1' element to a frog token.
### Response:
def _add_pos1(token):
"""
Adds a 'pos1' element to a frog token.
"""
result = token.copy()
result['pos1'] = _POSMAP[token['pos'].split("(")[0]]
return result |
def add_link(dataset, source, target, count=1):
"""Add a link.
Parameters
----------
dataset : `dict` of ([`int`, `str`] or [`list` of `int`, `list` of `str`])
Dataset.
source : `iterable` of `str`
Link source.
target : `str`
Link targ... | Add a link.
Parameters
----------
dataset : `dict` of ([`int`, `str`] or [`list` of `int`, `list` of `str`])
Dataset.
source : `iterable` of `str`
Link source.
target : `str`
Link target.
count : `int`, optional
Link count ... | Below is the the instruction that describes the task:
### Input:
Add a link.
Parameters
----------
dataset : `dict` of ([`int`, `str`] or [`list` of `int`, `list` of `str`])
Dataset.
source : `iterable` of `str`
Link source.
target : `str`
... |
def get_batched_changesets(self, changesets_request_data):
"""GetBatchedChangesets.
Returns changesets for a given list of changeset Ids.
:param :class:`<TfvcChangesetsRequestData> <azure.devops.v5_0.tfvc.models.TfvcChangesetsRequestData>` changesets_request_data: List of changeset IDs.
... | GetBatchedChangesets.
Returns changesets for a given list of changeset Ids.
:param :class:`<TfvcChangesetsRequestData> <azure.devops.v5_0.tfvc.models.TfvcChangesetsRequestData>` changesets_request_data: List of changeset IDs.
:rtype: [TfvcChangesetRef] | Below is the the instruction that describes the task:
### Input:
GetBatchedChangesets.
Returns changesets for a given list of changeset Ids.
:param :class:`<TfvcChangesetsRequestData> <azure.devops.v5_0.tfvc.models.TfvcChangesetsRequestData>` changesets_request_data: List of changeset IDs.
:... |
def crack1(self, rnum, snum, message, signsecret):
"""
find privkey, given signsecret k, message m, signature (r,s)
x= (s*k-m)/r
"""
m = self.GFn.value(message)
r = self.GFn.value(rnum)
s = self.GFn.value(snum)
k = self.GFn.value(signsecret)
return... | find privkey, given signsecret k, message m, signature (r,s)
x= (s*k-m)/r | Below is the the instruction that describes the task:
### Input:
find privkey, given signsecret k, message m, signature (r,s)
x= (s*k-m)/r
### Response:
def crack1(self, rnum, snum, message, signsecret):
"""
find privkey, given signsecret k, message m, signature (r,s)
x= (s*k-m)/r
... |
def _assert_valid_categorical_missing_value(value):
"""
Check that value is a valid categorical missing_value.
Raises a TypeError if the value is cannot be used as the missing_value for
a categorical_dtype Term.
"""
label_types = LabelArray.SUPPORTED_SCALAR_TYPES
if not isinstance(value, la... | Check that value is a valid categorical missing_value.
Raises a TypeError if the value is cannot be used as the missing_value for
a categorical_dtype Term. | Below is the the instruction that describes the task:
### Input:
Check that value is a valid categorical missing_value.
Raises a TypeError if the value is cannot be used as the missing_value for
a categorical_dtype Term.
### Response:
def _assert_valid_categorical_missing_value(value):
"""
Check t... |
def run_command(self, command, shell=True, env=None, execute='/bin/bash',
return_code=None):
"""Run a shell command.
The options available:
* ``shell`` to be enabled or disabled, which provides the ability
to execute arbitrary stings or not. if disabled co... | Run a shell command.
The options available:
* ``shell`` to be enabled or disabled, which provides the ability
to execute arbitrary stings or not. if disabled commands must be
in the format of a ``list``
* ``env`` is an environment override and or manipulati... | Below is the the instruction that describes the task:
### Input:
Run a shell command.
The options available:
* ``shell`` to be enabled or disabled, which provides the ability
to execute arbitrary stings or not. if disabled commands must be
in the format of a ``list`... |
def peek_string(self, lpBaseAddress, fUnicode = False, dwMaxSize = 0x1000):
"""
Tries to read an ASCII or Unicode string
from the address space of the process.
@see: L{read_string}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin reading.
... | Tries to read an ASCII or Unicode string
from the address space of the process.
@see: L{read_string}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin reading.
@type fUnicode: bool
@param fUnicode: C{True} is the string is expected to be Unicode,... | Below is the the instruction that describes the task:
### Input:
Tries to read an ASCII or Unicode string
from the address space of the process.
@see: L{read_string}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin reading.
@type fUnicode: bool
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.