code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def local_histogram(image, bins=19, rang="image", cutoffp=(0.0, 100.0), size=None, footprint=None, output=None, mode="ignore", origin=0, mask=slice(None)):
r"""
Computes multi-dimensional histograms over a region around each voxel.
Supply an image and (optionally) a mask and get the local histogram of ... | r"""
Computes multi-dimensional histograms over a region around each voxel.
Supply an image and (optionally) a mask and get the local histogram of local
neighbourhoods around each voxel. These neighbourhoods are cubic with a sidelength of
size in voxels or, when a shape instead of an integer is pas... | Below is the the instruction that describes the task:
### Input:
r"""
Computes multi-dimensional histograms over a region around each voxel.
Supply an image and (optionally) a mask and get the local histogram of local
neighbourhoods around each voxel. These neighbourhoods are cubic with a sidelengt... |
def facets(mesh, engine=None):
"""
Find the list of parallel adjacent faces.
Parameters
---------
mesh : trimesh.Trimesh
engine : str
Which graph engine to use:
('scipy', 'networkx', 'graphtool')
Returns
---------
facets : sequence of (n,) int
Groups of face ... | Find the list of parallel adjacent faces.
Parameters
---------
mesh : trimesh.Trimesh
engine : str
Which graph engine to use:
('scipy', 'networkx', 'graphtool')
Returns
---------
facets : sequence of (n,) int
Groups of face indexes of
parallel adjacent faces. | Below is the the instruction that describes the task:
### Input:
Find the list of parallel adjacent faces.
Parameters
---------
mesh : trimesh.Trimesh
engine : str
Which graph engine to use:
('scipy', 'networkx', 'graphtool')
Returns
---------
facets : sequence of (n,) i... |
def unpickle(pickle_file):
"""Unpickle a python object from the given path."""
pickle = None
with open(pickle_file, "rb") as pickle_f:
pickle = dill.load(pickle_f)
if not pickle:
LOG.error("Could not load python object from file")
return pickle | Unpickle a python object from the given path. | Below is the the instruction that describes the task:
### Input:
Unpickle a python object from the given path.
### Response:
def unpickle(pickle_file):
"""Unpickle a python object from the given path."""
pickle = None
with open(pickle_file, "rb") as pickle_f:
pickle = dill.load(pickle_f)
if... |
def download_file_insecure(url, target):
'''
Use Python to download the file, even though it cannot authenticate the
connection.
'''
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
src = dst = None
try:
src = urlopen(url)
... | Use Python to download the file, even though it cannot authenticate the
connection. | Below is the the instruction that describes the task:
### Input:
Use Python to download the file, even though it cannot authenticate the
connection.
### Response:
def download_file_insecure(url, target):
'''
Use Python to download the file, even though it cannot authenticate the
connection.
'''... |
def _get_next_child_node(self, parent):
"""
Iterates among children of the given parent and looks for a suitable node to process
In case given parent has no suitable nodes, a younger parent will be found
and the logic will be repeated for him
"""
children_keys... | Iterates among children of the given parent and looks for a suitable node to process
In case given parent has no suitable nodes, a younger parent will be found
and the logic will be repeated for him | Below is the the instruction that describes the task:
### Input:
Iterates among children of the given parent and looks for a suitable node to process
In case given parent has no suitable nodes, a younger parent will be found
and the logic will be repeated for him
### Response:
def _get_next... |
def write_contents_to_file(self, entities, path_patterns=None,
contents=None, link_to=None,
content_mode='text', conflicts='fail',
strict=False):
"""
Write arbitrary data to a file defined by the passed entities... | Write arbitrary data to a file defined by the passed entities and
path patterns.
Args:
entities (dict): A dictionary of entities, with Entity names in
keys and values for the desired file in values.
path_patterns (list): Optional path patterns to use when buildin... | Below is the the instruction that describes the task:
### Input:
Write arbitrary data to a file defined by the passed entities and
path patterns.
Args:
entities (dict): A dictionary of entities, with Entity names in
keys and values for the desired file in values.
... |
def _next_rdelim(items, pos):
"""Return position of next matching closing delimiter."""
for num, item in enumerate(items):
if item > pos:
break
else:
raise RuntimeError("Mismatched delimiters")
del items[num]
return item | Return position of next matching closing delimiter. | Below is the the instruction that describes the task:
### Input:
Return position of next matching closing delimiter.
### Response:
def _next_rdelim(items, pos):
"""Return position of next matching closing delimiter."""
for num, item in enumerate(items):
if item > pos:
break
else:
... |
def batch(self, batch_size, batch_num, fluxes=True):
"""Create a batch generator.
This is useful to generate n batches of m samples each.
Parameters
----------
batch_size : int
The number of samples contained in each batch (m).
batch_num : int
Th... | Create a batch generator.
This is useful to generate n batches of m samples each.
Parameters
----------
batch_size : int
The number of samples contained in each batch (m).
batch_num : int
The number of batches in the generator (n).
fluxes : boole... | Below is the the instruction that describes the task:
### Input:
Create a batch generator.
This is useful to generate n batches of m samples each.
Parameters
----------
batch_size : int
The number of samples contained in each batch (m).
batch_num : int
... |
def rest(f):
"""Decorator for simple REST endpoints.
Functions must return one of these values:
- a dict to jsonify
- nothing for an empty 204 response
- a tuple containing a status code and a dict to jsonify
"""
@wraps(f)
def wrapper(*args, **kwargs):
ret = f(*args, **kwargs)
... | Decorator for simple REST endpoints.
Functions must return one of these values:
- a dict to jsonify
- nothing for an empty 204 response
- a tuple containing a status code and a dict to jsonify | Below is the the instruction that describes the task:
### Input:
Decorator for simple REST endpoints.
Functions must return one of these values:
- a dict to jsonify
- nothing for an empty 204 response
- a tuple containing a status code and a dict to jsonify
### Response:
def rest(f):
"""Decora... |
def salt_syndic():
'''
Start the salt syndic.
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
pid = os.getpid()
try:
syndic = salt.cli.daemons.Syndic()
syndic.start()
except KeyboardInterrupt:
os.kill(pid, 15) | Start the salt syndic. | Below is the the instruction that describes the task:
### Input:
Start the salt syndic.
### Response:
def salt_syndic():
'''
Start the salt syndic.
'''
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
pid = os.getpid()
try:
syndic = salt... |
def write_notebook_rst(txt, res, fnm, pth):
"""
Write the converted notebook text `txt` and resources `res` to
filename `fnm` in directory `pth`.
"""
# Extended filename used for output images
extfnm = fnm + '_files'
# Directory into which output images are written
extpth = os.path.join... | Write the converted notebook text `txt` and resources `res` to
filename `fnm` in directory `pth`. | Below is the the instruction that describes the task:
### Input:
Write the converted notebook text `txt` and resources `res` to
filename `fnm` in directory `pth`.
### Response:
def write_notebook_rst(txt, res, fnm, pth):
"""
Write the converted notebook text `txt` and resources `res` to
filename `f... |
def unflag_message(current):
"""
remove flag of a message
.. code-block:: python
# request:
{
'view':'_zops_flag_message',
'key': key,
}
# response:
{
'
'status': 'OK',
'code': 200,
}
"... | remove flag of a message
.. code-block:: python
# request:
{
'view':'_zops_flag_message',
'key': key,
}
# response:
{
'
'status': 'OK',
'code': 200,
} | Below is the the instruction that describes the task:
### Input:
remove flag of a message
.. code-block:: python
# request:
{
'view':'_zops_flag_message',
'key': key,
}
# response:
{
'
'status': 'OK',
'code... |
def get_bootstrap(cls, name, ctx):
'''Returns an instance of a bootstrap with the given name.
This is the only way you should access a bootstrap class, as
it sets the bootstrap directory correctly.
'''
if name is None:
return None
if not hasattr(cls, 'bootstr... | Returns an instance of a bootstrap with the given name.
This is the only way you should access a bootstrap class, as
it sets the bootstrap directory correctly. | Below is the the instruction that describes the task:
### Input:
Returns an instance of a bootstrap with the given name.
This is the only way you should access a bootstrap class, as
it sets the bootstrap directory correctly.
### Response:
def get_bootstrap(cls, name, ctx):
'''Returns an in... |
def _get_client():
"""Create a new client for the HNV REST API."""
return utils.get_client(url=CONFIG.HNV.url,
username=CONFIG.HNV.username,
password=CONFIG.HNV.password,
allow_insecure=CONFIG.HNV.https_allow... | Create a new client for the HNV REST API. | Below is the the instruction that describes the task:
### Input:
Create a new client for the HNV REST API.
### Response:
def _get_client():
"""Create a new client for the HNV REST API."""
return utils.get_client(url=CONFIG.HNV.url,
username=CONFIG.HNV.username,
... |
def _checkpoint(self):
"""Save and/or get a state checkpoint previous to current instruction"""
#Fixme[felipe] add a with self.disabled_events context mangr to Eventful
if self._checkpoint_data is None:
if not self._published_pre_instruction_events:
self._published_pr... | Save and/or get a state checkpoint previous to current instruction | Below is the the instruction that describes the task:
### Input:
Save and/or get a state checkpoint previous to current instruction
### Response:
def _checkpoint(self):
"""Save and/or get a state checkpoint previous to current instruction"""
#Fixme[felipe] add a with self.disabled_events context ma... |
def _table_sort_by(table, sort_exprs):
"""
Sort table by the indicated column expressions and sort orders
(ascending/descending)
Parameters
----------
sort_exprs : sorting expressions
Must be one of:
- Column name or expression
- Sort key, e.g. desc(col)
- (column ... | Sort table by the indicated column expressions and sort orders
(ascending/descending)
Parameters
----------
sort_exprs : sorting expressions
Must be one of:
- Column name or expression
- Sort key, e.g. desc(col)
- (column name, True (ascending) / False (descending))
E... | Below is the the instruction that describes the task:
### Input:
Sort table by the indicated column expressions and sort orders
(ascending/descending)
Parameters
----------
sort_exprs : sorting expressions
Must be one of:
- Column name or expression
- Sort key, e.g. desc(col)
... |
def get_change(self, change_id):
"""
Get information about a proposed set of changes, as submitted
by the change_rrsets method.
Returns a Python data structure with status information about the
changes.
:type change_id: str
:param change_id: The unique identifier... | Get information about a proposed set of changes, as submitted
by the change_rrsets method.
Returns a Python data structure with status information about the
changes.
:type change_id: str
:param change_id: The unique identifier for the set of changes.
This ID is retur... | Below is the the instruction that describes the task:
### Input:
Get information about a proposed set of changes, as submitted
by the change_rrsets method.
Returns a Python data structure with status information about the
changes.
:type change_id: str
:param change_id: The u... |
def hook(self, name, state):
r"""Registers a backward hook.
The hook will be called every time a gradient with respect to the
Tensor is computed. The hook should have the following signature::
hook (grad) -> Tensor or None
The hook should not modify its argument, but it ca... | r"""Registers a backward hook.
The hook will be called every time a gradient with respect to the
Tensor is computed. The hook should have the following signature::
hook (grad) -> Tensor or None
The hook should not modify its argument, but it can optionally return
a new gra... | Below is the the instruction that describes the task:
### Input:
r"""Registers a backward hook.
The hook will be called every time a gradient with respect to the
Tensor is computed. The hook should have the following signature::
hook (grad) -> Tensor or None
The hook should no... |
def get_help(self, ctx):
"""Formats the help into a string and returns it. This creates a
formatter and will call into the following formatting methods:
"""
formatter = ctx.make_formatter()
self.format_help(ctx, formatter)
return formatter.getvalue().rstrip('\n') | Formats the help into a string and returns it. This creates a
formatter and will call into the following formatting methods: | Below is the the instruction that describes the task:
### Input:
Formats the help into a string and returns it. This creates a
formatter and will call into the following formatting methods:
### Response:
def get_help(self, ctx):
"""Formats the help into a string and returns it. This creates a
... |
def dht_findprovs(self, multihash, *multihashes, **kwargs):
"""Finds peers in the DHT that can provide a specific value.
.. code-block:: python
>>> c.dht_findprovs("QmNPXDC6wTXVmZ9Uoc8X1oqxRRJr4f1sDuyQu … mpW2")
[{'ID': 'QmaxqKpiYNr62uSFBhxJAMmEMkT6dvc3oHkrZNpH2VMTLZ',
... | Finds peers in the DHT that can provide a specific value.
.. code-block:: python
>>> c.dht_findprovs("QmNPXDC6wTXVmZ9Uoc8X1oqxRRJr4f1sDuyQu … mpW2")
[{'ID': 'QmaxqKpiYNr62uSFBhxJAMmEMkT6dvc3oHkrZNpH2VMTLZ',
'Extra': '', 'Type': 6, 'Responses': None},
{'ID': '... | Below is the the instruction that describes the task:
### Input:
Finds peers in the DHT that can provide a specific value.
.. code-block:: python
>>> c.dht_findprovs("QmNPXDC6wTXVmZ9Uoc8X1oqxRRJr4f1sDuyQu … mpW2")
[{'ID': 'QmaxqKpiYNr62uSFBhxJAMmEMkT6dvc3oHkrZNpH2VMTLZ',
... |
def get_token(value):
"""token = [CFWS] 1*ttext [CFWS]
The RFC equivalent of ttext is any US-ASCII chars except space, ctls, or
tspecials. We also exclude tabs even though the RFC doesn't.
The RFC implies the CFWS but is not explicit about it in the BNF.
"""
mtoken = Token()
if value and... | token = [CFWS] 1*ttext [CFWS]
The RFC equivalent of ttext is any US-ASCII chars except space, ctls, or
tspecials. We also exclude tabs even though the RFC doesn't.
The RFC implies the CFWS but is not explicit about it in the BNF. | Below is the the instruction that describes the task:
### Input:
token = [CFWS] 1*ttext [CFWS]
The RFC equivalent of ttext is any US-ASCII chars except space, ctls, or
tspecials. We also exclude tabs even though the RFC doesn't.
The RFC implies the CFWS but is not explicit about it in the BNF.
### Re... |
def get_objective_lookup_session(self, proxy):
"""Gets the ``OsidSession`` associated with the objective lookup service.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: an ``ObjectiveLookupSession``
:rtype: ``osid.learning.ObjectiveLookupSession``
:raise... | Gets the ``OsidSession`` associated with the objective lookup service.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: an ``ObjectiveLookupSession``
:rtype: ``osid.learning.ObjectiveLookupSession``
:raise: ``NullArgument`` -- ``proxy`` is ``null``
:raise... | Below is the the instruction that describes the task:
### Input:
Gets the ``OsidSession`` associated with the objective lookup service.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: an ``ObjectiveLookupSession``
:rtype: ``osid.learning.ObjectiveLookupSession``
... |
def get_args(parser):
"""
Converts arguments extracted from a parser to a dict,
and will dismiss arguments which default to NOT_SET.
:param parser: an ``argparse.ArgumentParser`` instance.
:type parser: argparse.ArgumentParser
:return: Dictionary with the configs found in the parsed CLI argumen... | Converts arguments extracted from a parser to a dict,
and will dismiss arguments which default to NOT_SET.
:param parser: an ``argparse.ArgumentParser`` instance.
:type parser: argparse.ArgumentParser
:return: Dictionary with the configs found in the parsed CLI arguments.
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Converts arguments extracted from a parser to a dict,
and will dismiss arguments which default to NOT_SET.
:param parser: an ``argparse.ArgumentParser`` instance.
:type parser: argparse.ArgumentParser
:return: Dictionary with the conf... |
def add_member_by_id(self, member_id, membership_type='normal'):
'''
Add a member to the board using the id. Membership type can be
normal or admin. Returns JSON of all members if successful or raises an
Unauthorised exception if not.
'''
return self.fetch_json(
... | Add a member to the board using the id. Membership type can be
normal or admin. Returns JSON of all members if successful or raises an
Unauthorised exception if not. | Below is the the instruction that describes the task:
### Input:
Add a member to the board using the id. Membership type can be
normal or admin. Returns JSON of all members if successful or raises an
Unauthorised exception if not.
### Response:
def add_member_by_id(self, member_id, membership_type=... |
def _addFlushBatch(self):
"""
Sends all waiting documents to Solr
"""
if len(self._add_batch) > 0:
language_batches = {}
# Create command JSONs for each of language endpoints
for lang in self.endpoints:
# Append documents with language... | Sends all waiting documents to Solr | Below is the the instruction that describes the task:
### Input:
Sends all waiting documents to Solr
### Response:
def _addFlushBatch(self):
"""
Sends all waiting documents to Solr
"""
if len(self._add_batch) > 0:
language_batches = {}
# Create command JSONs... |
def parse(self):
""" parse the data
"""
# convert the xlsx file to csv first
delimiter = "|"
csv_file = self.xlsx_to_csv(self.getInputFile(), delimiter=delimiter)
reader = csv.DictReader(csv_file, delimiter=delimiter)
for n, row in enumerate(reader):
... | parse the data | Below is the the instruction that describes the task:
### Input:
parse the data
### Response:
def parse(self):
""" parse the data
"""
# convert the xlsx file to csv first
delimiter = "|"
csv_file = self.xlsx_to_csv(self.getInputFile(), delimiter=delimiter)
reader = ... |
def pending(self, partitions=None):
"""
Gets the pending message count
Keyword Arguments:
partitions (list): list of partitions to check for, default is to check all
"""
if partitions is None:
partitions = self.offsets.keys()
total = 0
re... | Gets the pending message count
Keyword Arguments:
partitions (list): list of partitions to check for, default is to check all | Below is the the instruction that describes the task:
### Input:
Gets the pending message count
Keyword Arguments:
partitions (list): list of partitions to check for, default is to check all
### Response:
def pending(self, partitions=None):
"""
Gets the pending message count
... |
def get_gradebook_column_summary_mdata():
"""Return default mdata map for GradebookColumnSummary"""
return {
'gradebook_column': {
'element_label': {
'text': 'gradebook column',
'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),
'scriptTypeId': str(... | Return default mdata map for GradebookColumnSummary | Below is the the instruction that describes the task:
### Input:
Return default mdata map for GradebookColumnSummary
### Response:
def get_gradebook_column_summary_mdata():
"""Return default mdata map for GradebookColumnSummary"""
return {
'gradebook_column': {
'element_label': {
... |
def _get_csrf_token(self):
"""Return the CSRF Token of easyname login form."""
from bs4 import BeautifulSoup
home_response = self.session.get(self.URLS['login'])
self._log('Home', home_response)
assert home_response.status_code == 200, \
'Could not load Easyname login... | Return the CSRF Token of easyname login form. | Below is the the instruction that describes the task:
### Input:
Return the CSRF Token of easyname login form.
### Response:
def _get_csrf_token(self):
"""Return the CSRF Token of easyname login form."""
from bs4 import BeautifulSoup
home_response = self.session.get(self.URLS['login'])
... |
def setidd(cls, iddinfo, iddindex, block, idd_version):
"""Set the IDD to be used by eppy.
Parameters
----------
iddinfo : list
Comments and metadata about fields in the IDD.
block : list
Field names in the IDD.
"""
cls.idd_info = iddinfo... | Set the IDD to be used by eppy.
Parameters
----------
iddinfo : list
Comments and metadata about fields in the IDD.
block : list
Field names in the IDD. | Below is the the instruction that describes the task:
### Input:
Set the IDD to be used by eppy.
Parameters
----------
iddinfo : list
Comments and metadata about fields in the IDD.
block : list
Field names in the IDD.
### Response:
def setidd(cls, iddinfo, i... |
def _set_resource_monitor(self, v, load=False):
"""
Setter method for resource_monitor, mapped from YANG variable /resource_monitor (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_resource_monitor is considered as a private
method. Backends looking to pop... | Setter method for resource_monitor, mapped from YANG variable /resource_monitor (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_resource_monitor is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._se... | Below is the the instruction that describes the task:
### Input:
Setter method for resource_monitor, mapped from YANG variable /resource_monitor (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_resource_monitor is considered as a private
method. Backends looki... |
def get_save_request_from_user(self):
"""Queries user if grid should be saved"""
msg = _("There are unsaved changes.\nDo you want to save?")
dlg = GMD.GenericMessageDialog(
self.main_window, msg,
_("Unsaved changes"), wx.YES_NO | wx.ICON_QUESTION | wx.CANCEL)
s... | Queries user if grid should be saved | Below is the the instruction that describes the task:
### Input:
Queries user if grid should be saved
### Response:
def get_save_request_from_user(self):
"""Queries user if grid should be saved"""
msg = _("There are unsaved changes.\nDo you want to save?")
dlg = GMD.GenericMessageDialog(
... |
def _create_data(data, active_chan, ref_chan=[], grp_name=None):
"""Create data after montage.
Parameters
----------
data : instance of ChanTime
the raw data
active_chan : list of str
the channel(s) of interest, without reference or group
ref_chan : list of str
reference... | Create data after montage.
Parameters
----------
data : instance of ChanTime
the raw data
active_chan : list of str
the channel(s) of interest, without reference or group
ref_chan : list of str
reference channel(s), without group
grp_name : str
name of channel gr... | Below is the the instruction that describes the task:
### Input:
Create data after montage.
Parameters
----------
data : instance of ChanTime
the raw data
active_chan : list of str
the channel(s) of interest, without reference or group
ref_chan : list of str
reference ch... |
def open_filezip(file_path, find_str):
"""
Open the wrapped file.
Read directly from the zip without extracting its content.
"""
if zipfile.is_zipfile(file_path):
zipf = zipfile.ZipFile(file_path)
interesting_files = [f for f in zipf.infolist() if find_str in f]
for inside_f... | Open the wrapped file.
Read directly from the zip without extracting its content. | Below is the the instruction that describes the task:
### Input:
Open the wrapped file.
Read directly from the zip without extracting its content.
### Response:
def open_filezip(file_path, find_str):
"""
Open the wrapped file.
Read directly from the zip without extracting its content.
"""
i... |
def remove_child(self, *sprites):
"""Remove one or several :class:`Sprite` sprites from scene """
# first drop focus
scene = self.get_scene()
if scene:
child_sprites = list(self.all_child_sprites())
if scene._focus_sprite in child_sprites:
scene.... | Remove one or several :class:`Sprite` sprites from scene | Below is the the instruction that describes the task:
### Input:
Remove one or several :class:`Sprite` sprites from scene
### Response:
def remove_child(self, *sprites):
"""Remove one or several :class:`Sprite` sprites from scene """
# first drop focus
scene = self.get_scene()
if ... |
def mat2quat(rmat, precise=False):
"""
Converts given rotation matrix to quaternion.
Args:
rmat: 3x3 rotation matrix
precise: If isprecise is True, the input matrix is assumed to be a precise
rotation matrix and a faster algorithm is used.
Returns:
vec4 float quate... | Converts given rotation matrix to quaternion.
Args:
rmat: 3x3 rotation matrix
precise: If isprecise is True, the input matrix is assumed to be a precise
rotation matrix and a faster algorithm is used.
Returns:
vec4 float quaternion angles | Below is the the instruction that describes the task:
### Input:
Converts given rotation matrix to quaternion.
Args:
rmat: 3x3 rotation matrix
precise: If isprecise is True, the input matrix is assumed to be a precise
rotation matrix and a faster algorithm is used.
Returns:
... |
def account_delete(request, username,
template_name=accounts_settings.ACCOUNTS_PROFILE_DETAIL_TEMPLATE,
extra_context=None, **kwargs):
"""
Delete an account.
"""
user = get_object_or_404(get_user_model(),
username__iexact=username)
user.is_active = False
... | Delete an account. | Below is the the instruction that describes the task:
### Input:
Delete an account.
### Response:
def account_delete(request, username,
template_name=accounts_settings.ACCOUNTS_PROFILE_DETAIL_TEMPLATE,
extra_context=None, **kwargs):
"""
Delete an account.
"""
user = get_object_or_40... |
def _launch_remote(self, host, config_port, race, name, interface):
"""Make sure this stays synced with bin/play_vs_agent.py."""
self._tcp_conn, settings = tcp_client(Addr(host, config_port))
self._map_name = settings["map_name"]
if settings["remote"]:
self._udp_sock = udp_server(
Addr... | Make sure this stays synced with bin/play_vs_agent.py. | Below is the the instruction that describes the task:
### Input:
Make sure this stays synced with bin/play_vs_agent.py.
### Response:
def _launch_remote(self, host, config_port, race, name, interface):
"""Make sure this stays synced with bin/play_vs_agent.py."""
self._tcp_conn, settings = tcp_client(Addr(h... |
def clear_instances(self, instances=None):
"""Request to "remove" the given instances list or all if not provided
:param instances: instances to remove (all instances are removed if None)
:type instances:
:return: None
"""
if instances is None:
instances = se... | Request to "remove" the given instances list or all if not provided
:param instances: instances to remove (all instances are removed if None)
:type instances:
:return: None | Below is the the instruction that describes the task:
### Input:
Request to "remove" the given instances list or all if not provided
:param instances: instances to remove (all instances are removed if None)
:type instances:
:return: None
### Response:
def clear_instances(self, instances=No... |
def extract_paths(self, paths, ignore_nopath):
"""
Extract the given paths from the domain
Attempt to extract all files defined in ``paths`` with the method
defined in :func:`~lago.plugins.vm.VMProviderPlugin.extract_paths`,
if it fails, and `guestfs` is available it will try ex... | Extract the given paths from the domain
Attempt to extract all files defined in ``paths`` with the method
defined in :func:`~lago.plugins.vm.VMProviderPlugin.extract_paths`,
if it fails, and `guestfs` is available it will try extracting the
files with guestfs.
Args:
... | Below is the the instruction that describes the task:
### Input:
Extract the given paths from the domain
Attempt to extract all files defined in ``paths`` with the method
defined in :func:`~lago.plugins.vm.VMProviderPlugin.extract_paths`,
if it fails, and `guestfs` is available it will try ... |
def lag_plot(series, lag=1, ax=None, **kwds):
"""Lag plot for time series.
Parameters
----------
series : Time series
lag : lag of the scatter plot, default 1
ax : Matplotlib axis object, optional
kwds : Matplotlib scatter method keyword arguments, optional
Returns
-------
clas... | Lag plot for time series.
Parameters
----------
series : Time series
lag : lag of the scatter plot, default 1
ax : Matplotlib axis object, optional
kwds : Matplotlib scatter method keyword arguments, optional
Returns
-------
class:`matplotlib.axis.Axes` | Below is the the instruction that describes the task:
### Input:
Lag plot for time series.
Parameters
----------
series : Time series
lag : lag of the scatter plot, default 1
ax : Matplotlib axis object, optional
kwds : Matplotlib scatter method keyword arguments, optional
Returns
... |
def p_parameter_4(p):
"""parameter_4 : qualifierList objectRef parameterName
| qualifierList objectRef parameterName array
"""
args = {}
if len(p) == 5:
args['is_array'] = True
args['array_size'] = p[4]
quals = OrderedDict([(x.name, x) for x in p[1]]... | parameter_4 : qualifierList objectRef parameterName
| qualifierList objectRef parameterName array | Below is the the instruction that describes the task:
### Input:
parameter_4 : qualifierList objectRef parameterName
| qualifierList objectRef parameterName array
### Response:
def p_parameter_4(p):
"""parameter_4 : qualifierList objectRef parameterName
| qualifierList obj... |
def _extract_calibration(xroot):
"""Extract AHRS calibration information from XML root.
Parameters
----------
xroot: XML root
Returns
-------
Aoff: numpy.array with shape(3,)
Arot: numpy.array with shape(3,3)
Hoff: numpy.array with shape(3,)
Hrot: numpy.array with shape(3,3)
... | Extract AHRS calibration information from XML root.
Parameters
----------
xroot: XML root
Returns
-------
Aoff: numpy.array with shape(3,)
Arot: numpy.array with shape(3,3)
Hoff: numpy.array with shape(3,)
Hrot: numpy.array with shape(3,3) | Below is the the instruction that describes the task:
### Input:
Extract AHRS calibration information from XML root.
Parameters
----------
xroot: XML root
Returns
-------
Aoff: numpy.array with shape(3,)
Arot: numpy.array with shape(3,3)
Hoff: numpy.array with shape(3,)
Hrot: ... |
def rectangle(self, x1, y1, x2, y2, color="black", outline=False, outline_color="black"):
"""
Draws a rectangle between 2 points
:param int x1:
The x position of the starting point.
:param int y1:
The y position of the starting point.
:param int x2:
... | Draws a rectangle between 2 points
:param int x1:
The x position of the starting point.
:param int y1:
The y position of the starting point.
:param int x2:
The x position of the end point.
:param int y2:
The y position of the end point.... | Below is the the instruction that describes the task:
### Input:
Draws a rectangle between 2 points
:param int x1:
The x position of the starting point.
:param int y1:
The y position of the starting point.
:param int x2:
The x position of the end point.... |
def _execute_handler(self, p_command, p_todo_id=None, p_output=None):
"""
Executes a command, given as a string.
"""
p_output = p_output or self._output
self._console_visible = False
self._last_cmd = (p_command, p_output == self._output)
try:
p_comma... | Executes a command, given as a string. | Below is the the instruction that describes the task:
### Input:
Executes a command, given as a string.
### Response:
def _execute_handler(self, p_command, p_todo_id=None, p_output=None):
"""
Executes a command, given as a string.
"""
p_output = p_output or self._output
self... |
def add_section(self, alias, section):
"""
Add a sub-section to this section.
"""
if not isinstance(alias, six.string_types):
raise TypeError('Section name must be a string, got a {!r}'.format(type(alias)))
self._tree[alias] = section
if self.settings.str_pa... | Add a sub-section to this section. | Below is the the instruction that describes the task:
### Input:
Add a sub-section to this section.
### Response:
def add_section(self, alias, section):
"""
Add a sub-section to this section.
"""
if not isinstance(alias, six.string_types):
raise TypeError('Section name m... |
def authenticate_connection(username, password, db=None):
"""
Authenticates the current database connection with the passed username
and password. If the database connection uses all default parameters,
this can be called without connect_to_database. Otherwise, it should
be preceded by a connect_t... | Authenticates the current database connection with the passed username
and password. If the database connection uses all default parameters,
this can be called without connect_to_database. Otherwise, it should
be preceded by a connect_to_database call.
@param username: the username with which you... | Below is the the instruction that describes the task:
### Input:
Authenticates the current database connection with the passed username
and password. If the database connection uses all default parameters,
this can be called without connect_to_database. Otherwise, it should
be preceded by a connect_to... |
def get_for_objects(self, queryset):
"""
Get log entries for the objects in the specified queryset.
:param queryset: The queryset to get the log entries for.
:type queryset: QuerySet
:return: The LogEntry objects for the objects in the given queryset.
:rtype: QuerySet
... | Get log entries for the objects in the specified queryset.
:param queryset: The queryset to get the log entries for.
:type queryset: QuerySet
:return: The LogEntry objects for the objects in the given queryset.
:rtype: QuerySet | Below is the the instruction that describes the task:
### Input:
Get log entries for the objects in the specified queryset.
:param queryset: The queryset to get the log entries for.
:type queryset: QuerySet
:return: The LogEntry objects for the objects in the given queryset.
:rtype:... |
def _add_keyword_low(self, kwpath, value, params):
"""Adds keyword"""
if len(kwpath) == 1:
params[kwpath[0]] = value
elif kwpath[0] not in params.keys():
new_subsection = {}
params[kwpath[0]] = new_subsection
self._add_keyword_low(kwpath[1:], value... | Adds keyword | Below is the the instruction that describes the task:
### Input:
Adds keyword
### Response:
def _add_keyword_low(self, kwpath, value, params):
"""Adds keyword"""
if len(kwpath) == 1:
params[kwpath[0]] = value
elif kwpath[0] not in params.keys():
new_subsection = {}
... |
def set(self, value):
'''
Atomically sets the value to `value`.
:param value: The value to set.
'''
with self._lock.exclusive:
self._value = value
return value | Atomically sets the value to `value`.
:param value: The value to set. | Below is the the instruction that describes the task:
### Input:
Atomically sets the value to `value`.
:param value: The value to set.
### Response:
def set(self, value):
'''
Atomically sets the value to `value`.
:param value: The value to set.
'''
with self._lock.... |
def unpack(self, buff, offset=0):
"""Unpack *buff* into this object.
This method will convert a binary data into a readable value according
to the attribute format.
Args:
buff (bytes): Binary buffer.
offset (int): Where to begin unpacking.
Raises:
... | Unpack *buff* into this object.
This method will convert a binary data into a readable value according
to the attribute format.
Args:
buff (bytes): Binary buffer.
offset (int): Where to begin unpacking.
Raises:
:exc:`~.exceptions.UnpackException`: I... | Below is the the instruction that describes the task:
### Input:
Unpack *buff* into this object.
This method will convert a binary data into a readable value according
to the attribute format.
Args:
buff (bytes): Binary buffer.
offset (int): Where to begin unpacking... |
def get_config_from_env(cls):
"""
.. deprecated:: 2.5.3
Gets configuration out of environment.
Returns list of dicts - list of namenode representations
"""
core_path = os.path.join(os.environ['HADOOP_HOME'], 'conf', 'core-site.xml')
core_configs = cls.read_core_c... | .. deprecated:: 2.5.3
Gets configuration out of environment.
Returns list of dicts - list of namenode representations | Below is the the instruction that describes the task:
### Input:
.. deprecated:: 2.5.3
Gets configuration out of environment.
Returns list of dicts - list of namenode representations
### Response:
def get_config_from_env(cls):
"""
.. deprecated:: 2.5.3
Gets configuration ou... |
def player_stats(game_id):
"""Return dictionary of individual stats of a game with matching id.
The additional pitching/batting is mostly the same stats, except it
contains some useful stats such as groundouts/flyouts per pitcher
(go/ao). MLB decided to have two box score files, thus we return... | Return dictionary of individual stats of a game with matching id.
The additional pitching/batting is mostly the same stats, except it
contains some useful stats such as groundouts/flyouts per pitcher
(go/ao). MLB decided to have two box score files, thus we return the
data from both. | Below is the the instruction that describes the task:
### Input:
Return dictionary of individual stats of a game with matching id.
The additional pitching/batting is mostly the same stats, except it
contains some useful stats such as groundouts/flyouts per pitcher
(go/ao). MLB decided to have ... |
def fromstring(cls, ptb_string, namespace='ptb', precedence=False,
ignore_traces=True):
"""create a PTBDocumentGraph from a string containing PTB parses."""
temp = tempfile.NamedTemporaryFile(delete=False)
temp.write(ptb_string)
temp.close()
ptb_docgraph = cls(p... | create a PTBDocumentGraph from a string containing PTB parses. | Below is the the instruction that describes the task:
### Input:
create a PTBDocumentGraph from a string containing PTB parses.
### Response:
def fromstring(cls, ptb_string, namespace='ptb', precedence=False,
ignore_traces=True):
"""create a PTBDocumentGraph from a string containing PTB p... |
def equals_exact(self, other, tolerance):
""" invariant to crs. """
# This method cannot be delegated because it has an extra parameter
return self._shape.equals_exact(other.get_shape(self.crs), tolerance=tolerance) | invariant to crs. | Below is the the instruction that describes the task:
### Input:
invariant to crs.
### Response:
def equals_exact(self, other, tolerance):
""" invariant to crs. """
# This method cannot be delegated because it has an extra parameter
return self._shape.equals_exact(other.get_shape(self.crs),... |
def on_play_speed(self, *args):
"""Change the interval at which ``self.play`` is called to match my
current ``play_speed``.
"""
Clock.unschedule(self.play)
Clock.schedule_interval(self.play, 1.0 / self.play_speed) | Change the interval at which ``self.play`` is called to match my
current ``play_speed``. | Below is the the instruction that describes the task:
### Input:
Change the interval at which ``self.play`` is called to match my
current ``play_speed``.
### Response:
def on_play_speed(self, *args):
"""Change the interval at which ``self.play`` is called to match my
current ``play_speed``.... |
def make_pushable(collector, **kwargs):
"""Make only the pushable images and their dependencies"""
configuration = collector.configuration
configuration["harpoon"].do_push = True
configuration["harpoon"].only_pushable = True
make_all(collector, **kwargs) | Make only the pushable images and their dependencies | Below is the the instruction that describes the task:
### Input:
Make only the pushable images and their dependencies
### Response:
def make_pushable(collector, **kwargs):
"""Make only the pushable images and their dependencies"""
configuration = collector.configuration
configuration["harpoon"].do_push... |
def abort():
"""..."""
uid_list = list(server_runner.active_execution_responses.keys())
while len(uid_list) > 0:
uid = uid_list.pop()
response = server_runner.active_execution_responses.get(uid)
if not response:
continue
try:
del server_runner.activ... | ... | Below is the the instruction that describes the task:
### Input:
...
### Response:
def abort():
"""..."""
uid_list = list(server_runner.active_execution_responses.keys())
while len(uid_list) > 0:
uid = uid_list.pop()
response = server_runner.active_execution_responses.get(uid)
... |
def linsrgb_to_srgb (linsrgb):
"""Convert physically linear RGB values into sRGB ones. The transform is
uniform in the components, so *linsrgb* can be of any shape.
*linsrgb* values should range between 0 and 1, inclusively.
"""
# From Wikipedia, but easy analogue to the above.
gamma = 1.055 *... | Convert physically linear RGB values into sRGB ones. The transform is
uniform in the components, so *linsrgb* can be of any shape.
*linsrgb* values should range between 0 and 1, inclusively. | Below is the the instruction that describes the task:
### Input:
Convert physically linear RGB values into sRGB ones. The transform is
uniform in the components, so *linsrgb* can be of any shape.
*linsrgb* values should range between 0 and 1, inclusively.
### Response:
def linsrgb_to_srgb (linsrgb):
"... |
def cache_data(self, cache_directory: str) -> None:
"""
When you call this method, we will use this directory to store a cache of already-processed
``Instances`` in every file passed to :func:`read`, serialized as one string-formatted
``Instance`` per line. If the cache file for a given... | When you call this method, we will use this directory to store a cache of already-processed
``Instances`` in every file passed to :func:`read`, serialized as one string-formatted
``Instance`` per line. If the cache file for a given ``file_path`` exists, we read the
``Instances`` from the cache ... | Below is the the instruction that describes the task:
### Input:
When you call this method, we will use this directory to store a cache of already-processed
``Instances`` in every file passed to :func:`read`, serialized as one string-formatted
``Instance`` per line. If the cache file for a given ``... |
def formatted(self):
"""str: The IBAN formatted in blocks of 4 digits."""
return ' '.join(self.compact[i:i + 4] for i in range(0, len(self.compact), 4)) | str: The IBAN formatted in blocks of 4 digits. | Below is the the instruction that describes the task:
### Input:
str: The IBAN formatted in blocks of 4 digits.
### Response:
def formatted(self):
"""str: The IBAN formatted in blocks of 4 digits."""
return ' '.join(self.compact[i:i + 4] for i in range(0, len(self.compact), 4)) |
def uses_base_tear_down(cls):
"""Checks whether the tearDown method is the BasePlug implementation."""
this_tear_down = getattr(cls, 'tearDown')
base_tear_down = getattr(BasePlug, 'tearDown')
return this_tear_down.__code__ is base_tear_down.__code__ | Checks whether the tearDown method is the BasePlug implementation. | Below is the the instruction that describes the task:
### Input:
Checks whether the tearDown method is the BasePlug implementation.
### Response:
def uses_base_tear_down(cls):
"""Checks whether the tearDown method is the BasePlug implementation."""
this_tear_down = getattr(cls, 'tearDown')
base_tear_do... |
def _process_protocol_v2(self, argv, ifile, ofile):
""" Processes records on the `input stream optionally writing records to the output stream.
:param ifile: Input file object.
:type ifile: file or InputType
:param ofile: Output file object.
:type ofile: file or OutputType
... | Processes records on the `input stream optionally writing records to the output stream.
:param ifile: Input file object.
:type ifile: file or InputType
:param ofile: Output file object.
:type ofile: file or OutputType
:return: :const:`None` | Below is the the instruction that describes the task:
### Input:
Processes records on the `input stream optionally writing records to the output stream.
:param ifile: Input file object.
:type ifile: file or InputType
:param ofile: Output file object.
:type ofile: file or OutputType... |
def image_channel_compress_top(body_output, targets, model_hparams, vocab_size):
"""Transforms body output to return logits.
Args:
body_output: Tensor of shape [batch, img_len, img_len, depth].
targets:
model_hparams: HParams, model hyperparmeters.
vocab_size: int, vocabulary size.
Returns:
... | Transforms body output to return logits.
Args:
body_output: Tensor of shape [batch, img_len, img_len, depth].
targets:
model_hparams: HParams, model hyperparmeters.
vocab_size: int, vocabulary size.
Returns:
Tensor of shape [batch, img_len, img_len, channels, vocab_size]. | Below is the the instruction that describes the task:
### Input:
Transforms body output to return logits.
Args:
body_output: Tensor of shape [batch, img_len, img_len, depth].
targets:
model_hparams: HParams, model hyperparmeters.
vocab_size: int, vocabulary size.
Returns:
Tensor of shape [... |
def set_reboot_required_witnessed():
'''
This function is used to remember that an event indicating that a reboot is
required was witnessed. This function writes to a temporary filesystem so
the event gets cleared upon reboot.
Returns:
bool: ``True`` if successful, otherwise ``False``
... | This function is used to remember that an event indicating that a reboot is
required was witnessed. This function writes to a temporary filesystem so
the event gets cleared upon reboot.
Returns:
bool: ``True`` if successful, otherwise ``False``
.. code-block:: bash
salt '*' system.set... | Below is the the instruction that describes the task:
### Input:
This function is used to remember that an event indicating that a reboot is
required was witnessed. This function writes to a temporary filesystem so
the event gets cleared upon reboot.
Returns:
bool: ``True`` if successful, other... |
def remove(self,
package,
echo=None,
options=None,
timeout=shutit_global.shutit_global_object.default_timeout,
note=None):
"""Distro-independent remove function.
Takes a package name and runs relevant remove function.
@param package: Package to remove,... | Distro-independent remove function.
Takes a package name and runs relevant remove function.
@param package: Package to remove, which is run through package_map.
@param options: Dict of options to pass to the remove command,
mapped by install_type.
@param timeout: See send(). Default: 3600... | Below is the the instruction that describes the task:
### Input:
Distro-independent remove function.
Takes a package name and runs relevant remove function.
@param package: Package to remove, which is run through package_map.
@param options: Dict of options to pass to the remove command,
... |
def parse_date(datestring, default_timezone=UTC):
"""Parses ISO 8601 dates into datetime objects
The timezone is parsed from the date string. However it is quite common to
have dates without a timezone (not strictly correct). In this case the
default timezone specified in default_timezone is used. ... | Parses ISO 8601 dates into datetime objects
The timezone is parsed from the date string. However it is quite common to
have dates without a timezone (not strictly correct). In this case the
default timezone specified in default_timezone is used. This is UTC by
default. | Below is the the instruction that describes the task:
### Input:
Parses ISO 8601 dates into datetime objects
The timezone is parsed from the date string. However it is quite common to
have dates without a timezone (not strictly correct). In this case the
default timezone specified in default_timezo... |
def _strip_ctype(name, ctype, protocol=2):
"""Strip the ctype from a channel name for the given nds server version
This is needed because NDS1 servers store trend channels _including_
the suffix, but not raw channels, and NDS2 doesn't do this.
"""
# parse channel type from name (e.g. 'L1:GDS-CALIB_... | Strip the ctype from a channel name for the given nds server version
This is needed because NDS1 servers store trend channels _including_
the suffix, but not raw channels, and NDS2 doesn't do this. | Below is the the instruction that describes the task:
### Input:
Strip the ctype from a channel name for the given nds server version
This is needed because NDS1 servers store trend channels _including_
the suffix, but not raw channels, and NDS2 doesn't do this.
### Response:
def _strip_ctype(name, ctype,... |
def make_timestamp(ts: OptTs = None) -> int:
"""Create zipkin timestamp in microseconds, or convert available one
from second. Useful when user supplies ts from time.time() call.
"""
ts = ts if ts is not None else time.time()
return int(ts * 1000 * 1000) | Create zipkin timestamp in microseconds, or convert available one
from second. Useful when user supplies ts from time.time() call. | Below is the the instruction that describes the task:
### Input:
Create zipkin timestamp in microseconds, or convert available one
from second. Useful when user supplies ts from time.time() call.
### Response:
def make_timestamp(ts: OptTs = None) -> int:
"""Create zipkin timestamp in microseconds, or conve... |
def dispatch(intent_request):
"""
Called when the user specifies an intent for this bot.
"""
logger.debug('dispatch userId={}, intentName={}'.format(intent_request['userId'], intent_request['currentIntent']['name']))
intent_name = intent_request['currentIntent']['name']
# Dispatch to your bot... | Called when the user specifies an intent for this bot. | Below is the the instruction that describes the task:
### Input:
Called when the user specifies an intent for this bot.
### Response:
def dispatch(intent_request):
"""
Called when the user specifies an intent for this bot.
"""
logger.debug('dispatch userId={}, intentName={}'.format(intent_request[... |
def find_one(self, *args, **kwargs):
"""Same as :meth:`pymongo.collection.Collection.find_one`, except
it returns the right document class.
"""
data = super(Collection, self).find_one(*args, **kwargs)
if data:
return self.document_class(data)
return None | Same as :meth:`pymongo.collection.Collection.find_one`, except
it returns the right document class. | Below is the the instruction that describes the task:
### Input:
Same as :meth:`pymongo.collection.Collection.find_one`, except
it returns the right document class.
### Response:
def find_one(self, *args, **kwargs):
"""Same as :meth:`pymongo.collection.Collection.find_one`, except
it return... |
def E(self,*args,**kwargs):
"""
NAME:
E
PURPOSE:
calculate the energy
INPUT:
t - (optional) time at which to get the radius
pot= linearPotential instance or list thereof
OUTPUT:
energy
HISTORY:
2010-09-15 -... | NAME:
E
PURPOSE:
calculate the energy
INPUT:
t - (optional) time at which to get the radius
pot= linearPotential instance or list thereof
OUTPUT:
energy
HISTORY:
2010-09-15 - Written - Bovy (NYU) | Below is the the instruction that describes the task:
### Input:
NAME:
E
PURPOSE:
calculate the energy
INPUT:
t - (optional) time at which to get the radius
pot= linearPotential instance or list thereof
OUTPUT:
energy
HISTORY:
... |
def _unique(list_of_dicts):
'''
Returns an unique list of dictionaries given a list that may contain duplicates.
'''
unique_list = []
for ele in list_of_dicts:
if ele not in unique_list:
unique_list.append(ele)
return unique_list | Returns an unique list of dictionaries given a list that may contain duplicates. | Below is the the instruction that describes the task:
### Input:
Returns an unique list of dictionaries given a list that may contain duplicates.
### Response:
def _unique(list_of_dicts):
'''
Returns an unique list of dictionaries given a list that may contain duplicates.
'''
unique_list = []
f... |
def auth_interactive(self, username, handler, event, submethods=''):
"""
response_list = handler(title, instructions, prompt_list)
"""
self.transport.lock.acquire()
try:
self.auth_event = event
self.auth_method = 'keyboard-interactive'
self.use... | response_list = handler(title, instructions, prompt_list) | Below is the the instruction that describes the task:
### Input:
response_list = handler(title, instructions, prompt_list)
### Response:
def auth_interactive(self, username, handler, event, submethods=''):
"""
response_list = handler(title, instructions, prompt_list)
"""
self.transp... |
def ggsave(name, plot, data=None, *args, **kwargs):
"""Save a GGStatements object to destination name
@param name output file name. if None, don't run R command
@param kwargs keyword args to pass to ggsave. The following are special
keywords for the python save method
data: a python da... | Save a GGStatements object to destination name
@param name output file name. if None, don't run R command
@param kwargs keyword args to pass to ggsave. The following are special
keywords for the python save method
data: a python data object (list, dict, DataFrame) used to populate
... | Below is the the instruction that describes the task:
### Input:
Save a GGStatements object to destination name
@param name output file name. if None, don't run R command
@param kwargs keyword args to pass to ggsave. The following are special
keywords for the python save method
data: a... |
def alter_database(self, dbname, db):
"""
Parameters:
- dbname
- db
"""
self.send_alter_database(dbname, db)
self.recv_alter_database() | Parameters:
- dbname
- db | Below is the the instruction that describes the task:
### Input:
Parameters:
- dbname
- db
### Response:
def alter_database(self, dbname, db):
"""
Parameters:
- dbname
- db
"""
self.send_alter_database(dbname, db)
self.recv_alter_database() |
async def connect(self):
"""
Connects to Telegram.
"""
await self._sender.connect(self._connection(
self.session.server_address,
self.session.port,
self.session.dc_id,
loop=self._loop,
loggers=self._log,
proxy=self._... | Connects to Telegram. | Below is the the instruction that describes the task:
### Input:
Connects to Telegram.
### Response:
async def connect(self):
"""
Connects to Telegram.
"""
await self._sender.connect(self._connection(
self.session.server_address,
self.session.port,
... |
def new(self, page_name, **dict):
'''
Create a new item with the provided dict information
at the given page_name. Returns the new item.
As of version 2.2 of Redmine, this doesn't seem to function.
'''
self._item_new_path = '/projects/%s/wiki/%s.json' % \
(s... | Create a new item with the provided dict information
at the given page_name. Returns the new item.
As of version 2.2 of Redmine, this doesn't seem to function. | Below is the the instruction that describes the task:
### Input:
Create a new item with the provided dict information
at the given page_name. Returns the new item.
As of version 2.2 of Redmine, this doesn't seem to function.
### Response:
def new(self, page_name, **dict):
'''
Crea... |
def delete(self):
"""
Deletes this record set.
"""
cset = ChangeSet(connection=self.connection, hosted_zone_id=self.zone_id)
cset.add_change('DELETE', self)
return self.connection._change_resource_record_sets(cset) | Deletes this record set. | Below is the the instruction that describes the task:
### Input:
Deletes this record set.
### Response:
def delete(self):
"""
Deletes this record set.
"""
cset = ChangeSet(connection=self.connection, hosted_zone_id=self.zone_id)
cset.add_change('DELETE', self)
retu... |
def _partition_estimators(n_estimators, n_jobs):
"""Private function used to partition estimators between jobs."""
# Compute the number of jobs
if n_jobs == -1:
n_jobs = min(cpu_count(), n_estimators)
else:
n_jobs = min(n_jobs, n_estimators)
# Partition estimators between jobs
... | Private function used to partition estimators between jobs. | Below is the the instruction that describes the task:
### Input:
Private function used to partition estimators between jobs.
### Response:
def _partition_estimators(n_estimators, n_jobs):
"""Private function used to partition estimators between jobs."""
# Compute the number of jobs
if n_jobs == -1:
... |
def update_agent_db_refs(self, agent, agent_text, do_rename=True):
"""Update db_refs of agent using the grounding map
If the grounding map is missing one of the HGNC symbol or Uniprot ID,
attempts to reconstruct one from the other.
Parameters
----------
agent : :py:clas... | Update db_refs of agent using the grounding map
If the grounding map is missing one of the HGNC symbol or Uniprot ID,
attempts to reconstruct one from the other.
Parameters
----------
agent : :py:class:`indra.statements.Agent`
The agent whose db_refs will be updated... | Below is the the instruction that describes the task:
### Input:
Update db_refs of agent using the grounding map
If the grounding map is missing one of the HGNC symbol or Uniprot ID,
attempts to reconstruct one from the other.
Parameters
----------
agent : :py:class:`indra.... |
def get_analog_single(
self, component_info=None, data=None, component_position=None
):
"""Get a single analog data channel."""
components = []
append_components = components.append
for _ in range(component_info.device_count):
component_position, device = QRTPacke... | Get a single analog data channel. | Below is the the instruction that describes the task:
### Input:
Get a single analog data channel.
### Response:
def get_analog_single(
self, component_info=None, data=None, component_position=None
):
"""Get a single analog data channel."""
components = []
append_components = co... |
def get_valid_times_for_job(self, num_job, allow_overlap=True):
""" Get the times for which this job is valid. """
if self.compatibility_mode:
return self.get_valid_times_for_job_legacy(num_job)
else:
return self.get_valid_times_for_job_workflow(num_job,
... | Get the times for which this job is valid. | Below is the the instruction that describes the task:
### Input:
Get the times for which this job is valid.
### Response:
def get_valid_times_for_job(self, num_job, allow_overlap=True):
""" Get the times for which this job is valid. """
if self.compatibility_mode:
return self.get_valid_... |
def middle_frame(obj):
"Only display the (approximately) middle frame of an animated plot"
plot, renderer, fmt = single_frame_plot(obj)
middle_frame = int(len(plot) / 2)
plot.update(middle_frame)
return {'text/html': renderer.html(plot, fmt)} | Only display the (approximately) middle frame of an animated plot | Below is the the instruction that describes the task:
### Input:
Only display the (approximately) middle frame of an animated plot
### Response:
def middle_frame(obj):
"Only display the (approximately) middle frame of an animated plot"
plot, renderer, fmt = single_frame_plot(obj)
middle_frame = int(len... |
def get_all_connected_interfaces():
"""! @brief Returns all the connected devices with a CMSIS-DAPv2 interface."""
# find all cmsis-dap devices
try:
all_devices = usb.core.find(find_all=True, custom_match=HasCmsisDapv2Interface())
except usb.core.NoBackendError:
c... | ! @brief Returns all the connected devices with a CMSIS-DAPv2 interface. | Below is the the instruction that describes the task:
### Input:
! @brief Returns all the connected devices with a CMSIS-DAPv2 interface.
### Response:
def get_all_connected_interfaces():
"""! @brief Returns all the connected devices with a CMSIS-DAPv2 interface."""
# find all cmsis-dap devices
... |
def list_tags(userdata):
"""List all used macros within a UserData script.
:param userdata: The UserData script.
:type userdata: str
"""
macros = re.findall('@(.*?)@', userdata)
logging.info('List of available macros:')
for macro in macros:
logging.in... | List all used macros within a UserData script.
:param userdata: The UserData script.
:type userdata: str | Below is the the instruction that describes the task:
### Input:
List all used macros within a UserData script.
:param userdata: The UserData script.
:type userdata: str
### Response:
def list_tags(userdata):
"""List all used macros within a UserData script.
:param userdata: The U... |
def load(cls, rr, pk):
'''
Retrieves a document from the database, by primary key.
'''
if pk is None:
return None
d = rr.table(cls.table).get(pk).run()
if d is None:
return None
doc = cls(rr, d)
return doc | Retrieves a document from the database, by primary key. | Below is the the instruction that describes the task:
### Input:
Retrieves a document from the database, by primary key.
### Response:
def load(cls, rr, pk):
'''
Retrieves a document from the database, by primary key.
'''
if pk is None:
return None
d = rr.table(c... |
def get_xml(connection, table_names = None):
"""
Construct an XML document tree wrapping around the contents of the
database. On success the return value is a ligolw.LIGO_LW element
containing the tables as children. Arguments are a connection to
to a database, and an optional list of table names to dump. If
t... | Construct an XML document tree wrapping around the contents of the
database. On success the return value is a ligolw.LIGO_LW element
containing the tables as children. Arguments are a connection to
to a database, and an optional list of table names to dump. If
table_names is not provided the set is obtained from... | Below is the the instruction that describes the task:
### Input:
Construct an XML document tree wrapping around the contents of the
database. On success the return value is a ligolw.LIGO_LW element
containing the tables as children. Arguments are a connection to
to a database, and an optional list of table nam... |
def ephemeris(self, **kwargs):
"""Generator giving the propagation of the orbit at different dates
Args:
start (Date)
stop (Date or timedelta)
step (timedelta)
Yield:
Orbit
"""
for orb in self.iter(inclusive=True, **kwargs):
... | Generator giving the propagation of the orbit at different dates
Args:
start (Date)
stop (Date or timedelta)
step (timedelta)
Yield:
Orbit | Below is the the instruction that describes the task:
### Input:
Generator giving the propagation of the orbit at different dates
Args:
start (Date)
stop (Date or timedelta)
step (timedelta)
Yield:
Orbit
### Response:
def ephemeris(self, **kwargs):
... |
def parse_bowtie_stats(self, stats_file):
"""
Parses Bowtie2 stats file, returns series with values.
:param str stats_file: Bowtie2 output file with alignment statistics.
"""
import pandas as pd
stats = pd.Series(index=["readCount", "unpaired", "unaligned", "unique", "mu... | Parses Bowtie2 stats file, returns series with values.
:param str stats_file: Bowtie2 output file with alignment statistics. | Below is the the instruction that describes the task:
### Input:
Parses Bowtie2 stats file, returns series with values.
:param str stats_file: Bowtie2 output file with alignment statistics.
### Response:
def parse_bowtie_stats(self, stats_file):
"""
Parses Bowtie2 stats file, returns serie... |
def refreshWidgets(self):
"""
This function manually refreshed all widgets attached to this simulation.
You want to call this function if any particle data has been manually changed.
"""
if hasattr(self, '_widgets'):
for w in self._widgets:
w.... | This function manually refreshed all widgets attached to this simulation.
You want to call this function if any particle data has been manually changed. | Below is the the instruction that describes the task:
### Input:
This function manually refreshed all widgets attached to this simulation.
You want to call this function if any particle data has been manually changed.
### Response:
def refreshWidgets(self):
"""
This function manual... |
def setColorAlpha(self, fixed=None, proportional=None):
"""
Change the alpha of the current :py:class:`Color`.
:param fixed: Set the absolute 0-1 value of the alpha.
:param proportional: Set the relative value of the alpha (Es: If the current alpha is 0.8, a proportional value of 0.5 will set the final value... | Change the alpha of the current :py:class:`Color`.
:param fixed: Set the absolute 0-1 value of the alpha.
:param proportional: Set the relative value of the alpha (Es: If the current alpha is 0.8, a proportional value of 0.5 will set the final value to 0.4).
:rtype: Nothing. | Below is the the instruction that describes the task:
### Input:
Change the alpha of the current :py:class:`Color`.
:param fixed: Set the absolute 0-1 value of the alpha.
:param proportional: Set the relative value of the alpha (Es: If the current alpha is 0.8, a proportional value of 0.5 will set the final ... |
def from_bytes(cls, b):
"""Create an APNG from raw bytes.
:arg bytes b: The raw bytes of the APNG file.
:rtype: APNG
"""
hdr = None
head_chunks = []
end = ("IEND", make_chunk("IEND", b""))
frame_chunks = []
frames = []
num_plays = 0
frame_has_head_chunks = False
control = None
for ... | Create an APNG from raw bytes.
:arg bytes b: The raw bytes of the APNG file.
:rtype: APNG | Below is the the instruction that describes the task:
### Input:
Create an APNG from raw bytes.
:arg bytes b: The raw bytes of the APNG file.
:rtype: APNG
### Response:
def from_bytes(cls, b):
"""Create an APNG from raw bytes.
:arg bytes b: The raw bytes of the APNG file.
:rtype: APNG
"""
hdr =... |
def parent(self, parent):
""" Parents
:param parent: Parent to set for the object
:type parent: Collection
:return:
"""
self._parent = parent
self.graph.add(
(self.asNode(), RDF_NAMESPACES.CAPITAINS.parent, parent.asNode())
)
parent._a... | Parents
:param parent: Parent to set for the object
:type parent: Collection
:return: | Below is the the instruction that describes the task:
### Input:
Parents
:param parent: Parent to set for the object
:type parent: Collection
:return:
### Response:
def parent(self, parent):
""" Parents
:param parent: Parent to set for the object
:type parent: Coll... |
def cdr(ol,**kwargs):
'''
from elist.elist import *
ol=[1,2,3,4]
id(ol)
new = cdr(ol)
new
id(new)
####
ol=[1,2,3,4]
id(ol)
rslt = cdr(ol,mode="original")
rslt
id(rslt)
'''
if('mode' in kwargs):
mode = kwa... | from elist.elist import *
ol=[1,2,3,4]
id(ol)
new = cdr(ol)
new
id(new)
####
ol=[1,2,3,4]
id(ol)
rslt = cdr(ol,mode="original")
rslt
id(rslt) | Below is the the instruction that describes the task:
### Input:
from elist.elist import *
ol=[1,2,3,4]
id(ol)
new = cdr(ol)
new
id(new)
####
ol=[1,2,3,4]
id(ol)
rslt = cdr(ol,mode="original")
rslt
id(rslt)
### Response:
def cd... |
def cmd_work(self, connection, sender, target, payload):
"""
Does some job
"""
connection.action(target, "is doing something...")
time.sleep(int(payload or "5"))
connection.action(target, "has finished !")
connection.privmsg(target, "My answer is: 42.") | Does some job | Below is the the instruction that describes the task:
### Input:
Does some job
### Response:
def cmd_work(self, connection, sender, target, payload):
"""
Does some job
"""
connection.action(target, "is doing something...")
time.sleep(int(payload or "5"))
connection.a... |
def modpath_all(module, entry_point):
"""
Provides the raw __path__. Incompatible with PEP 302-based import
hooks and incompatible with zip_safe packages.
Deprecated. Will be removed by calmjs-4.0.
"""
module_paths = getattr(module, '__path__', [])
if not module_paths:
logger.war... | Provides the raw __path__. Incompatible with PEP 302-based import
hooks and incompatible with zip_safe packages.
Deprecated. Will be removed by calmjs-4.0. | Below is the the instruction that describes the task:
### Input:
Provides the raw __path__. Incompatible with PEP 302-based import
hooks and incompatible with zip_safe packages.
Deprecated. Will be removed by calmjs-4.0.
### Response:
def modpath_all(module, entry_point):
"""
Provides the raw __... |
def close(self):
"""Close the stream."""
self.flush()
if self._myfd is not None:
self._myfd.close()
self._myfd = None | Close the stream. | Below is the the instruction that describes the task:
### Input:
Close the stream.
### Response:
def close(self):
"""Close the stream."""
self.flush()
if self._myfd is not None:
self._myfd.close()
self._myfd = None |
def rouge_2(hypotheses, references):
"""
Calculate ROUGE-2 F1, precision, recall scores
"""
rouge_2 = [
rouge_n([hyp], [ref], 2) for hyp, ref in zip(hypotheses, references)
]
rouge_2_f, _, _ = map(np.mean, zip(*rouge_2))
return rouge_2_f | Calculate ROUGE-2 F1, precision, recall scores | Below is the the instruction that describes the task:
### Input:
Calculate ROUGE-2 F1, precision, recall scores
### Response:
def rouge_2(hypotheses, references):
"""
Calculate ROUGE-2 F1, precision, recall scores
"""
rouge_2 = [
rouge_n([hyp], [ref], 2) for hyp, ref in zip(hypotheses, refe... |
def to_lal_type_str(pytype):
"""Convert the input python type to a LAL type string
Examples
--------
To convert a python type:
>>> from gwpy.utils.lal import to_lal_type_str
>>> to_lal_type_str(float)
'REAL8'
To convert a `numpy.dtype`:
>>> import numpy
>>> to_lal_type_str(nu... | Convert the input python type to a LAL type string
Examples
--------
To convert a python type:
>>> from gwpy.utils.lal import to_lal_type_str
>>> to_lal_type_str(float)
'REAL8'
To convert a `numpy.dtype`:
>>> import numpy
>>> to_lal_type_str(numpy.dtype('uint32'))
'UINT4'
... | Below is the the instruction that describes the task:
### Input:
Convert the input python type to a LAL type string
Examples
--------
To convert a python type:
>>> from gwpy.utils.lal import to_lal_type_str
>>> to_lal_type_str(float)
'REAL8'
To convert a `numpy.dtype`:
>>> import... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.