code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _itodq(self, n):
"""Convert long to dotquad or hextet."""
if self.v == 4:
return '.'.join(map(str, [
(n >> 24) & 0xff,
(n >> 16) & 0xff,
(n >> 8) & 0xff,
n & 0xff,
]))
else:
n = '%032x' % n
... | Convert long to dotquad or hextet. | Below is the the instruction that describes the task:
### Input:
Convert long to dotquad or hextet.
### Response:
def _itodq(self, n):
"""Convert long to dotquad or hextet."""
if self.v == 4:
return '.'.join(map(str, [
(n >> 24) & 0xff,
(n >> 16) & 0xff,
... |
def start_output (self):
"""Write start of checking info as xml comment."""
super(SitemapXmlLogger, self).start_output()
self.xml_start_output()
attrs = {u"xmlns": u"http://www.sitemaps.org/schemas/sitemap/0.9"}
self.xml_starttag(u'urlset', attrs)
self.flush() | Write start of checking info as xml comment. | Below is the the instruction that describes the task:
### Input:
Write start of checking info as xml comment.
### Response:
def start_output (self):
"""Write start of checking info as xml comment."""
super(SitemapXmlLogger, self).start_output()
self.xml_start_output()
attrs = {u"xml... |
def merging_cli(debug=False):
"""
simple commandline interface of the merging module.
This function is called when you use the ``discoursegraphs`` application
directly on the command line.
"""
parser = argparse.ArgumentParser()
parser.add_argument('-t', '--tiger-file',
... | simple commandline interface of the merging module.
This function is called when you use the ``discoursegraphs`` application
directly on the command line. | Below is the the instruction that describes the task:
### Input:
simple commandline interface of the merging module.
This function is called when you use the ``discoursegraphs`` application
directly on the command line.
### Response:
def merging_cli(debug=False):
"""
simple commandline interface o... |
def perform_exit():
"""perform_exit
Handling at-the-exit events
---------------------------
This will cleanup each worker process which
could be in the middle of a request/sleep/block
action. This has been tested on python 3 with
Celery and single processes.
"""
if SPLUNK_DEBUG:
... | perform_exit
Handling at-the-exit events
---------------------------
This will cleanup each worker process which
could be in the middle of a request/sleep/block
action. This has been tested on python 3 with
Celery and single processes. | Below is the the instruction that describes the task:
### Input:
perform_exit
Handling at-the-exit events
---------------------------
This will cleanup each worker process which
could be in the middle of a request/sleep/block
action. This has been tested on python 3 with
Celery and single ... |
def _populate_profile_flags_from_dn_regex(self, profile):
"""
Populate the given profile object flags from AUTH_LDAP_PROFILE_FLAGS_BY_DN_REGEX.
Returns True if the profile was modified
"""
save_profile = True
for field, regex in self.settings.PROFILE_FLAGS_BY_DN_REGEX.ite... | Populate the given profile object flags from AUTH_LDAP_PROFILE_FLAGS_BY_DN_REGEX.
Returns True if the profile was modified | Below is the the instruction that describes the task:
### Input:
Populate the given profile object flags from AUTH_LDAP_PROFILE_FLAGS_BY_DN_REGEX.
Returns True if the profile was modified
### Response:
def _populate_profile_flags_from_dn_regex(self, profile):
"""
Populate the given profile ... |
def set_expire(name, expire):
'''
Sets the time at which the account expires (in seconds since the UNIX
epoch). See ``man 8 usermod`` on NetBSD and OpenBSD or ``man 8 pw`` on
FreeBSD.
A value of ``0`` sets the account to never expire.
CLI Example:
.. code-block:: bash
salt '*' sh... | Sets the time at which the account expires (in seconds since the UNIX
epoch). See ``man 8 usermod`` on NetBSD and OpenBSD or ``man 8 pw`` on
FreeBSD.
A value of ``0`` sets the account to never expire.
CLI Example:
.. code-block:: bash
salt '*' shadow.set_expire username 1419980400 | Below is the the instruction that describes the task:
### Input:
Sets the time at which the account expires (in seconds since the UNIX
epoch). See ``man 8 usermod`` on NetBSD and OpenBSD or ``man 8 pw`` on
FreeBSD.
A value of ``0`` sets the account to never expire.
CLI Example:
.. code-block:... |
def disable(self, msgid, scope="package", line=None, ignore_unknown=False):
"""don't output message of the given id"""
self._set_msg_status(
msgid, enable=False, scope=scope, line=line, ignore_unknown=ignore_unknown
)
self._register_by_id_managed_msg(msgid, line) | don't output message of the given id | Below is the the instruction that describes the task:
### Input:
don't output message of the given id
### Response:
def disable(self, msgid, scope="package", line=None, ignore_unknown=False):
"""don't output message of the given id"""
self._set_msg_status(
msgid, enable=False, scope=sco... |
def brew_recipe(recipe_name):
"""Returns a pipeline string from a recipe name.
Parameters
----------
recipe_name : str
Name of the recipe. Must match the name attribute in one of the classes
defined in :mod:`flowcraft.generator.recipes`
Returns
-------
str
Pipeline ... | Returns a pipeline string from a recipe name.
Parameters
----------
recipe_name : str
Name of the recipe. Must match the name attribute in one of the classes
defined in :mod:`flowcraft.generator.recipes`
Returns
-------
str
Pipeline string ready for parsing and processi... | Below is the the instruction that describes the task:
### Input:
Returns a pipeline string from a recipe name.
Parameters
----------
recipe_name : str
Name of the recipe. Must match the name attribute in one of the classes
defined in :mod:`flowcraft.generator.recipes`
Returns
-... |
def getBuyerInfo(self, auction_id, buyer_id):
"""Return buyer info."""
# TODO: add price from getBids
rc = self.__ask__('doGetPostBuyData', itemsArray=self.ArrayOfLong([auction_id]), buyerFilterArray=self.ArrayOfLong([buyer_id]))
rc = rc[0]['usersPostBuyData']['item'][0]['userData']
... | Return buyer info. | Below is the the instruction that describes the task:
### Input:
Return buyer info.
### Response:
def getBuyerInfo(self, auction_id, buyer_id):
"""Return buyer info."""
# TODO: add price from getBids
rc = self.__ask__('doGetPostBuyData', itemsArray=self.ArrayOfLong([auction_id]), buyerFilte... |
def reset_script(self):
"""Clear any partially received script."""
self.remote_bridge.status = BRIDGE_STATUS.IDLE
self.remote_bridge.error = 0
self.remote_bridge.parsed_script = None
self._device.script = bytearray()
return [0] | Clear any partially received script. | Below is the the instruction that describes the task:
### Input:
Clear any partially received script.
### Response:
def reset_script(self):
"""Clear any partially received script."""
self.remote_bridge.status = BRIDGE_STATUS.IDLE
self.remote_bridge.error = 0
self.remote_bridge.pars... |
def rate(s=switchpoint, e=early_mean, l=late_mean):
''' Concatenate Poisson means '''
out = empty(len(disasters_array))
out[:s] = e
out[s:] = l
return out | Concatenate Poisson means | Below is the the instruction that describes the task:
### Input:
Concatenate Poisson means
### Response:
def rate(s=switchpoint, e=early_mean, l=late_mean):
''' Concatenate Poisson means '''
out = empty(len(disasters_array))
out[:s] = e
out[s:] = l
return out |
def change_dict_keys(self, data_dict, prefix):
"""
Prefixes 'L_'/'R_' to the collection keys
:param data_dict: dictionary which is to be altered
:type data_dict: dict
:param prefix: prefix to be attached before every key
:type prefix: string
... | Prefixes 'L_'/'R_' to the collection keys
:param data_dict: dictionary which is to be altered
:type data_dict: dict
:param prefix: prefix to be attached before every key
:type prefix: string
:return dict_: dict | Below is the the instruction that describes the task:
### Input:
Prefixes 'L_'/'R_' to the collection keys
:param data_dict: dictionary which is to be altered
:type data_dict: dict
:param prefix: prefix to be attached before every key
:type prefix: string
... |
def _get_total_read_size(self):
"""How much event data to process at once."""
if self.read_size:
read_size = EVENT_SIZE * self.read_size
else:
read_size = EVENT_SIZE
return read_size | How much event data to process at once. | Below is the the instruction that describes the task:
### Input:
How much event data to process at once.
### Response:
def _get_total_read_size(self):
"""How much event data to process at once."""
if self.read_size:
read_size = EVENT_SIZE * self.read_size
else:
read_... |
def _start_managers(self):
"""
(internal) starts input and output pool queue manager threads.
"""
self._task_queue = _Weave(self._tasks, self.stride)
# here we determine the size of the maximum memory consumption
self._semaphore_value = (self.buffer or (len(self._tasks) *... | (internal) starts input and output pool queue manager threads. | Below is the the instruction that describes the task:
### Input:
(internal) starts input and output pool queue manager threads.
### Response:
def _start_managers(self):
"""
(internal) starts input and output pool queue manager threads.
"""
self._task_queue = _Weave(self._tasks, self... |
def almost_eq(arr1, arr2, thresh=1E-11, ret_error=False):
""" checks if floating point number are equal to a threshold
"""
error = np.abs(arr1 - arr2)
passed = error < thresh
if ret_error:
return passed, error
return passed | checks if floating point number are equal to a threshold | Below is the the instruction that describes the task:
### Input:
checks if floating point number are equal to a threshold
### Response:
def almost_eq(arr1, arr2, thresh=1E-11, ret_error=False):
""" checks if floating point number are equal to a threshold
"""
error = np.abs(arr1 - arr2)
passed = err... |
async def unset_lock(self, resource, lock_identifier):
"""
Unlock this instance
:param resource: redis key to set
:param lock_identifier: uniquie id of lock
:raises: LockError if the lock resource acquired with different lock_identifier
"""
try:
with a... | Unlock this instance
:param resource: redis key to set
:param lock_identifier: uniquie id of lock
:raises: LockError if the lock resource acquired with different lock_identifier | Below is the the instruction that describes the task:
### Input:
Unlock this instance
:param resource: redis key to set
:param lock_identifier: uniquie id of lock
:raises: LockError if the lock resource acquired with different lock_identifier
### Response:
async def unset_lock(self, resourc... |
def credentials(login=None):
"""
Find user credentials. We should have parsed the command line for a ``--login`` option.
We will try to find credentials in environment variables.
We will ask user if we cannot find any in arguments nor environment
"""
if not login:
login = environ.get("PR... | Find user credentials. We should have parsed the command line for a ``--login`` option.
We will try to find credentials in environment variables.
We will ask user if we cannot find any in arguments nor environment | Below is the the instruction that describes the task:
### Input:
Find user credentials. We should have parsed the command line for a ``--login`` option.
We will try to find credentials in environment variables.
We will ask user if we cannot find any in arguments nor environment
### Response:
def credential... |
def _read_audio_data(self, file_path):
"""
Read audio data from file.
:rtype: tuple (True, (duration, sample_rate, codec, data)) or (False, None) on exception
"""
try:
self.log(u"Reading audio data...")
# if we know the TTS outputs to PCM16 mono WAVE
... | Read audio data from file.
:rtype: tuple (True, (duration, sample_rate, codec, data)) or (False, None) on exception | Below is the the instruction that describes the task:
### Input:
Read audio data from file.
:rtype: tuple (True, (duration, sample_rate, codec, data)) or (False, None) on exception
### Response:
def _read_audio_data(self, file_path):
"""
Read audio data from file.
:rtype: tuple (T... |
def upload(self, pkg_path):
"""
Upload a python script (or kecpkg) to the service.
.. versionadded:: 1.13
:param pkg_path: path to the python script or kecpkg to upload.
:type pkg_path: basestring
:raises APIError: if the python package could not be uploaded.
:r... | Upload a python script (or kecpkg) to the service.
.. versionadded:: 1.13
:param pkg_path: path to the python script or kecpkg to upload.
:type pkg_path: basestring
:raises APIError: if the python package could not be uploaded.
:raises OSError: if the python package could not b... | Below is the the instruction that describes the task:
### Input:
Upload a python script (or kecpkg) to the service.
.. versionadded:: 1.13
:param pkg_path: path to the python script or kecpkg to upload.
:type pkg_path: basestring
:raises APIError: if the python package could not be... |
def get(cls, expression):
"""
Retrieve the model instance matching the given expression.
If the number of matching results is not equal to one, then
a ``ValueError`` will be raised.
:param expression: A boolean expression to filter by.
:returns: The matching :py:class:`M... | Retrieve the model instance matching the given expression.
If the number of matching results is not equal to one, then
a ``ValueError`` will be raised.
:param expression: A boolean expression to filter by.
:returns: The matching :py:class:`Model` instance.
:raises: ``ValueError`... | Below is the the instruction that describes the task:
### Input:
Retrieve the model instance matching the given expression.
If the number of matching results is not equal to one, then
a ``ValueError`` will be raised.
:param expression: A boolean expression to filter by.
:returns: Th... |
def rule_command_cmdlist_interface_u_interface_fe_leaf_interface_fortygigabitethernet_leaf(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
rule = ET.SubElement(config, "rule", xmlns="urn:brocade.com:mgmt:brocade-aaa")
index_key = ET.SubElement(rule, "ind... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def rule_command_cmdlist_interface_u_interface_fe_leaf_interface_fortygigabitethernet_leaf(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
rule = ET.SubElemen... |
def _get_option_value(self, key):
"""
Get option value(s), or use default value if no override value.
Two output values for 'p' type values (parameters), else one.
Returns a single value or tuple of two values
"""
fn_name = "set_{}_value".format(key)
if key in se... | Get option value(s), or use default value if no override value.
Two output values for 'p' type values (parameters), else one.
Returns a single value or tuple of two values | Below is the the instruction that describes the task:
### Input:
Get option value(s), or use default value if no override value.
Two output values for 'p' type values (parameters), else one.
Returns a single value or tuple of two values
### Response:
def _get_option_value(self, key):
"""
... |
def get_provides_by_kind(self, kind):
""" Returns an array of provides of a certain kind """
provs = []
for p in self.provides:
if p.kind == kind:
provs.append(p)
return provs | Returns an array of provides of a certain kind | Below is the the instruction that describes the task:
### Input:
Returns an array of provides of a certain kind
### Response:
def get_provides_by_kind(self, kind):
""" Returns an array of provides of a certain kind """
provs = []
for p in self.provides:
if p.kind == kind:
... |
def parse_from_import_statement(self):
"""Parse a 'from x import y' statement.
The purpose is to find __future__ statements.
"""
self.log.debug("parsing from/import statement.")
is_future_import = self._parse_from_import_source()
self._parse_from_import_names(is_future_i... | Parse a 'from x import y' statement.
The purpose is to find __future__ statements. | Below is the the instruction that describes the task:
### Input:
Parse a 'from x import y' statement.
The purpose is to find __future__ statements.
### Response:
def parse_from_import_statement(self):
"""Parse a 'from x import y' statement.
The purpose is to find __future__ statements.
... |
def from_inline(cls: Type[MembershipType], version: int, currency: str, membership_type: str,
inline: str) -> MembershipType:
"""
Return Membership instance from inline format
:param version: Version of the document
:param currency: Name of the currency
:para... | Return Membership instance from inline format
:param version: Version of the document
:param currency: Name of the currency
:param membership_type: "IN" or "OUT" to enter or exit membership
:param inline: Inline string format
:return: | Below is the the instruction that describes the task:
### Input:
Return Membership instance from inline format
:param version: Version of the document
:param currency: Name of the currency
:param membership_type: "IN" or "OUT" to enter or exit membership
:param inline: Inline string... |
def show_keypair(kwargs=None, call=None):
'''
Show the details of an SSH keypair
'''
if call != 'function':
log.error(
'The show_keypair function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'keyname' not in kwa... | Show the details of an SSH keypair | Below is the the instruction that describes the task:
### Input:
Show the details of an SSH keypair
### Response:
def show_keypair(kwargs=None, call=None):
'''
Show the details of an SSH keypair
'''
if call != 'function':
log.error(
'The show_keypair function must be called with... |
async def _deferred_init(self):
"""
Run those things in a sepearate tasks as they are not required for the
bot to work and they take a lot of time to run.
"""
await self._check_subscriptions()
await self._set_whitelist()
await self._set_get_started()
awai... | Run those things in a sepearate tasks as they are not required for the
bot to work and they take a lot of time to run. | Below is the the instruction that describes the task:
### Input:
Run those things in a sepearate tasks as they are not required for the
bot to work and they take a lot of time to run.
### Response:
async def _deferred_init(self):
"""
Run those things in a sepearate tasks as they are not req... |
def taper_timeseries(tsdata, tapermethod=None, return_lal=False):
"""
Taper either or both ends of a time series using wrapped
LALSimulation functions
Parameters
----------
tsdata : TimeSeries
Series to be tapered, dtype must be either float32 or float64
tapermethod : string
... | Taper either or both ends of a time series using wrapped
LALSimulation functions
Parameters
----------
tsdata : TimeSeries
Series to be tapered, dtype must be either float32 or float64
tapermethod : string
Should be one of ('TAPER_NONE', 'TAPER_START', 'TAPER_END',
'TAPER_ST... | Below is the the instruction that describes the task:
### Input:
Taper either or both ends of a time series using wrapped
LALSimulation functions
Parameters
----------
tsdata : TimeSeries
Series to be tapered, dtype must be either float32 or float64
tapermethod : string
Should b... |
def update(self, user, **kwargs):
"""If parent resource is not an editable state, should not be able to update"""
yield self.get_parent()
if not self.parent.editable:
err = 'Cannot update child of {} resource'.format(self.parent.state.name)
raise exceptions.Unauthorized(... | If parent resource is not an editable state, should not be able to update | Below is the the instruction that describes the task:
### Input:
If parent resource is not an editable state, should not be able to update
### Response:
def update(self, user, **kwargs):
"""If parent resource is not an editable state, should not be able to update"""
yield self.get_parent()
... |
def _get_event_and_context(self, event, arg_type):
"""Return an INDRA Event based on an event entry."""
eid = _choose_id(event, arg_type)
ev = self.concept_dict[eid]
concept, metadata = self._make_concept(ev)
ev_delta = {'adjectives': [],
'states': get_states(... | Return an INDRA Event based on an event entry. | Below is the the instruction that describes the task:
### Input:
Return an INDRA Event based on an event entry.
### Response:
def _get_event_and_context(self, event, arg_type):
"""Return an INDRA Event based on an event entry."""
eid = _choose_id(event, arg_type)
ev = self.concept_dict[eid]... |
def list_templates(self, offset=0, count=20):
"""
获取本账号内所有模板
详情请参考
https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&id=open1500465446_j4CgR
:param offset: 用于分页,表示起始量,最小值为0
:type offset: int
:param count: 用于分页,表示拉取数量,最大值为20
:type count: int
... | 获取本账号内所有模板
详情请参考
https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&id=open1500465446_j4CgR
:param offset: 用于分页,表示起始量,最小值为0
:type offset: int
:param count: 用于分页,表示拉取数量,最大值为20
:type count: int
:return: 模板列表
:rtype: list[dict] | Below is the the instruction that describes the task:
### Input:
获取本账号内所有模板
详情请参考
https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&id=open1500465446_j4CgR
:param offset: 用于分页,表示起始量,最小值为0
:type offset: int
:param count: 用于分页,表示拉取数量,最大值为20
:type count: i... |
def mousePressEvent(self, event):
"""
Starts the selection process for this widget and snapshot area.
:param event | <QMousePressEvent>
"""
self._region.setX(event.pos().x())
self._region.setY(event.pos().y())
super(XSnapshotWidget, self).mou... | Starts the selection process for this widget and snapshot area.
:param event | <QMousePressEvent> | Below is the the instruction that describes the task:
### Input:
Starts the selection process for this widget and snapshot area.
:param event | <QMousePressEvent>
### Response:
def mousePressEvent(self, event):
"""
Starts the selection process for this widget and snapshot ... |
def table_api_get(self, *paths, **kparams):
""" helper to make GET /api/now/v1/table requests """
url = self.flattened_params_url("/api/now/v1/table", *paths, **kparams)
rjson = self.req("get", url).text
return json.loads(rjson) | helper to make GET /api/now/v1/table requests | Below is the the instruction that describes the task:
### Input:
helper to make GET /api/now/v1/table requests
### Response:
def table_api_get(self, *paths, **kparams):
""" helper to make GET /api/now/v1/table requests """
url = self.flattened_params_url("/api/now/v1/table", *paths, **kparams)
... |
def _sf2(args):
"""
A shallow wrapper for sigma_filter.
Parameters
----------
args : list
A list of arguments for sigma_filter
Returns
-------
None
"""
# an easier to debug traceback when multiprocessing
# thanks to https://stackoverflow.com/a/16618842/1710603
t... | A shallow wrapper for sigma_filter.
Parameters
----------
args : list
A list of arguments for sigma_filter
Returns
-------
None | Below is the the instruction that describes the task:
### Input:
A shallow wrapper for sigma_filter.
Parameters
----------
args : list
A list of arguments for sigma_filter
Returns
-------
None
### Response:
def _sf2(args):
"""
A shallow wrapper for sigma_filter.
Param... |
def do_direct_authorization(self, session):
""" Direct Authorization, more info: https://vk.com/dev/auth_direct """
logger.info('Doing direct authorization, app_id=%s', self.app_id)
auth_data = {
'client_id': self.app_id,
'client_secret': self._client_secret,
... | Direct Authorization, more info: https://vk.com/dev/auth_direct | Below is the the instruction that describes the task:
### Input:
Direct Authorization, more info: https://vk.com/dev/auth_direct
### Response:
def do_direct_authorization(self, session):
""" Direct Authorization, more info: https://vk.com/dev/auth_direct """
logger.info('Doing direct authorization,... |
def _load_lsm_data(self, data_var,
conversion_factor=1,
calc_4d_method=None,
calc_4d_dim=None,
time_step=None):
"""
This extracts the LSM data from a folder of netcdf files
"""
data = self.xd.lsm.... | This extracts the LSM data from a folder of netcdf files | Below is the the instruction that describes the task:
### Input:
This extracts the LSM data from a folder of netcdf files
### Response:
def _load_lsm_data(self, data_var,
conversion_factor=1,
calc_4d_method=None,
calc_4d_dim=None,
... |
def fields_metadata(self):
"""
Returns fields metadata as a dataframe.
"""
return (pd.concat([f.metadata() for f in self.fields], axis = 1)
.transpose()
.sort_values(["step_num", "frame", "label", "position"])) | Returns fields metadata as a dataframe. | Below is the the instruction that describes the task:
### Input:
Returns fields metadata as a dataframe.
### Response:
def fields_metadata(self):
"""
Returns fields metadata as a dataframe.
"""
return (pd.concat([f.metadata() for f in self.fields], axis = 1)
.transpose()
.... |
def parsewarn(self, msg, line=None):
"""Emit parse warning."""
if line is None:
line = self.sline
self.dowarn('warning: ' + msg + ' on line {}'.format(line)) | Emit parse warning. | Below is the the instruction that describes the task:
### Input:
Emit parse warning.
### Response:
def parsewarn(self, msg, line=None):
"""Emit parse warning."""
if line is None:
line = self.sline
self.dowarn('warning: ' + msg + ' on line {}'.format(line)) |
def norm(field, vmin=0, vmax=255):
"""Truncates field to 0,1; then normalizes to a uin8 on [0,255]"""
field = 255*np.clip(field, 0, 1)
field = field.astype('uint8')
return field | Truncates field to 0,1; then normalizes to a uin8 on [0,255] | Below is the the instruction that describes the task:
### Input:
Truncates field to 0,1; then normalizes to a uin8 on [0,255]
### Response:
def norm(field, vmin=0, vmax=255):
"""Truncates field to 0,1; then normalizes to a uin8 on [0,255]"""
field = 255*np.clip(field, 0, 1)
field = field.astype('uint8'... |
def active_network_addresses(hypervisor):
"""Query libvirt for the already reserved addresses."""
active = []
for network in hypervisor.listNetworks():
try:
xml = hypervisor.networkLookupByName(network).XMLDesc(0)
except libvirt.libvirtError: # network has been destroyed meanwh... | Query libvirt for the already reserved addresses. | Below is the the instruction that describes the task:
### Input:
Query libvirt for the already reserved addresses.
### Response:
def active_network_addresses(hypervisor):
"""Query libvirt for the already reserved addresses."""
active = []
for network in hypervisor.listNetworks():
try:
... |
def transfer(self, data):
"""Transfers data over SPI.
Arguments:
data: The data to transfer.
Returns:
The data returned by the SPI device.
"""
settings = self.transfer_settings
settings.spi_tx_size = len(data)
self.transfer_settings = set... | Transfers data over SPI.
Arguments:
data: The data to transfer.
Returns:
The data returned by the SPI device. | Below is the the instruction that describes the task:
### Input:
Transfers data over SPI.
Arguments:
data: The data to transfer.
Returns:
The data returned by the SPI device.
### Response:
def transfer(self, data):
"""Transfers data over SPI.
Arguments:
... |
def eth_getCode(self, address, default_block=BLOCK_TAG_LATEST):
"""TODO: documentation
https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getcode
NEEDS TESTING
"""
if isinstance(default_block, str):
if default_block not in BLOCK_TAGS:
raise ValueErro... | TODO: documentation
https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getcode
NEEDS TESTING | Below is the the instruction that describes the task:
### Input:
TODO: documentation
https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getcode
NEEDS TESTING
### Response:
def eth_getCode(self, address, default_block=BLOCK_TAG_LATEST):
"""TODO: documentation
https://github.com/et... |
def run_commands(*commands, **kwargs):
'''
Sends the commands over the transport to the device.
This function sends the commands to the device using the nodes
transport. This is a lower layer function that shouldn't normally
need to be used, preferring instead to use ``config()`` or ``enable()``.
... | Sends the commands over the transport to the device.
This function sends the commands to the device using the nodes
transport. This is a lower layer function that shouldn't normally
need to be used, preferring instead to use ``config()`` or ``enable()``.
transport: ``https``
Specifies the typ... | Below is the the instruction that describes the task:
### Input:
Sends the commands over the transport to the device.
This function sends the commands to the device using the nodes
transport. This is a lower layer function that shouldn't normally
need to be used, preferring instead to use ``config()``... |
def get_activate_url(self, card_id, outer_str=None):
"""
获取开卡插件 Url, 内含调用开卡插件所需的参数
详情请参考
https://mp.weixin.qq.com/wiki?id=mp1499332673_Unm7V
:param card_id: 会员卡的card_id
:param outer_str: 渠道值,用于统计本次领取的渠道参数
:return: 内含调用开卡插件所需的参数的 Url
"""
return sel... | 获取开卡插件 Url, 内含调用开卡插件所需的参数
详情请参考
https://mp.weixin.qq.com/wiki?id=mp1499332673_Unm7V
:param card_id: 会员卡的card_id
:param outer_str: 渠道值,用于统计本次领取的渠道参数
:return: 内含调用开卡插件所需的参数的 Url | Below is the the instruction that describes the task:
### Input:
获取开卡插件 Url, 内含调用开卡插件所需的参数
详情请参考
https://mp.weixin.qq.com/wiki?id=mp1499332673_Unm7V
:param card_id: 会员卡的card_id
:param outer_str: 渠道值,用于统计本次领取的渠道参数
:return: 内含调用开卡插件所需的参数的 Url
### Response:
def get_activate_ur... |
def rm(self, container_alias):
'''
a method to remove an active container
:param container_alias: string with name or id of container
:return: string with container id
'''
title = '%s.rm' % self.__class__.__name__
# validate inputs
... | a method to remove an active container
:param container_alias: string with name or id of container
:return: string with container id | Below is the the instruction that describes the task:
### Input:
a method to remove an active container
:param container_alias: string with name or id of container
:return: string with container id
### Response:
def rm(self, container_alias):
'''
a method to... |
def list_records(self, domain, limit=None, offset=None):
"""
Returns a list of all records configured for the specified domain.
"""
uri = "/domains/%s/records%s" % (utils.get_id(domain),
self._get_pagination_qs(limit, offset))
return self._list_records(uri) | Returns a list of all records configured for the specified domain. | Below is the the instruction that describes the task:
### Input:
Returns a list of all records configured for the specified domain.
### Response:
def list_records(self, domain, limit=None, offset=None):
"""
Returns a list of all records configured for the specified domain.
"""
uri =... |
def handle_typed_values(val, type_name, value_type):
"""Translate typed values into the appropriate python object.
Takes an element name, value, and type and returns a list
with the string value(s) properly converted to a python type.
TypedValues are handled in ucar.ma2.DataType in net... | Translate typed values into the appropriate python object.
Takes an element name, value, and type and returns a list
with the string value(s) properly converted to a python type.
TypedValues are handled in ucar.ma2.DataType in netcdfJava
in the DataType enum. Possibilities are:
... | Below is the the instruction that describes the task:
### Input:
Translate typed values into the appropriate python object.
Takes an element name, value, and type and returns a list
with the string value(s) properly converted to a python type.
TypedValues are handled in ucar.ma2.DataType i... |
def attributes_in_restriction(self):
"""
:return: list of attributes that are probably used in the restriction.
The function errs on the side of false positives.
For example, if the restriction is "val='id'", then the attribute 'id' would be flagged.
This is used inte... | :return: list of attributes that are probably used in the restriction.
The function errs on the side of false positives.
For example, if the restriction is "val='id'", then the attribute 'id' would be flagged.
This is used internally for optimizing SQL statements. | Below is the the instruction that describes the task:
### Input:
:return: list of attributes that are probably used in the restriction.
The function errs on the side of false positives.
For example, if the restriction is "val='id'", then the attribute 'id' would be flagged.
This ... |
def push_all(self, record_shard_pairs):
"""Push multiple (record, shard) pairs at once, with only one :meth:`heapq.heapify` call to maintain order.
:param record_shard_pairs: list of ``(record, shard)`` tuples
(see :func:`~bloop.stream.buffer.RecordBuffer.push`).
"""
# Faste... | Push multiple (record, shard) pairs at once, with only one :meth:`heapq.heapify` call to maintain order.
:param record_shard_pairs: list of ``(record, shard)`` tuples
(see :func:`~bloop.stream.buffer.RecordBuffer.push`). | Below is the the instruction that describes the task:
### Input:
Push multiple (record, shard) pairs at once, with only one :meth:`heapq.heapify` call to maintain order.
:param record_shard_pairs: list of ``(record, shard)`` tuples
(see :func:`~bloop.stream.buffer.RecordBuffer.push`).
### Respo... |
def CompareTo(self, other_hash_value):
"""Compares the passed hash value with the hash value of this object
"""
if len(self.hash_value) != len(other_hash_value):
raise ValueError("Length of hashes doesn't match.")
# The hash byte array that is returned from ComputeHash metho... | Compares the passed hash value with the hash value of this object | Below is the the instruction that describes the task:
### Input:
Compares the passed hash value with the hash value of this object
### Response:
def CompareTo(self, other_hash_value):
"""Compares the passed hash value with the hash value of this object
"""
if len(self.hash_value) != len(oth... |
def complete(self):
"""
Make the graph a complete graph.
@attention: This will modify the current graph.
"""
for each in self.nodes():
for other in self.nodes():
if (each != other and not self.has_edge((each, other))):
self... | Make the graph a complete graph.
@attention: This will modify the current graph. | Below is the the instruction that describes the task:
### Input:
Make the graph a complete graph.
@attention: This will modify the current graph.
### Response:
def complete(self):
"""
Make the graph a complete graph.
@attention: This will modify the current graph.
... |
def _do_include(self, rule, p_selectors, p_parents, p_children, scope, media, c_lineno, c_property, c_codestr, code, name):
"""
Implements @include, for @mixins
"""
funct, params, _ = name.partition('(')
funct = funct.strip()
funct = self.do_glob_math(
funct, ... | Implements @include, for @mixins | Below is the the instruction that describes the task:
### Input:
Implements @include, for @mixins
### Response:
def _do_include(self, rule, p_selectors, p_parents, p_children, scope, media, c_lineno, c_property, c_codestr, code, name):
"""
Implements @include, for @mixins
"""
funct,... |
def warn(msg, level=0, prefix=True):
"""Prints the specified message as a warning; prepends "WARNING" to
the message, so that can be left off.
"""
if will_print(level):
printer(("WARNING: " if prefix else "") + msg, "yellow") | Prints the specified message as a warning; prepends "WARNING" to
the message, so that can be left off. | Below is the the instruction that describes the task:
### Input:
Prints the specified message as a warning; prepends "WARNING" to
the message, so that can be left off.
### Response:
def warn(msg, level=0, prefix=True):
"""Prints the specified message as a warning; prepends "WARNING" to
the message, so ... |
def list_to_raw_list(poselist):
"""
Flatten a normal pose list into a raw list
:param poselist: a formatted list [[x,y,z], [x,y,z,w]]
:return: a raw list [x, y, z, x, y, z, w]
"""
if not (isinstance(poselist, list) or isinstance(poselist, tuple)):
raise TypeError(
"flatten_po... | Flatten a normal pose list into a raw list
:param poselist: a formatted list [[x,y,z], [x,y,z,w]]
:return: a raw list [x, y, z, x, y, z, w] | Below is the the instruction that describes the task:
### Input:
Flatten a normal pose list into a raw list
:param poselist: a formatted list [[x,y,z], [x,y,z,w]]
:return: a raw list [x, y, z, x, y, z, w]
### Response:
def list_to_raw_list(poselist):
"""
Flatten a normal pose list into a raw list
... |
def p_function_statement(self, p):
'function_statement : funcvardecls function_calc'
p[0] = p[1] + (p[2],)
p.set_lineno(0, p.lineno(1)) | function_statement : funcvardecls function_calc | Below is the the instruction that describes the task:
### Input:
function_statement : funcvardecls function_calc
### Response:
def p_function_statement(self, p):
'function_statement : funcvardecls function_calc'
p[0] = p[1] + (p[2],)
p.set_lineno(0, p.lineno(1)) |
def stage_platform_hpp(capnproot):
"""stage platform.hpp into libcapnp sources
Tries ./configure first (except on Windows),
then falls back on included platform.hpp previously generated.
"""
platform_hpp = pjoin(capnproot, 'src', 'platform.hpp')
if os.path.exists(platform_hpp):
info("a... | stage platform.hpp into libcapnp sources
Tries ./configure first (except on Windows),
then falls back on included platform.hpp previously generated. | Below is the the instruction that describes the task:
### Input:
stage platform.hpp into libcapnp sources
Tries ./configure first (except on Windows),
then falls back on included platform.hpp previously generated.
### Response:
def stage_platform_hpp(capnproot):
"""stage platform.hpp into libcapnp sou... |
def tables(self):
"""
A list containing the tables in this container, in document order.
Read-only.
"""
from .table import Table
return [Table(tbl, self) for tbl in self._element.tbl_lst] | A list containing the tables in this container, in document order.
Read-only. | Below is the the instruction that describes the task:
### Input:
A list containing the tables in this container, in document order.
Read-only.
### Response:
def tables(self):
"""
A list containing the tables in this container, in document order.
Read-only.
"""
from .... |
def play_tour(self, name=None, interval=0):
""" Plays a tour on the current website.
@Params
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.
interval - The delay time between autoplaying tour steps.
... | Plays a tour on the current website.
@Params
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.
interval - The delay time between autoplaying tour steps.
If set to 0 (default), the tour i... | Below is the the instruction that describes the task:
### Input:
Plays a tour on the current website.
@Params
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.
interval - The delay time between autoplaying... |
def print_debug(self, text, indent=0):
"""Only prints debug info on screen when self.debug == True."""
if self.debug:
if indent > 0:
print(" "*self.debug, text)
self.debug += indent
if indent <= 0:
print(" "*self.debug, text) | Only prints debug info on screen when self.debug == True. | Below is the the instruction that describes the task:
### Input:
Only prints debug info on screen when self.debug == True.
### Response:
def print_debug(self, text, indent=0):
"""Only prints debug info on screen when self.debug == True."""
if self.debug:
if indent > 0:
p... |
def arr_base10toN(anum10, aradix, *args):
"""
ARGS
anum10 in number in base 10
aradix in convert <anum10> to number in base
+ <aradix>
OPTIONAL
forcelength in if nonzero, indicates the length
... | ARGS
anum10 in number in base 10
aradix in convert <anum10> to number in base
+ <aradix>
OPTIONAL
forcelength in if nonzero, indicates the length
+ of the return array. Useful ... | Below is the the instruction that describes the task:
### Input:
ARGS
anum10 in number in base 10
aradix in convert <anum10> to number in base
+ <aradix>
OPTIONAL
forcelength in if nonzero, indicates the le... |
def list_nodes_full(mask='mask[id]', call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
ret = {}
conn = get_conn(service='SoftLay... | Return a list of the VMs that are on the provider | Below is the the instruction that describes the task:
### Input:
Return a list of the VMs that are on the provider
### Response:
def list_nodes_full(mask='mask[id]', call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
... |
def read_csvlc(lcfile):
'''This reads a HAT data server or LCC-Server produced CSV light curve
into an lcdict.
This will automatically figure out the format of the file
provided. Currently, it can read:
- legacy HAT data server CSV LCs (e.g. from
https://hatsouth.org/planets/lightcurves.html... | This reads a HAT data server or LCC-Server produced CSV light curve
into an lcdict.
This will automatically figure out the format of the file
provided. Currently, it can read:
- legacy HAT data server CSV LCs (e.g. from
https://hatsouth.org/planets/lightcurves.html) with an extension of the
... | Below is the the instruction that describes the task:
### Input:
This reads a HAT data server or LCC-Server produced CSV light curve
into an lcdict.
This will automatically figure out the format of the file
provided. Currently, it can read:
- legacy HAT data server CSV LCs (e.g. from
https:/... |
def edit_protection(self, strict=github.GithubObject.NotSet, contexts=github.GithubObject.NotSet, enforce_admins=github.GithubObject.NotSet, dismissal_users=github.GithubObject.NotSet, dismissal_teams=github.GithubObject.NotSet, dismiss_stale_reviews=github.GithubObject.NotSet, require_code_owner_reviews=github.GithubO... | :calls: `PUT /repos/:owner/:repo/branches/:branch/protection <https://developer.github.com/v3/repos/branches>`_
:strict: bool
:contexts: list of strings
:enforce_admins: bool
:dismissal_users: list of strings
:dismissal_teams: list of strings
:dismiss_stale_reviews: bool
... | Below is the the instruction that describes the task:
### Input:
:calls: `PUT /repos/:owner/:repo/branches/:branch/protection <https://developer.github.com/v3/repos/branches>`_
:strict: bool
:contexts: list of strings
:enforce_admins: bool
:dismissal_users: list of strings
:d... |
def append_tag(self, field_number, wire_type):
"""Appends a tag containing field number and wire type information."""
self._stream.append_var_uint32(wire_format.pack_tag(field_number, wire_type)) | Appends a tag containing field number and wire type information. | Below is the the instruction that describes the task:
### Input:
Appends a tag containing field number and wire type information.
### Response:
def append_tag(self, field_number, wire_type):
"""Appends a tag containing field number and wire type information."""
self._stream.append_var_uint32(wire_f... |
def get_app_status(system_key):
"""
Get Undergraduate application status
@return ApplicationStatus object
@InvalidSystemKey if system_key is not valid
"""
if invalid_system_key(system_key):
raise InvalidSystemKey(
"Invalid system key in get_app_status({})".format(system_key))... | Get Undergraduate application status
@return ApplicationStatus object
@InvalidSystemKey if system_key is not valid | Below is the the instruction that describes the task:
### Input:
Get Undergraduate application status
@return ApplicationStatus object
@InvalidSystemKey if system_key is not valid
### Response:
def get_app_status(system_key):
"""
Get Undergraduate application status
@return ApplicationStatus ob... |
def start(self, auto_register=True):
"""
Tells the container to start this agent.
It returns a coroutine or a future depending on whether it is called from a coroutine or a synchronous method.
Args:
auto_register (bool): register the agent in the server (Default value = True... | Tells the container to start this agent.
It returns a coroutine or a future depending on whether it is called from a coroutine or a synchronous method.
Args:
auto_register (bool): register the agent in the server (Default value = True) | Below is the the instruction that describes the task:
### Input:
Tells the container to start this agent.
It returns a coroutine or a future depending on whether it is called from a coroutine or a synchronous method.
Args:
auto_register (bool): register the agent in the server (Default ... |
def apply(modifications, state):
""" applies modifications to given state
Parameters
----------
modifications: list of tuples
created by this class.list method.
state: dict
state dictionary
"""
count = 0
for a in modifications:
... | applies modifications to given state
Parameters
----------
modifications: list of tuples
created by this class.list method.
state: dict
state dictionary | Below is the the instruction that describes the task:
### Input:
applies modifications to given state
Parameters
----------
modifications: list of tuples
created by this class.list method.
state: dict
state dictionary
### Response:
def apply(modifications, st... |
def min(self):
"""Return the minimum value in this histogram.
If there are no values in the histogram at all, return 10.
Returns:
int: The minimum value in the histogram.
"""
if len(self._data) == 0:
return 10
return next(iter(sorted(self._data.k... | Return the minimum value in this histogram.
If there are no values in the histogram at all, return 10.
Returns:
int: The minimum value in the histogram. | Below is the the instruction that describes the task:
### Input:
Return the minimum value in this histogram.
If there are no values in the histogram at all, return 10.
Returns:
int: The minimum value in the histogram.
### Response:
def min(self):
"""Return the minimum value in... |
def _sign_input(cls, input_, message, key_pairs):
"""Signs a single Input.
Note:
This method works only for the following Cryptoconditions
currently:
- Ed25519Fulfillment
- ThresholdSha256.
Args:
in... | Signs a single Input.
Note:
This method works only for the following Cryptoconditions
currently:
- Ed25519Fulfillment
- ThresholdSha256.
Args:
input_ (:class:`~bigchaindb.common.transaction.
... | Below is the the instruction that describes the task:
### Input:
Signs a single Input.
Note:
This method works only for the following Cryptoconditions
currently:
- Ed25519Fulfillment
- ThresholdSha256.
Args:
... |
def from_euler_angles(alpha_beta_gamma, beta=None, gamma=None):
"""Improve your life drastically
Assumes the Euler angles correspond to the quaternion R via
R = exp(alpha*z/2) * exp(beta*y/2) * exp(gamma*z/2)
The angles naturally must be in radians for this to make any sense.
NOTE: Before op... | Improve your life drastically
Assumes the Euler angles correspond to the quaternion R via
R = exp(alpha*z/2) * exp(beta*y/2) * exp(gamma*z/2)
The angles naturally must be in radians for this to make any sense.
NOTE: Before opening an issue reporting something "wrong" with this
function, be s... | Below is the the instruction that describes the task:
### Input:
Improve your life drastically
Assumes the Euler angles correspond to the quaternion R via
R = exp(alpha*z/2) * exp(beta*y/2) * exp(gamma*z/2)
The angles naturally must be in radians for this to make any sense.
NOTE: Before open... |
def check_pdb_status(pdbid):
"""Returns the status and up-to-date entry in the PDB for a given PDB ID"""
url = 'http://www.rcsb.org/pdb/rest/idStatus?structureId=%s' % pdbid
xmlf = urlopen(url)
xml = et.parse(xmlf)
xmlf.close()
status = None
current_pdbid = pdbid
for df in xml.xpath('//r... | Returns the status and up-to-date entry in the PDB for a given PDB ID | Below is the the instruction that describes the task:
### Input:
Returns the status and up-to-date entry in the PDB for a given PDB ID
### Response:
def check_pdb_status(pdbid):
"""Returns the status and up-to-date entry in the PDB for a given PDB ID"""
url = 'http://www.rcsb.org/pdb/rest/idStatus?structur... |
def search():
""" Search a movie on TMDB.
"""
redis_key = 's_%s' % request.args['query'].lower()
cached = redis_ro_conn.get(redis_key)
if cached:
return Response(cached)
else:
try:
found = get_on_tmdb(u'/search/movie', query=request.args['query'])
movies =... | Search a movie on TMDB. | Below is the the instruction that describes the task:
### Input:
Search a movie on TMDB.
### Response:
def search():
""" Search a movie on TMDB.
"""
redis_key = 's_%s' % request.args['query'].lower()
cached = redis_ro_conn.get(redis_key)
if cached:
return Response(cached)
else:
... |
def custom_template_name(self):
"""
Returns the path for the custom special coverage template we want.
"""
base_path = getattr(settings, "CUSTOM_SPECIAL_COVERAGE_PATH", "special_coverage/custom")
if base_path is None:
base_path = ""
return "{0}/{1}_custom.html... | Returns the path for the custom special coverage template we want. | Below is the the instruction that describes the task:
### Input:
Returns the path for the custom special coverage template we want.
### Response:
def custom_template_name(self):
"""
Returns the path for the custom special coverage template we want.
"""
base_path = getattr(settings, ... |
def evaluate(self, reference_scene_list, estimated_scene_list=None, estimated_scene_probabilities=None):
"""Evaluate file pair (reference and estimated)
Parameters
----------
reference_scene_list : list of dict or dcase_util.containers.MetaDataContainer
Reference scene list... | Evaluate file pair (reference and estimated)
Parameters
----------
reference_scene_list : list of dict or dcase_util.containers.MetaDataContainer
Reference scene list.
Default value None
estimated_scene_list : list of dict or dcase_util.containers.MetaDataConta... | Below is the the instruction that describes the task:
### Input:
Evaluate file pair (reference and estimated)
Parameters
----------
reference_scene_list : list of dict or dcase_util.containers.MetaDataContainer
Reference scene list.
Default value None
estim... |
def evaluate(self, verbose=True, passes=None):
"""Summary
Returns:
TYPE: Description
"""
if self.is_pivot:
index, pivot, columns = LazyOpResult(
self.expr,
self.weld_type,
0
).evaluate(verbose=verbose, p... | Summary
Returns:
TYPE: Description | Below is the the instruction that describes the task:
### Input:
Summary
Returns:
TYPE: Description
### Response:
def evaluate(self, verbose=True, passes=None):
"""Summary
Returns:
TYPE: Description
"""
if self.is_pivot:
index, pivot, co... |
def write(url, content, **args):
"""Put an object into a ftp URL."""
with FTPResource(url, **args) as resource:
resource.write(content) | Put an object into a ftp URL. | Below is the the instruction that describes the task:
### Input:
Put an object into a ftp URL.
### Response:
def write(url, content, **args):
"""Put an object into a ftp URL."""
with FTPResource(url, **args) as resource:
resource.write(content) |
def emit_save_figure(self):
"""
Emit a signal when the toolbutton to save the figure is clicked.
"""
self.sig_save_figure.emit(self.canvas.fig, self.canvas.fmt) | Emit a signal when the toolbutton to save the figure is clicked. | Below is the the instruction that describes the task:
### Input:
Emit a signal when the toolbutton to save the figure is clicked.
### Response:
def emit_save_figure(self):
"""
Emit a signal when the toolbutton to save the figure is clicked.
"""
self.sig_save_figure.emit(self.canvas.... |
def use_comparative_log_entry_view(self):
"""Pass through to provider LogEntryLookupSession.use_comparative_log_entry_view"""
self._object_views['log_entry'] = COMPARATIVE
# self._get_provider_session('log_entry_lookup_session') # To make sure the session is tracked
for session in self._... | Pass through to provider LogEntryLookupSession.use_comparative_log_entry_view | Below is the the instruction that describes the task:
### Input:
Pass through to provider LogEntryLookupSession.use_comparative_log_entry_view
### Response:
def use_comparative_log_entry_view(self):
"""Pass through to provider LogEntryLookupSession.use_comparative_log_entry_view"""
self._object_vie... |
def get_weights(self):
"""
Returns:
dict: Model's trained weights.
"""
if self.is_trained() is False:
# print("Model not fitted yet. Use object.fit() to fit the model.")
return None
var_res = self._var_res
weights = self._var_res_to_we... | Returns:
dict: Model's trained weights. | Below is the the instruction that describes the task:
### Input:
Returns:
dict: Model's trained weights.
### Response:
def get_weights(self):
"""
Returns:
dict: Model's trained weights.
"""
if self.is_trained() is False:
# print("Model not fitted ... |
def use_plenary_objective_bank_view(self):
"""Pass through to provider ObjectiveObjectiveBankSession.use_plenary_objective_bank_view"""
self._objective_bank_view = PLENARY
# self._get_provider_session('objective_objective_bank_session') # To make sure the session is tracked
for session i... | Pass through to provider ObjectiveObjectiveBankSession.use_plenary_objective_bank_view | Below is the the instruction that describes the task:
### Input:
Pass through to provider ObjectiveObjectiveBankSession.use_plenary_objective_bank_view
### Response:
def use_plenary_objective_bank_view(self):
"""Pass through to provider ObjectiveObjectiveBankSession.use_plenary_objective_bank_view"""
... |
def update_params(self, param_d):
"""Update the attributes in self.obj that match the keys in
`param_d`.
"""
for param in self.paramlst:
if param.name in param_d:
value = param_d[param.name]
setattr(self.obj, param.name, value) | Update the attributes in self.obj that match the keys in
`param_d`. | Below is the the instruction that describes the task:
### Input:
Update the attributes in self.obj that match the keys in
`param_d`.
### Response:
def update_params(self, param_d):
"""Update the attributes in self.obj that match the keys in
`param_d`.
"""
for param in self.p... |
def replace_pattern(pattern,
repl,
count=0,
flags=8,
bufsize=1,
append_if_not_found=False,
prepend_if_not_found=False,
not_found_content=None,
search_only=False... | .. versionadded:: 2019.2.0
Replace occurrences of a pattern in the configuration source. If
``show_changes`` is ``True``, then a diff of what changed will be returned,
otherwise a ``True`` will be returned when changes are made, and ``False``
when no changes are made.
This is a pure Python implemen... | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 2019.2.0
Replace occurrences of a pattern in the configuration source. If
``show_changes`` is ``True``, then a diff of what changed will be returned,
otherwise a ``True`` will be returned when changes are made, and ``Fal... |
def smooth(self):
"""
Read/write boolean specifying whether to use curve smoothing to
form the line connecting the data points in this series into
a continuous curve. If |False|, a series of straight line segments
are used to connect the points.
"""
smooth = self.... | Read/write boolean specifying whether to use curve smoothing to
form the line connecting the data points in this series into
a continuous curve. If |False|, a series of straight line segments
are used to connect the points. | Below is the the instruction that describes the task:
### Input:
Read/write boolean specifying whether to use curve smoothing to
form the line connecting the data points in this series into
a continuous curve. If |False|, a series of straight line segments
are used to connect the points.
###... |
def findall(text):
"""Find all the timestrings within a block of text.
>>> timestring.findall("once upon a time, about 3 weeks ago, there was a boy whom was born on august 15th at 7:20 am. epic.")
[
('3 weeks ago,', <timestring.Date 2014-02-09 00:00:00 4483019280>),
('august 15th at 7:20 am', <ti... | Find all the timestrings within a block of text.
>>> timestring.findall("once upon a time, about 3 weeks ago, there was a boy whom was born on august 15th at 7:20 am. epic.")
[
('3 weeks ago,', <timestring.Date 2014-02-09 00:00:00 4483019280>),
('august 15th at 7:20 am', <timestring.Date 2014-08-15 0... | Below is the the instruction that describes the task:
### Input:
Find all the timestrings within a block of text.
>>> timestring.findall("once upon a time, about 3 weeks ago, there was a boy whom was born on august 15th at 7:20 am. epic.")
[
('3 weeks ago,', <timestring.Date 2014-02-09 00:00:00 448301... |
def extrapolate_error(self):
"""Estimate the numerical error to be expected when applying all
methods available based on the results of the current and the
last method.
Note that this expolation strategy cannot be applied on the first
method. If the current method is the first ... | Estimate the numerical error to be expected when applying all
methods available based on the results of the current and the
last method.
Note that this expolation strategy cannot be applied on the first
method. If the current method is the first one, `-999.9` is returned.
>>> ... | Below is the the instruction that describes the task:
### Input:
Estimate the numerical error to be expected when applying all
methods available based on the results of the current and the
last method.
Note that this expolation strategy cannot be applied on the first
method. If the... |
def fill_series(x, year):
"""Returns the value of a timeseries (indexed over years) for a year
by linear interpolation.
Parameters
----------
x: pandas.Series
a timeseries to be interpolated
year: int
year of interpolation
"""
x = x.dropna()
if year in x.index and no... | Returns the value of a timeseries (indexed over years) for a year
by linear interpolation.
Parameters
----------
x: pandas.Series
a timeseries to be interpolated
year: int
year of interpolation | Below is the the instruction that describes the task:
### Input:
Returns the value of a timeseries (indexed over years) for a year
by linear interpolation.
Parameters
----------
x: pandas.Series
a timeseries to be interpolated
year: int
year of interpolation
### Response:
def f... |
def read(
self,
validity_check=False,
indexes=None,
resampling=None,
dst_nodata=None,
gdal_opts=None,
**kwargs
):
"""
Read reprojected & resampled input data.
Parameters
----------
validity_check : bool
vect... | Read reprojected & resampled input data.
Parameters
----------
validity_check : bool
vector file: also run checks if reprojected geometry is valid,
otherwise throw RuntimeError (default: True)
indexes : list or int
raster file: a list of band numbers... | Below is the the instruction that describes the task:
### Input:
Read reprojected & resampled input data.
Parameters
----------
validity_check : bool
vector file: also run checks if reprojected geometry is valid,
otherwise throw RuntimeError (default: True)
... |
def from_dict(data, ctx):
"""
Instantiate a new AccountSummary from a dict (generally from loading a
JSON response). The data used to instantiate the AccountSummary is a
shallow copy of the dict passed in, with any complex child types
instantiated appropriately.
"""
... | Instantiate a new AccountSummary from a dict (generally from loading a
JSON response). The data used to instantiate the AccountSummary is a
shallow copy of the dict passed in, with any complex child types
instantiated appropriately. | Below is the the instruction that describes the task:
### Input:
Instantiate a new AccountSummary from a dict (generally from loading a
JSON response). The data used to instantiate the AccountSummary is a
shallow copy of the dict passed in, with any complex child types
instantiated appropria... |
def register(self, plugin, columnType=None, columnName=None):
"""
Registers a plugin to handle particular column types and column names
based on user selection.
:param plugin | <XOrbQueryPlugin>
columnType | <orb.ColumnType> || None
... | Registers a plugin to handle particular column types and column names
based on user selection.
:param plugin | <XOrbQueryPlugin>
columnType | <orb.ColumnType> || None
columnName | <str> || None | Below is the the instruction that describes the task:
### Input:
Registers a plugin to handle particular column types and column names
based on user selection.
:param plugin | <XOrbQueryPlugin>
columnType | <orb.ColumnType> || None
colum... |
def factorize(number):
"""
Get the prime factors of an integer except for 1.
Parameters
----------
number : int
Returns
-------
primes : iterable
Examples
--------
>>> factorize(-17)
[-1, 17]
>>> factorize(8)
[2, 2, 2]
>>> factorize(3**25)
[3, 3, 3, 3, ... | Get the prime factors of an integer except for 1.
Parameters
----------
number : int
Returns
-------
primes : iterable
Examples
--------
>>> factorize(-17)
[-1, 17]
>>> factorize(8)
[2, 2, 2]
>>> factorize(3**25)
[3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,... | Below is the the instruction that describes the task:
### Input:
Get the prime factors of an integer except for 1.
Parameters
----------
number : int
Returns
-------
primes : iterable
Examples
--------
>>> factorize(-17)
[-1, 17]
>>> factorize(8)
[2, 2, 2]
>>> ... |
def from_meta(cls, meta, meta_all=None):
"""Copy DocstringMeta from another instance."""
if len(meta.args) == 2:
name = meta.args[1]
meta_type = None
for x in meta_all:
if x.args[1] == name and x.args[0] == 'type':
meta_type = x.des... | Copy DocstringMeta from another instance. | Below is the the instruction that describes the task:
### Input:
Copy DocstringMeta from another instance.
### Response:
def from_meta(cls, meta, meta_all=None):
"""Copy DocstringMeta from another instance."""
if len(meta.args) == 2:
name = meta.args[1]
meta_type = None
... |
def add_data(self, X, y, err_y=0, n=0, T=None):
"""Add data to the training data set of the GaussianProcess instance.
Parameters
----------
X : array, (`M`, `D`)
`M` input values of dimension `D`.
y : array, (`M`,)
`M` target values.
er... | Add data to the training data set of the GaussianProcess instance.
Parameters
----------
X : array, (`M`, `D`)
`M` input values of dimension `D`.
y : array, (`M`,)
`M` target values.
err_y : array, (`M`,) or scalar float, optional
Non-... | Below is the the instruction that describes the task:
### Input:
Add data to the training data set of the GaussianProcess instance.
Parameters
----------
X : array, (`M`, `D`)
`M` input values of dimension `D`.
y : array, (`M`,)
`M` target values.
... |
def df(self, list_of_points, force_read=True):
"""
When connected, calling DF should force a reading on the network.
"""
his = []
for point in list_of_points:
try:
his.append(self._findPoint(point, force_read=force_read).history)
... | When connected, calling DF should force a reading on the network. | Below is the the instruction that describes the task:
### Input:
When connected, calling DF should force a reading on the network.
### Response:
def df(self, list_of_points, force_read=True):
"""
When connected, calling DF should force a reading on the network.
"""
his = []
... |
def adjust_commission_cost_basis(self, asset, cost):
"""
A note about cost-basis in zipline: all positions are considered
to share a cost basis, even if they were executed in different
transactions with different commission costs, different prices, etc.
Due to limitations about ... | A note about cost-basis in zipline: all positions are considered
to share a cost basis, even if they were executed in different
transactions with different commission costs, different prices, etc.
Due to limitations about how zipline handles positions, zipline will
currently spread an e... | Below is the the instruction that describes the task:
### Input:
A note about cost-basis in zipline: all positions are considered
to share a cost basis, even if they were executed in different
transactions with different commission costs, different prices, etc.
Due to limitations about how ... |
def batch_write_vasp_input(transformed_structures, vasp_input_set=MPRelaxSet,
output_dir=".", create_directory=True,
subfolder=None,
include_cif=False, **kwargs):
"""
Batch write vasp input for a sequence of transformed structures ... | Batch write vasp input for a sequence of transformed structures to
output_dir, following the format output_dir/{group}/{formula}_{number}.
Args:
transformed_structures: Sequence of TransformedStructures.
vasp_input_set: pymatgen.io.vaspio_set.VaspInputSet to creates
vasp input files... | Below is the the instruction that describes the task:
### Input:
Batch write vasp input for a sequence of transformed structures to
output_dir, following the format output_dir/{group}/{formula}_{number}.
Args:
transformed_structures: Sequence of TransformedStructures.
vasp_input_set: pymatg... |
def _get_binding_info(host_header='', ip_address='*', port=80):
'''
Combine the host header, IP address, and TCP port into bindingInformation
format. Binding Information specifies information to communicate with a
site. It includes the IP address, the port number, and an optional host
header (usuall... | Combine the host header, IP address, and TCP port into bindingInformation
format. Binding Information specifies information to communicate with a
site. It includes the IP address, the port number, and an optional host
header (usually a host name) to communicate with the site.
Args:
host_header ... | Below is the the instruction that describes the task:
### Input:
Combine the host header, IP address, and TCP port into bindingInformation
format. Binding Information specifies information to communicate with a
site. It includes the IP address, the port number, and an optional host
header (usually a hos... |
def send_dynamic_message(sender, message):
"""Send a dynamic message to the listeners.
Dynamic messages represents a progress. Usually it will be appended to
the previous messages.
.. versionadded:: 3.3
:param sender: The sender.
:type sender: object
:param message: An instance of our ri... | Send a dynamic message to the listeners.
Dynamic messages represents a progress. Usually it will be appended to
the previous messages.
.. versionadded:: 3.3
:param sender: The sender.
:type sender: object
:param message: An instance of our rich message class.
:type message: safe.messagin... | Below is the the instruction that describes the task:
### Input:
Send a dynamic message to the listeners.
Dynamic messages represents a progress. Usually it will be appended to
the previous messages.
.. versionadded:: 3.3
:param sender: The sender.
:type sender: object
:param message: An... |
def clean(self):
"""Global cleanup."""
super(LineFormSet, self).clean()
if any(self.errors):
# Already seen errors, let's skip.
return
self.clean_unique_fields() | Global cleanup. | Below is the the instruction that describes the task:
### Input:
Global cleanup.
### Response:
def clean(self):
"""Global cleanup."""
super(LineFormSet, self).clean()
if any(self.errors):
# Already seen errors, let's skip.
return
self.clean_unique_fields() |
def get_used_entities(self,use_specs):
"""
Returns the entities which are imported by a use statement. These
are contained in dicts.
"""
if len(use_specs.strip()) == 0:
return (self.pub_procs, self.pub_absints, self.pub_types, self.pub_vars)
only = bool(self.O... | Returns the entities which are imported by a use statement. These
are contained in dicts. | Below is the the instruction that describes the task:
### Input:
Returns the entities which are imported by a use statement. These
are contained in dicts.
### Response:
def get_used_entities(self,use_specs):
"""
Returns the entities which are imported by a use statement. These
are c... |
def initialize(self, secret_shares=5, secret_threshold=3, pgp_keys=None, root_token_pgp_key=None,
stored_shares=None, recovery_shares=None, recovery_threshold=None, recovery_pgp_keys=None):
"""Initialize a new Vault.
The Vault must not have been previously initialized. The recovery o... | Initialize a new Vault.
The Vault must not have been previously initialized. The recovery options, as well as the stored shares option,
are only available when using Vault HSM.
Supported methods:
PUT: /sys/init. Produces: 200 application/json
:param secret_shares: The numb... | Below is the the instruction that describes the task:
### Input:
Initialize a new Vault.
The Vault must not have been previously initialized. The recovery options, as well as the stored shares option,
are only available when using Vault HSM.
Supported methods:
PUT: /sys/init. P... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.