code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _parse_status(self, output):
'''
Unit testing is so much easier when Vagrant is removed from the
equation.
'''
parsed = self._parse_machine_readable_output(output)
statuses = []
# group tuples by target name
# assuming tuples are sorted by target name,... | Unit testing is so much easier when Vagrant is removed from the
equation. | Below is the the instruction that describes the task:
### Input:
Unit testing is so much easier when Vagrant is removed from the
equation.
### Response:
def _parse_status(self, output):
'''
Unit testing is so much easier when Vagrant is removed from the
equation.
'''
... |
def ref2names2commdct(ref2names, commdct):
"""embed ref2names into commdct"""
for comm in commdct:
for cdct in comm:
try:
refs = cdct['object-list'][0]
validobjects = ref2names[refs]
cdct.update({'validobjects':validobjects})
except... | embed ref2names into commdct | Below is the the instruction that describes the task:
### Input:
embed ref2names into commdct
### Response:
def ref2names2commdct(ref2names, commdct):
"""embed ref2names into commdct"""
for comm in commdct:
for cdct in comm:
try:
refs = cdct['object-list'][0]
... |
def _flush(self, close=False):
"""Flushes remaining output records in the output queues to plasma.
None is used as special type of record that is propagated from sources
to sink to notify that the end of data in a stream.
Attributes:
close (bool): A flag denoting whether t... | Flushes remaining output records in the output queues to plasma.
None is used as special type of record that is propagated from sources
to sink to notify that the end of data in a stream.
Attributes:
close (bool): A flag denoting whether the channel should be
also mar... | Below is the the instruction that describes the task:
### Input:
Flushes remaining output records in the output queues to plasma.
None is used as special type of record that is propagated from sources
to sink to notify that the end of data in a stream.
Attributes:
close (bool)... |
def _find_files(directory):
"""
Find XML files in the directory
"""
pattern = "{directory}/*.xml".format(
directory=directory,
)
files = glob(pattern)
return files | Find XML files in the directory | Below is the the instruction that describes the task:
### Input:
Find XML files in the directory
### Response:
def _find_files(directory):
"""
Find XML files in the directory
"""
pattern = "{directory}/*.xml".format(
directory=directory,
)
files = glob(pattern)
return files |
def get_brightness(self):
"""
Return the average brightness of the image.
"""
# Only download the image if it has changed
if not self.connection.has_changed():
return self.image_brightness
image_path = self.connection.download_image()
converted_image... | Return the average brightness of the image. | Below is the the instruction that describes the task:
### Input:
Return the average brightness of the image.
### Response:
def get_brightness(self):
"""
Return the average brightness of the image.
"""
# Only download the image if it has changed
if not self.connection.has_cha... |
def get_page_square_dpi(pageinfo, options):
"Get the DPI when we require xres == yres, scaled to physical units"
xres = pageinfo.xres or 0
yres = pageinfo.yres or 0
userunit = pageinfo.userunit or 1
return float(
max(
(xres * userunit) or VECTOR_PAGE_DPI,
(yres * user... | Get the DPI when we require xres == yres, scaled to physical units | Below is the the instruction that describes the task:
### Input:
Get the DPI when we require xres == yres, scaled to physical units
### Response:
def get_page_square_dpi(pageinfo, options):
"Get the DPI when we require xres == yres, scaled to physical units"
xres = pageinfo.xres or 0
yres = pageinfo.yr... |
def get_child_directories(path):
"""Return names of immediate child directories"""
if not _is_valid_directory(path):
raise exceptions.InvalidDirectory
entries = os.listdir(path)
directory_names = []
for entry in entries:
abs_entry_path = os.path.join(path, entry)
if _is_val... | Return names of immediate child directories | Below is the the instruction that describes the task:
### Input:
Return names of immediate child directories
### Response:
def get_child_directories(path):
"""Return names of immediate child directories"""
if not _is_valid_directory(path):
raise exceptions.InvalidDirectory
entries = os.listdir... |
def _sort_lows_and_highs(func):
"Decorator for extract_cycles"
@functools.wraps(func)
def wrapper(*args, **kwargs):
for low, high, mult in func(*args, **kwargs):
if low < high:
yield low, high, mult
else:
yield high, low, mult
return wrappe... | Decorator for extract_cycles | Below is the the instruction that describes the task:
### Input:
Decorator for extract_cycles
### Response:
def _sort_lows_and_highs(func):
"Decorator for extract_cycles"
@functools.wraps(func)
def wrapper(*args, **kwargs):
for low, high, mult in func(*args, **kwargs):
if low < high... |
def send_terrain_data_bit(self, bit):
'''send some terrain data'''
lat = self.current_request.lat * 1.0e-7
lon = self.current_request.lon * 1.0e-7
bit_spacing = self.current_request.grid_spacing * 4
(lat, lon) = mp_util.gps_offset(lat, lon,
... | send some terrain data | Below is the the instruction that describes the task:
### Input:
send some terrain data
### Response:
def send_terrain_data_bit(self, bit):
'''send some terrain data'''
lat = self.current_request.lat * 1.0e-7
lon = self.current_request.lon * 1.0e-7
bit_spacing = self.current_request... |
def addresses(self):
"""
Access the addresses
:returns: twilio.rest.api.v2010.account.address.AddressList
:rtype: twilio.rest.api.v2010.account.address.AddressList
"""
if self._addresses is None:
self._addresses = AddressList(self._version, account_sid=self._... | Access the addresses
:returns: twilio.rest.api.v2010.account.address.AddressList
:rtype: twilio.rest.api.v2010.account.address.AddressList | Below is the the instruction that describes the task:
### Input:
Access the addresses
:returns: twilio.rest.api.v2010.account.address.AddressList
:rtype: twilio.rest.api.v2010.account.address.AddressList
### Response:
def addresses(self):
"""
Access the addresses
:returns:... |
def ddl_target_table(self):
"""Optional[TableReference]: Return the DDL target table, present
for CREATE/DROP TABLE/VIEW queries.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.ddlTargetTable
"""
prop = self._job_statistics().get(... | Optional[TableReference]: Return the DDL target table, present
for CREATE/DROP TABLE/VIEW queries.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.ddlTargetTable | Below is the the instruction that describes the task:
### Input:
Optional[TableReference]: Return the DDL target table, present
for CREATE/DROP TABLE/VIEW queries.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.ddlTargetTable
### Response:
def ddl_t... |
def prepare_question_encoder(inputs, hparams):
"""Prepare question encoder.
Args:
inputs: a Tensor.
hparams: run hyperparameters
Returns:
encoder_input: a Tensor, bottom of encoder stack
encoder_self_attention_bias: a bias tensor for use in encoder self-attention
"""
encoder_input = inputs
... | Prepare question encoder.
Args:
inputs: a Tensor.
hparams: run hyperparameters
Returns:
encoder_input: a Tensor, bottom of encoder stack
encoder_self_attention_bias: a bias tensor for use in encoder self-attention | Below is the the instruction that describes the task:
### Input:
Prepare question encoder.
Args:
inputs: a Tensor.
hparams: run hyperparameters
Returns:
encoder_input: a Tensor, bottom of encoder stack
encoder_self_attention_bias: a bias tensor for use in encoder self-attention
### Response:
... |
def promote_owner(self, stream_id, user_id):
''' promote user to owner in stream '''
req_hook = 'pod/v1/room/' + stream_id + '/membership/promoteOwner'
req_args = '{ "id": %s }' % user_id
status_code, response = self.__rest__.POST_query(req_hook, req_args)
self.logger.debug('%s: ... | promote user to owner in stream | Below is the the instruction that describes the task:
### Input:
promote user to owner in stream
### Response:
def promote_owner(self, stream_id, user_id):
''' promote user to owner in stream '''
req_hook = 'pod/v1/room/' + stream_id + '/membership/promoteOwner'
req_args = '{ "id": %s }' % ... |
def list(cls, session, first_name=None, last_name=None, email=None,
modified_since=None):
"""List the customers.
Customers can be filtered on any combination of first name, last name,
email, and modifiedSince.
Args:
session (requests.sessions.Session): Authenti... | List the customers.
Customers can be filtered on any combination of first name, last name,
email, and modifiedSince.
Args:
session (requests.sessions.Session): Authenticated session.
first_name (str, optional): First name of customer.
last_name (str, optiona... | Below is the the instruction that describes the task:
### Input:
List the customers.
Customers can be filtered on any combination of first name, last name,
email, and modifiedSince.
Args:
session (requests.sessions.Session): Authenticated session.
first_name (str, o... |
def process_target(self):
"""Return target with transformations, if any"""
if isinstance(self.target, str):
# Replace single and double quotes with escaped single-quote
self.target = self.target.replace("'", "\'").replace('"', "\'")
return "\"{target}\"".format(target... | Return target with transformations, if any | Below is the the instruction that describes the task:
### Input:
Return target with transformations, if any
### Response:
def process_target(self):
"""Return target with transformations, if any"""
if isinstance(self.target, str):
# Replace single and double quotes with escaped single-qu... |
def set_ids(self, set_image_id, image_id, set_parent_id, parent_id):
"""Changes the UUID and parent UUID for a hard disk medium.
in set_image_id of type bool
Select whether a new image UUID is set or not.
in image_id of type str
New UUID for the image. If an empty strin... | Changes the UUID and parent UUID for a hard disk medium.
in set_image_id of type bool
Select whether a new image UUID is set or not.
in image_id of type str
New UUID for the image. If an empty string is passed, then a new
UUID is automatically created, provided that... | Below is the the instruction that describes the task:
### Input:
Changes the UUID and parent UUID for a hard disk medium.
in set_image_id of type bool
Select whether a new image UUID is set or not.
in image_id of type str
New UUID for the image. If an empty string is passed... |
def randint(nbits: int) -> int:
"""Generate an int with nbits random bits.
Raises ValueError if nbits <= 0, and TypeError if it's not an integer.
>>> randint(16) #doctest:+SKIP
1871
"""
if not isinstance(nbits, int):
raise TypeError('number of bits should be an integer')
if nbits... | Generate an int with nbits random bits.
Raises ValueError if nbits <= 0, and TypeError if it's not an integer.
>>> randint(16) #doctest:+SKIP
1871 | Below is the the instruction that describes the task:
### Input:
Generate an int with nbits random bits.
Raises ValueError if nbits <= 0, and TypeError if it's not an integer.
>>> randint(16) #doctest:+SKIP
1871
### Response:
def randint(nbits: int) -> int:
"""Generate an int with nbits random b... |
def threshold_monitor_hidden_threshold_monitor_security_pause(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
threshold_monitor_hidden = ET.SubElement(config, "threshold-monitor-hidden", xmlns="urn:brocade.com:mgmt:brocade-threshold-monitor")
threshold_m... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def threshold_monitor_hidden_threshold_monitor_security_pause(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
threshold_monitor_hidden = ET.SubElement(config,... |
def has_ist_trigger(self):
"""Return True if this BuildConfig has ImageStreamTag trigger."""
triggers = self.template['spec'].get('triggers', [])
if not triggers:
return False
for trigger in triggers:
if trigger['type'] == 'ImageChange' and \
t... | Return True if this BuildConfig has ImageStreamTag trigger. | Below is the the instruction that describes the task:
### Input:
Return True if this BuildConfig has ImageStreamTag trigger.
### Response:
def has_ist_trigger(self):
"""Return True if this BuildConfig has ImageStreamTag trigger."""
triggers = self.template['spec'].get('triggers', [])
if not... |
def parse_args():
"""
Parse the command line arguments
"""
parser = argparse.ArgumentParser(description = "Add random data from YubiHSM to Linux entropy",
add_help = True,
formatter_class = argparse.ArgumentDefaultsHelpFormatter,
... | Parse the command line arguments | Below is the the instruction that describes the task:
### Input:
Parse the command line arguments
### Response:
def parse_args():
"""
Parse the command line arguments
"""
parser = argparse.ArgumentParser(description = "Add random data from YubiHSM to Linux entropy",
... |
def predict_withGradients(self, X):
"""
Returns the mean, standard deviation, mean gradient and standard deviation gradient at X for all the MCMC samples.
"""
if X.ndim==1: X = X[None,:]
ps = self.model.param_array.copy()
means = []
stds = []
dmdxs = []
... | Returns the mean, standard deviation, mean gradient and standard deviation gradient at X for all the MCMC samples. | Below is the the instruction that describes the task:
### Input:
Returns the mean, standard deviation, mean gradient and standard deviation gradient at X for all the MCMC samples.
### Response:
def predict_withGradients(self, X):
"""
Returns the mean, standard deviation, mean gradient and standard ... |
def _wrap_response(request, data=None, metadata=None, status=200):
"""Creates the JSON response envelope to be sent back to the client.
"""
envelope = metadata or {}
if data is not None:
envelope['data'] = data
return web.Response(
status=status,
... | Creates the JSON response envelope to be sent back to the client. | Below is the the instruction that describes the task:
### Input:
Creates the JSON response envelope to be sent back to the client.
### Response:
def _wrap_response(request, data=None, metadata=None, status=200):
"""Creates the JSON response envelope to be sent back to the client.
"""
envelo... |
def certify_enum(value, kind=None, required=True):
"""
Certifier for enum.
:param value:
The value to be certified.
:param kind:
The enum type that value should be an instance of.
:param bool required:
Whether the value can be `None`. Defaults to True.
:raises CertifierT... | Certifier for enum.
:param value:
The value to be certified.
:param kind:
The enum type that value should be an instance of.
:param bool required:
Whether the value can be `None`. Defaults to True.
:raises CertifierTypeError:
The type is invalid | Below is the the instruction that describes the task:
### Input:
Certifier for enum.
:param value:
The value to be certified.
:param kind:
The enum type that value should be an instance of.
:param bool required:
Whether the value can be `None`. Defaults to True.
:raises Cert... |
def rubberstamp(rest):
"Approve something"
parts = ["Bad credit? No credit? Slow credit?"]
rest = rest.strip()
if rest:
parts.append("%s is" % rest)
karma.Karma.store.change(rest, 1)
parts.append("APPROVED!")
return " ".join(parts) | Approve something | Below is the the instruction that describes the task:
### Input:
Approve something
### Response:
def rubberstamp(rest):
"Approve something"
parts = ["Bad credit? No credit? Slow credit?"]
rest = rest.strip()
if rest:
parts.append("%s is" % rest)
karma.Karma.store.change(rest, 1)
parts.append("APPROVED!")
... |
async def merge_imports_tree(cache, imports, target_trees, base_tree=None):
'''Take an Imports struct and a dictionary of resolved trees and merge the
unified imports tree. If base_tree is supplied, merge that too. There are a
couple reasons for structuring this function the way it is:
- We want to ... | Take an Imports struct and a dictionary of resolved trees and merge the
unified imports tree. If base_tree is supplied, merge that too. There are a
couple reasons for structuring this function the way it is:
- We want to cache merged trees, so that we don't have to do expensive
git operations ... | Below is the the instruction that describes the task:
### Input:
Take an Imports struct and a dictionary of resolved trees and merge the
unified imports tree. If base_tree is supplied, merge that too. There are a
couple reasons for structuring this function the way it is:
- We want to cache merged t... |
def properties(self):
"""
Property for accessing property (doh!) manager of the current job.
:return: instance of :class:`yagocd.resources.property.PropertyManager`
:rtype: yagocd.resources.property.PropertyManager
"""
return PropertyManager(
session=self._se... | Property for accessing property (doh!) manager of the current job.
:return: instance of :class:`yagocd.resources.property.PropertyManager`
:rtype: yagocd.resources.property.PropertyManager | Below is the the instruction that describes the task:
### Input:
Property for accessing property (doh!) manager of the current job.
:return: instance of :class:`yagocd.resources.property.PropertyManager`
:rtype: yagocd.resources.property.PropertyManager
### Response:
def properties(self):
... |
def visit_subscript(self, node, parent):
"""visit a Subscript node by returning a fresh instance of it"""
context = self._get_context(node)
newnode = nodes.Subscript(
ctx=context, lineno=node.lineno, col_offset=node.col_offset, parent=parent
)
newnode.postinit(
... | visit a Subscript node by returning a fresh instance of it | Below is the the instruction that describes the task:
### Input:
visit a Subscript node by returning a fresh instance of it
### Response:
def visit_subscript(self, node, parent):
"""visit a Subscript node by returning a fresh instance of it"""
context = self._get_context(node)
newnode = nod... |
def add_sticker_to_set(self, user_id, name, png_sticker, emojis, mask_position=None):
"""
Use this method to add a new sticker to a set created by the bot. Returns True on success.
:param user_id:
:param name:
:param png_sticker:
:param emojis:
:param mask_positio... | Use this method to add a new sticker to a set created by the bot. Returns True on success.
:param user_id:
:param name:
:param png_sticker:
:param emojis:
:param mask_position:
:return: | Below is the the instruction that describes the task:
### Input:
Use this method to add a new sticker to a set created by the bot. Returns True on success.
:param user_id:
:param name:
:param png_sticker:
:param emojis:
:param mask_position:
:return:
### Response:
de... |
def assign(self, other):
"""Assign ``other`` to ``self``.
This is implemented without `FunctionSpace.lincomb` to ensure that
``self == other`` evaluates to True after ``self.assign(other)``.
"""
if other not in self.space:
raise TypeError('`other` {!r} is not an elem... | Assign ``other`` to ``self``.
This is implemented without `FunctionSpace.lincomb` to ensure that
``self == other`` evaluates to True after ``self.assign(other)``. | Below is the the instruction that describes the task:
### Input:
Assign ``other`` to ``self``.
This is implemented without `FunctionSpace.lincomb` to ensure that
``self == other`` evaluates to True after ``self.assign(other)``.
### Response:
def assign(self, other):
"""Assign ``other`` to ... |
def approve(self, peer_jid):
"""
Approve a subscription request from jid
Args:
peer_jid (str): the JID to approve
"""
self.roster.approve(aioxmpp.JID.fromstr(peer_jid).bare()) | Approve a subscription request from jid
Args:
peer_jid (str): the JID to approve | Below is the the instruction that describes the task:
### Input:
Approve a subscription request from jid
Args:
peer_jid (str): the JID to approve
### Response:
def approve(self, peer_jid):
"""
Approve a subscription request from jid
Args:
peer_jid (str): the JI... |
def group_join(self, inner_iterable, outer_key_selector=identity, inner_key_selector=identity,
result_selector=lambda outer, grouping: grouping):
'''Match elements of two sequences using keys and group the results.
The group_join() query produces a hierarchical result, with all of the
... | Match elements of two sequences using keys and group the results.
The group_join() query produces a hierarchical result, with all of the
inner elements in the result grouped against the matching outer
element.
The order of elements from outer is maintained. For each of these the
... | Below is the the instruction that describes the task:
### Input:
Match elements of two sequences using keys and group the results.
The group_join() query produces a hierarchical result, with all of the
inner elements in the result grouped against the matching outer
element.
The ord... |
def advanced_search(self, terms, relation=None, index=0, limit=25, **kwargs):
"""
Advanced search of track, album or artist.
See `Search section of Deezer API
<https://developers.deezer.com/api/search>`_ for search terms.
:returns: a list of :class:`~deezer.resources.Resource` ... | Advanced search of track, album or artist.
See `Search section of Deezer API
<https://developers.deezer.com/api/search>`_ for search terms.
:returns: a list of :class:`~deezer.resources.Resource` objects.
>>> client.advanced_search({"artist": "Daft Punk", "album": "Homework"})
... | Below is the the instruction that describes the task:
### Input:
Advanced search of track, album or artist.
See `Search section of Deezer API
<https://developers.deezer.com/api/search>`_ for search terms.
:returns: a list of :class:`~deezer.resources.Resource` objects.
>>> client.... |
def round(self, decimals=0, *args, **kwargs):
"""
Round each value in Panel to a specified number of decimal places.
.. versionadded:: 0.18.0
Parameters
----------
decimals : int
Number of decimal places to round to (default: 0).
If decimals is n... | Round each value in Panel to a specified number of decimal places.
.. versionadded:: 0.18.0
Parameters
----------
decimals : int
Number of decimal places to round to (default: 0).
If decimals is negative, it specifies the number of
positions to the l... | Below is the the instruction that describes the task:
### Input:
Round each value in Panel to a specified number of decimal places.
.. versionadded:: 0.18.0
Parameters
----------
decimals : int
Number of decimal places to round to (default: 0).
If decimals i... |
def set_vocabulary(self, peer_id, from_dialogue=None, update=False):
"""
Получает вокабулар из функции get_vocabulary и делает его активным.
"""
self.tokens_array = self.get_vocabulary(
peer_id,
from_dialogue,
update
)
self.create_base... | Получает вокабулар из функции get_vocabulary и делает его активным. | Below is the the instruction that describes the task:
### Input:
Получает вокабулар из функции get_vocabulary и делает его активным.
### Response:
def set_vocabulary(self, peer_id, from_dialogue=None, update=False):
"""
Получает вокабулар из функции get_vocabulary и делает его активным.
"""... |
def nodeChunk(lines):
"""
Parse NODE Method
"""
# Constants
KEYWORDS = ('NODE',
'X_Y',
'ELEV')
result = {'node': None,
'x': None,
'y': None,
'elev': None}
chunks = pt.chunk(KEYWORDS, lines)
# Parse chunks associ... | Parse NODE Method | Below is the the instruction that describes the task:
### Input:
Parse NODE Method
### Response:
def nodeChunk(lines):
"""
Parse NODE Method
"""
# Constants
KEYWORDS = ('NODE',
'X_Y',
'ELEV')
result = {'node': None,
'x': None,
'y'... |
def location_nearbystops(self, origin_coord_lat, origin_coord_long):
""" location.nearbystops """
response = self._request(
'location.nearbystops',
originCoordLat=origin_coord_lat,
originCoordLong=origin_coord_long)
return _get_node(response, 'LocationList', '... | location.nearbystops | Below is the the instruction that describes the task:
### Input:
location.nearbystops
### Response:
def location_nearbystops(self, origin_coord_lat, origin_coord_long):
""" location.nearbystops """
response = self._request(
'location.nearbystops',
originCoordLat=origin_coord... |
def destroy(
self, request, pk=None, parent_lookup_seedteam=None,
parent_lookup_seedteam__organization=None):
'''Remove a permission from a team.'''
self.check_team_permissions(
request, parent_lookup_seedteam,
parent_lookup_seedteam__organization)
... | Remove a permission from a team. | Below is the the instruction that describes the task:
### Input:
Remove a permission from a team.
### Response:
def destroy(
self, request, pk=None, parent_lookup_seedteam=None,
parent_lookup_seedteam__organization=None):
'''Remove a permission from a team.'''
self.check_tea... |
def tocimxmlstr(self, indent=None, ignore_path=False):
"""
Return the CIM-XML representation of this CIM instance,
as a :term:`unicode string`.
*New in pywbem 0.9.*
For the returned CIM-XML representation, see
:meth:`~pywbem.CIMInstance.tocimxml`.
Parameters:
... | Return the CIM-XML representation of this CIM instance,
as a :term:`unicode string`.
*New in pywbem 0.9.*
For the returned CIM-XML representation, see
:meth:`~pywbem.CIMInstance.tocimxml`.
Parameters:
indent (:term:`string` or :term:`integer`):
`None` in... | Below is the the instruction that describes the task:
### Input:
Return the CIM-XML representation of this CIM instance,
as a :term:`unicode string`.
*New in pywbem 0.9.*
For the returned CIM-XML representation, see
:meth:`~pywbem.CIMInstance.tocimxml`.
Parameters:
... |
def send_message(target, data, auth=None, debug=False):
"""Send a single message to AMQP endpoint.
:param target: The target AMQP endpoint.
:type target: str, bytes or ~uamqp.address.Target
:param data: The contents of the message to send.
:type data: str, bytes or ~uamqp.message.Message
:param... | Send a single message to AMQP endpoint.
:param target: The target AMQP endpoint.
:type target: str, bytes or ~uamqp.address.Target
:param data: The contents of the message to send.
:type data: str, bytes or ~uamqp.message.Message
:param auth: The authentication credentials for the endpoint.
Th... | Below is the the instruction that describes the task:
### Input:
Send a single message to AMQP endpoint.
:param target: The target AMQP endpoint.
:type target: str, bytes or ~uamqp.address.Target
:param data: The contents of the message to send.
:type data: str, bytes or ~uamqp.message.Message
... |
def attribute(self, keys):
"""
TODO: document this method
:param keys:
"""
if self['meta']['prefix'] is None:
k = keys
else:
k = self['meta']['prefix'] + "." + keys
return self.get(k) | TODO: document this method
:param keys: | Below is the the instruction that describes the task:
### Input:
TODO: document this method
:param keys:
### Response:
def attribute(self, keys):
"""
TODO: document this method
:param keys:
"""
if self['meta']['prefix'] is None:
k = keys
else:
... |
def argument(*args, **kwargs):
"""Decorator to define an argparse option or argument.
The arguments to this decorator are the same as the
`ArgumentParser.add_argument <https://docs.python.org/3/library/\
argparse.html#the-add-argument-method>`_
method.
"""
def decorator(f):
if not hasat... | Decorator to define an argparse option or argument.
The arguments to this decorator are the same as the
`ArgumentParser.add_argument <https://docs.python.org/3/library/\
argparse.html#the-add-argument-method>`_
method. | Below is the the instruction that describes the task:
### Input:
Decorator to define an argparse option or argument.
The arguments to this decorator are the same as the
`ArgumentParser.add_argument <https://docs.python.org/3/library/\
argparse.html#the-add-argument-method>`_
method.
### Response:
def ... |
def read_float_matrix(rx_specifier):
""" Return float matrix as np array for the given rx specifier. """
path, offset = rx_specifier.strip().split(':', maxsplit=1)
offset = int(offset)
sample_format = 4
with open(path, 'rb') as f:
# move to offset
f.seek... | Return float matrix as np array for the given rx specifier. | Below is the the instruction that describes the task:
### Input:
Return float matrix as np array for the given rx specifier.
### Response:
def read_float_matrix(rx_specifier):
""" Return float matrix as np array for the given rx specifier. """
path, offset = rx_specifier.strip().split(':', maxspli... |
def get_tree_info(decision_tree,
feature_names=None,
**export_graphviz_kwargs):
# type: (...) -> TreeInfo
"""
Convert DecisionTreeClassifier or DecisionTreeRegressor
to an inspectable object.
"""
return TreeInfo(
criterion=decision_tree.criterion,
... | Convert DecisionTreeClassifier or DecisionTreeRegressor
to an inspectable object. | Below is the the instruction that describes the task:
### Input:
Convert DecisionTreeClassifier or DecisionTreeRegressor
to an inspectable object.
### Response:
def get_tree_info(decision_tree,
feature_names=None,
**export_graphviz_kwargs):
# type: (...) -> TreeInfo
... |
def setup(self):
'''
Make sure the monitor is ready for fuzzing
'''
super(BaseMonitor, self).setup()
self.monitor_thread = LoopFuncThread(self._monitor_func)
self.monitor_thread.start() | Make sure the monitor is ready for fuzzing | Below is the the instruction that describes the task:
### Input:
Make sure the monitor is ready for fuzzing
### Response:
def setup(self):
'''
Make sure the monitor is ready for fuzzing
'''
super(BaseMonitor, self).setup()
self.monitor_thread = LoopFuncThread(self._monitor_f... |
def get_help_datapacks(module_name, server_prefix):
"""
Get the help datapacks for a module
Args:
module_name (str): The module to get help data for
server_prefix (str): The command prefix for this server
Returns:
datapacks (list): The help datapacks for the module
"""
... | Get the help datapacks for a module
Args:
module_name (str): The module to get help data for
server_prefix (str): The command prefix for this server
Returns:
datapacks (list): The help datapacks for the module | Below is the the instruction that describes the task:
### Input:
Get the help datapacks for a module
Args:
module_name (str): The module to get help data for
server_prefix (str): The command prefix for this server
Returns:
datapacks (list): The help datapacks for the module
### Res... |
def _get_ncbi_db_url():
"""returns NCBI DB URL based on environment variables and code version
* if NCBI_DB_URL is set, use that
* Otherwise, if _NCBI_URL_KEY is set, use that as the name of a
config file entry and use the corresponding URL
* Otherwise,
"""
if "NCBI_DB_URL" in os.enviro... | returns NCBI DB URL based on environment variables and code version
* if NCBI_DB_URL is set, use that
* Otherwise, if _NCBI_URL_KEY is set, use that as the name of a
config file entry and use the corresponding URL
* Otherwise, | Below is the the instruction that describes the task:
### Input:
returns NCBI DB URL based on environment variables and code version
* if NCBI_DB_URL is set, use that
* Otherwise, if _NCBI_URL_KEY is set, use that as the name of a
config file entry and use the corresponding URL
* Otherwise,
### R... |
def assets2s3():
""" Upload assets files to S3 """
import flask_s3
header("Assets2S3...")
print("")
print("Building assets files..." )
print("")
build_assets(application.app)
print("")
print("Uploading assets files to S3 ...")
flask_s3.create_all(application.app)
print("") | Upload assets files to S3 | Below is the the instruction that describes the task:
### Input:
Upload assets files to S3
### Response:
def assets2s3():
""" Upload assets files to S3 """
import flask_s3
header("Assets2S3...")
print("")
print("Building assets files..." )
print("")
build_assets(application.app)
pr... |
def mac_address(self):
"""Returns the MAC address of the network interface.
If multiple interfaces are provided,
the address of the first found is returned.
"""
if self._mac_address is None:
self._mac_address = self._get_mac_address()
return self._mac_addre... | Returns the MAC address of the network interface.
If multiple interfaces are provided,
the address of the first found is returned. | Below is the the instruction that describes the task:
### Input:
Returns the MAC address of the network interface.
If multiple interfaces are provided,
the address of the first found is returned.
### Response:
def mac_address(self):
"""Returns the MAC address of the network interface.
... |
def instrs_to_body(instrs, context):
"""
Convert a list of Instruction objects to a list of AST body nodes.
"""
stack = []
body = []
process_instrs(instrs, stack, body, context)
if stack:
raise DecompilationError(
"Non-empty stack at the end of instrs_to_body(): %s." % s... | Convert a list of Instruction objects to a list of AST body nodes. | Below is the the instruction that describes the task:
### Input:
Convert a list of Instruction objects to a list of AST body nodes.
### Response:
def instrs_to_body(instrs, context):
"""
Convert a list of Instruction objects to a list of AST body nodes.
"""
stack = []
body = []
process_inst... |
def add_pending_model_content(cursor, publication_id, model):
"""Updates the pending model's content.
This is a secondary step not in ``add_pending_model, because
content reference resolution requires the identifiers as they
will appear in the end publication.
"""
cursor.execute("""\
SEL... | Updates the pending model's content.
This is a secondary step not in ``add_pending_model, because
content reference resolution requires the identifiers as they
will appear in the end publication. | Below is the the instruction that describes the task:
### Input:
Updates the pending model's content.
This is a secondary step not in ``add_pending_model, because
content reference resolution requires the identifiers as they
will appear in the end publication.
### Response:
def add_pending_model_conten... |
def getData(self):
"""Get data of the GitHub user."""
url = self.server + self.name
data = GitHubUser.__getDataFromURL(url)
web = BeautifulSoup(data, "lxml")
self.__getContributions(web)
self.__getLocation(web)
self.__getAvatar(web)
self.__getNumberOfRepos... | Get data of the GitHub user. | Below is the the instruction that describes the task:
### Input:
Get data of the GitHub user.
### Response:
def getData(self):
"""Get data of the GitHub user."""
url = self.server + self.name
data = GitHubUser.__getDataFromURL(url)
web = BeautifulSoup(data, "lxml")
self.__ge... |
def import_identity(self, label: str, encrypted_pri_key: str, pwd: str, salt: str, b58_address: str) -> Identity:
"""
This interface is used to import identity by providing encrypted private key, password, salt and
base58 encode address which should be correspond to the encrypted private key pro... | This interface is used to import identity by providing encrypted private key, password, salt and
base58 encode address which should be correspond to the encrypted private key provided.
:param label: a label for identity.
:param encrypted_pri_key: an encrypted private key in base64 encoding from... | Below is the the instruction that describes the task:
### Input:
This interface is used to import identity by providing encrypted private key, password, salt and
base58 encode address which should be correspond to the encrypted private key provided.
:param label: a label for identity.
:para... |
def ensure_active_group(self):
"""Ensure that the group is active (i.e. joined and synced)"""
with self._client._lock, self._lock:
if self._heartbeat_thread is None:
self._start_heartbeat_thread()
while self.need_rejoin() or self._rejoin_incomplete():
... | Ensure that the group is active (i.e. joined and synced) | Below is the the instruction that describes the task:
### Input:
Ensure that the group is active (i.e. joined and synced)
### Response:
def ensure_active_group(self):
"""Ensure that the group is active (i.e. joined and synced)"""
with self._client._lock, self._lock:
if self._heartbeat_t... |
def load_local_dataset(self, ds_str):
'''
Returns a dataset instance for the local resource
:param ds_str: Path to the resource
'''
if cdl.is_cdl(ds_str):
ds_str = self.generate_dataset(ds_str)
if netcdf.is_netcdf(ds_str):
return MemoizedDataset(... | Returns a dataset instance for the local resource
:param ds_str: Path to the resource | Below is the the instruction that describes the task:
### Input:
Returns a dataset instance for the local resource
:param ds_str: Path to the resource
### Response:
def load_local_dataset(self, ds_str):
'''
Returns a dataset instance for the local resource
:param ds_str: Path to t... |
def is_parent_of_repository(self, id_, repository_id):
"""Tests if an ``Id`` is a direct parent of a repository.
arg: id (osid.id.Id): an ``Id``
arg: repository_id (osid.id.Id): the ``Id`` of a repository
return: (boolean) - ``true`` if this ``id`` is a parent of
`... | Tests if an ``Id`` is a direct parent of a repository.
arg: id (osid.id.Id): an ``Id``
arg: repository_id (osid.id.Id): the ``Id`` of a repository
return: (boolean) - ``true`` if this ``id`` is a parent of
``repository_id,`` ``false`` otherwise
raise: NotFound - ... | Below is the the instruction that describes the task:
### Input:
Tests if an ``Id`` is a direct parent of a repository.
arg: id (osid.id.Id): an ``Id``
arg: repository_id (osid.id.Id): the ``Id`` of a repository
return: (boolean) - ``true`` if this ``id`` is a parent of
... |
def intr_write(self, dev_handle, ep, intf, data, timeout):
r"""Perform an interrupt write.
dev_handle is the value returned by the open_device() method.
The ep parameter is the bEndpointAddress field whose endpoint
the data will be sent to. intf is the bInterfaceNumber field
of ... | r"""Perform an interrupt write.
dev_handle is the value returned by the open_device() method.
The ep parameter is the bEndpointAddress field whose endpoint
the data will be sent to. intf is the bInterfaceNumber field
of the interface containing the endpoint. The data parameter
i... | Below is the the instruction that describes the task:
### Input:
r"""Perform an interrupt write.
dev_handle is the value returned by the open_device() method.
The ep parameter is the bEndpointAddress field whose endpoint
the data will be sent to. intf is the bInterfaceNumber field
o... |
def trans_new(name, transform, inverse, breaks=None,
minor_breaks=None, _format=None,
domain=(-np.inf, np.inf), doc='', **kwargs):
"""
Create a transformation class object
Parameters
----------
name : str
Name of the transformation
transform : callable ``f(x)... | Create a transformation class object
Parameters
----------
name : str
Name of the transformation
transform : callable ``f(x)``
A function (preferably a `ufunc`) that computes
the transformation.
inverse : callable ``f(x)``
A function (preferably a `ufunc`) that compu... | Below is the the instruction that describes the task:
### Input:
Create a transformation class object
Parameters
----------
name : str
Name of the transformation
transform : callable ``f(x)``
A function (preferably a `ufunc`) that computes
the transformation.
inverse : c... |
def to_minutes(days=0, hours=0, minutes=0, seconds=0, milliseconds=0,
round_to_int=True):
"""Returns the computed total number of minutes
"""
total = float(days)*24*60 + float(hours)*60 + float(minutes) + \
float(seconds)/60 + float(milliseconds)/1000/60
return int(round(total)) i... | Returns the computed total number of minutes | Below is the the instruction that describes the task:
### Input:
Returns the computed total number of minutes
### Response:
def to_minutes(days=0, hours=0, minutes=0, seconds=0, milliseconds=0,
round_to_int=True):
"""Returns the computed total number of minutes
"""
total = float(days)*24... |
def destroy(cls, url):
"""
This operation deletes an existing endpoint from the list of all endpoints,
and makes the server stop listening on the endpoint.
*Note*: deleting and disconnecting an endpoint is allowed in the system database only.
Calling this action ... | This operation deletes an existing endpoint from the list of all endpoints,
and makes the server stop listening on the endpoint.
*Note*: deleting and disconnecting an endpoint is allowed in the system database only.
Calling this action in any other database will make the server retu... | Below is the the instruction that describes the task:
### Input:
This operation deletes an existing endpoint from the list of all endpoints,
and makes the server stop listening on the endpoint.
*Note*: deleting and disconnecting an endpoint is allowed in the system database only.
... |
def reset(self):
"""Reset stacks and instruction pointer."""
self.data_stack = stack.Stack()
self.return_stack = stack.Stack()
self.instruction_pointer = 0
return self | Reset stacks and instruction pointer. | Below is the the instruction that describes the task:
### Input:
Reset stacks and instruction pointer.
### Response:
def reset(self):
"""Reset stacks and instruction pointer."""
self.data_stack = stack.Stack()
self.return_stack = stack.Stack()
self.instruction_pointer = 0
re... |
def calculate_clock_skew(self):
"""
Computer average and standard deviation
using all the data points.
"""
n = self.statx_n(self.data_points)
"""
Required to be able to compute the standard
deviation.
"""
if n < 1:
return Decim... | Computer average and standard deviation
using all the data points. | Below is the the instruction that describes the task:
### Input:
Computer average and standard deviation
using all the data points.
### Response:
def calculate_clock_skew(self):
"""
Computer average and standard deviation
using all the data points.
"""
n = self.statx... |
def get_loss_ratios(self):
"""
:returns: a 1-dimensional composite array with loss ratios by loss type
"""
lst = [('user_provided', numpy.bool)]
for cp in self.curve_params:
lst.append((cp.loss_type, F32, len(cp.ratios)))
loss_ratios = numpy.zeros(1, numpy.dty... | :returns: a 1-dimensional composite array with loss ratios by loss type | Below is the the instruction that describes the task:
### Input:
:returns: a 1-dimensional composite array with loss ratios by loss type
### Response:
def get_loss_ratios(self):
"""
:returns: a 1-dimensional composite array with loss ratios by loss type
"""
lst = [('user_provided', ... |
def login(self, login, password):
"""
Login to the remote telnet server.
:param login: Username to use for logging in
:param password: Password to use for logging in
:raise: `InvalidLogin` on failed login
"""
self.client.read_until('Username: ')
self.... | Login to the remote telnet server.
:param login: Username to use for logging in
:param password: Password to use for logging in
:raise: `InvalidLogin` on failed login | Below is the the instruction that describes the task:
### Input:
Login to the remote telnet server.
:param login: Username to use for logging in
:param password: Password to use for logging in
:raise: `InvalidLogin` on failed login
### Response:
def login(self, login, password):
""... |
def draw_step(self):
"""iterator that computes all vertices coordinates and edge routing after
just one step (one layer after the other from top to bottom to top).
Purely inefficient ! Use it only for "animation" or debugging purpose.
"""
ostep = self.ordering_step()
... | iterator that computes all vertices coordinates and edge routing after
just one step (one layer after the other from top to bottom to top).
Purely inefficient ! Use it only for "animation" or debugging purpose. | Below is the the instruction that describes the task:
### Input:
iterator that computes all vertices coordinates and edge routing after
just one step (one layer after the other from top to bottom to top).
Purely inefficient ! Use it only for "animation" or debugging purpose.
### Response:
def... |
def getBucketIndices(self, input):
""" See method description in base.py """
if input == SENTINEL_VALUE_FOR_MISSING_DATA:
# Encoder each sub-field
return [None] * len(self.encoders)
else:
assert isinstance(input, datetime.datetime)
# Get the scalar values for each sub-field
... | See method description in base.py | Below is the the instruction that describes the task:
### Input:
See method description in base.py
### Response:
def getBucketIndices(self, input):
""" See method description in base.py """
if input == SENTINEL_VALUE_FOR_MISSING_DATA:
# Encoder each sub-field
return [None] * len(self.encoders)... |
def validate_range(low=None, high=None):
"""
Validate the range of a field with either low, high, or equal.
Should work with anything that supports '>' and '<' operators.
:param low: Smallest value required.
:param high: Longest value required.
:raises: ``ValidationError('range_low')``
:rai... | Validate the range of a field with either low, high, or equal.
Should work with anything that supports '>' and '<' operators.
:param low: Smallest value required.
:param high: Longest value required.
:raises: ``ValidationError('range_low')``
:raises: ``ValidationError('range_high')``
:raises: `... | Below is the the instruction that describes the task:
### Input:
Validate the range of a field with either low, high, or equal.
Should work with anything that supports '>' and '<' operators.
:param low: Smallest value required.
:param high: Longest value required.
:raises: ``ValidationError('range_... |
def upload(self, picture, resize=None, rotation=None, noexif=None,
callback=None):
"""
wraps upload function
:param str/tuple/list picture: Path to picture as str or picture data. \
If data a tuple or list with the file name as str \
and data as byte objec... | wraps upload function
:param str/tuple/list picture: Path to picture as str or picture data. \
If data a tuple or list with the file name as str \
and data as byte object in that order.
:param str resize: Aresolution in the folowing format: \
'80x80'(optional)
... | Below is the the instruction that describes the task:
### Input:
wraps upload function
:param str/tuple/list picture: Path to picture as str or picture data. \
If data a tuple or list with the file name as str \
and data as byte object in that order.
:param str resize: Areso... |
def round(self, eps=1e-14, rmax=1000000):
"""Applies TT rounding procedure to the TT-vector and **returns rounded tensor**.
:param eps: Rounding accuracy.
:type eps: float
:param rmax: Maximal rank
:type rmax: int
:returns: tensor -- rounded TT-vector.
Usage exa... | Applies TT rounding procedure to the TT-vector and **returns rounded tensor**.
:param eps: Rounding accuracy.
:type eps: float
:param rmax: Maximal rank
:type rmax: int
:returns: tensor -- rounded TT-vector.
Usage example:
>>> a = tt.ones(2, 10)
>>> b =... | Below is the the instruction that describes the task:
### Input:
Applies TT rounding procedure to the TT-vector and **returns rounded tensor**.
:param eps: Rounding accuracy.
:type eps: float
:param rmax: Maximal rank
:type rmax: int
:returns: tensor -- rounded TT-vector.
... |
def calc_worklog(stdout=Ellipsis, stderr=Ellipsis, verbose=False):
'''
calc_worklog constructs the worklog from the stdout, stderr, stdin, and verbose arguments.
'''
try: cols = int(os.environ['COLUMNS'])
except Exception: cols = 80
return pimms.worklog(columns=cols, stdout=stdout, stderr=stderr... | calc_worklog constructs the worklog from the stdout, stderr, stdin, and verbose arguments. | Below is the the instruction that describes the task:
### Input:
calc_worklog constructs the worklog from the stdout, stderr, stdin, and verbose arguments.
### Response:
def calc_worklog(stdout=Ellipsis, stderr=Ellipsis, verbose=False):
'''
calc_worklog constructs the worklog from the stdout, stderr, stdin... |
def quadrant(xcoord, ycoord):
"""
Find the quadrant a pair of coordinates are located in
:type xcoord: integer
:param xcoord: The x coordinate to find the quadrant for
:type ycoord: integer
:param ycoord: The y coordinate to find the quadrant for
"""
xneg = bool(xcoord < 0)
yneg =... | Find the quadrant a pair of coordinates are located in
:type xcoord: integer
:param xcoord: The x coordinate to find the quadrant for
:type ycoord: integer
:param ycoord: The y coordinate to find the quadrant for | Below is the the instruction that describes the task:
### Input:
Find the quadrant a pair of coordinates are located in
:type xcoord: integer
:param xcoord: The x coordinate to find the quadrant for
:type ycoord: integer
:param ycoord: The y coordinate to find the quadrant for
### Response:
def q... |
def key(self, id_num):
"""Get the specified deploy key.
:param int id_num: (required), id of the key
:returns: :class:`Key <github3.users.Key>` if successful, else None
"""
json = None
if int(id_num) > 0:
url = self._build_url('keys', str(id_num), base_url=se... | Get the specified deploy key.
:param int id_num: (required), id of the key
:returns: :class:`Key <github3.users.Key>` if successful, else None | Below is the the instruction that describes the task:
### Input:
Get the specified deploy key.
:param int id_num: (required), id of the key
:returns: :class:`Key <github3.users.Key>` if successful, else None
### Response:
def key(self, id_num):
"""Get the specified deploy key.
:pa... |
def delete(self):
"""Delete this file"""
if not self.remote:
if not os.path.exists(self.projectpath + self.basedir + '/' + self.filename):
return False
else:
os.unlink(self.projectpath + self.basedir + '/' + self.filename)
#Remove meta... | Delete this file | Below is the the instruction that describes the task:
### Input:
Delete this file
### Response:
def delete(self):
"""Delete this file"""
if not self.remote:
if not os.path.exists(self.projectpath + self.basedir + '/' + self.filename):
return False
else:
... |
def is_complete(self):
"""Do all required parameters have values?"""
return all(p.name in self.values for p in self.parameters if p.required) | Do all required parameters have values? | Below is the the instruction that describes the task:
### Input:
Do all required parameters have values?
### Response:
def is_complete(self):
"""Do all required parameters have values?"""
return all(p.name in self.values for p in self.parameters if p.required) |
def get_configuration():
"""
get a configuration (snapshot) that can be used to call configure
snapshot = get_configuration()
configure(**snapshot)
"""
root = getLogger()
name_levels = [('', logging.getLevelName(root.level))]
name_levels.extend(
(name, logging.getLevelName(logger... | get a configuration (snapshot) that can be used to call configure
snapshot = get_configuration()
configure(**snapshot) | Below is the the instruction that describes the task:
### Input:
get a configuration (snapshot) that can be used to call configure
snapshot = get_configuration()
configure(**snapshot)
### Response:
def get_configuration():
"""
get a configuration (snapshot) that can be used to call configure
sn... |
def _check_init(self, node):
"""check that the __init__ method call super or ancestors'__init__
method
"""
if not self.linter.is_message_enabled(
"super-init-not-called"
) and not self.linter.is_message_enabled("non-parent-init-called"):
return
kla... | check that the __init__ method call super or ancestors'__init__
method | Below is the the instruction that describes the task:
### Input:
check that the __init__ method call super or ancestors'__init__
method
### Response:
def _check_init(self, node):
"""check that the __init__ method call super or ancestors'__init__
method
"""
if not self.linter... |
def get_function_descriptor_list(self):
"""Return a list of bytes representing the function descriptor.
This function is used to pass this function descriptor to backend.
Returns:
A list of bytes.
"""
descriptor_list = []
if self.is_for_driver_task:
... | Return a list of bytes representing the function descriptor.
This function is used to pass this function descriptor to backend.
Returns:
A list of bytes. | Below is the the instruction that describes the task:
### Input:
Return a list of bytes representing the function descriptor.
This function is used to pass this function descriptor to backend.
Returns:
A list of bytes.
### Response:
def get_function_descriptor_list(self):
"""R... |
def _create_window_function(name, doc=''):
""" Create a window function by name """
def _():
sc = SparkContext._active_spark_context
jc = getattr(sc._jvm.functions, name)()
return Column(jc)
_.__name__ = name
_.__doc__ = 'Window function: ' + doc
return _ | Create a window function by name | Below is the the instruction that describes the task:
### Input:
Create a window function by name
### Response:
def _create_window_function(name, doc=''):
""" Create a window function by name """
def _():
sc = SparkContext._active_spark_context
jc = getattr(sc._jvm.functions, name)()
... |
def to_json(self, filename):
"""
Writes the experimental setup to a JSON file
Parameters
----------
filename : str
Absolute path where to write the JSON file
"""
with open(filename, 'w') as fp:
json.dump(dict(stimuli=self.stimuli, inhibito... | Writes the experimental setup to a JSON file
Parameters
----------
filename : str
Absolute path where to write the JSON file | Below is the the instruction that describes the task:
### Input:
Writes the experimental setup to a JSON file
Parameters
----------
filename : str
Absolute path where to write the JSON file
### Response:
def to_json(self, filename):
"""
Writes the experimental s... |
def InitUI(self):
"""
Initialize interface for drop down menu
"""
if self.data_type in ['orient', 'ages']:
belongs_to = []
else:
parent_table_name = self.parent_type + "s"
if parent_table_name in self.contribution.tables:
belong... | Initialize interface for drop down menu | Below is the the instruction that describes the task:
### Input:
Initialize interface for drop down menu
### Response:
def InitUI(self):
"""
Initialize interface for drop down menu
"""
if self.data_type in ['orient', 'ages']:
belongs_to = []
else:
par... |
def remove(self, membership_id):
"""Remove a member from the group.
:param str membership_id: the ID of a member in this group
:return: ``True`` if the member was successfully removed
:rtype: bool
"""
path = '{}/remove'.format(membership_id)
url = utils.urljoin(s... | Remove a member from the group.
:param str membership_id: the ID of a member in this group
:return: ``True`` if the member was successfully removed
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Remove a member from the group.
:param str membership_id: the ID of a member in this group
:return: ``True`` if the member was successfully removed
:rtype: bool
### Response:
def remove(self, membership_id):
"""Remove... |
def find_project_config_path(path=None):
"""Find project config path."""
path = Path(path) if path else Path.cwd()
abspath = path.absolute()
project_path = get_project_config_path(abspath)
if project_path:
return project_path
for parent in abspath.parents:
project_path = get_pr... | Find project config path. | Below is the the instruction that describes the task:
### Input:
Find project config path.
### Response:
def find_project_config_path(path=None):
"""Find project config path."""
path = Path(path) if path else Path.cwd()
abspath = path.absolute()
project_path = get_project_config_path(abspath)
... |
def read_sudoers():
""" Read the sudoers entry for the specified user.
args:
username (str): username.
returns:`r
str: sudoers entry for the specified user.
"""
sudoers_path = '/etc/sudoers'
rnd_chars = random_string(length=RANDOM_FILE_EXT_LENGTH)
tmp_sudoers_path = '/tmp/s... | Read the sudoers entry for the specified user.
args:
username (str): username.
returns:`r
str: sudoers entry for the specified user. | Below is the the instruction that describes the task:
### Input:
Read the sudoers entry for the specified user.
args:
username (str): username.
returns:`r
str: sudoers entry for the specified user.
### Response:
def read_sudoers():
""" Read the sudoers entry for the specified user.
... |
def loadHistory(self):
""" Loads the shop sale history
Raises
parseException
"""
pg = self.usr.getPage("http://www.neopets.com/market.phtml?type=sales")\
try:
rows = pg.find("b", text = "Date").parent.parent.parent.find_all("tr")
... | Loads the shop sale history
Raises
parseException | Below is the the instruction that describes the task:
### Input:
Loads the shop sale history
Raises
parseException
### Response:
def loadHistory(self):
""" Loads the shop sale history
Raises
parseException
"""
pg = self.usr.get... |
def _microcanonical_average_moments(moments, alpha):
"""
Compute the average moments of the cluster size distributions
Helper function for :func:`microcanonical_averages`
Parameters
----------
moments : 2-D :py:class:`numpy.ndarray` of int
``moments.shape[1] == 5`.
Each array ... | Compute the average moments of the cluster size distributions
Helper function for :func:`microcanonical_averages`
Parameters
----------
moments : 2-D :py:class:`numpy.ndarray` of int
``moments.shape[1] == 5`.
Each array ``moments[r, :]`` is the ``moments`` field of the output of
... | Below is the the instruction that describes the task:
### Input:
Compute the average moments of the cluster size distributions
Helper function for :func:`microcanonical_averages`
Parameters
----------
moments : 2-D :py:class:`numpy.ndarray` of int
``moments.shape[1] == 5`.
Each ar... |
def validate(self, *args, **kwargs):
"""
Step 4 (6 for invariant). Process contract (validator)
"""
# Schemes validation interface
if is_scheme(self.validator):
params = getcallargs(self.function, *args, **kwargs)
params.update(kwargs)
validato... | Step 4 (6 for invariant). Process contract (validator) | Below is the the instruction that describes the task:
### Input:
Step 4 (6 for invariant). Process contract (validator)
### Response:
def validate(self, *args, **kwargs):
"""
Step 4 (6 for invariant). Process contract (validator)
"""
# Schemes validation interface
if is_sche... |
def update_job(self, job_record, uow, new_state):
""" method updates job record with a new unit_of_work and new state"""
original_job_state = job_record.state
job_record.state = new_state
job_record.related_unit_of_work = uow.db_id
self.job_dao.update(job_record)
msg = '... | method updates job record with a new unit_of_work and new state | Below is the the instruction that describes the task:
### Input:
method updates job record with a new unit_of_work and new state
### Response:
def update_job(self, job_record, uow, new_state):
""" method updates job record with a new unit_of_work and new state"""
original_job_state = job_record.sta... |
def pisaPreLoop(node, context, collect=False):
"""
Collect all CSS definitions
"""
data = u""
if node.nodeType == Node.TEXT_NODE and collect:
data = node.data
elif node.nodeType == Node.ELEMENT_NODE:
name = node.tagName.lower()
if name in ("style", "link"):
... | Collect all CSS definitions | Below is the the instruction that describes the task:
### Input:
Collect all CSS definitions
### Response:
def pisaPreLoop(node, context, collect=False):
"""
Collect all CSS definitions
"""
data = u""
if node.nodeType == Node.TEXT_NODE and collect:
data = node.data
elif node.nodeT... |
def _fill(self):
"""Advance the iterator without returning the old head."""
try:
self._head = self._iterable.next()
except StopIteration:
self._head = None | Advance the iterator without returning the old head. | Below is the the instruction that describes the task:
### Input:
Advance the iterator without returning the old head.
### Response:
def _fill(self):
"""Advance the iterator without returning the old head."""
try:
self._head = self._iterable.next()
except StopIteration:
self._head = None |
def list(self, list_folders=False, list_files=False):
"""
A simple generator that yields a File or Folder object based on
the arguments.
"""
a_files = os.listdir(self.folder.path)
for a_file in a_files:
path = self.folder.child(a_file)
if os.path.... | A simple generator that yields a File or Folder object based on
the arguments. | Below is the the instruction that describes the task:
### Input:
A simple generator that yields a File or Folder object based on
the arguments.
### Response:
def list(self, list_folders=False, list_files=False):
"""
A simple generator that yields a File or Folder object based on
the... |
def add_xenon_worker(self, worker_config):
"""Adds a worker to the pool; sets gears in motion."""
c = XenonInteractiveWorker(self.machine, worker_config)
w = RemoteWorker(
worker_config.name, threading.Lock(),
worker_config.n_threads, [], *c.setup())
with self.wl... | Adds a worker to the pool; sets gears in motion. | Below is the the instruction that describes the task:
### Input:
Adds a worker to the pool; sets gears in motion.
### Response:
def add_xenon_worker(self, worker_config):
"""Adds a worker to the pool; sets gears in motion."""
c = XenonInteractiveWorker(self.machine, worker_config)
w = Remot... |
def get_value(self, variant_line=None, variant_dict=None, entry=None,
raw_entry=None, vcf_header=None, csq_format=None, dict_key=None,
individual_id=None):
"""
Return the value as specified by plugin
Get value will return one value or None if no correct value is found.... | Return the value as specified by plugin
Get value will return one value or None if no correct value is found.
Arguments:
variant_line (str): A vcf variant line
variant_dict (dict): A variant dictionary
entry (list): A splitted entry
raw_e... | Below is the the instruction that describes the task:
### Input:
Return the value as specified by plugin
Get value will return one value or None if no correct value is found.
Arguments:
variant_line (str): A vcf variant line
variant_dict (dict): A variant di... |
def opened(self):
"""Handler called when the WebSocket connection is opened. The first
thing to do then is to authenticate ourselves."""
request = {
'type': 'authenticate',
'token': self._token,
'userAgent': '{} ws4py/{}'.format(version.user_agent,
... | Handler called when the WebSocket connection is opened. The first
thing to do then is to authenticate ourselves. | Below is the the instruction that describes the task:
### Input:
Handler called when the WebSocket connection is opened. The first
thing to do then is to authenticate ourselves.
### Response:
def opened(self):
"""Handler called when the WebSocket connection is opened. The first
thing to do ... |
def get_account_authToken(self, account=None, account_name=''):
""" Use the DelegateAuthRequest to provide a token and his lifetime
for the provided account.
If account is provided we use it,
else we retreive the account from the provided account_name.
"""
if account is ... | Use the DelegateAuthRequest to provide a token and his lifetime
for the provided account.
If account is provided we use it,
else we retreive the account from the provided account_name. | Below is the the instruction that describes the task:
### Input:
Use the DelegateAuthRequest to provide a token and his lifetime
for the provided account.
If account is provided we use it,
else we retreive the account from the provided account_name.
### Response:
def get_account_authToken(... |
def on_update_page_links(self, evt):
""" Perform PDF update of changed links."""
if not self.update_links: # skip if unsupported links
evt.Skip()
return
pg = self.doc[getint(self.TextToPage.Value) -1]
for i in range(len(self.page_links)):
... | Perform PDF update of changed links. | Below is the the instruction that describes the task:
### Input:
Perform PDF update of changed links.
### Response:
def on_update_page_links(self, evt):
""" Perform PDF update of changed links."""
if not self.update_links: # skip if unsupported links
evt.Skip()
... |
def folders(self, mountPoint):
"""Get an iterator of JFSFolder() from the given mountPoint.
"mountPoint" may be either an actual mountPoint element from JFSDevice.mountPoints{} or its .name. """
if isinstance(mountPoint, six.string_types):
# shortcut: pass a mountpoint name
... | Get an iterator of JFSFolder() from the given mountPoint.
"mountPoint" may be either an actual mountPoint element from JFSDevice.mountPoints{} or its .name. | Below is the the instruction that describes the task:
### Input:
Get an iterator of JFSFolder() from the given mountPoint.
"mountPoint" may be either an actual mountPoint element from JFSDevice.mountPoints{} or its .name.
### Response:
def folders(self, mountPoint):
"""Get an iterator of JFSFolder... |
def index_feature(self, feature_name, tokenize=lambda x: x, structured=False):
"""
Creates a new :class:`.FeatureSet` from the attribute ``feature_name``
in each :class:`.Paper`\.
New :class:`.FeatureSet`\s are added to :attr:`.features`\.
Parameters
----------
... | Creates a new :class:`.FeatureSet` from the attribute ``feature_name``
in each :class:`.Paper`\.
New :class:`.FeatureSet`\s are added to :attr:`.features`\.
Parameters
----------
feature_name : str
The name of a :class:`.Paper` attribute. | Below is the the instruction that describes the task:
### Input:
Creates a new :class:`.FeatureSet` from the attribute ``feature_name``
in each :class:`.Paper`\.
New :class:`.FeatureSet`\s are added to :attr:`.features`\.
Parameters
----------
feature_name : str
... |
def _set(self, name, value):
"""
Args:
name (str | unicode): Name of slot to set.
value: Associated value
"""
if value is not UNSET:
if isinstance(value, Slotted):
current = getattr(self, name, UNSET)
if current is None ... | Args:
name (str | unicode): Name of slot to set.
value: Associated value | Below is the the instruction that describes the task:
### Input:
Args:
name (str | unicode): Name of slot to set.
value: Associated value
### Response:
def _set(self, name, value):
"""
Args:
name (str | unicode): Name of slot to set.
value: Associated... |
def _validate_indexers(
self, indexers: Mapping,
) -> List[Tuple[Any, Union[slice, Variable]]]:
""" Here we make sure
+ indexer has a valid keys
+ indexer is in a valid data type
+ string indexers are cast to the appropriate date type if the
associated index is a Da... | Here we make sure
+ indexer has a valid keys
+ indexer is in a valid data type
+ string indexers are cast to the appropriate date type if the
associated index is a DatetimeIndex or CFTimeIndex | Below is the the instruction that describes the task:
### Input:
Here we make sure
+ indexer has a valid keys
+ indexer is in a valid data type
+ string indexers are cast to the appropriate date type if the
associated index is a DatetimeIndex or CFTimeIndex
### Response:
def _vali... |
def _track(self, state, live_defs, statements):
"""
Given all live definitions prior to this program point, track the changes, and return a new list of live
definitions. We scan through the action list of the new state to track the changes.
:param state: The input state at tha... | Given all live definitions prior to this program point, track the changes, and return a new list of live
definitions. We scan through the action list of the new state to track the changes.
:param state: The input state at that program point.
:param live_defs: All live definition... | Below is the the instruction that describes the task:
### Input:
Given all live definitions prior to this program point, track the changes, and return a new list of live
definitions. We scan through the action list of the new state to track the changes.
:param state: The input state at th... |
def content_type(self):
"""
Returns the content type of the request in all cases where it is
different than a submitted form - application/x-www-form-urlencoded
"""
type_formencoded = "application/x-www-form-urlencoded"
ctype = self.request.META.get('CONTENT_TYPE', type_... | Returns the content type of the request in all cases where it is
different than a submitted form - application/x-www-form-urlencoded | Below is the the instruction that describes the task:
### Input:
Returns the content type of the request in all cases where it is
different than a submitted form - application/x-www-form-urlencoded
### Response:
def content_type(self):
"""
Returns the content type of the request in all case... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.