code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def std(self) -> Optional[float]: #, ddof=0):
"""Standard deviation of all values entered into histogram.
This number is precise, because we keep the necessary data
separate from bin contents.
Returns
-------
float
"""
# TODO: Add DOF
if self._s... | Standard deviation of all values entered into histogram.
This number is precise, because we keep the necessary data
separate from bin contents.
Returns
-------
float | Below is the the instruction that describes the task:
### Input:
Standard deviation of all values entered into histogram.
This number is precise, because we keep the necessary data
separate from bin contents.
Returns
-------
float
### Response:
def std(self) -> Optional[fl... |
def read(self, entity=None, attrs=None, ignore=None, params=None):
"""Fetch an attribute missing from the server's response.
For more information, see `Bugzilla #1237257
<https://bugzilla.redhat.com/show_bug.cgi?id=1237257>`_.
Add content_view_component to the response if needed, as
... | Fetch an attribute missing from the server's response.
For more information, see `Bugzilla #1237257
<https://bugzilla.redhat.com/show_bug.cgi?id=1237257>`_.
Add content_view_component to the response if needed, as
:meth:`nailgun.entity_mixins.EntityReadMixin.read` can't initialize
... | Below is the the instruction that describes the task:
### Input:
Fetch an attribute missing from the server's response.
For more information, see `Bugzilla #1237257
<https://bugzilla.redhat.com/show_bug.cgi?id=1237257>`_.
Add content_view_component to the response if needed, as
:me... |
def configure(**kwargs):
"""Global configuration for event handling."""
for key in kwargs:
if key == 'is_logging_enabled':
Event.is_logging_enabled = kwargs[key]
elif key == 'collector_queue':
Event.collector_queue = kwargs[key]
else:
... | Global configuration for event handling. | Below is the the instruction that describes the task:
### Input:
Global configuration for event handling.
### Response:
def configure(**kwargs):
"""Global configuration for event handling."""
for key in kwargs:
if key == 'is_logging_enabled':
Event.is_logging_enabled = k... |
def set_path(dicts, keys, v):
""" Helper function for modifying nested dictionaries
:param dicts: dict: the given dictionary
:param keys: list str: path to added value
:param v: str: value to be added
Example:
>>> d = dict()
>>> set_path(d, ['a', 'b', 'c'], 'd')
>>> d
... | Helper function for modifying nested dictionaries
:param dicts: dict: the given dictionary
:param keys: list str: path to added value
:param v: str: value to be added
Example:
>>> d = dict()
>>> set_path(d, ['a', 'b', 'c'], 'd')
>>> d
{'a': {'b': {'c': ['d']}}}
... | Below is the the instruction that describes the task:
### Input:
Helper function for modifying nested dictionaries
:param dicts: dict: the given dictionary
:param keys: list str: path to added value
:param v: str: value to be added
Example:
>>> d = dict()
>>> set_path(d, ['a', 'b'... |
def summarize(objects):
"""Summarize an objects list.
Return a list of lists, whereas each row consists of::
[str(type), number of objects of this type, total size of these objects].
No guarantee regarding the order is given.
"""
count = {}
total_size = {}
for o in objects:
... | Summarize an objects list.
Return a list of lists, whereas each row consists of::
[str(type), number of objects of this type, total size of these objects].
No guarantee regarding the order is given. | Below is the the instruction that describes the task:
### Input:
Summarize an objects list.
Return a list of lists, whereas each row consists of::
[str(type), number of objects of this type, total size of these objects].
No guarantee regarding the order is given.
### Response:
def summarize(objects... |
def delete(self, *args, **kwargs):
"""Handles updating the related `votes` and `score` fields attached to the model."""
# XXX: circular import
from fields import RatingField
qs = self.distinct().values_list('content_type', 'object_id').order_by('content_type')
to_update = [... | Handles updating the related `votes` and `score` fields attached to the model. | Below is the the instruction that describes the task:
### Input:
Handles updating the related `votes` and `score` fields attached to the model.
### Response:
def delete(self, *args, **kwargs):
"""Handles updating the related `votes` and `score` fields attached to the model."""
# XXX: circular impor... |
def config_(name: str, local: bool, package: str, section: str,
key: Optional[str]):
"""Extract or list values from config."""
cfg = config.read_configs(package, name, local=local)
if key:
with suppress(NoOptionError, NoSectionError):
echo(cfg.get(section, key))
else:
... | Extract or list values from config. | Below is the the instruction that describes the task:
### Input:
Extract or list values from config.
### Response:
def config_(name: str, local: bool, package: str, section: str,
key: Optional[str]):
"""Extract or list values from config."""
cfg = config.read_configs(package, name, local=local)... |
def delete_blob(call=None, kwargs=None): # pylint: disable=unused-argument
'''
Delete a blob from a container.
'''
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit(
'A container must be specified'
)
if 'blob' not in kwa... | Delete a blob from a container. | Below is the the instruction that describes the task:
### Input:
Delete a blob from a container.
### Response:
def delete_blob(call=None, kwargs=None): # pylint: disable=unused-argument
'''
Delete a blob from a container.
'''
if kwargs is None:
kwargs = {}
if 'container' not in kwargs... |
def ReplaceHomoglyphs(s):
"""Returns s with unicode homoglyphs replaced by ascii equivalents."""
homoglyphs = {
'\xa0': ' ', # ?
'\u00e3': '', # TODO(gsfowler) drop after .proto spurious char elided
'\u00a0': ' ', # ?
'\u00a9': '(C)', # COPYRIGHT SIGN (would you... | Returns s with unicode homoglyphs replaced by ascii equivalents. | Below is the the instruction that describes the task:
### Input:
Returns s with unicode homoglyphs replaced by ascii equivalents.
### Response:
def ReplaceHomoglyphs(s):
"""Returns s with unicode homoglyphs replaced by ascii equivalents."""
homoglyphs = {
'\xa0': ' ', # ?
'\u00e3': ... |
def generate_template(template_name, **context):
"""Load and generate a template."""
context.update(href=href, format_datetime=format_datetime)
return template_loader.load(template_name).generate(**context) | Load and generate a template. | Below is the the instruction that describes the task:
### Input:
Load and generate a template.
### Response:
def generate_template(template_name, **context):
"""Load and generate a template."""
context.update(href=href, format_datetime=format_datetime)
return template_loader.load(template_name).generat... |
def graph_from_dot_file(path, encoding=None):
"""Load graphs from DOT file at `path`.
@param path: to DOT file
@param encoding: as passed to `io.open`.
For example, `'utf-8'`.
@return: Graphs that result from parsing.
@rtype: `list` of `pydot.Dot`
"""
with io.open(path, 'rt', encod... | Load graphs from DOT file at `path`.
@param path: to DOT file
@param encoding: as passed to `io.open`.
For example, `'utf-8'`.
@return: Graphs that result from parsing.
@rtype: `list` of `pydot.Dot` | Below is the the instruction that describes the task:
### Input:
Load graphs from DOT file at `path`.
@param path: to DOT file
@param encoding: as passed to `io.open`.
For example, `'utf-8'`.
@return: Graphs that result from parsing.
@rtype: `list` of `pydot.Dot`
### Response:
def graph_f... |
def _compile_prefixes(self):
'''
Create a dict of all OS prefixes and their compiled regexs
'''
self.compiled_prefixes = {}
for dev_os, os_config in self.config.items():
if not os_config:
continue
self.compiled_prefixes[dev_os] = []
... | Create a dict of all OS prefixes and their compiled regexs | Below is the the instruction that describes the task:
### Input:
Create a dict of all OS prefixes and their compiled regexs
### Response:
def _compile_prefixes(self):
'''
Create a dict of all OS prefixes and their compiled regexs
'''
self.compiled_prefixes = {}
for dev_os, o... |
def read_limits(self, limit=None, page_size=None):
"""
Takes a limit on the max number of records to read and a max page_size
and calculates the max number of pages to read.
:param int limit: Max number of records to read.
:param int page_size: Max page size.
:return dic... | Takes a limit on the max number of records to read and a max page_size
and calculates the max number of pages to read.
:param int limit: Max number of records to read.
:param int page_size: Max page size.
:return dict: A dictionary of paging limits. | Below is the the instruction that describes the task:
### Input:
Takes a limit on the max number of records to read and a max page_size
and calculates the max number of pages to read.
:param int limit: Max number of records to read.
:param int page_size: Max page size.
:return dict:... |
def container_rename_folder(object_id, input_params={}, always_retry=False, **kwargs):
"""
Invokes the /container-xxxx/renameFolder API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Folders-and-Deletion#API-method%3A-%2Fclass-xxxx%2FrenameFolder
"""
return DXHTTPReq... | Invokes the /container-xxxx/renameFolder API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Folders-and-Deletion#API-method%3A-%2Fclass-xxxx%2FrenameFolder | Below is the the instruction that describes the task:
### Input:
Invokes the /container-xxxx/renameFolder API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Folders-and-Deletion#API-method%3A-%2Fclass-xxxx%2FrenameFolder
### Response:
def container_rename_folder(object_id, inpu... |
def _clean_post_content(blog_url, content):
"""
Replace import path with something relative to blog.
"""
content = re.sub(
"<img.src=\"%s(.*)\"" % blog_url,
lambda s: "<img src=\"%s\"" % _get_relative_upload(s.groups(1)[0]),
content)
return content | Replace import path with something relative to blog. | Below is the the instruction that describes the task:
### Input:
Replace import path with something relative to blog.
### Response:
def _clean_post_content(blog_url, content):
"""
Replace import path with something relative to blog.
"""
content = re.sub(
"<img.src=\"%s(.*)\"" % blog_url,
... |
def clear_search_defaults(self, args=None):
"""
Clear all search defaults specified by the list of parameter names
given as ``args``. If ``args`` is not given, then clear all existing
search defaults.
Examples::
conn.set_search_defaults(scope=ldap.SCOPE_BASE, attrs... | Clear all search defaults specified by the list of parameter names
given as ``args``. If ``args`` is not given, then clear all existing
search defaults.
Examples::
conn.set_search_defaults(scope=ldap.SCOPE_BASE, attrs=['cn'])
conn.clear_search_defaults(['scope'])
... | Below is the the instruction that describes the task:
### Input:
Clear all search defaults specified by the list of parameter names
given as ``args``. If ``args`` is not given, then clear all existing
search defaults.
Examples::
conn.set_search_defaults(scope=ldap.SCOPE_BASE, ... |
def _mapFuture(callable_, *iterables):
"""Similar to the built-in map function, but each of its
iteration will spawn a separate independent parallel Future that will run
either locally or remotely as `callable(*args)`.
:param callable: Any callable object (function or class object with *__call__*
... | Similar to the built-in map function, but each of its
iteration will spawn a separate independent parallel Future that will run
either locally or remotely as `callable(*args)`.
:param callable: Any callable object (function or class object with *__call__*
method); this object will be called to exec... | Below is the the instruction that describes the task:
### Input:
Similar to the built-in map function, but each of its
iteration will spawn a separate independent parallel Future that will run
either locally or remotely as `callable(*args)`.
:param callable: Any callable object (function or class objec... |
def disassemble_string(self, lpAddress, code):
"""
Disassemble instructions from a block of binary code.
@type lpAddress: int
@param lpAddress: Memory address where the code was read from.
@type code: str
@param code: Binary code to disassemble.
@rtype: list... | Disassemble instructions from a block of binary code.
@type lpAddress: int
@param lpAddress: Memory address where the code was read from.
@type code: str
@param code: Binary code to disassemble.
@rtype: list of tuple( long, int, str, str )
@return: List of tuples. E... | Below is the the instruction that describes the task:
### Input:
Disassemble instructions from a block of binary code.
@type lpAddress: int
@param lpAddress: Memory address where the code was read from.
@type code: str
@param code: Binary code to disassemble.
@rtype: li... |
def cmd_fernet_genkey(writecfg):
"""Generate a new Fernet Key, optionally write it to ~/.habu.json
Example:
\b
$ habu.fernet.genkey
xgvWCIvjwe9Uq7NBvwO796iI4dsGD623QOT9GWqnuhg=
"""
key = Fernet.generate_key()
print(key.decode())
if writecfg:
habucfg = loadcfg(environment=... | Generate a new Fernet Key, optionally write it to ~/.habu.json
Example:
\b
$ habu.fernet.genkey
xgvWCIvjwe9Uq7NBvwO796iI4dsGD623QOT9GWqnuhg= | Below is the the instruction that describes the task:
### Input:
Generate a new Fernet Key, optionally write it to ~/.habu.json
Example:
\b
$ habu.fernet.genkey
xgvWCIvjwe9Uq7NBvwO796iI4dsGD623QOT9GWqnuhg=
### Response:
def cmd_fernet_genkey(writecfg):
"""Generate a new Fernet Key, optionally... |
def iso8601_date(d):
"""
Return a string representation of a date that the Twilio API understands
Format is YYYY-MM-DD. Returns None if d is not a string, datetime, or date
"""
if d == values.unset:
return d
elif isinstance(d, datetime.datetime):
return str(d.date())
elif isi... | Return a string representation of a date that the Twilio API understands
Format is YYYY-MM-DD. Returns None if d is not a string, datetime, or date | Below is the the instruction that describes the task:
### Input:
Return a string representation of a date that the Twilio API understands
Format is YYYY-MM-DD. Returns None if d is not a string, datetime, or date
### Response:
def iso8601_date(d):
"""
Return a string representation of a date that the T... |
def get_items(self) -> Iterator[StoryItem]:
"""Retrieve all items from a story."""
yield from (StoryItem(self._context, item, self.owner_profile) for item in reversed(self._node['items'])) | Retrieve all items from a story. | Below is the the instruction that describes the task:
### Input:
Retrieve all items from a story.
### Response:
def get_items(self) -> Iterator[StoryItem]:
"""Retrieve all items from a story."""
yield from (StoryItem(self._context, item, self.owner_profile) for item in reversed(self._node['items'])... |
def main(output):
"""
Generate a c7n-org gcp projects config file
"""
client = Session().client('cloudresourcemanager', 'v1', 'projects')
results = []
for page in client.execute_paged_query('list', {}):
for project in page.get('projects', []):
if project['lifecycleState'] ... | Generate a c7n-org gcp projects config file | Below is the the instruction that describes the task:
### Input:
Generate a c7n-org gcp projects config file
### Response:
def main(output):
"""
Generate a c7n-org gcp projects config file
"""
client = Session().client('cloudresourcemanager', 'v1', 'projects')
results = []
for page in cli... |
def comment_create(self, post_id, body, do_not_bump_post=None):
"""Action to lets you create a comment (Requires login).
Parameters:
post_id (int):
body (str):
do_not_bump_post (bool): Set to 1 if you do not want the post to be
bu... | Action to lets you create a comment (Requires login).
Parameters:
post_id (int):
body (str):
do_not_bump_post (bool): Set to 1 if you do not want the post to be
bumped to the top of the comment listing. | Below is the the instruction that describes the task:
### Input:
Action to lets you create a comment (Requires login).
Parameters:
post_id (int):
body (str):
do_not_bump_post (bool): Set to 1 if you do not want the post to be
bumped t... |
def set_meta(mcs, bases, attr):
"""
Get all of the ``Meta`` classes from bases and combine them with this
class.
Pops or creates ``Meta`` from attributes, combines all bases, adds
``_meta`` to attributes with all meta
:param bases: bases of this class
:param att... | Get all of the ``Meta`` classes from bases and combine them with this
class.
Pops or creates ``Meta`` from attributes, combines all bases, adds
``_meta`` to attributes with all meta
:param bases: bases of this class
:param attr: class attributes
:return: attributes with... | Below is the the instruction that describes the task:
### Input:
Get all of the ``Meta`` classes from bases and combine them with this
class.
Pops or creates ``Meta`` from attributes, combines all bases, adds
``_meta`` to attributes with all meta
:param bases: bases of this class
... |
def _match_national_number(number, number_desc, allow_prefix_match):
"""Returns whether the given national number (a string containing only decimal digits) matches
the national number pattern defined in the given PhoneNumberDesc object.
"""
# We don't want to consider it a prefix match when matching non... | Returns whether the given national number (a string containing only decimal digits) matches
the national number pattern defined in the given PhoneNumberDesc object. | Below is the the instruction that describes the task:
### Input:
Returns whether the given national number (a string containing only decimal digits) matches
the national number pattern defined in the given PhoneNumberDesc object.
### Response:
def _match_national_number(number, number_desc, allow_prefix_match)... |
def ExportingCursorWrapper(cursor_class, alias, vendor):
"""Returns a CursorWrapper class that knows its database's alias and
vendor name.
"""
class CursorWrapper(cursor_class):
"""Extends the base CursorWrapper to count events."""
def execute(self, *args, **kwargs):
execut... | Returns a CursorWrapper class that knows its database's alias and
vendor name. | Below is the the instruction that describes the task:
### Input:
Returns a CursorWrapper class that knows its database's alias and
vendor name.
### Response:
def ExportingCursorWrapper(cursor_class, alias, vendor):
"""Returns a CursorWrapper class that knows its database's alias and
vendor name.
""... |
def markers_pass(self, req, extras=None):
"""
Evaluate markers for req against each extra that
demanded it.
Return False if the req has a marker and fails
evaluation. Otherwise, return True.
"""
extra_evals = (
req.marker.evaluate({'extra': extra})
... | Evaluate markers for req against each extra that
demanded it.
Return False if the req has a marker and fails
evaluation. Otherwise, return True. | Below is the the instruction that describes the task:
### Input:
Evaluate markers for req against each extra that
demanded it.
Return False if the req has a marker and fails
evaluation. Otherwise, return True.
### Response:
def markers_pass(self, req, extras=None):
"""
Eval... |
def gradient(self):
"""Gradient operator of the functional."""
functional = self
class KLCrossEntCCGradient(Operator):
"""The gradient operator of this functional."""
def __init__(self):
"""Initialize a new instance."""
super(KLCrossEntC... | Gradient operator of the functional. | Below is the the instruction that describes the task:
### Input:
Gradient operator of the functional.
### Response:
def gradient(self):
"""Gradient operator of the functional."""
functional = self
class KLCrossEntCCGradient(Operator):
"""The gradient operator of this functiona... |
def check_proxy_code(self, address) -> bool:
"""
Check if proxy is valid
:param address: address of the proxy
:return: True if proxy is valid, False otherwise
"""
deployed_proxy_code = self.w3.eth.getCode(address)
proxy_code_fns = (get_paying_proxy_deployed_byteco... | Check if proxy is valid
:param address: address of the proxy
:return: True if proxy is valid, False otherwise | Below is the the instruction that describes the task:
### Input:
Check if proxy is valid
:param address: address of the proxy
:return: True if proxy is valid, False otherwise
### Response:
def check_proxy_code(self, address) -> bool:
"""
Check if proxy is valid
:param addres... |
def remove_opinion_layer(self):
"""
Removes the opinion layer (if exists) of the object (in memory)
"""
if self.opinion_layer is not None:
this_node = self.opinion_layer.get_node()
self.root.remove(this_node)
self.opinion_layer = None
if self.... | Removes the opinion layer (if exists) of the object (in memory) | Below is the the instruction that describes the task:
### Input:
Removes the opinion layer (if exists) of the object (in memory)
### Response:
def remove_opinion_layer(self):
"""
Removes the opinion layer (if exists) of the object (in memory)
"""
if self.opinion_layer is not None:
... |
def is_valid_hendecasyllables(self, scanned_line: str) -> bool:
"""Determine if a scansion pattern is one of the valid Hendecasyllables metrical patterns
:param scanned_line: a line containing a sequence of stressed and unstressed syllables
:return bool
>>> print(MetricalValidator().is... | Determine if a scansion pattern is one of the valid Hendecasyllables metrical patterns
:param scanned_line: a line containing a sequence of stressed and unstressed syllables
:return bool
>>> print(MetricalValidator().is_valid_hendecasyllables("-U-UU-U-U-U"))
True | Below is the the instruction that describes the task:
### Input:
Determine if a scansion pattern is one of the valid Hendecasyllables metrical patterns
:param scanned_line: a line containing a sequence of stressed and unstressed syllables
:return bool
>>> print(MetricalValidator().is_valid... |
def int80(self, cpu):
"""
32 bit dispatcher.
:param cpu: current CPU.
_terminate, transmit, receive, fdwait, allocate, deallocate and random
"""
syscalls = {0x00000001: self.sys_terminate,
0x00000002: self.sys_transmit,
0x00000003: ... | 32 bit dispatcher.
:param cpu: current CPU.
_terminate, transmit, receive, fdwait, allocate, deallocate and random | Below is the the instruction that describes the task:
### Input:
32 bit dispatcher.
:param cpu: current CPU.
_terminate, transmit, receive, fdwait, allocate, deallocate and random
### Response:
def int80(self, cpu):
"""
32 bit dispatcher.
:param cpu: current CPU.
_te... |
def aes_cbc_no_padding_decrypt(key, data, iv):
"""
Decrypts AES ciphertext in CBC mode using a 128, 192 or 256 bit key and no
padding.
:param key:
The encryption key - a byte string either 16, 24 or 32 bytes long
:param data:
The ciphertext - a byte string
:param iv:
T... | Decrypts AES ciphertext in CBC mode using a 128, 192 or 256 bit key and no
padding.
:param key:
The encryption key - a byte string either 16, 24 or 32 bytes long
:param data:
The ciphertext - a byte string
:param iv:
The initialization vector - a byte string 16-bytes long
... | Below is the the instruction that describes the task:
### Input:
Decrypts AES ciphertext in CBC mode using a 128, 192 or 256 bit key and no
padding.
:param key:
The encryption key - a byte string either 16, 24 or 32 bytes long
:param data:
The ciphertext - a byte string
:param iv:... |
def heron_class(class_name, lib_jars, extra_jars=None, args=None, java_defines=None):
'''
Execute a heron class given the args and the jars needed for class path
:param class_name:
:param lib_jars:
:param extra_jars:
:param args:
:param java_defines:
:return:
'''
# default optional params to empty l... | Execute a heron class given the args and the jars needed for class path
:param class_name:
:param lib_jars:
:param extra_jars:
:param args:
:param java_defines:
:return: | Below is the the instruction that describes the task:
### Input:
Execute a heron class given the args and the jars needed for class path
:param class_name:
:param lib_jars:
:param extra_jars:
:param args:
:param java_defines:
:return:
### Response:
def heron_class(class_name, lib_jars, extra_jars=None,... |
def run_checked (cmd, ret_ok=(0,), **kwargs):
"""Run command and raise PatoolError on error."""
retcode = run(cmd, **kwargs)
if retcode not in ret_ok:
msg = "Command `%s' returned non-zero exit status %d" % (cmd, retcode)
raise PatoolError(msg)
return retcode | Run command and raise PatoolError on error. | Below is the the instruction that describes the task:
### Input:
Run command and raise PatoolError on error.
### Response:
def run_checked (cmd, ret_ok=(0,), **kwargs):
"""Run command and raise PatoolError on error."""
retcode = run(cmd, **kwargs)
if retcode not in ret_ok:
msg = "Command `%s' r... |
def setup(self, address, port):
"""Connects to server at `address`:`port`.
Connects to a TCP server listening at `address`:`port` that implements
the protocol described in the file "Generic TCP I:O Protocol.md"
@arg address IP or address to connect to.
@arg port port to connect... | Connects to server at `address`:`port`.
Connects to a TCP server listening at `address`:`port` that implements
the protocol described in the file "Generic TCP I:O Protocol.md"
@arg address IP or address to connect to.
@arg port port to connect to.
@throw RuntimeError if connec... | Below is the the instruction that describes the task:
### Input:
Connects to server at `address`:`port`.
Connects to a TCP server listening at `address`:`port` that implements
the protocol described in the file "Generic TCP I:O Protocol.md"
@arg address IP or address to connect to.
... |
def _handle_ls(self):
""" Handles the ls subsubcommand. """
try:
arg1 = self.argument(1)
arg2 = self.argument(2)
todos = []
if arg2 == 'to' or arg1 == 'before':
# dep ls 1 to OR dep ls before 1
number = arg1 if arg2 == 'to'... | Handles the ls subsubcommand. | Below is the the instruction that describes the task:
### Input:
Handles the ls subsubcommand.
### Response:
def _handle_ls(self):
""" Handles the ls subsubcommand. """
try:
arg1 = self.argument(1)
arg2 = self.argument(2)
todos = []
if arg2 == 'to' o... |
def trifurcate_base(cls, newick):
""" Rewrites a newick string so that the base is a trifurcation
(usually means an unrooted tree) """
t = cls(newick)
t._tree.deroot()
return t.newick | Rewrites a newick string so that the base is a trifurcation
(usually means an unrooted tree) | Below is the the instruction that describes the task:
### Input:
Rewrites a newick string so that the base is a trifurcation
(usually means an unrooted tree)
### Response:
def trifurcate_base(cls, newick):
""" Rewrites a newick string so that the base is a trifurcation
(usually means an unr... |
def run(self):
"""
Starts a development server for the zengine application
"""
from zengine.wf_daemon import run_workers, Worker
worker_count = int(self.manager.args.workers or 1)
if not self.manager.args.daemonize:
print("Starting worker(s)")
if wor... | Starts a development server for the zengine application | Below is the the instruction that describes the task:
### Input:
Starts a development server for the zengine application
### Response:
def run(self):
"""
Starts a development server for the zengine application
"""
from zengine.wf_daemon import run_workers, Worker
worker_cou... |
def hit_ratio_table(self, train=False, valid=False, xval=False):
"""
Retrieve the Hit Ratios.
If all are False (default), then return the training metric value.
If more than one options is set to True, then return a dictionary of metrics where the keys are "train",
"valid", and ... | Retrieve the Hit Ratios.
If all are False (default), then return the training metric value.
If more than one options is set to True, then return a dictionary of metrics where the keys are "train",
"valid", and "xval".
:param train: If train is True, then return the hit ratio value for ... | Below is the the instruction that describes the task:
### Input:
Retrieve the Hit Ratios.
If all are False (default), then return the training metric value.
If more than one options is set to True, then return a dictionary of metrics where the keys are "train",
"valid", and "xval".
... |
def plot_weight_posteriors(names, qm_vals, qs_vals, fname):
"""Save a PNG plot with histograms of weight means and stddevs.
Args:
names: A Python `iterable` of `str` variable names.
qm_vals: A Python `iterable`, the same length as `names`,
whose elements are Numpy `array`s, of any shape, containing
... | Save a PNG plot with histograms of weight means and stddevs.
Args:
names: A Python `iterable` of `str` variable names.
qm_vals: A Python `iterable`, the same length as `names`,
whose elements are Numpy `array`s, of any shape, containing
posterior means of weight varibles.
qs_vals: A Python `i... | Below is the the instruction that describes the task:
### Input:
Save a PNG plot with histograms of weight means and stddevs.
Args:
names: A Python `iterable` of `str` variable names.
qm_vals: A Python `iterable`, the same length as `names`,
whose elements are Numpy `array`s, of any shape, containi... |
def count_elements(fname, element):
"""
returns (511, 35082) for ANC__WhereToHongKong.xml
"""
num = 0
tot = 0
for event, elem in iterparse(fname):
tot += 1
if elem.text != '':
#print(' tag = ', elem.tag)
#print(' event = ', event # always end
... | returns (511, 35082) for ANC__WhereToHongKong.xml | Below is the the instruction that describes the task:
### Input:
returns (511, 35082) for ANC__WhereToHongKong.xml
### Response:
def count_elements(fname, element):
"""
returns (511, 35082) for ANC__WhereToHongKong.xml
"""
num = 0
tot = 0
for event, elem in iterparse(fname):
tot += ... |
def user_exists(name, password=None, htpasswd_file=None, options='',
force=False, runas=None, update=False):
'''
Make sure the user is inside the specified htpasswd file
name
User name
password
User password
htpasswd_file
Path to the htpasswd file
opti... | Make sure the user is inside the specified htpasswd file
name
User name
password
User password
htpasswd_file
Path to the htpasswd file
options
See :mod:`salt.modules.htpasswd.useradd`
force
Touch the file even if user already created
runas
Th... | Below is the the instruction that describes the task:
### Input:
Make sure the user is inside the specified htpasswd file
name
User name
password
User password
htpasswd_file
Path to the htpasswd file
options
See :mod:`salt.modules.htpasswd.useradd`
force
... |
def is_server_or_cluster_db_address(value):
"""
checks if the specified value is in the form of
[server or cluster id][/database]
"""
# check if value is an id string
id_path = value.split("/")
id = id_path[0]
return len(id_path) <= 2 and (repository.lookup_server(id) or
... | checks if the specified value is in the form of
[server or cluster id][/database] | Below is the the instruction that describes the task:
### Input:
checks if the specified value is in the form of
[server or cluster id][/database]
### Response:
def is_server_or_cluster_db_address(value):
"""
checks if the specified value is in the form of
[server or cluster id][/database]
"""
... |
def filepaths(path, exclude=(), hidden=True, empty=True):
"""
Return list of absolute, sorted file paths
path: Path to file or directory
exclude: List of file name patterns to exclude
hidden: Whether to include hidden files
empty: Whether to include empty files
Raise PathNotFoundError if p... | Return list of absolute, sorted file paths
path: Path to file or directory
exclude: List of file name patterns to exclude
hidden: Whether to include hidden files
empty: Whether to include empty files
Raise PathNotFoundError if path doesn't exist. | Below is the the instruction that describes the task:
### Input:
Return list of absolute, sorted file paths
path: Path to file or directory
exclude: List of file name patterns to exclude
hidden: Whether to include hidden files
empty: Whether to include empty files
Raise PathNotFoundError if pa... |
def intensity(image):
'''Calculates the average intensity of the pixels in an image.
Accepts both RGB and grayscale images.
:param image: numpy.ndarray
:returns: image intensity
:rtype: float
'''
if len(image.shape) > 2:
# Convert to grayscale
image = cv2.cvtColor(image, cv2... | Calculates the average intensity of the pixels in an image.
Accepts both RGB and grayscale images.
:param image: numpy.ndarray
:returns: image intensity
:rtype: float | Below is the the instruction that describes the task:
### Input:
Calculates the average intensity of the pixels in an image.
Accepts both RGB and grayscale images.
:param image: numpy.ndarray
:returns: image intensity
:rtype: float
### Response:
def intensity(image):
'''Calculates the average ... |
def make_container_tree(folders,files,path_delim="/",parse_files=True):
'''make_container_tree will convert a list of folders and files into a json structure that represents a graph.
:param folders: a list of folders in the image
:param files: a list of files in the folder
:param parse_files: return 'fi... | make_container_tree will convert a list of folders and files into a json structure that represents a graph.
:param folders: a list of folders in the image
:param files: a list of files in the folder
:param parse_files: return 'files' lookup in result, to associate ID of node with files (default True)
:p... | Below is the the instruction that describes the task:
### Input:
make_container_tree will convert a list of folders and files into a json structure that represents a graph.
:param folders: a list of folders in the image
:param files: a list of files in the folder
:param parse_files: return 'files' looku... |
def getAttributesList(self):
'''
getAttributesList - Get a copy of all attributes as a list of tuples (name, value)
ALL values are converted to string and copied, so modifications will not affect the original attributes.
If you want types like "style" to work as before... | getAttributesList - Get a copy of all attributes as a list of tuples (name, value)
ALL values are converted to string and copied, so modifications will not affect the original attributes.
If you want types like "style" to work as before, you'll need to recreate those elements (like StyleA... | Below is the the instruction that describes the task:
### Input:
getAttributesList - Get a copy of all attributes as a list of tuples (name, value)
ALL values are converted to string and copied, so modifications will not affect the original attributes.
If you want types like "style" t... |
def _display_interval(i):
"""Convert a time interval into a human-readable string.
:param i: The interval to convert, in seconds.
"""
sigils = ["d", "h", "m", "s"]
factors = [24 * 60 * 60, 60 * 60, 60, 1]
remain = int(i)
result = ""
for fac, sig in zip(factors, sigils):
if remai... | Convert a time interval into a human-readable string.
:param i: The interval to convert, in seconds. | Below is the the instruction that describes the task:
### Input:
Convert a time interval into a human-readable string.
:param i: The interval to convert, in seconds.
### Response:
def _display_interval(i):
"""Convert a time interval into a human-readable string.
:param i: The interval to convert, in ... |
def accpro_results(self):
"""Parse the ACCpro output file and return a dict of secondary structure compositions.
"""
return ssbio.protein.sequence.utils.fasta.load_fasta_file_as_dict_of_seqs(self.out_accpro) | Parse the ACCpro output file and return a dict of secondary structure compositions. | Below is the the instruction that describes the task:
### Input:
Parse the ACCpro output file and return a dict of secondary structure compositions.
### Response:
def accpro_results(self):
"""Parse the ACCpro output file and return a dict of secondary structure compositions.
"""
return ssbi... |
def copy(self, new_grab=None):
"""
Clone the Response object.
"""
obj = self.__class__()
obj.process_grab(new_grab if new_grab else self.grab)
copy_keys = ('status', 'code', 'head', 'body', 'total_time',
'connect_time', 'name_lookup_time',
... | Clone the Response object. | Below is the the instruction that describes the task:
### Input:
Clone the Response object.
### Response:
def copy(self, new_grab=None):
"""
Clone the Response object.
"""
obj = self.__class__()
obj.process_grab(new_grab if new_grab else self.grab)
copy_keys = ('st... |
def _transform_value(value, policy, transform_type):
'''
helper function to transform the policy value into something that more
closely matches how the policy is displayed in the gpedit GUI
'''
t_kwargs = {}
if 'Transform' in policy:
if transform_type in policy['Transform']:
... | helper function to transform the policy value into something that more
closely matches how the policy is displayed in the gpedit GUI | Below is the the instruction that describes the task:
### Input:
helper function to transform the policy value into something that more
closely matches how the policy is displayed in the gpedit GUI
### Response:
def _transform_value(value, policy, transform_type):
'''
helper function to transform the p... |
def login(self, broker_name, account_cookie, account=None):
"""login 登录到交易前置
2018-07-02 在实盘中,登录到交易前置后,需要同步资产状态
Arguments:
broker_name {[type]} -- [description]
account_cookie {[type]} -- [description]
Keyword Arguments:
account {[type]} -- [descript... | login 登录到交易前置
2018-07-02 在实盘中,登录到交易前置后,需要同步资产状态
Arguments:
broker_name {[type]} -- [description]
account_cookie {[type]} -- [description]
Keyword Arguments:
account {[type]} -- [description] (default: {None})
Returns:
[type] -- [descrip... | Below is the the instruction that describes the task:
### Input:
login 登录到交易前置
2018-07-02 在实盘中,登录到交易前置后,需要同步资产状态
Arguments:
broker_name {[type]} -- [description]
account_cookie {[type]} -- [description]
Keyword Arguments:
account {[type]} -- [descriptio... |
def _ReadUUIDDataTypeDefinition(
self, definitions_registry, definition_values, definition_name,
is_member=False):
"""Reads an UUID data type definition.
Args:
definitions_registry (DataTypeDefinitionsRegistry): data type definitions
registry.
definition_values (dict[str, obje... | Reads an UUID data type definition.
Args:
definitions_registry (DataTypeDefinitionsRegistry): data type definitions
registry.
definition_values (dict[str, object]): definition values.
definition_name (str): name of the definition.
is_member (Optional[bool]): True if the data type ... | Below is the the instruction that describes the task:
### Input:
Reads an UUID data type definition.
Args:
definitions_registry (DataTypeDefinitionsRegistry): data type definitions
registry.
definition_values (dict[str, object]): definition values.
definition_name (str): name of the... |
def _flush(self):
"""
Decorator for flushing handlers with an lock, catching exceptions
"""
if not self.enabled:
return
try:
try:
self.lock.acquire()
self.flush()
except Exception:
self.log.error(... | Decorator for flushing handlers with an lock, catching exceptions | Below is the the instruction that describes the task:
### Input:
Decorator for flushing handlers with an lock, catching exceptions
### Response:
def _flush(self):
"""
Decorator for flushing handlers with an lock, catching exceptions
"""
if not self.enabled:
return
... |
async def close(self):
"""This function is a coroutine.
Closes all connections."""
if self._is_closed:
return
else:
await self.http.close()
self._is_closed = True | This function is a coroutine.
Closes all connections. | Below is the the instruction that describes the task:
### Input:
This function is a coroutine.
Closes all connections.
### Response:
async def close(self):
"""This function is a coroutine.
Closes all connections."""
if self._is_closed:
return
else:
... |
def get_lines(self, first, last):
"""Return SourceLines for lines between and including first & last."""
line = 1
linestring = []
linestrings = []
for char in self.string:
if line >= first and line <= last:
linestring.append(char)
if ch... | Return SourceLines for lines between and including first & last. | Below is the the instruction that describes the task:
### Input:
Return SourceLines for lines between and including first & last.
### Response:
def get_lines(self, first, last):
"""Return SourceLines for lines between and including first & last."""
line = 1
linestring = []
linestrin... |
def list(self) -> Iterable[ListEntry]:
"""Return all the entries in the list tree."""
for entry in self._iter(self._root, ''):
yield entry | Return all the entries in the list tree. | Below is the the instruction that describes the task:
### Input:
Return all the entries in the list tree.
### Response:
def list(self) -> Iterable[ListEntry]:
"""Return all the entries in the list tree."""
for entry in self._iter(self._root, ''):
yield entry |
def _request(self, typ, id=0, method='GET', params=None, data=None, url=None):
"""
send the request, return response obj
"""
headers = { "Accept": "application/json" }
auth = None
if self.user:
auth = (self.user, self.password)
if not url:
... | send the request, return response obj | Below is the the instruction that describes the task:
### Input:
send the request, return response obj
### Response:
def _request(self, typ, id=0, method='GET', params=None, data=None, url=None):
"""
send the request, return response obj
"""
headers = { "Accept": "application/json"... |
def add_overlay(orig, area, coast_dir, color=(0, 0, 0), width=0.5, resolution=None,
level_coast=1, level_borders=1, fill_value=None,
grid=None):
"""Add coastline, political borders and grid(graticules) to image.
Uses ``color`` for feature colors where ``color`` is a 3-element tu... | Add coastline, political borders and grid(graticules) to image.
Uses ``color`` for feature colors where ``color`` is a 3-element tuple
of integers between 0 and 255 representing (R, G, B).
.. warning::
This function currently loses the data mask (alpha band).
``resolution`` is chosen automat... | Below is the the instruction that describes the task:
### Input:
Add coastline, political borders and grid(graticules) to image.
Uses ``color`` for feature colors where ``color`` is a 3-element tuple
of integers between 0 and 255 representing (R, G, B).
.. warning::
This function currently lo... |
def generate_kubernetes(self):
""" Generate a sample kubernetes
"""
example = {}
example['spec'] = {}
example['spec']['containers'] = []
example['spec']['containers'].append({"name": '', "image": '', "env": []})
for key, value in self.spec.items():
if ... | Generate a sample kubernetes | Below is the the instruction that describes the task:
### Input:
Generate a sample kubernetes
### Response:
def generate_kubernetes(self):
""" Generate a sample kubernetes
"""
example = {}
example['spec'] = {}
example['spec']['containers'] = []
example['spec']['conta... |
def _CreateMultipleValuesCondition(self, values, operator):
"""Creates a condition with the provided list of values and operator."""
values = ['"%s"' % value if isinstance(value, str) or
isinstance(value, unicode) else str(value) for value in values]
return '%s %s [%s]' % (self._field, operato... | Creates a condition with the provided list of values and operator. | Below is the the instruction that describes the task:
### Input:
Creates a condition with the provided list of values and operator.
### Response:
def _CreateMultipleValuesCondition(self, values, operator):
"""Creates a condition with the provided list of values and operator."""
values = ['"%s"' % value if ... |
def set_container_setting(name, container, settings):
'''
Set the value of the setting for an IIS container.
.. versionadded:: 2016.11.0
Args:
name (str): The name of the IIS container.
container (str): The type of IIS container. The container types are:
AppPools, Sites, Ss... | Set the value of the setting for an IIS container.
.. versionadded:: 2016.11.0
Args:
name (str): The name of the IIS container.
container (str): The type of IIS container. The container types are:
AppPools, Sites, SslBindings
settings (dict): A dictionary of the setting nam... | Below is the the instruction that describes the task:
### Input:
Set the value of the setting for an IIS container.
.. versionadded:: 2016.11.0
Args:
name (str): The name of the IIS container.
container (str): The type of IIS container. The container types are:
AppPools, Sites,... |
def traverse(self, node):
"""Traverse the document tree rooted at node.
node(node): docutils node.
"""
self.find_and_replace(node)
for c in node.children:
self.traverse(c) | Traverse the document tree rooted at node.
node(node): docutils node. | Below is the the instruction that describes the task:
### Input:
Traverse the document tree rooted at node.
node(node): docutils node.
### Response:
def traverse(self, node):
"""Traverse the document tree rooted at node.
node(node): docutils node.
"""
self.find_and_replace(node)
for c in... |
def stab(nick, rest):
"Stab, shank or shiv some(one|thing)!"
if rest:
stabee = rest
else:
stabee = 'wildly at anything'
if random.random() < 0.9:
karma.Karma.store.change(stabee, -1)
weapon = random.choice(phrases.weapon_opts)
weaponadj = random.choice(phrases.weapon_adjs)
violentact = random.choice(phr... | Stab, shank or shiv some(one|thing)! | Below is the the instruction that describes the task:
### Input:
Stab, shank or shiv some(one|thing)!
### Response:
def stab(nick, rest):
"Stab, shank or shiv some(one|thing)!"
if rest:
stabee = rest
else:
stabee = 'wildly at anything'
if random.random() < 0.9:
karma.Karma.store.change(stabee, -1)
weap... |
def iou_coe(output, target, threshold=0.5, axis=(1, 2, 3), smooth=1e-5):
"""Non-differentiable Intersection over Union (IoU) for comparing the
similarity of two batch of data, usually be used for evaluating binary image segmentation.
The coefficient between 0 to 1, and 1 means totally match.
Parameters... | Non-differentiable Intersection over Union (IoU) for comparing the
similarity of two batch of data, usually be used for evaluating binary image segmentation.
The coefficient between 0 to 1, and 1 means totally match.
Parameters
-----------
output : tensor
A batch of distribution with shape:... | Below is the the instruction that describes the task:
### Input:
Non-differentiable Intersection over Union (IoU) for comparing the
similarity of two batch of data, usually be used for evaluating binary image segmentation.
The coefficient between 0 to 1, and 1 means totally match.
Parameters
------... |
def main():
"""Handles external calling for this module
Execute this python module and provide the args shown below to
external call this module to send email messages!
:return: None
"""
log = logging.getLogger(mod_logger + '.main')
parser = argparse.ArgumentParser(description='This module... | Handles external calling for this module
Execute this python module and provide the args shown below to
external call this module to send email messages!
:return: None | Below is the the instruction that describes the task:
### Input:
Handles external calling for this module
Execute this python module and provide the args shown below to
external call this module to send email messages!
:return: None
### Response:
def main():
"""Handles external calling for this m... |
def split_window(self, attach=False, vertical=True, start_directory=None):
"""
Split window at pane and return newly created :class:`Pane`.
Parameters
----------
attach : bool, optional
Attach / select pane after creation.
vertical : bool, optional
... | Split window at pane and return newly created :class:`Pane`.
Parameters
----------
attach : bool, optional
Attach / select pane after creation.
vertical : bool, optional
split vertically
start_directory : str, optional
specifies the working di... | Below is the the instruction that describes the task:
### Input:
Split window at pane and return newly created :class:`Pane`.
Parameters
----------
attach : bool, optional
Attach / select pane after creation.
vertical : bool, optional
split vertically
... |
def load_module(self, filename):
'''Load a benchmark module from file'''
if not isinstance(filename, string_types):
return filename
basename = os.path.splitext(os.path.basename(filename))[0]
basename = basename.replace('.bench', '')
modulename = 'benchmarks.{0}'.forma... | Load a benchmark module from file | Below is the the instruction that describes the task:
### Input:
Load a benchmark module from file
### Response:
def load_module(self, filename):
'''Load a benchmark module from file'''
if not isinstance(filename, string_types):
return filename
basename = os.path.splitext(os.pat... |
def loaded_instruments(self) -> Dict[str, Optional['InstrumentContext']]:
""" Get the instruments that have been loaded into the protocol.
:returns: A dict mapping mount names in lowercase to the instrument
in that mount, or `None` if no instrument is present.
"""
retu... | Get the instruments that have been loaded into the protocol.
:returns: A dict mapping mount names in lowercase to the instrument
in that mount, or `None` if no instrument is present. | Below is the the instruction that describes the task:
### Input:
Get the instruments that have been loaded into the protocol.
:returns: A dict mapping mount names in lowercase to the instrument
in that mount, or `None` if no instrument is present.
### Response:
def loaded_instruments(sel... |
def numenta(self, X, Y):
r"""
Method that updates the network's connections.
Numenta's classic update:
- Visible to hidden: $ \Delta W_{ij} = y_i \cdot ( \varepsilon_{\small{+}} \ x_j - \varepsilon_{\small{-}} \ \bar x_j ) $
- Bias: $ b_{i} = B_b \cdot \alpha_i $
"""
batc... | r"""
Method that updates the network's connections.
Numenta's classic update:
- Visible to hidden: $ \Delta W_{ij} = y_i \cdot ( \varepsilon_{\small{+}} \ x_j - \varepsilon_{\small{-}} \ \bar x_j ) $
- Bias: $ b_{i} = B_b \cdot \alpha_i $ | Below is the the instruction that describes the task:
### Input:
r"""
Method that updates the network's connections.
Numenta's classic update:
- Visible to hidden: $ \Delta W_{ij} = y_i \cdot ( \varepsilon_{\small{+}} \ x_j - \varepsilon_{\small{-}} \ \bar x_j ) $
- Bias: $ b_{i} ... |
def filter_dict_by_key(d, keys):
"""Filter the dict *d* to remove keys not in *keys*."""
return {k: v for k, v in d.items() if k in keys} | Filter the dict *d* to remove keys not in *keys*. | Below is the the instruction that describes the task:
### Input:
Filter the dict *d* to remove keys not in *keys*.
### Response:
def filter_dict_by_key(d, keys):
"""Filter the dict *d* to remove keys not in *keys*."""
return {k: v for k, v in d.items() if k in keys} |
def get_composers(self, *args, **kwargs):
"""Convenience method for `get_music_library_information`
with ``search_type='composers'``. For details of other arguments,
see `that method
<#soco.music_library.MusicLibrary.get_music_library_information>`_.
"""
args = tuple(['c... | Convenience method for `get_music_library_information`
with ``search_type='composers'``. For details of other arguments,
see `that method
<#soco.music_library.MusicLibrary.get_music_library_information>`_. | Below is the the instruction that describes the task:
### Input:
Convenience method for `get_music_library_information`
with ``search_type='composers'``. For details of other arguments,
see `that method
<#soco.music_library.MusicLibrary.get_music_library_information>`_.
### Response:
def ge... |
def set_(key, value, profile=None):
'''
Set a key/value pair in the vault service
'''
if '?' in key:
__utils__['versions.warn_until'](
'Neon',
(
'Using ? to seperate between the path and key for vault has been deprecated '
'and will be remo... | Set a key/value pair in the vault service | Below is the the instruction that describes the task:
### Input:
Set a key/value pair in the vault service
### Response:
def set_(key, value, profile=None):
'''
Set a key/value pair in the vault service
'''
if '?' in key:
__utils__['versions.warn_until'](
'Neon',
(
... |
def return_dat(self, chan, begsam, endsam):
"""Return the data as 2D numpy.ndarray.
Parameters
----------
chan : list of int
index (indices) of the channels to read
begsam : int
index of the first sample (inclusively)
endsam : int
inde... | Return the data as 2D numpy.ndarray.
Parameters
----------
chan : list of int
index (indices) of the channels to read
begsam : int
index of the first sample (inclusively)
endsam : int
index of the last sample (exclusively)
Returns
... | Below is the the instruction that describes the task:
### Input:
Return the data as 2D numpy.ndarray.
Parameters
----------
chan : list of int
index (indices) of the channels to read
begsam : int
index of the first sample (inclusively)
endsam : int
... |
def file_fingerprint(fullpath):
""" Get a metadata fingerprint for a file """
stat = os.stat(fullpath)
return ','.join([str(value) for value in [stat.st_ino, stat.st_mtime, stat.st_size] if value]) | Get a metadata fingerprint for a file | Below is the the instruction that describes the task:
### Input:
Get a metadata fingerprint for a file
### Response:
def file_fingerprint(fullpath):
""" Get a metadata fingerprint for a file """
stat = os.stat(fullpath)
return ','.join([str(value) for value in [stat.st_ino, stat.st_mtime, stat.st_size]... |
def initWithComplexQuery(query):
"""
create a query using a complex article query
"""
q = QueryArticles()
# provided an instance of ComplexArticleQuery
if isinstance(query, ComplexArticleQuery):
q._setVal("query", json.dumps(query.getQuery()))
# provid... | create a query using a complex article query | Below is the the instruction that describes the task:
### Input:
create a query using a complex article query
### Response:
def initWithComplexQuery(query):
"""
create a query using a complex article query
"""
q = QueryArticles()
# provided an instance of ComplexArticleQuery... |
def p_arg1(p):
"""
arg1 : STRING
| NUMBER
| IDENT
| GLOBAL
"""
# a hack to support "clear global"
p[0] = node.string(value=str(p[1]), lineno=p.lineno(1), lexpos=p.lexpos(1)) | arg1 : STRING
| NUMBER
| IDENT
| GLOBAL | Below is the the instruction that describes the task:
### Input:
arg1 : STRING
| NUMBER
| IDENT
| GLOBAL
### Response:
def p_arg1(p):
"""
arg1 : STRING
| NUMBER
| IDENT
| GLOBAL
"""
# a hack to support "clear global"
p[0] = node.string(value... |
def reference(self, ):
"""Reference a file
:returns: None
:rtype: None
:raises: None
"""
tfi = self.get_taskfileinfo_selection()
if tfi:
self.reftrack.reference(tfi) | Reference a file
:returns: None
:rtype: None
:raises: None | Below is the the instruction that describes the task:
### Input:
Reference a file
:returns: None
:rtype: None
:raises: None
### Response:
def reference(self, ):
"""Reference a file
:returns: None
:rtype: None
:raises: None
"""
tfi = self.get... |
def spatial_slice_zeros(x):
"""Experimental summary that shows how many planes are unused for a batch."""
return tf.cast(tf.reduce_all(tf.less_equal(x, 0.0), [0, 1, 2]),
tf.float32) | Experimental summary that shows how many planes are unused for a batch. | Below is the the instruction that describes the task:
### Input:
Experimental summary that shows how many planes are unused for a batch.
### Response:
def spatial_slice_zeros(x):
"""Experimental summary that shows how many planes are unused for a batch."""
return tf.cast(tf.reduce_all(tf.less_equal(x, 0.0), [0... |
def vT(self,*args,**kwargs):
"""
NAME:
vT
PURPOSE:
return tangential velocity at time t
INPUT:
t - (optional) time at which to get the tangential velocity
vo= (Object-wide default) physical scale for velocities to use to convert
use_... | NAME:
vT
PURPOSE:
return tangential velocity at time t
INPUT:
t - (optional) time at which to get the tangential velocity
vo= (Object-wide default) physical scale for velocities to use to convert
use_physical= use to override Object-wide default for... | Below is the the instruction that describes the task:
### Input:
NAME:
vT
PURPOSE:
return tangential velocity at time t
INPUT:
t - (optional) time at which to get the tangential velocity
vo= (Object-wide default) physical scale for velocities to use to con... |
def setup(self):
"""
Called by pytest to setup the collector cells in .
Here we start a kernel and setup the sanitize patterns.
"""
if self.parent.config.option.current_env:
kernel_name = CURRENT_ENV_KERNEL_NAME
else:
kernel_name = self.nb.metadat... | Called by pytest to setup the collector cells in .
Here we start a kernel and setup the sanitize patterns. | Below is the the instruction that describes the task:
### Input:
Called by pytest to setup the collector cells in .
Here we start a kernel and setup the sanitize patterns.
### Response:
def setup(self):
"""
Called by pytest to setup the collector cells in .
Here we start a kernel an... |
def add_element(self, name, ns_uri=None, attributes=None,
text=None, before_this_element=False):
"""
Add a new child element to this element, with an optional namespace
definition. If no namespace is provided the child will be assigned
to the default namespace.
:para... | Add a new child element to this element, with an optional namespace
definition. If no namespace is provided the child will be assigned
to the default namespace.
:param string name: a name for the child node. The name may be used
to apply a namespace to the child by including:
... | Below is the the instruction that describes the task:
### Input:
Add a new child element to this element, with an optional namespace
definition. If no namespace is provided the child will be assigned
to the default namespace.
:param string name: a name for the child node. The name may be us... |
def plain_text_iter(fname: str, text_type: str, data_side: str) -> Iterable[str]:
"""
Extract plain text from file as iterable. Also take steps to ensure that
whitespace characters (including unicode newlines) are normalized and
outputs are line-parallel with inputs considering ASCII newlines only.
... | Extract plain text from file as iterable. Also take steps to ensure that
whitespace characters (including unicode newlines) are normalized and
outputs are line-parallel with inputs considering ASCII newlines only.
:param fname: Path of possibly gzipped input file.
:param text_type: One of TEXT_*, indi... | Below is the the instruction that describes the task:
### Input:
Extract plain text from file as iterable. Also take steps to ensure that
whitespace characters (including unicode newlines) are normalized and
outputs are line-parallel with inputs considering ASCII newlines only.
:param fname: Path of p... |
def in_distance(self, distance, fields, points, annotate='_ed_distance'):
"""Filter rows inside a circunference of radius distance `distance`
:param distance: max distance to allow
:param fields: `tuple` with the fields to filter (latitude, longitude)
:param points: center o... | Filter rows inside a circunference of radius distance `distance`
:param distance: max distance to allow
:param fields: `tuple` with the fields to filter (latitude, longitude)
:param points: center of the circunference (latitude, longitude)
:param annotate: name where the... | Below is the the instruction that describes the task:
### Input:
Filter rows inside a circunference of radius distance `distance`
:param distance: max distance to allow
:param fields: `tuple` with the fields to filter (latitude, longitude)
:param points: center of the circunfere... |
def lzwdecode(data):
"""
>>> lzwdecode(b'\x80\x0b\x60\x50\x22\x0c\x0c\x85\x01')
'\x2d\x2d\x2d\x2d\x2d\x41\x2d\x2d\x2d\x42'
"""
fp = BytesIO(data)
return b''.join(LZWDecoder(fp).run()) | >>> lzwdecode(b'\x80\x0b\x60\x50\x22\x0c\x0c\x85\x01')
'\x2d\x2d\x2d\x2d\x2d\x41\x2d\x2d\x2d\x42' | Below is the the instruction that describes the task:
### Input:
>>> lzwdecode(b'\x80\x0b\x60\x50\x22\x0c\x0c\x85\x01')
'\x2d\x2d\x2d\x2d\x2d\x41\x2d\x2d\x2d\x42'
### Response:
def lzwdecode(data):
"""
>>> lzwdecode(b'\x80\x0b\x60\x50\x22\x0c\x0c\x85\x01')
'\x2d\x2d\x2d\x2d\x2d\x41\x2d\x2d\x2d\x42'... |
def get_gallery_folder_list(self, scope='content/read'):
"""
Retrieve a list of the Mxit user's gallery folders
User authentication required with the following scope: 'content/read'
"""
folder_list = _get(
token=self.oauth.get_user_token(scope),
uri='/user... | Retrieve a list of the Mxit user's gallery folders
User authentication required with the following scope: 'content/read' | Below is the the instruction that describes the task:
### Input:
Retrieve a list of the Mxit user's gallery folders
User authentication required with the following scope: 'content/read'
### Response:
def get_gallery_folder_list(self, scope='content/read'):
"""
Retrieve a list of the Mxit us... |
def constraint_range_dict(self,*args,**kwargs):
"""
Creates a list of dictionaries which each give a constraint for a certain
section of the dimension.
bins arguments overwrites resolution
"""
bins = self.bins(*args,**kwargs)
return [{self.name+'__gt... | Creates a list of dictionaries which each give a constraint for a certain
section of the dimension.
bins arguments overwrites resolution | Below is the the instruction that describes the task:
### Input:
Creates a list of dictionaries which each give a constraint for a certain
section of the dimension.
bins arguments overwrites resolution
### Response:
def constraint_range_dict(self,*args,**kwargs):
"""
C... |
def add_noise(data, sigma=1.0, noise_type='gauss'):
r"""Add noise to data
This method adds Gaussian or Poisson noise to the input data
Parameters
----------
data : np.ndarray, list or tuple
Input data array
sigma : float or list, optional
Standard deviation of the noise to be a... | r"""Add noise to data
This method adds Gaussian or Poisson noise to the input data
Parameters
----------
data : np.ndarray, list or tuple
Input data array
sigma : float or list, optional
Standard deviation of the noise to be added ('gauss' only)
noise_type : str {'gauss', 'pois... | Below is the the instruction that describes the task:
### Input:
r"""Add noise to data
This method adds Gaussian or Poisson noise to the input data
Parameters
----------
data : np.ndarray, list or tuple
Input data array
sigma : float or list, optional
Standard deviation of the ... |
def dispatch_command(function, *args, **kwargs):
"""
A wrapper for :func:`dispatch` that creates a one-command parser.
Uses :attr:`PARSER_FORMATTER`.
This::
dispatch_command(foo)
...is a shortcut for::
parser = ArgumentParser()
set_default_command(parser, foo)
dis... | A wrapper for :func:`dispatch` that creates a one-command parser.
Uses :attr:`PARSER_FORMATTER`.
This::
dispatch_command(foo)
...is a shortcut for::
parser = ArgumentParser()
set_default_command(parser, foo)
dispatch(parser)
This function can be also used as a decora... | Below is the the instruction that describes the task:
### Input:
A wrapper for :func:`dispatch` that creates a one-command parser.
Uses :attr:`PARSER_FORMATTER`.
This::
dispatch_command(foo)
...is a shortcut for::
parser = ArgumentParser()
set_default_command(parser, foo)
... |
def set_ipv4(self, ip):
""" Sets the IP address (ifr_addr) of the device
parameter 'ip' should be string representation of IP address
This does the same as ifconfig.
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
bin_ip = socket.inet_aton(ip)
... | Sets the IP address (ifr_addr) of the device
parameter 'ip' should be string representation of IP address
This does the same as ifconfig. | Below is the the instruction that describes the task:
### Input:
Sets the IP address (ifr_addr) of the device
parameter 'ip' should be string representation of IP address
This does the same as ifconfig.
### Response:
def set_ipv4(self, ip):
""" Sets the IP address (ifr_addr) of the ... |
def masked_pick_probability(x, y, temp, cos_distance):
"""The pairwise sampling probabilities for the elements of x for neighbor
points which share labels.
:param x: a matrix
:param y: a list of labels for each element of x
:param temp: Temperature
:cos_distance: Boolean for using cosine or Eucl... | The pairwise sampling probabilities for the elements of x for neighbor
points which share labels.
:param x: a matrix
:param y: a list of labels for each element of x
:param temp: Temperature
:cos_distance: Boolean for using cosine or Euclidean distance
:returns: A tensor for the pairwise sampli... | Below is the the instruction that describes the task:
### Input:
The pairwise sampling probabilities for the elements of x for neighbor
points which share labels.
:param x: a matrix
:param y: a list of labels for each element of x
:param temp: Temperature
:cos_distance: Boolean for using cosine ... |
def register(
self,
app: 'Quart',
first_registration: bool,
*,
url_prefix: Optional[str]=None,
) -> None:
"""Register this blueprint on the app given."""
state = self.make_setup_state(app, first_registration, url_prefix=url_prefix)
... | Register this blueprint on the app given. | Below is the the instruction that describes the task:
### Input:
Register this blueprint on the app given.
### Response:
def register(
self,
app: 'Quart',
first_registration: bool,
*,
url_prefix: Optional[str]=None,
) -> None:
"""Register this... |
def to_iterable(value, allow_none=True):
"""
Tries to convert the given value to an iterable, if necessary.
If the given value is a list, a list is returned; if it is a string, a list
containing one string is returned, ...
:param value: Any object
:param allow_none: If True, the method returns ... | Tries to convert the given value to an iterable, if necessary.
If the given value is a list, a list is returned; if it is a string, a list
containing one string is returned, ...
:param value: Any object
:param allow_none: If True, the method returns None if value is None, else
it... | Below is the the instruction that describes the task:
### Input:
Tries to convert the given value to an iterable, if necessary.
If the given value is a list, a list is returned; if it is a string, a list
containing one string is returned, ...
:param value: Any object
:param allow_none: If True, the... |
def create_cluster(cluster_dict, datacenter=None, cluster=None,
service_instance=None):
'''
Creates a cluster.
Note: cluster_dict['name'] will be overridden by the cluster param value
config_dict
Dictionary with the config values of the new cluster.
datacenter
N... | Creates a cluster.
Note: cluster_dict['name'] will be overridden by the cluster param value
config_dict
Dictionary with the config values of the new cluster.
datacenter
Name of datacenter containing the cluster.
Ignored if already contained by proxy details.
Default value ... | Below is the the instruction that describes the task:
### Input:
Creates a cluster.
Note: cluster_dict['name'] will be overridden by the cluster param value
config_dict
Dictionary with the config values of the new cluster.
datacenter
Name of datacenter containing the cluster.
... |
def delete_queue(self, queue_name):
"""
Delete a queue with the specified name.
:param queue_name:
:return:
"""
self.connect()
channel = self.connection.channel()
channel.queue_delete(queue=queue_name)
self.close() | Delete a queue with the specified name.
:param queue_name:
:return: | Below is the the instruction that describes the task:
### Input:
Delete a queue with the specified name.
:param queue_name:
:return:
### Response:
def delete_queue(self, queue_name):
"""
Delete a queue with the specified name.
:param queue_name:
:return:
"""
... |
def MWColorMapping(maptype='jet', reverse=True):
"""Maps amino-acid molecular weights to colors. Otherwise, this
function is identical to *KyteDoolittleColorMapping*
"""
d = {'A':89,'R':174,'N':132,'D':133,'C':121,'Q':146,'E':147,\
'G':75,'H':155,'I':131,'L':131,'K':146,'M':149,'F':165,\
... | Maps amino-acid molecular weights to colors. Otherwise, this
function is identical to *KyteDoolittleColorMapping* | Below is the the instruction that describes the task:
### Input:
Maps amino-acid molecular weights to colors. Otherwise, this
function is identical to *KyteDoolittleColorMapping*
### Response:
def MWColorMapping(maptype='jet', reverse=True):
"""Maps amino-acid molecular weights to colors. Otherwise, this
... |
def to_html(self):
"""Render a Cell MessageElement as html
:returns: The html representation of the Cell MessageElement
:rtype: basestring
"""
# Apply bootstrap alignment classes first
if self.align is 'left':
if self.style_class is None:
self... | Render a Cell MessageElement as html
:returns: The html representation of the Cell MessageElement
:rtype: basestring | Below is the the instruction that describes the task:
### Input:
Render a Cell MessageElement as html
:returns: The html representation of the Cell MessageElement
:rtype: basestring
### Response:
def to_html(self):
"""Render a Cell MessageElement as html
:returns: The html represe... |
def eda_EventRelated(epoch, event_length, window_post=4):
"""
Extract event-related EDA and Skin Conductance Response (SCR).
Parameters
----------
epoch : pandas.DataFrame
An epoch contains in the epochs dict returned by :function:`neurokit.create_epochs()` on dataframe returned by :functio... | Extract event-related EDA and Skin Conductance Response (SCR).
Parameters
----------
epoch : pandas.DataFrame
An epoch contains in the epochs dict returned by :function:`neurokit.create_epochs()` on dataframe returned by :function:`neurokit.bio_process()`. Index must range from -4s to +4s (relative... | Below is the the instruction that describes the task:
### Input:
Extract event-related EDA and Skin Conductance Response (SCR).
Parameters
----------
epoch : pandas.DataFrame
An epoch contains in the epochs dict returned by :function:`neurokit.create_epochs()` on dataframe returned by :function... |
def _get_page_elements(self):
"""Return page elements and page objects of this page object
:returns: list of page elements and page objects
"""
page_elements = []
for attribute, value in list(self.__dict__.items()) + list(self.__class__.__dict__.items()):
if attribut... | Return page elements and page objects of this page object
:returns: list of page elements and page objects | Below is the the instruction that describes the task:
### Input:
Return page elements and page objects of this page object
:returns: list of page elements and page objects
### Response:
def _get_page_elements(self):
"""Return page elements and page objects of this page object
:returns: li... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.