code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def call(self, node, children):
'call = name "(" arguments ")"'
name, _, arguments, _ = children
return name(*arguments) | call = name "(" arguments ")" | Below is the the instruction that describes the task:
### Input:
call = name "(" arguments ")"
### Response:
def call(self, node, children):
'call = name "(" arguments ")"'
name, _, arguments, _ = children
return name(*arguments) |
def start(self, max_val):
"""
:arg max_val Maximum value
:type max_val int
"""
self._timer.init_timer(max_value=max_val)
self._infinite_mode = max_val <= 0
self._infinite_position = 0
self._max = max_val
self._fill_empty()
self._value = 0
self.progress(0)
self._status =... | :arg max_val Maximum value
:type max_val int | Below is the the instruction that describes the task:
### Input:
:arg max_val Maximum value
:type max_val int
### Response:
def start(self, max_val):
"""
:arg max_val Maximum value
:type max_val int
"""
self._timer.init_timer(max_value=max_val)
self._infinite_mode = max_val <= 0
se... |
def get_kwargs(self, args):
"""
Given a Namespace object drawn from argparse, determines the
keyword arguments to pass to the underlying function. Note
that, if the underlying function accepts all keyword
arguments, the dictionary returned will contain the entire
content... | Given a Namespace object drawn from argparse, determines the
keyword arguments to pass to the underlying function. Note
that, if the underlying function accepts all keyword
arguments, the dictionary returned will contain the entire
contents of the Namespace object. Also note that an
... | Below is the the instruction that describes the task:
### Input:
Given a Namespace object drawn from argparse, determines the
keyword arguments to pass to the underlying function. Note
that, if the underlying function accepts all keyword
arguments, the dictionary returned will contain the e... |
def AddFile(self, filepath):
"""Adds a file path as a source.
Args:
filepath: a string representing a path to the file.
Returns:
True if the file is not an already existing source.
"""
if filepath not in self._files:
self._files.add(filepath)
return True
return False | Adds a file path as a source.
Args:
filepath: a string representing a path to the file.
Returns:
True if the file is not an already existing source. | Below is the the instruction that describes the task:
### Input:
Adds a file path as a source.
Args:
filepath: a string representing a path to the file.
Returns:
True if the file is not an already existing source.
### Response:
def AddFile(self, filepath):
"""Adds a file path as a source.... |
def load_from_file(filepath, format_=FileFormat.py, update_data_callback=None,
disable_memcache=False):
"""Load data from a file.
Note:
Any functions from a .py file will be converted to `SourceCode` objects.
Args:
filepath (str): File to load.
format_ (`FileForm... | Load data from a file.
Note:
Any functions from a .py file will be converted to `SourceCode` objects.
Args:
filepath (str): File to load.
format_ (`FileFormat`): Format of file contents.
update_data_callback (callable): Used to change data before it is
returned or c... | Below is the the instruction that describes the task:
### Input:
Load data from a file.
Note:
Any functions from a .py file will be converted to `SourceCode` objects.
Args:
filepath (str): File to load.
format_ (`FileFormat`): Format of file contents.
update_data_callback (... |
def instruments(
self,
accountID,
**kwargs
):
"""
Get the list of tradeable instruments for the given Account. The list
of tradeable instruments is dependent on the regulatory division that
the Account is located in, thus should be the same for all Accounts
... | Get the list of tradeable instruments for the given Account. The list
of tradeable instruments is dependent on the regulatory division that
the Account is located in, thus should be the same for all Accounts
owned by a single user.
Args:
accountID:
Account Id... | Below is the the instruction that describes the task:
### Input:
Get the list of tradeable instruments for the given Account. The list
of tradeable instruments is dependent on the regulatory division that
the Account is located in, thus should be the same for all Accounts
owned by a single u... |
def credential_list_mappings(self):
"""
Access the credential_list_mappings
:returns: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingList
:rtype: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingList
"""... | Access the credential_list_mappings
:returns: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingList
:rtype: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingList | Below is the the instruction that describes the task:
### Input:
Access the credential_list_mappings
:returns: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingList
:rtype: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingLis... |
def warn_on_var_indirection(self) -> bool:
"""If True, warn when a Var reference cannot be direct linked (iff
use_var_indirection is False).."""
return not self.use_var_indirection and self._opts.entry(
WARN_ON_VAR_INDIRECTION, True
) | If True, warn when a Var reference cannot be direct linked (iff
use_var_indirection is False).. | Below is the the instruction that describes the task:
### Input:
If True, warn when a Var reference cannot be direct linked (iff
use_var_indirection is False)..
### Response:
def warn_on_var_indirection(self) -> bool:
"""If True, warn when a Var reference cannot be direct linked (iff
use_va... |
def tally(self, chain):
"""Adds current value to trace."""
try:
# I changed str(x) to '%f'%x to solve a bug appearing due to
# locale settings. In french for instance, str prints a comma
# instead of a colon to indicate the decimal, which confuses
# the d... | Adds current value to trace. | Below is the the instruction that describes the task:
### Input:
Adds current value to trace.
### Response:
def tally(self, chain):
"""Adds current value to trace."""
try:
# I changed str(x) to '%f'%x to solve a bug appearing due to
# locale settings. In french for instance... |
def get_object(self, cont, obj, local_file=None, return_bin=False):
'''
Retrieve a file from Swift
'''
try:
if local_file is None and return_bin is False:
return False
headers, body = self.conn.get_object(cont, obj, resp_chunk_size=65536)
... | Retrieve a file from Swift | Below is the the instruction that describes the task:
### Input:
Retrieve a file from Swift
### Response:
def get_object(self, cont, obj, local_file=None, return_bin=False):
'''
Retrieve a file from Swift
'''
try:
if local_file is None and return_bin is False:
... |
def prepare_series(self) -> None:
# noinspection PyUnresolvedReferences
"""Call |XMLSubseries.prepare_series| of all |XMLSubseries|
objects with the same memory |set| object.
>>> from hydpy.auxs.xmltools import XMLInterface, XMLSubseries
>>> from hydpy import data
>>> in... | Call |XMLSubseries.prepare_series| of all |XMLSubseries|
objects with the same memory |set| object.
>>> from hydpy.auxs.xmltools import XMLInterface, XMLSubseries
>>> from hydpy import data
>>> interface = XMLInterface('single_run.xml', data.get_path('LahnH'))
>>> series_io = in... | Below is the the instruction that describes the task:
### Input:
Call |XMLSubseries.prepare_series| of all |XMLSubseries|
objects with the same memory |set| object.
>>> from hydpy.auxs.xmltools import XMLInterface, XMLSubseries
>>> from hydpy import data
>>> interface = XMLInterface... |
def _write_metadata(self, handle):
'''Write metadata to a file handle.
Parameters
----------
handle : file
Write metadata and C3D motion frames to the given file handle. The
writer does not close the handle.
'''
self.check_metadata()
# he... | Write metadata to a file handle.
Parameters
----------
handle : file
Write metadata and C3D motion frames to the given file handle. The
writer does not close the handle. | Below is the the instruction that describes the task:
### Input:
Write metadata to a file handle.
Parameters
----------
handle : file
Write metadata and C3D motion frames to the given file handle. The
writer does not close the handle.
### Response:
def _write_metada... |
def create_buffer(self, bins, repeats, base_buffer_size, max_buffer_size=0):
"""Create buffer for reading samples"""
samples = bins * repeats
buffer_repeats = 1
buffer_size = math.ceil(samples / base_buffer_size) * base_buffer_size
if not max_buffer_size:
# Max buffe... | Create buffer for reading samples | Below is the the instruction that describes the task:
### Input:
Create buffer for reading samples
### Response:
def create_buffer(self, bins, repeats, base_buffer_size, max_buffer_size=0):
"""Create buffer for reading samples"""
samples = bins * repeats
buffer_repeats = 1
buffer_si... |
def _height_and_width(self):
"""
Query console for dimensions
Returns named tuple (columns, lines)
"""
# In Python 3.3+ we can let the standard library handle this
if GTS_SUPPORTED:
return os.get_terminal_size(self.stream_fd)
window = get_csbi(self.s... | Query console for dimensions
Returns named tuple (columns, lines) | Below is the the instruction that describes the task:
### Input:
Query console for dimensions
Returns named tuple (columns, lines)
### Response:
def _height_and_width(self):
"""
Query console for dimensions
Returns named tuple (columns, lines)
"""
# In Python 3.3+ w... |
def UpdateChainAndProcess(self, parser_mediator, registry_key, **kwargs):
"""Updates the parser chain and processes a Windows Registry key or value.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
registry_key ... | Updates the parser chain and processes a Windows Registry key or value.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
registry_key (dfwinreg.WinRegistryKey): Windows Registry key.
Raises:
ValueError: I... | Below is the the instruction that describes the task:
### Input:
Updates the parser chain and processes a Windows Registry key or value.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
registry_key (dfwinreg.Wi... |
def encode_field(self, field, value):
"""Encode a python field value to a JSON value.
Args:
field: A ProtoRPC field instance.
value: A python value supported by field.
Returns:
A JSON serializable value appropriate for field.
"""
# Override the handling of 64-bit integers, so the... | Encode a python field value to a JSON value.
Args:
field: A ProtoRPC field instance.
value: A python value supported by field.
Returns:
A JSON serializable value appropriate for field. | Below is the the instruction that describes the task:
### Input:
Encode a python field value to a JSON value.
Args:
field: A ProtoRPC field instance.
value: A python value supported by field.
Returns:
A JSON serializable value appropriate for field.
### Response:
def encode_field(self, ... |
def siblings(self, node):
""" Returns a :class:`QuerySet` of all siblings of a given
:class:`CTENode` `node`.
:param node: a :class:`CTENode` whose siblings are required.
:returns: A :class:`QuerySet` of all siblings of the given `node`.
"""
# We need to rea... | Returns a :class:`QuerySet` of all siblings of a given
:class:`CTENode` `node`.
:param node: a :class:`CTENode` whose siblings are required.
:returns: A :class:`QuerySet` of all siblings of the given `node`. | Below is the the instruction that describes the task:
### Input:
Returns a :class:`QuerySet` of all siblings of a given
:class:`CTENode` `node`.
:param node: a :class:`CTENode` whose siblings are required.
:returns: A :class:`QuerySet` of all siblings of the given `node`.
### R... |
async def enable(self, ctx, *, command: str):
"""Enables a command for this server.
You must have Manage Server permissions or the
Bot Admin role to use this command.
"""
command = command.lower()
guild_id = ctx.message.server.id
cmds = self.config.get('commands'... | Enables a command for this server.
You must have Manage Server permissions or the
Bot Admin role to use this command. | Below is the the instruction that describes the task:
### Input:
Enables a command for this server.
You must have Manage Server permissions or the
Bot Admin role to use this command.
### Response:
async def enable(self, ctx, *, command: str):
"""Enables a command for this server.
... |
def padRectEqually(rect, padding, bounds, clipExcess = True):
"""
Applies equal padding to all sides of a rectangle,
ensuring the padded rectangle falls within the specified bounds.
The input rectangle, bounds, and return value are all a tuple of (x,y,w,h).
"""
return padRect(rect, padding, padding, padding, pa... | Applies equal padding to all sides of a rectangle,
ensuring the padded rectangle falls within the specified bounds.
The input rectangle, bounds, and return value are all a tuple of (x,y,w,h). | Below is the the instruction that describes the task:
### Input:
Applies equal padding to all sides of a rectangle,
ensuring the padded rectangle falls within the specified bounds.
The input rectangle, bounds, and return value are all a tuple of (x,y,w,h).
### Response:
def padRectEqually(rect, padding, bounds... |
def from_raw(self, rval: RawList, jptr: JSONPointer = "") -> ArrayValue:
"""Override the superclass method."""
if not isinstance(rval, list):
raise RawTypeError(jptr, "array")
res = ArrayValue()
i = 0
for en in rval:
i += 1
res.append(self.entr... | Override the superclass method. | Below is the the instruction that describes the task:
### Input:
Override the superclass method.
### Response:
def from_raw(self, rval: RawList, jptr: JSONPointer = "") -> ArrayValue:
"""Override the superclass method."""
if not isinstance(rval, list):
raise RawTypeError(jptr, "array")
... |
async def post(self, cmd, data=None, timeout=None, **args):
"""Perform DAAP POST command with optional data."""
def _post_request():
headers = copy(_DMAP_HEADERS)
headers['Content-Type'] = 'application/x-www-form-urlencoded'
return self.http.post_data(
... | Perform DAAP POST command with optional data. | Below is the the instruction that describes the task:
### Input:
Perform DAAP POST command with optional data.
### Response:
async def post(self, cmd, data=None, timeout=None, **args):
"""Perform DAAP POST command with optional data."""
def _post_request():
headers = copy(_DMAP_HEADERS)... |
def ind_lm(index, lmax):
"""Convert single index to corresponding (ell, m) pair"""
import numpy as np
lm = np.empty(2, dtype=np.float64)
_ind_lm(index, lmax, lm)
return lm | Convert single index to corresponding (ell, m) pair | Below is the the instruction that describes the task:
### Input:
Convert single index to corresponding (ell, m) pair
### Response:
def ind_lm(index, lmax):
"""Convert single index to corresponding (ell, m) pair"""
import numpy as np
lm = np.empty(2, dtype=np.float64)
_ind_lm(index, lmax, lm)
re... |
def bitScoreToEValue(bitScore, dbSize, dbSequenceCount, queryLength,
lengthAdjustment):
"""
Convert a bit score to an e-value.
@param bitScore: The C{float} bit score to convert.
@param dbSize: The C{int} total size of the database (i.e., the sum of
the lengths of all seque... | Convert a bit score to an e-value.
@param bitScore: The C{float} bit score to convert.
@param dbSize: The C{int} total size of the database (i.e., the sum of
the lengths of all sequences in the BLAST database).
@param dbSequenceCount: The C{int} number of sequences in the database.
@param query... | Below is the the instruction that describes the task:
### Input:
Convert a bit score to an e-value.
@param bitScore: The C{float} bit score to convert.
@param dbSize: The C{int} total size of the database (i.e., the sum of
the lengths of all sequences in the BLAST database).
@param dbSequenceCo... |
def verify_duplicates(duplicates, uniques):
"""Verify that a set of intersections had expected duplicates.
.. note::
This is a helper used only by :func:`generic_intersect`.
Args:
duplicates (List[.Intersection]): List of intersections
corresponding to duplicates that were filt... | Verify that a set of intersections had expected duplicates.
.. note::
This is a helper used only by :func:`generic_intersect`.
Args:
duplicates (List[.Intersection]): List of intersections
corresponding to duplicates that were filtered out.
uniques (List[.Intersection]): Li... | Below is the the instruction that describes the task:
### Input:
Verify that a set of intersections had expected duplicates.
.. note::
This is a helper used only by :func:`generic_intersect`.
Args:
duplicates (List[.Intersection]): List of intersections
corresponding to duplica... |
def review_metadata_csv(filedir, input_filepath):
"""
Check validity of metadata fields.
:param filedir: This field is the filepath of the directory whose csv
has to be made.
:param outputfilepath: This field is the file path of the output csv.
:param max_bytes: This field is the maximum fi... | Check validity of metadata fields.
:param filedir: This field is the filepath of the directory whose csv
has to be made.
:param outputfilepath: This field is the file path of the output csv.
:param max_bytes: This field is the maximum file size to consider. Its
default value is 128m. | Below is the the instruction that describes the task:
### Input:
Check validity of metadata fields.
:param filedir: This field is the filepath of the directory whose csv
has to be made.
:param outputfilepath: This field is the file path of the output csv.
:param max_bytes: This field is the max... |
def get_compliance_task(self, id):
'''**Description**
Get a compliance task.
**Arguments**
- id: the id of the compliance task to get.
**Success Return Value**
A JSON representation of the compliance task.
'''
res = requests.get(self.url + '/... | **Description**
Get a compliance task.
**Arguments**
- id: the id of the compliance task to get.
**Success Return Value**
A JSON representation of the compliance task. | Below is the the instruction that describes the task:
### Input:
**Description**
Get a compliance task.
**Arguments**
- id: the id of the compliance task to get.
**Success Return Value**
A JSON representation of the compliance task.
### Response:
def get_compli... |
def __update_density(self, compound='', element=''):
"""Re-calculate the density of the element given due to stoichiometric changes as
well as the compound density (if density is not locked)
Parameters:
===========
compound: string (default is '') name of compound
elemen... | Re-calculate the density of the element given due to stoichiometric changes as
well as the compound density (if density is not locked)
Parameters:
===========
compound: string (default is '') name of compound
element: string (default is '') name of element | Below is the the instruction that describes the task:
### Input:
Re-calculate the density of the element given due to stoichiometric changes as
well as the compound density (if density is not locked)
Parameters:
===========
compound: string (default is '') name of compound
e... |
def update_required(srcpth, dstpth):
"""
If the file at `dstpth` is generated from the file at `srcpth`,
determine whether an update is required. Returns True if `dstpth`
does not exist, or if `srcpth` has been more recently modified
than `dstpth`.
"""
return not os.path.exists(dstpth) or ... | If the file at `dstpth` is generated from the file at `srcpth`,
determine whether an update is required. Returns True if `dstpth`
does not exist, or if `srcpth` has been more recently modified
than `dstpth`. | Below is the the instruction that describes the task:
### Input:
If the file at `dstpth` is generated from the file at `srcpth`,
determine whether an update is required. Returns True if `dstpth`
does not exist, or if `srcpth` has been more recently modified
than `dstpth`.
### Response:
def update_requ... |
def deprecated(func):
"""
A decorator for marking functions as deprecated. Results in
a printed warning message when the function is used.
"""
def decorated(*args, **kwargs):
warnings.warn('Call to deprecated function %s.' % func.__name__,
category=DeprecationWarning,
... | A decorator for marking functions as deprecated. Results in
a printed warning message when the function is used. | Below is the the instruction that describes the task:
### Input:
A decorator for marking functions as deprecated. Results in
a printed warning message when the function is used.
### Response:
def deprecated(func):
"""
A decorator for marking functions as deprecated. Results in
a printed warning mes... |
def render(self, url, template=None, expiration=0):
"""
Render feed template
"""
template = template or self.default_template
return render_to_string(template, self.get_context(url, expiration)) | Render feed template | Below is the the instruction that describes the task:
### Input:
Render feed template
### Response:
def render(self, url, template=None, expiration=0):
"""
Render feed template
"""
template = template or self.default_template
return render_to_string(template, self.g... |
def read_whole_packet(self):
""" Reads single packet and returns bytes payload of the packet
Can only be called when transport's read pointer is at the beginning
of the packet.
"""
self._read_packet()
return readall(self, self._size - _header.size) | Reads single packet and returns bytes payload of the packet
Can only be called when transport's read pointer is at the beginning
of the packet. | Below is the the instruction that describes the task:
### Input:
Reads single packet and returns bytes payload of the packet
Can only be called when transport's read pointer is at the beginning
of the packet.
### Response:
def read_whole_packet(self):
""" Reads single packet and returns by... |
def private_config_content(self, private_config):
"""
Update the private config
:param private_config: content of the private configuration file
"""
try:
private_config_path = os.path.join(self.working_dir, "private-config.cfg")
if private_config is Non... | Update the private config
:param private_config: content of the private configuration file | Below is the the instruction that describes the task:
### Input:
Update the private config
:param private_config: content of the private configuration file
### Response:
def private_config_content(self, private_config):
"""
Update the private config
:param private_config: content ... |
def __insert_image_info(self, title, _from, info):
"""
Insert API image INFO into matching image dict
We make one imageinfo request containing only unique image
filenames. We reduce duplication by asking for image data per
file, instead of per "kind" or source (Wikipedia, Wikida... | Insert API image INFO into matching image dict
We make one imageinfo request containing only unique image
filenames. We reduce duplication by asking for image data per
file, instead of per "kind" or source (Wikipedia, Wikidata,
etc.), because some sources reference the same image file. ... | Below is the the instruction that describes the task:
### Input:
Insert API image INFO into matching image dict
We make one imageinfo request containing only unique image
filenames. We reduce duplication by asking for image data per
file, instead of per "kind" or source (Wikipedia, Wikidata... |
def fastaRead(fileHandleOrFile):
"""iteratively yields a sequence for each '>' it encounters, ignores '#' lines
"""
fileHandle = _getFileHandle(fileHandleOrFile)
line = fileHandle.readline()
chars_to_remove = "\n "
valid_chars = {x for x in string.ascii_letters + "-"}
while line != '':
... | iteratively yields a sequence for each '>' it encounters, ignores '#' lines | Below is the the instruction that describes the task:
### Input:
iteratively yields a sequence for each '>' it encounters, ignores '#' lines
### Response:
def fastaRead(fileHandleOrFile):
"""iteratively yields a sequence for each '>' it encounters, ignores '#' lines
"""
fileHandle = _getFileHandle(file... |
def _lab_data(self):
""" Returns a dictionary that represents the lab object
Keys: obj, title, url, address, confidence, accredited,
accreditation_body, accreditation_logo, logo
"""
portal = self.context.portal_url.getPortalObject()
lab = self.context.bika_s... | Returns a dictionary that represents the lab object
Keys: obj, title, url, address, confidence, accredited,
accreditation_body, accreditation_logo, logo | Below is the the instruction that describes the task:
### Input:
Returns a dictionary that represents the lab object
Keys: obj, title, url, address, confidence, accredited,
accreditation_body, accreditation_logo, logo
### Response:
def _lab_data(self):
""" Returns a dictionary... |
def push_results(self):
"""Push the checks/actions results to our schedulers
:return: None
"""
# For all schedulers, we check for wait_homerun
# and we send back results
for scheduler_link_uuid in self.schedulers:
scheduler_link = self.schedulers[scheduler_li... | Push the checks/actions results to our schedulers
:return: None | Below is the the instruction that describes the task:
### Input:
Push the checks/actions results to our schedulers
:return: None
### Response:
def push_results(self):
"""Push the checks/actions results to our schedulers
:return: None
"""
# For all schedulers, we check for ... |
def get_developer_certificate(self, developer_certificate_id, authorization, **kwargs): # noqa: E501
"""Fetch an existing developer certificate to connect to the bootstrap server. # noqa: E501
This REST API is intended to be used by customers to fetch an existing developer certificate (a certificate ... | Fetch an existing developer certificate to connect to the bootstrap server. # noqa: E501
This REST API is intended to be used by customers to fetch an existing developer certificate (a certificate that can be flashed into multiple devices to connect to bootstrap server). **Example usage:** curl -X GET \"http... | Below is the the instruction that describes the task:
### Input:
Fetch an existing developer certificate to connect to the bootstrap server. # noqa: E501
This REST API is intended to be used by customers to fetch an existing developer certificate (a certificate that can be flashed into multiple devices to... |
def _check_task(taskid):
"""Check Spinnaker Task status.
Args:
taskid (str): Existing Spinnaker Task ID.
Returns:
str: Task status.
"""
try:
taskurl = taskid.get('ref', '0000')
except AttributeError:
taskurl = taskid
taskid = taskurl.split('/tasks/')[-1]
... | Check Spinnaker Task status.
Args:
taskid (str): Existing Spinnaker Task ID.
Returns:
str: Task status. | Below is the the instruction that describes the task:
### Input:
Check Spinnaker Task status.
Args:
taskid (str): Existing Spinnaker Task ID.
Returns:
str: Task status.
### Response:
def _check_task(taskid):
"""Check Spinnaker Task status.
Args:
taskid (str): Existing Spi... |
def umount(mountpoint, persist=False):
"""Unmount a filesystem"""
cmd_args = ['umount', mountpoint]
try:
subprocess.check_output(cmd_args)
except subprocess.CalledProcessError as e:
log('Error unmounting {}\n{}'.format(mountpoint, e.output))
return False
if persist:
... | Unmount a filesystem | Below is the the instruction that describes the task:
### Input:
Unmount a filesystem
### Response:
def umount(mountpoint, persist=False):
"""Unmount a filesystem"""
cmd_args = ['umount', mountpoint]
try:
subprocess.check_output(cmd_args)
except subprocess.CalledProcessError as e:
l... |
def _handle_datapath(self, inport, packet):
'''
Handle single packet on the data plane.
'''
inport = self._switchyard_net.port_by_name(inport)
portnum = inport.ifnum
log_info("Processing packet: {}->{}".format(portnum, packet))
actions = None
for tnum,t i... | Handle single packet on the data plane. | Below is the the instruction that describes the task:
### Input:
Handle single packet on the data plane.
### Response:
def _handle_datapath(self, inport, packet):
'''
Handle single packet on the data plane.
'''
inport = self._switchyard_net.port_by_name(inport)
portnum = inp... |
def expected_related_units(reltype=None):
"""Get a generator for units we expect to join relation based on
goal-state.
Note that you can not use this function for the peer relation, take a look
at expected_peer_units() for that.
This function will raise KeyError if you request information for a
... | Get a generator for units we expect to join relation based on
goal-state.
Note that you can not use this function for the peer relation, take a look
at expected_peer_units() for that.
This function will raise KeyError if you request information for a
relation type for which juju goal-state does no... | Below is the the instruction that describes the task:
### Input:
Get a generator for units we expect to join relation based on
goal-state.
Note that you can not use this function for the peer relation, take a look
at expected_peer_units() for that.
This function will raise KeyError if you request ... |
def ls(self, path, offset=None, amount=None):
"""
Return list of files/directories. Each item is a dict.
Keys: 'path', 'creationdate', 'displayname', 'length', 'lastmodified', 'isDir'.
"""
def parseContent(content):
result = []
root = ET.fromstri... | Return list of files/directories. Each item is a dict.
Keys: 'path', 'creationdate', 'displayname', 'length', 'lastmodified', 'isDir'. | Below is the the instruction that describes the task:
### Input:
Return list of files/directories. Each item is a dict.
Keys: 'path', 'creationdate', 'displayname', 'length', 'lastmodified', 'isDir'.
### Response:
def ls(self, path, offset=None, amount=None):
"""
Return list of files/direc... |
def set_parent(self, new_parent, init=False):
"Associate the header to the control (it could be recreated)"
self._created = False
SubComponent.set_parent(self, new_parent, init)
# if index not given, append the column at the last position:
if self.index == -1 or self.index >... | Associate the header to the control (it could be recreated) | Below is the the instruction that describes the task:
### Input:
Associate the header to the control (it could be recreated)
### Response:
def set_parent(self, new_parent, init=False):
"Associate the header to the control (it could be recreated)"
self._created = False
SubComponent.set_pa... |
def OpenSourcePath(self, source_path):
"""Opens the source path.
Args:
source_path (str): source path.
"""
source_path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_OS, location=source_path)
self.AddScanNode(source_path_spec, None) | Opens the source path.
Args:
source_path (str): source path. | Below is the the instruction that describes the task:
### Input:
Opens the source path.
Args:
source_path (str): source path.
### Response:
def OpenSourcePath(self, source_path):
"""Opens the source path.
Args:
source_path (str): source path.
"""
source_path_spec = path_spec_facto... |
def _set_attributes_on_managed_object(self, managed_object, attributes):
"""
Given a kmip.pie object and a dictionary of attributes, attempt to set
the attribute values on the object.
"""
for attribute_name, attribute_value in six.iteritems(attributes):
object_type = ... | Given a kmip.pie object and a dictionary of attributes, attempt to set
the attribute values on the object. | Below is the the instruction that describes the task:
### Input:
Given a kmip.pie object and a dictionary of attributes, attempt to set
the attribute values on the object.
### Response:
def _set_attributes_on_managed_object(self, managed_object, attributes):
"""
Given a kmip.pie object and ... |
def build_properties(self, hide_implicit_preds=True):
"""
2015-06-04: removed sparql 1.1 queries
2015-06-03: analogous to get classes
# instantiate properties making sure duplicates are pruned
# but the most specific rdftype is kept
# eg OWL:ObjectProperty over RDF:prope... | 2015-06-04: removed sparql 1.1 queries
2015-06-03: analogous to get classes
# instantiate properties making sure duplicates are pruned
# but the most specific rdftype is kept
# eg OWL:ObjectProperty over RDF:property | Below is the the instruction that describes the task:
### Input:
2015-06-04: removed sparql 1.1 queries
2015-06-03: analogous to get classes
# instantiate properties making sure duplicates are pruned
# but the most specific rdftype is kept
# eg OWL:ObjectProperty over RDF:property
#... |
def pack_req(cls, order_id, status_filter_list, code, start, end,
trd_env, acc_id, trd_mkt, conn_id):
"""Convert from user request for trading days to PLS request"""
from futuquant.common.pb.Trd_GetOrderList_pb2 import Request
req = Request()
req.c2s.header.trdEnv = TRD_... | Convert from user request for trading days to PLS request | Below is the the instruction that describes the task:
### Input:
Convert from user request for trading days to PLS request
### Response:
def pack_req(cls, order_id, status_filter_list, code, start, end,
trd_env, acc_id, trd_mkt, conn_id):
"""Convert from user request for trading days to PL... |
def new_notebook(metadata=None, worksheets=None):
"""Create a notebook by name, id and a list of worksheets."""
nb = NotebookNode()
nb.nbformat = 2
if worksheets is None:
nb.worksheets = []
else:
nb.worksheets = list(worksheets)
if metadata is None:
nb.metadata = new_meta... | Create a notebook by name, id and a list of worksheets. | Below is the the instruction that describes the task:
### Input:
Create a notebook by name, id and a list of worksheets.
### Response:
def new_notebook(metadata=None, worksheets=None):
"""Create a notebook by name, id and a list of worksheets."""
nb = NotebookNode()
nb.nbformat = 2
if worksheets is... |
def analyze(self, config_string=None):
"""
Analyze the given container and
return the corresponding job object.
On error, it will return ``None``.
:param string config_string: the configuration string generated by wizard
:rtype: :class:`~aeneas.job.Job` or ``None``
... | Analyze the given container and
return the corresponding job object.
On error, it will return ``None``.
:param string config_string: the configuration string generated by wizard
:rtype: :class:`~aeneas.job.Job` or ``None`` | Below is the the instruction that describes the task:
### Input:
Analyze the given container and
return the corresponding job object.
On error, it will return ``None``.
:param string config_string: the configuration string generated by wizard
:rtype: :class:`~aeneas.job.Job` or ``N... |
def _init_header(self, string):
""" Extracts header part from TAF/METAR string and populates header dict
Args:
TAF/METAR report string
Raises:
MalformedTAF: An error parsing the report
Returns:
Header dictionary
"""
taf_header_patte... | Extracts header part from TAF/METAR string and populates header dict
Args:
TAF/METAR report string
Raises:
MalformedTAF: An error parsing the report
Returns:
Header dictionary | Below is the the instruction that describes the task:
### Input:
Extracts header part from TAF/METAR string and populates header dict
Args:
TAF/METAR report string
Raises:
MalformedTAF: An error parsing the report
Returns:
Header dictionary
### Response... |
def dataset(
node_parser,
include=lambda x: True,
input_transform=None,
target_transform=None):
"""Convert immediate children of a GroupNode into a torch.data.Dataset
Keyword arguments
* node_parser=callable that converts a DataNode to a Dataset item
* include=lambda x: T... | Convert immediate children of a GroupNode into a torch.data.Dataset
Keyword arguments
* node_parser=callable that converts a DataNode to a Dataset item
* include=lambda x: True
lambda(quilt.nodes.GroupNode) => {True, False}
intended to filter nodes based on metadata
* input_transform=None; o... | Below is the the instruction that describes the task:
### Input:
Convert immediate children of a GroupNode into a torch.data.Dataset
Keyword arguments
* node_parser=callable that converts a DataNode to a Dataset item
* include=lambda x: True
lambda(quilt.nodes.GroupNode) => {True, False}
int... |
def listVars(prefix="", equals="\t= ", **kw):
"""List IRAF variables."""
keylist = getVarList()
if len(keylist) == 0:
print('No IRAF variables defined')
else:
keylist.sort()
for word in keylist:
print("%s%s%s%s" % (prefix, word, equals, envget(word))) | List IRAF variables. | Below is the the instruction that describes the task:
### Input:
List IRAF variables.
### Response:
def listVars(prefix="", equals="\t= ", **kw):
"""List IRAF variables."""
keylist = getVarList()
if len(keylist) == 0:
print('No IRAF variables defined')
else:
keylist.sort()
... |
def account_setup(remote, token, resp):
"""Perform additional setup after user have been logged in."""
resource = get_resource(remote)
with db.session.begin_nested():
person_id = resource.get('PersonID', [None])
external_id = resource.get('uidNumber', person_id)[0]
# Set CERN perso... | Perform additional setup after user have been logged in. | Below is the the instruction that describes the task:
### Input:
Perform additional setup after user have been logged in.
### Response:
def account_setup(remote, token, resp):
"""Perform additional setup after user have been logged in."""
resource = get_resource(remote)
with db.session.begin_nested():... |
def save(self, data, **kwargs):
""" sends a passed in action_list to elasticsearch
args:
data: that data dictionary to save
kwargs:
id: es id to use / None = auto
"""
lg = logging.getLogger("%s.%s" % (self.ln, inspect.stack()[0][3]))
... | sends a passed in action_list to elasticsearch
args:
data: that data dictionary to save
kwargs:
id: es id to use / None = auto | Below is the the instruction that describes the task:
### Input:
sends a passed in action_list to elasticsearch
args:
data: that data dictionary to save
kwargs:
id: es id to use / None = auto
### Response:
def save(self, data, **kwargs):
""" sends a passed i... |
def configure_event_hooks(config):
""" Returns an EventHandler instance with registered hooks. """
def print_event_info(**kwargs):
print kwargs.get('event_params', {})
def job_complete_email(email_handler, **kwargs):
email_handler.send_job_completed(kwargs['event_params'])
def job_fai... | Returns an EventHandler instance with registered hooks. | Below is the the instruction that describes the task:
### Input:
Returns an EventHandler instance with registered hooks.
### Response:
def configure_event_hooks(config):
""" Returns an EventHandler instance with registered hooks. """
def print_event_info(**kwargs):
print kwargs.get('event_params',... |
def create_submission(self, source_code, language_name=None, language_id=None,
std_input="", run=True, private=False):
"""
Create a submission and upload it to Ideone.
Keyword Arguments
-----------------
* source_code: a string of the programs source c... | Create a submission and upload it to Ideone.
Keyword Arguments
-----------------
* source_code: a string of the programs source code
* language_name: the human readable language string (e.g. 'python')
* language_id: the ID of the programming language
* std_input: the st... | Below is the the instruction that describes the task:
### Input:
Create a submission and upload it to Ideone.
Keyword Arguments
-----------------
* source_code: a string of the programs source code
* language_name: the human readable language string (e.g. 'python')
* langua... |
def read_secret_metadata(self, path, mount_point=DEFAULT_MOUNT_POINT):
"""Retrieve the metadata and versions for the secret at the specified path.
Supported methods:
GET: /{mount_point}/metadata/{path}. Produces: 200 application/json
:param path: Specifies the path of the secret t... | Retrieve the metadata and versions for the secret at the specified path.
Supported methods:
GET: /{mount_point}/metadata/{path}. Produces: 200 application/json
:param path: Specifies the path of the secret to read. This is specified as part of the URL.
:type path: str | unicode
... | Below is the the instruction that describes the task:
### Input:
Retrieve the metadata and versions for the secret at the specified path.
Supported methods:
GET: /{mount_point}/metadata/{path}. Produces: 200 application/json
:param path: Specifies the path of the secret to read. This ... |
def resize(self, shape):
"""Resize the image to the given *shape* tuple, in place. For zooming,
nearest neighbour method is used, while for shrinking, decimation is
used. Therefore, *shape* must be a multiple or a divisor of the image
shape.
"""
if self.is_empty():
... | Resize the image to the given *shape* tuple, in place. For zooming,
nearest neighbour method is used, while for shrinking, decimation is
used. Therefore, *shape* must be a multiple or a divisor of the image
shape. | Below is the the instruction that describes the task:
### Input:
Resize the image to the given *shape* tuple, in place. For zooming,
nearest neighbour method is used, while for shrinking, decimation is
used. Therefore, *shape* must be a multiple or a divisor of the image
shape.
### Response:... |
def add_jump(self, name, min, max, num, warp=None, var_type=float):
""" An integer/float-valued enumerable with `num` items, bounded
between [`min`, `max`]. Note that the right endpoint of the interval
includes `max`. This is a wrapper around the add_enum. `jump` can be
a float or int.
... | An integer/float-valued enumerable with `num` items, bounded
between [`min`, `max`]. Note that the right endpoint of the interval
includes `max`. This is a wrapper around the add_enum. `jump` can be
a float or int. | Below is the the instruction that describes the task:
### Input:
An integer/float-valued enumerable with `num` items, bounded
between [`min`, `max`]. Note that the right endpoint of the interval
includes `max`. This is a wrapper around the add_enum. `jump` can be
a float or int.
### Response... |
def _compute_delta_beta(self, df, events, start, stop, weights):
""" approximate change in betas as a result of excluding ith row"""
score_residuals = self._compute_residuals(df, events, start, stop, weights) * weights[:, None]
naive_var = inv(self._hessian_)
delta_betas = -score_resid... | approximate change in betas as a result of excluding ith row | Below is the the instruction that describes the task:
### Input:
approximate change in betas as a result of excluding ith row
### Response:
def _compute_delta_beta(self, df, events, start, stop, weights):
""" approximate change in betas as a result of excluding ith row"""
score_residuals = self._c... |
def listen(self, **kwargs: Any) -> Server:
"""
bind host, port or sock
"""
loop = cast(asyncio.AbstractEventLoop, self._loop)
return (yield from loop.create_server(
lambda: self._protocol(
loop=loop,
handle=self._handle,
... | bind host, port or sock | Below is the the instruction that describes the task:
### Input:
bind host, port or sock
### Response:
def listen(self, **kwargs: Any) -> Server:
"""
bind host, port or sock
"""
loop = cast(asyncio.AbstractEventLoop, self._loop)
return (yield from loop.create_server(
... |
def clear_es():
"""Clear all indexes in the es core"""
# TODO: should receive a catalog slug.
ESHypermap.es.indices.delete(ESHypermap.index_name, ignore=[400, 404])
LOGGER.debug('Elasticsearch: Index cleared') | Clear all indexes in the es core | Below is the the instruction that describes the task:
### Input:
Clear all indexes in the es core
### Response:
def clear_es():
"""Clear all indexes in the es core"""
# TODO: should receive a catalog slug.
ESHypermap.es.indices.delete(ESHypermap.index_name, ignore=[400, 404])
LOGGER... |
def extract_value(self, agg, idx, name=''):
"""
Extract member number *idx* from aggregate.
"""
if not isinstance(idx, (tuple, list)):
idx = [idx]
instr = instructions.ExtractValue(self.block, agg, idx, name=name)
self._insert(instr)
return instr | Extract member number *idx* from aggregate. | Below is the the instruction that describes the task:
### Input:
Extract member number *idx* from aggregate.
### Response:
def extract_value(self, agg, idx, name=''):
"""
Extract member number *idx* from aggregate.
"""
if not isinstance(idx, (tuple, list)):
idx = [idx]
... |
def define_options(address, port, tracker_url, base_url):
'''
:param address:
:param port:
:param tracker_url:
:return:
'''
define("address", default=address)
define("port", default=port)
define("tracker_url", default=tracker_url)
define("base_url", default=base_url) | :param address:
:param port:
:param tracker_url:
:return: | Below is the the instruction that describes the task:
### Input:
:param address:
:param port:
:param tracker_url:
:return:
### Response:
def define_options(address, port, tracker_url, base_url):
'''
:param address:
:param port:
:param tracker_url:
:return:
'''
define("address", default=address)... |
def len_on_depth(d, depth):
"""Get the number of nodes on specific depth.
"""
counter = 0
for node in DictTree.v_depth(d, depth-1):
counter += DictTree.length(node)
return counter | Get the number of nodes on specific depth. | Below is the the instruction that describes the task:
### Input:
Get the number of nodes on specific depth.
### Response:
def len_on_depth(d, depth):
"""Get the number of nodes on specific depth.
"""
counter = 0
for node in DictTree.v_depth(d, depth-1):
counter += DictTr... |
def inspect(source: dict):
"""
Inspects the data and structure of the source dictionary object and
adds the results to the display for viewing.
:param source:
A dictionary object to be inspected.
:return:
"""
r = _get_report()
r.append_body(render.inspect(source)) | Inspects the data and structure of the source dictionary object and
adds the results to the display for viewing.
:param source:
A dictionary object to be inspected.
:return: | Below is the the instruction that describes the task:
### Input:
Inspects the data and structure of the source dictionary object and
adds the results to the display for viewing.
:param source:
A dictionary object to be inspected.
:return:
### Response:
def inspect(source: dict):
"""
In... |
def idf(self, term, transform=None):
r"""Calculate the Inverse Document Frequency of a term in the corpus.
Parameters
----------
term : str
The term to calculate the IDF of
transform : function
A function to apply to each document term before checking for... | r"""Calculate the Inverse Document Frequency of a term in the corpus.
Parameters
----------
term : str
The term to calculate the IDF of
transform : function
A function to apply to each document term before checking for the
presence of term
Re... | Below is the the instruction that describes the task:
### Input:
r"""Calculate the Inverse Document Frequency of a term in the corpus.
Parameters
----------
term : str
The term to calculate the IDF of
transform : function
A function to apply to each document ... |
def _conditional_toward_zero(method, sign):
"""
Whether to round toward zero.
:param method: rounding method
:type method: element of RoundingMethods.METHODS()
:param int sign: -1, 0, or 1 as appropriate
Complexity: O(1)
"""
return method is RoundingMeth... | Whether to round toward zero.
:param method: rounding method
:type method: element of RoundingMethods.METHODS()
:param int sign: -1, 0, or 1 as appropriate
Complexity: O(1) | Below is the the instruction that describes the task:
### Input:
Whether to round toward zero.
:param method: rounding method
:type method: element of RoundingMethods.METHODS()
:param int sign: -1, 0, or 1 as appropriate
Complexity: O(1)
### Response:
def _conditional_toward_zero(... |
def extract_line(geom, dem, **kwargs):
"""
Extract a linear feature from a `rasterio` geospatial dataset.
"""
kwargs.setdefault('masked', True)
coords_in = coords_array(geom)
# Transform geometry into pixels
f = lambda *x: ~dem.transform * x
px = transform(f,geom)
# Subdivide geom... | Extract a linear feature from a `rasterio` geospatial dataset. | Below is the the instruction that describes the task:
### Input:
Extract a linear feature from a `rasterio` geospatial dataset.
### Response:
def extract_line(geom, dem, **kwargs):
"""
Extract a linear feature from a `rasterio` geospatial dataset.
"""
kwargs.setdefault('masked', True)
coords_i... |
def remove_range(cls, elem, end_elem, delete_end=True):
"""delete everything from elem to end_elem, including elem.
if delete_end==True, also including end_elem; otherwise, leave it."""
while elem is not None and elem != end_elem and end_elem not in elem.xpath("descendant::*"):
p... | delete everything from elem to end_elem, including elem.
if delete_end==True, also including end_elem; otherwise, leave it. | Below is the the instruction that describes the task:
### Input:
delete everything from elem to end_elem, including elem.
if delete_end==True, also including end_elem; otherwise, leave it.
### Response:
def remove_range(cls, elem, end_elem, delete_end=True):
"""delete everything from elem to end_... |
def parse_setup(options: Union[List, str]) -> str:
"""Convert potentially a list of commands into a single string.
This creates a single string with newlines between each element of the list
so that they will all run after each other in a bash script.
"""
if isinstance(options, str):
retur... | Convert potentially a list of commands into a single string.
This creates a single string with newlines between each element of the list
so that they will all run after each other in a bash script. | Below is the the instruction that describes the task:
### Input:
Convert potentially a list of commands into a single string.
This creates a single string with newlines between each element of the list
so that they will all run after each other in a bash script.
### Response:
def parse_setup(options: Unio... |
def readabt(filename, dirs='.'):
"""Read abt_*.fio type files from beamline B1, HASYLAB.
Input:
filename: the name of the file.
dirs: directories to search for files in
Output:
A dictionary. The fields are self-explanatory.
"""
# resolve filename
filename = misc.findfil... | Read abt_*.fio type files from beamline B1, HASYLAB.
Input:
filename: the name of the file.
dirs: directories to search for files in
Output:
A dictionary. The fields are self-explanatory. | Below is the the instruction that describes the task:
### Input:
Read abt_*.fio type files from beamline B1, HASYLAB.
Input:
filename: the name of the file.
dirs: directories to search for files in
Output:
A dictionary. The fields are self-explanatory.
### Response:
def readabt(fi... |
def namedb_get_names_in_namespace( cur, namespace_id, current_block, offset=None, count=None ):
"""
Get a list of all names in a namespace, optionally
paginated with offset and count. Exclude expired names
"""
unexpired_query, unexpired_args = namedb_select_where_unexpired_names( current_block )
... | Get a list of all names in a namespace, optionally
paginated with offset and count. Exclude expired names | Below is the the instruction that describes the task:
### Input:
Get a list of all names in a namespace, optionally
paginated with offset and count. Exclude expired names
### Response:
def namedb_get_names_in_namespace( cur, namespace_id, current_block, offset=None, count=None ):
"""
Get a list of all... |
def create_record_mx(self, zone_id, record, data, ttl=60, priority=10):
"""Create a mx resource record on a domain.
:param integer id: the zone's ID
:param record: the name of the record to add
:param data: the record's value
:param integer ttl: the TTL or time-to-live value (de... | Create a mx resource record on a domain.
:param integer id: the zone's ID
:param record: the name of the record to add
:param data: the record's value
:param integer ttl: the TTL or time-to-live value (default: 60)
:param integer priority: the priority of the target host | Below is the the instruction that describes the task:
### Input:
Create a mx resource record on a domain.
:param integer id: the zone's ID
:param record: the name of the record to add
:param data: the record's value
:param integer ttl: the TTL or time-to-live value (default: 60)
... |
def get_string_onset(edge):
"""return the onset (int) of a string"""
onset_label = edge.find('labels[@name="SSTART"]')
onset_str = onset_label.xpath('@valueString')[0]
return int(onset_str) | return the onset (int) of a string | Below is the the instruction that describes the task:
### Input:
return the onset (int) of a string
### Response:
def get_string_onset(edge):
"""return the onset (int) of a string"""
onset_label = edge.find('labels[@name="SSTART"]')
onset_str = onset_label.xpath('@valueString')[0]
return int(onset_... |
def reduce_to_parent_states(models):
"""Remove all models of states that have a state model with parent relation in the list
The function filters the list of models, so that for no model in the list, one of it (grand-)parents is also in
the list. E.g. if the input models consists of a hierarchy state with ... | Remove all models of states that have a state model with parent relation in the list
The function filters the list of models, so that for no model in the list, one of it (grand-)parents is also in
the list. E.g. if the input models consists of a hierarchy state with two of its child states, the resulting list
... | Below is the the instruction that describes the task:
### Input:
Remove all models of states that have a state model with parent relation in the list
The function filters the list of models, so that for no model in the list, one of it (grand-)parents is also in
the list. E.g. if the input models consists o... |
def _is_variable_extends(extend_node):
"""
Check whether an ``{% extends variable %}`` is used in the template.
:type extend_node: ExtendsNode
"""
if django.VERSION < (1, 4):
return extend_node.parent_name_expr # Django 1.3
else:
# The FilterExpression.var can be either a strin... | Check whether an ``{% extends variable %}`` is used in the template.
:type extend_node: ExtendsNode | Below is the the instruction that describes the task:
### Input:
Check whether an ``{% extends variable %}`` is used in the template.
:type extend_node: ExtendsNode
### Response:
def _is_variable_extends(extend_node):
"""
Check whether an ``{% extends variable %}`` is used in the template.
:type ... |
def i18n_locale_fallbacks_calculate(lc):
"""
Calculate all child locales from a locale.
e.g. for locale="pt_BR.us-ascii", returns ["pt_BR.us-ascii", "pt_BR.us", "pt_BR", "pt"]
:param lc: locale for which the child locales are needed
:return: all child locales (including the parameter lc)
"""
... | Calculate all child locales from a locale.
e.g. for locale="pt_BR.us-ascii", returns ["pt_BR.us-ascii", "pt_BR.us", "pt_BR", "pt"]
:param lc: locale for which the child locales are needed
:return: all child locales (including the parameter lc) | Below is the the instruction that describes the task:
### Input:
Calculate all child locales from a locale.
e.g. for locale="pt_BR.us-ascii", returns ["pt_BR.us-ascii", "pt_BR.us", "pt_BR", "pt"]
:param lc: locale for which the child locales are needed
:return: all child locales (including the parameter... |
def download(self, url, post=False, parameters=None, timeout=None):
# type: (str, bool, Optional[Dict], Optional[float]) -> requests.Response
"""Download url
Args:
url (str): URL to download
post (bool): Whether to use POST instead of GET. Defaults to False.
... | Download url
Args:
url (str): URL to download
post (bool): Whether to use POST instead of GET. Defaults to False.
parameters (Optional[Dict]): Parameters to pass. Defaults to None.
timeout (Optional[float]): Timeout for connecting to URL. Defaults to None (no tim... | Below is the the instruction that describes the task:
### Input:
Download url
Args:
url (str): URL to download
post (bool): Whether to use POST instead of GET. Defaults to False.
parameters (Optional[Dict]): Parameters to pass. Defaults to None.
timeout (Opti... |
def disassociate_notification_template(self, workflow,
notification_template, status):
"""Disassociate a notification template from this workflow.
=====API DOCS=====
Disassociate a notification template from this workflow job template.
:param ... | Disassociate a notification template from this workflow.
=====API DOCS=====
Disassociate a notification template from this workflow job template.
:param job_template: The workflow job template to disassociate from.
:type job_template: str
:param notification_template: The notif... | Below is the the instruction that describes the task:
### Input:
Disassociate a notification template from this workflow.
=====API DOCS=====
Disassociate a notification template from this workflow job template.
:param job_template: The workflow job template to disassociate from.
:t... |
def getkeypress(self):
u'''Return next key press event from the queue, ignoring others.'''
ck = System.ConsoleKey
while 1:
e = System.Console.ReadKey(True)
if e.Key == System.ConsoleKey.PageDown: #PageDown
self.scroll_window(12)
elif e.K... | u'''Return next key press event from the queue, ignoring others. | Below is the the instruction that describes the task:
### Input:
u'''Return next key press event from the queue, ignoring others.
### Response:
def getkeypress(self):
u'''Return next key press event from the queue, ignoring others.'''
ck = System.ConsoleKey
while 1:
e = Syst... |
def do_set(parser, token):
'''Calls an arbitrary method on an object.'''
code = token.contents
firstspace = code.find(' ')
if firstspace >= 0:
code = code[firstspace+1:]
return Setter(code) | Calls an arbitrary method on an object. | Below is the the instruction that describes the task:
### Input:
Calls an arbitrary method on an object.
### Response:
def do_set(parser, token):
'''Calls an arbitrary method on an object.'''
code = token.contents
firstspace = code.find(' ')
if firstspace >= 0:
code = code[firstspace+1:]
return Sette... |
def detect_control_flow(self, offset, targets, inst_index):
"""
Detect type of block structures and their boundaries to fix optimized jumps
in python2.3+
"""
code = self.code
inst = self.insts[inst_index]
op = inst.opcode
# Detect parent structure
... | Detect type of block structures and their boundaries to fix optimized jumps
in python2.3+ | Below is the the instruction that describes the task:
### Input:
Detect type of block structures and their boundaries to fix optimized jumps
in python2.3+
### Response:
def detect_control_flow(self, offset, targets, inst_index):
"""
Detect type of block structures and their boundaries to fi... |
def dump_migration_session_state(raw):
"""
Serialize a migration session state to yaml using nicer formatting
Args:
raw: object to serialize
Returns: string (of yaml)
Specifically, this forces the "output" member of state step dicts (e.g.
state[0]['output']) to use block formatting. Fo... | Serialize a migration session state to yaml using nicer formatting
Args:
raw: object to serialize
Returns: string (of yaml)
Specifically, this forces the "output" member of state step dicts (e.g.
state[0]['output']) to use block formatting. For example, rather than this:
- migration: [app... | Below is the the instruction that describes the task:
### Input:
Serialize a migration session state to yaml using nicer formatting
Args:
raw: object to serialize
Returns: string (of yaml)
Specifically, this forces the "output" member of state step dicts (e.g.
state[0]['output']) to use bl... |
def set_opt(self, name, value):
""" Set option.
"""
self.cache['opts'][name] = value
if name == 'compress':
self.cache['delims'] = self.def_delims if not value else (
'',
'',
'') | Set option. | Below is the the instruction that describes the task:
### Input:
Set option.
### Response:
def set_opt(self, name, value):
""" Set option.
"""
self.cache['opts'][name] = value
if name == 'compress':
self.cache['delims'] = self.def_delims if not value else (
... |
async def receiver_handler(websocket):
runner.addifnew(websocket)
# The commented only works with python3-websockets 4.x
'''
async for message in websocket:
await consumer(websocket, message)
'''
while True:
message = await websocket.recv()
await consumer(websocket, mes... | async for message in websocket:
await consumer(websocket, message) | Below is the the instruction that describes the task:
### Input:
async for message in websocket:
await consumer(websocket, message)
### Response:
async def receiver_handler(websocket):
runner.addifnew(websocket)
# The commented only works with python3-websockets 4.x
'''
async for message i... |
def from_json(cls, attributes):
"""Construct an object from a parsed response.
:param dict attributes: object attributes from parsed response
"""
return cls(**{to_snake_case(k): v for k, v in attributes.items()}) | Construct an object from a parsed response.
:param dict attributes: object attributes from parsed response | Below is the the instruction that describes the task:
### Input:
Construct an object from a parsed response.
:param dict attributes: object attributes from parsed response
### Response:
def from_json(cls, attributes):
"""Construct an object from a parsed response.
:param dict attributes: ... |
def csv_to_PyDbLite(src,dest,fieldnames=None,fieldtypes=None,dialect='excel'):
"""Convert a CSV file to a PyDbLite base
src is the file object from which csv values are read
dest is the name of the PyDbLite base
If fieldnames is not set, the CSV file *must* have row names
in the first line
... | Convert a CSV file to a PyDbLite base
src is the file object from which csv values are read
dest is the name of the PyDbLite base
If fieldnames is not set, the CSV file *must* have row names
in the first line
fieldtypes is a dictionary mapping field names to a function
used to convert the... | Below is the the instruction that describes the task:
### Input:
Convert a CSV file to a PyDbLite base
src is the file object from which csv values are read
dest is the name of the PyDbLite base
If fieldnames is not set, the CSV file *must* have row names
in the first line
fieldtypes is a ... |
def get_resources_by_search(self, resource_query, resource_search):
"""Gets the search results matching the given search query using the given search.
arg: resource_query (osid.resource.ResourceQuery): the
resource query
arg: resource_search (osid.resource.ResourceSearch):... | Gets the search results matching the given search query using the given search.
arg: resource_query (osid.resource.ResourceQuery): the
resource query
arg: resource_search (osid.resource.ResourceSearch): the
resource search
return: (osid.resource.ResourceSea... | Below is the the instruction that describes the task:
### Input:
Gets the search results matching the given search query using the given search.
arg: resource_query (osid.resource.ResourceQuery): the
resource query
arg: resource_search (osid.resource.ResourceSearch): the
... |
def remove_watcher(self, fd):
"""Stops watching a fd."""
if not isinstance(fd, int):
fd = fd.fileno()
if fd not in self.callbacks:
return
self.callbacks.pop(fd, None)
self.epoll.unregister(fd) | Stops watching a fd. | Below is the the instruction that describes the task:
### Input:
Stops watching a fd.
### Response:
def remove_watcher(self, fd):
"""Stops watching a fd."""
if not isinstance(fd, int):
fd = fd.fileno()
if fd not in self.callbacks:
return
self.callbacks.pop(... |
def order_upgrades(self, upgrades, history=None):
"""Order upgrades according to their dependencies.
(topological sort using
Kahn's algorithm - http://en.wikipedia.org/wiki/Topological_sorting).
:param upgrades: Dict of upgrades
:param history: Dict of applied upgrades
... | Order upgrades according to their dependencies.
(topological sort using
Kahn's algorithm - http://en.wikipedia.org/wiki/Topological_sorting).
:param upgrades: Dict of upgrades
:param history: Dict of applied upgrades | Below is the the instruction that describes the task:
### Input:
Order upgrades according to their dependencies.
(topological sort using
Kahn's algorithm - http://en.wikipedia.org/wiki/Topological_sorting).
:param upgrades: Dict of upgrades
:param history: Dict of applied upgrades
... |
def hot_questions(self):
"""获取话题下热门的问题
:return: 话题下的热门动态中的问题,按热门度顺序返回生成器
:rtype: Question.Iterable
"""
from .question import Question
hot_questions_url = Topic_Hot_Questions_Url.format(self.id)
params = {'start': 0, '_xsrf': self.xsrf}
res = self._session... | 获取话题下热门的问题
:return: 话题下的热门动态中的问题,按热门度顺序返回生成器
:rtype: Question.Iterable | Below is the the instruction that describes the task:
### Input:
获取话题下热门的问题
:return: 话题下的热门动态中的问题,按热门度顺序返回生成器
:rtype: Question.Iterable
### Response:
def hot_questions(self):
"""获取话题下热门的问题
:return: 话题下的热门动态中的问题,按热门度顺序返回生成器
:rtype: Question.Iterable
"""
from... |
def best_periods(self):
"""Compute the scores under the various models
Parameters
----------
periods : array_like
array of periods at which to compute scores
Returns
-------
best_periods : dict
Dictionary of best periods. Dictionary keys ... | Compute the scores under the various models
Parameters
----------
periods : array_like
array of periods at which to compute scores
Returns
-------
best_periods : dict
Dictionary of best periods. Dictionary keys are the unique filter
n... | Below is the the instruction that describes the task:
### Input:
Compute the scores under the various models
Parameters
----------
periods : array_like
array of periods at which to compute scores
Returns
-------
best_periods : dict
Dictionary... |
def id_maker(obj):
"""
Makes an ID from the object's class name and the datetime now in ISO format.
:param obj: the class from which to make the ID
:return: ID
"""
dtfmt = '%Y%m%d-%H%M%S'
return '%s-%s' % (obj.__class__.__name__, datetime.now().strftime(dtfmt)) | Makes an ID from the object's class name and the datetime now in ISO format.
:param obj: the class from which to make the ID
:return: ID | Below is the the instruction that describes the task:
### Input:
Makes an ID from the object's class name and the datetime now in ISO format.
:param obj: the class from which to make the ID
:return: ID
### Response:
def id_maker(obj):
"""
Makes an ID from the object's class name and the datetime n... |
def mangleIR(data, ignore_errors=False):
"""Mangle a raw Kira data packet into shorthand"""
try:
# Packet mangling algorithm inspired by Rex Becket's kirarx vera plugin
# Determine a median value for the timing packets and categorize each
# timing as longer or shorter than that. This wil... | Mangle a raw Kira data packet into shorthand | Below is the the instruction that describes the task:
### Input:
Mangle a raw Kira data packet into shorthand
### Response:
def mangleIR(data, ignore_errors=False):
"""Mangle a raw Kira data packet into shorthand"""
try:
# Packet mangling algorithm inspired by Rex Becket's kirarx vera plugin
... |
def series_expand(
self, param: Symbol, about, order: int) -> tuple:
r"""Expand the expression as a truncated power series in a
scalar parameter.
When expanding an expr for a parameter $x$ about the point $x_0$ up to
order $N$, the resulting coefficients $(c_1, \dots, c_N)$ ... | r"""Expand the expression as a truncated power series in a
scalar parameter.
When expanding an expr for a parameter $x$ about the point $x_0$ up to
order $N$, the resulting coefficients $(c_1, \dots, c_N)$ fulfill
.. math::
\text{expr} = \sum_{n=0}^{N} c_n (x - x_0)^n + O(... | Below is the the instruction that describes the task:
### Input:
r"""Expand the expression as a truncated power series in a
scalar parameter.
When expanding an expr for a parameter $x$ about the point $x_0$ up to
order $N$, the resulting coefficients $(c_1, \dots, c_N)$ fulfill
.. ... |
def get_resnet(version, num_layers, pretrained=False, ctx=cpu(),
root=os.path.join(base.data_dir(), 'models'), **kwargs):
r"""ResNet V1 model from `"Deep Residual Learning for Image Recognition"
<http://arxiv.org/abs/1512.03385>`_ paper.
ResNet V2 model from `"Identity Mappings in Deep Residu... | r"""ResNet V1 model from `"Deep Residual Learning for Image Recognition"
<http://arxiv.org/abs/1512.03385>`_ paper.
ResNet V2 model from `"Identity Mappings in Deep Residual Networks"
<https://arxiv.org/abs/1603.05027>`_ paper.
Parameters
----------
version : int
Version of ResNet. Opti... | Below is the the instruction that describes the task:
### Input:
r"""ResNet V1 model from `"Deep Residual Learning for Image Recognition"
<http://arxiv.org/abs/1512.03385>`_ paper.
ResNet V2 model from `"Identity Mappings in Deep Residual Networks"
<https://arxiv.org/abs/1603.05027>`_ paper.
Parame... |
def dump(self, indent='', depth=0, full=True):
"""
Diagnostic method for listing out the contents of
a :class:`ParseResults`. Accepts an optional ``indent`` argument so
that this string can be embedded in a nested display of other data.
Example::
integer = Word(nums... | Diagnostic method for listing out the contents of
a :class:`ParseResults`. Accepts an optional ``indent`` argument so
that this string can be embedded in a nested display of other data.
Example::
integer = Word(nums)
date_str = integer("year") + '/' + integer("month") +... | Below is the the instruction that describes the task:
### Input:
Diagnostic method for listing out the contents of
a :class:`ParseResults`. Accepts an optional ``indent`` argument so
that this string can be embedded in a nested display of other data.
Example::
integer = Word(nu... |
def multiple_replace(text: str, rep: Dict[str, str]) -> str:
"""
Returns a version of ``text`` in which the keys of ``rep`` (a dict) have
been replaced by their values.
As per
http://stackoverflow.com/questions/6116978/python-replace-multiple-strings.
"""
rep = dict((re.escape(k), v) for k,... | Returns a version of ``text`` in which the keys of ``rep`` (a dict) have
been replaced by their values.
As per
http://stackoverflow.com/questions/6116978/python-replace-multiple-strings. | Below is the the instruction that describes the task:
### Input:
Returns a version of ``text`` in which the keys of ``rep`` (a dict) have
been replaced by their values.
As per
http://stackoverflow.com/questions/6116978/python-replace-multiple-strings.
### Response:
def multiple_replace(text: str, rep:... |
def items(self):
"""
Items are the discussions on the entries.
"""
content_type = ContentType.objects.get_for_model(Entry)
return comments.get_model().objects.filter(
content_type=content_type, is_public=True).order_by(
'-submit_date')[:self.limit] | Items are the discussions on the entries. | Below is the the instruction that describes the task:
### Input:
Items are the discussions on the entries.
### Response:
def items(self):
"""
Items are the discussions on the entries.
"""
content_type = ContentType.objects.get_for_model(Entry)
return comments.get_model().obj... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.