code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def generate_base_provider_parser():
"""Function that generates the base provider to be used by all dns providers."""
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('action', help='specify the action to take', default='list',
choices=['create', 'list', 'update',... | Function that generates the base provider to be used by all dns providers. | Below is the the instruction that describes the task:
### Input:
Function that generates the base provider to be used by all dns providers.
### Response:
def generate_base_provider_parser():
"""Function that generates the base provider to be used by all dns providers."""
parser = argparse.ArgumentParser(ad... |
def _AskUser(self):
"""Prompt the user for the next action.
Returns:
A string, the character entered by the user.
"""
if self._show_percent:
progress = int(self._displayed*100 / (len(self._text.splitlines())))
progress_text = ' (%d%%)' % progress
else:
progress_text = ''
... | Prompt the user for the next action.
Returns:
A string, the character entered by the user. | Below is the the instruction that describes the task:
### Input:
Prompt the user for the next action.
Returns:
A string, the character entered by the user.
### Response:
def _AskUser(self):
"""Prompt the user for the next action.
Returns:
A string, the character entered by the user.
"... |
def design_matrix(phases, degree):
r"""
Constructs an :math:`N \times 2n+1` matrix of the form:
.. math::
\begin{bmatrix}
1
& \sin(1 \cdot 2\pi \cdot \phi_0)
& \cos(1 \cdot 2\pi \cdot \phi_0)
& \ldots
& \sin(n \cdot 2\pi... | r"""
Constructs an :math:`N \times 2n+1` matrix of the form:
.. math::
\begin{bmatrix}
1
& \sin(1 \cdot 2\pi \cdot \phi_0)
& \cos(1 \cdot 2\pi \cdot \phi_0)
& \ldots
& \sin(n \cdot 2\pi \cdot \phi_0)
& \cos(n \cdot 2... | Below is the the instruction that describes the task:
### Input:
r"""
Constructs an :math:`N \times 2n+1` matrix of the form:
.. math::
\begin{bmatrix}
1
& \sin(1 \cdot 2\pi \cdot \phi_0)
& \cos(1 \cdot 2\pi \cdot \phi_0)
& \ldots
... |
def set_pre_handler(self, handler):
'''pre handler push
return: ret_error or ret_ok
'''
set_flag = False
for protoc in self._pre_handler_table:
if isinstance(handler, self._pre_handler_table[protoc]["type"]):
self._pre_handler_table[protoc]["obj"] = ha... | pre handler push
return: ret_error or ret_ok | Below is the the instruction that describes the task:
### Input:
pre handler push
return: ret_error or ret_ok
### Response:
def set_pre_handler(self, handler):
'''pre handler push
return: ret_error or ret_ok
'''
set_flag = False
for protoc in self._pre_handler_table:... |
def sync_time(self):
"""Sets the time on the pyboard to match the time on the host."""
now = time.localtime(time.time())
self.remote(set_time, (now.tm_year, now.tm_mon, now.tm_mday, now.tm_wday + 1,
now.tm_hour, now.tm_min, now.tm_sec, 0))
return now | Sets the time on the pyboard to match the time on the host. | Below is the the instruction that describes the task:
### Input:
Sets the time on the pyboard to match the time on the host.
### Response:
def sync_time(self):
"""Sets the time on the pyboard to match the time on the host."""
now = time.localtime(time.time())
self.remote(set_time, (now.tm_y... |
def torestfrequency(self, f0, d0):
"""Convert a frequency measure and a doppler measure (e.g.
obtained from another spectral line with a known rest frequency) to
a rest frequency.
:param f0: frequency reference code (see :meth:`frequency`)
:param v0: a doppler measure
E... | Convert a frequency measure and a doppler measure (e.g.
obtained from another spectral line with a known rest frequency) to
a rest frequency.
:param f0: frequency reference code (see :meth:`frequency`)
:param v0: a doppler measure
Example::
dp = dm.doppler('radio',... | Below is the the instruction that describes the task:
### Input:
Convert a frequency measure and a doppler measure (e.g.
obtained from another spectral line with a known rest frequency) to
a rest frequency.
:param f0: frequency reference code (see :meth:`frequency`)
:param v0: a dop... |
def get_repository_ids_by_asset(self, asset_id):
"""Gets the list of ``Repository`` ``Ids`` mapped to an ``Asset``.
arg: asset_id (osid.id.Id): ``Id`` of an ``Asset``
return: (osid.id.IdList) - list of repository ``Ids``
raise: NotFound - ``asset_id`` is not found
raise: N... | Gets the list of ``Repository`` ``Ids`` mapped to an ``Asset``.
arg: asset_id (osid.id.Id): ``Id`` of an ``Asset``
return: (osid.id.IdList) - list of repository ``Ids``
raise: NotFound - ``asset_id`` is not found
raise: NullArgument - ``asset_id`` is ``null``
raise: Opera... | Below is the the instruction that describes the task:
### Input:
Gets the list of ``Repository`` ``Ids`` mapped to an ``Asset``.
arg: asset_id (osid.id.Id): ``Id`` of an ``Asset``
return: (osid.id.IdList) - list of repository ``Ids``
raise: NotFound - ``asset_id`` is not found
... |
def _write_mosaic(self, key, outfile):
"""Write out mosaic data (or any new data generated within Ginga)
to single-extension FITS.
"""
maxsize = self.settings.get('max_mosaic_size', 1e8) # Default 10k x 10k
channel = self.fv.get_channel(self.chname)
image = channel.data... | Write out mosaic data (or any new data generated within Ginga)
to single-extension FITS. | Below is the the instruction that describes the task:
### Input:
Write out mosaic data (or any new data generated within Ginga)
to single-extension FITS.
### Response:
def _write_mosaic(self, key, outfile):
"""Write out mosaic data (or any new data generated within Ginga)
to single-extensio... |
def execute_no_results(self, sock_info, generator):
"""Execute all operations, returning no results (w=0).
"""
if self.uses_collation:
raise ConfigurationError(
'Collation is unsupported for unacknowledged writes.')
if self.uses_array_filters:
rais... | Execute all operations, returning no results (w=0). | Below is the the instruction that describes the task:
### Input:
Execute all operations, returning no results (w=0).
### Response:
def execute_no_results(self, sock_info, generator):
"""Execute all operations, returning no results (w=0).
"""
if self.uses_collation:
raise Configu... |
def eager_send(chainlet, chunks):
"""
Eager version of `lazy_send` evaluating the return value immediately
:note: The return value by an ``n`` to ``m`` link is considered fully evaluated.
:param chainlet: the chainlet to receive and return data
:type chainlet: chainlink.ChainLink
:param chunks... | Eager version of `lazy_send` evaluating the return value immediately
:note: The return value by an ``n`` to ``m`` link is considered fully evaluated.
:param chainlet: the chainlet to receive and return data
:type chainlet: chainlink.ChainLink
:param chunks: the stream slice of data to pass to ``chainl... | Below is the the instruction that describes the task:
### Input:
Eager version of `lazy_send` evaluating the return value immediately
:note: The return value by an ``n`` to ``m`` link is considered fully evaluated.
:param chainlet: the chainlet to receive and return data
:type chainlet: chainlink.Chai... |
def urlsafe_nopadding_b64decode(data):
'''URL safe Base64 decode without padding (=)'''
padding = len(data) % 4
if padding != 0:
padding = 4 - padding
padding = '=' * padding
data = data + padding
return urlsafe_b64decode(data) | URL safe Base64 decode without padding (=) | Below is the the instruction that describes the task:
### Input:
URL safe Base64 decode without padding (=)
### Response:
def urlsafe_nopadding_b64decode(data):
'''URL safe Base64 decode without padding (=)'''
padding = len(data) % 4
if padding != 0:
padding = 4 - padding
padding = '=' * p... |
def NDP_Attack_Fake_Router(ra, iface=None, mac_src_filter=None,
ip_src_filter=None):
"""
The purpose of this function is to send provided RA message at layer 2
(i.e. providing a packet starting with IPv6 will not work) in response
to received RS messages. In the end, the funct... | The purpose of this function is to send provided RA message at layer 2
(i.e. providing a packet starting with IPv6 will not work) in response
to received RS messages. In the end, the function is a simple wrapper
around sendp() that monitor the link for RS messages.
It is probably better explained with ... | Below is the the instruction that describes the task:
### Input:
The purpose of this function is to send provided RA message at layer 2
(i.e. providing a packet starting with IPv6 will not work) in response
to received RS messages. In the end, the function is a simple wrapper
around sendp() that monitor... |
def handle_stmt(self, stmt, p_elem, pset={}):
"""
Run handler method for statement `stmt`.
`p_elem` is the parent node in the output schema. `pset` is
the current "patch set" - a dictionary with keys being QNames
of schema nodes at the current level of hierarchy for which
... | Run handler method for statement `stmt`.
`p_elem` is the parent node in the output schema. `pset` is
the current "patch set" - a dictionary with keys being QNames
of schema nodes at the current level of hierarchy for which
(or descendants thereof) any pending patches exist. The values
... | Below is the the instruction that describes the task:
### Input:
Run handler method for statement `stmt`.
`p_elem` is the parent node in the output schema. `pset` is
the current "patch set" - a dictionary with keys being QNames
of schema nodes at the current level of hierarchy for which
... |
def post(action, params=None, version=6):
"""
For the documentation, see https://foosoft.net/projects/anki-connect/
:param str action:
:param dict params:
:param int version:
:return:
"""
if params is None:
params = dict()
to_send = {
... | For the documentation, see https://foosoft.net/projects/anki-connect/
:param str action:
:param dict params:
:param int version:
:return: | Below is the the instruction that describes the task:
### Input:
For the documentation, see https://foosoft.net/projects/anki-connect/
:param str action:
:param dict params:
:param int version:
:return:
### Response:
def post(action, params=None, version=6):
"""
For... |
def convert_to_mosek(sdp):
"""Convert an SDP relaxation to a MOSEK task.
:param sdp: The SDP relaxation to convert.
:type sdp: :class:`ncpol2sdpa.sdp`.
:returns: :class:`mosek.Task`.
"""
import mosek
# Cheat when variables are complex and convert with PICOS
if sdp.complex_matrix:
... | Convert an SDP relaxation to a MOSEK task.
:param sdp: The SDP relaxation to convert.
:type sdp: :class:`ncpol2sdpa.sdp`.
:returns: :class:`mosek.Task`. | Below is the the instruction that describes the task:
### Input:
Convert an SDP relaxation to a MOSEK task.
:param sdp: The SDP relaxation to convert.
:type sdp: :class:`ncpol2sdpa.sdp`.
:returns: :class:`mosek.Task`.
### Response:
def convert_to_mosek(sdp):
"""Convert an SDP relaxation to a MOSE... |
def select_inputs(self, address, nfees, ntokens, min_confirmations=6):
"""
Selects the inputs for the spool transaction.
Args:
address (str): bitcoin address to select inputs for
nfees (int): number of fees
ntokens (int): number of tokens
min_conf... | Selects the inputs for the spool transaction.
Args:
address (str): bitcoin address to select inputs for
nfees (int): number of fees
ntokens (int): number of tokens
min_confirmations (Optional[int]): minimum number of required
confirmations; defaul... | Below is the the instruction that describes the task:
### Input:
Selects the inputs for the spool transaction.
Args:
address (str): bitcoin address to select inputs for
nfees (int): number of fees
ntokens (int): number of tokens
min_confirmations (Optional[in... |
def find_closest(db, pos):
"""Find the closest point in db to pos.
:returns: Closest dataset as well as the distance in meters.
"""
def get_dist(d1, d2):
"""Get distance between d1 and d2 in meters."""
lat1, lon1 = d1['latitude'], d1['longitude']
lat2, lon2 = d2['latitude'], d2['... | Find the closest point in db to pos.
:returns: Closest dataset as well as the distance in meters. | Below is the the instruction that describes the task:
### Input:
Find the closest point in db to pos.
:returns: Closest dataset as well as the distance in meters.
### Response:
def find_closest(db, pos):
"""Find the closest point in db to pos.
:returns: Closest dataset as well as the distance in meters... |
def url_to_text(self, url):
'''
Download PDF file and transform its document to string.
Args:
url: PDF url.
Returns:
string.
'''
path, headers = urllib.request.urlretrieve(url)
return self.path_to_text(path) | Download PDF file and transform its document to string.
Args:
url: PDF url.
Returns:
string. | Below is the the instruction that describes the task:
### Input:
Download PDF file and transform its document to string.
Args:
url: PDF url.
Returns:
string.
### Response:
def url_to_text(self, url):
'''
Download PDF file and transform its document to str... |
def is_manage_allowed(self):
"""Check if manage is allowed
"""
checkPermission = self.context.portal_membership.checkPermission
return checkPermission(ManageWorksheets, self.context) | Check if manage is allowed | Below is the the instruction that describes the task:
### Input:
Check if manage is allowed
### Response:
def is_manage_allowed(self):
"""Check if manage is allowed
"""
checkPermission = self.context.portal_membership.checkPermission
return checkPermission(ManageWorksheets, self.con... |
def nextChainableJobGraph(jobGraph, jobStore):
"""Returns the next chainable jobGraph after this jobGraph if one
exists, or None if the chain must terminate.
"""
#If no more jobs to run or services not finished, quit
if len(jobGraph.stack) == 0 or len(jobGraph.services) > 0 or jobGraph.checkpoint !=... | Returns the next chainable jobGraph after this jobGraph if one
exists, or None if the chain must terminate. | Below is the the instruction that describes the task:
### Input:
Returns the next chainable jobGraph after this jobGraph if one
exists, or None if the chain must terminate.
### Response:
def nextChainableJobGraph(jobGraph, jobStore):
"""Returns the next chainable jobGraph after this jobGraph if one
exi... |
def _write_avg_gradient(self)->None:
"Writes the average of the gradients to Tensorboard."
avg_gradient = sum(x.data.mean() for x in self.gradients)/len(self.gradients)
self._add_gradient_scalar('avg_gradient', scalar_value=avg_gradient) | Writes the average of the gradients to Tensorboard. | Below is the the instruction that describes the task:
### Input:
Writes the average of the gradients to Tensorboard.
### Response:
def _write_avg_gradient(self)->None:
"Writes the average of the gradients to Tensorboard."
avg_gradient = sum(x.data.mean() for x in self.gradients)/len(self.gradients)... |
def send_command_return_multilines(self, obj, command, *arguments):
""" Send command with no output.
:param obj: requested object.
:param command: command to send.
:param arguments: list of command arguments.
:return: list of command output lines.
:rtype: list(str)
... | Send command with no output.
:param obj: requested object.
:param command: command to send.
:param arguments: list of command arguments.
:return: list of command output lines.
:rtype: list(str) | Below is the the instruction that describes the task:
### Input:
Send command with no output.
:param obj: requested object.
:param command: command to send.
:param arguments: list of command arguments.
:return: list of command output lines.
:rtype: list(str)
### Response:
d... |
def main():
"""This main function saves the stdin termios settings, calls real_main,
and restores stdin termios settings when it returns.
"""
save_settings = None
stdin_fd = -1
try:
import termios
stdin_fd = sys.stdin.fileno()
save_settings = termios.tcgetattr(stdin_fd... | This main function saves the stdin termios settings, calls real_main,
and restores stdin termios settings when it returns. | Below is the the instruction that describes the task:
### Input:
This main function saves the stdin termios settings, calls real_main,
and restores stdin termios settings when it returns.
### Response:
def main():
"""This main function saves the stdin termios settings, calls real_main,
and restor... |
def calculate_derivative_T(self, T, P, zs, ws, method, order=1):
r'''Method to calculate a derivative of a mixture property with respect
to temperature at constant pressure and composition
of a given order using a specified method. Uses SciPy's derivative
function, with a delta of 1E-... | r'''Method to calculate a derivative of a mixture property with respect
to temperature at constant pressure and composition
of a given order using a specified method. Uses SciPy's derivative
function, with a delta of 1E-6 K and a number of points equal to
2*order + 1.
This m... | Below is the the instruction that describes the task:
### Input:
r'''Method to calculate a derivative of a mixture property with respect
to temperature at constant pressure and composition
of a given order using a specified method. Uses SciPy's derivative
function, with a delta of 1E-6 K ... |
def validate_course_run_id(self, value):
"""
Validates that the course run id is part of the Enterprise Customer's catalog.
"""
enterprise_customer = self.context.get('enterprise_customer')
if not enterprise_customer.catalog_contains_course(value):
raise serializers.... | Validates that the course run id is part of the Enterprise Customer's catalog. | Below is the the instruction that describes the task:
### Input:
Validates that the course run id is part of the Enterprise Customer's catalog.
### Response:
def validate_course_run_id(self, value):
"""
Validates that the course run id is part of the Enterprise Customer's catalog.
"""
... |
def upload_file(self, localFileName, remoteFileName=None, connId='default'):
"""
Sends file from local drive to current directory on FTP server in binary mode.
Returns server output.
Parameters:
- localFileName - file name or path to a file on a local drive.
- remoteFileN... | Sends file from local drive to current directory on FTP server in binary mode.
Returns server output.
Parameters:
- localFileName - file name or path to a file on a local drive.
- remoteFileName (optional) - a name or path containing name under which file should be saved.
- connI... | Below is the the instruction that describes the task:
### Input:
Sends file from local drive to current directory on FTP server in binary mode.
Returns server output.
Parameters:
- localFileName - file name or path to a file on a local drive.
- remoteFileName (optional) - a name or p... |
def center(self, coords):
""" center the map on a "map pixel"
"""
x, y = [round(i, 0) for i in coords]
self.view_rect.center = x, y
tw, th = self.data.tile_size
left, ox = divmod(x, tw)
top, oy = divmod(y, th)
vec = int(ox / 2), int(oy)
iso = v... | center the map on a "map pixel" | Below is the the instruction that describes the task:
### Input:
center the map on a "map pixel"
### Response:
def center(self, coords):
""" center the map on a "map pixel"
"""
x, y = [round(i, 0) for i in coords]
self.view_rect.center = x, y
tw, th = self.data.tile_size
... |
def _mmInit(self):
"""Create the minimum match dictionary of keys"""
# cache references to speed up loop a bit
mmkeys = {}
mmkeysGet = mmkeys.setdefault
minkeylength = self.minkeylength
for key in self.data.keys():
# add abbreviations as short as minkeylength
... | Create the minimum match dictionary of keys | Below is the the instruction that describes the task:
### Input:
Create the minimum match dictionary of keys
### Response:
def _mmInit(self):
"""Create the minimum match dictionary of keys"""
# cache references to speed up loop a bit
mmkeys = {}
mmkeysGet = mmkeys.setdefault
... |
def get_attrs_declarations(item_type):
"""
Helper method to return a dictionary of tuples. Each key is attr_name, and value is (attr_type, attr_is_optional)
:param item_type:
:return:
"""
# this will raise an error if the type is not an attr-created type
attribs = fields(item_type)
re... | Helper method to return a dictionary of tuples. Each key is attr_name, and value is (attr_type, attr_is_optional)
:param item_type:
:return: | Below is the the instruction that describes the task:
### Input:
Helper method to return a dictionary of tuples. Each key is attr_name, and value is (attr_type, attr_is_optional)
:param item_type:
:return:
### Response:
def get_attrs_declarations(item_type):
"""
Helper method to return a dictionar... |
def nonce_solid(name, n_inputs, n_outputs):
"""Creates a solid with the given number of (meaningless) inputs and outputs.
Config controls the behavior of the nonce solid."""
@solid(
name=name,
inputs=[
InputDefinition(name='input_{}'.format(i)) for i in range(n_inputs)
... | Creates a solid with the given number of (meaningless) inputs and outputs.
Config controls the behavior of the nonce solid. | Below is the the instruction that describes the task:
### Input:
Creates a solid with the given number of (meaningless) inputs and outputs.
Config controls the behavior of the nonce solid.
### Response:
def nonce_solid(name, n_inputs, n_outputs):
"""Creates a solid with the given number of (meaningless) i... |
def _GetStat(self):
"""Retrieves information about the file entry.
Returns:
VFSStat: a stat object.
"""
stat_object = super(APFSFileEntry, self)._GetStat()
# File data stat information.
stat_object.size = self._fsapfs_file_entry.size
# Ownership and permissions stat information.
... | Retrieves information about the file entry.
Returns:
VFSStat: a stat object. | Below is the the instruction that describes the task:
### Input:
Retrieves information about the file entry.
Returns:
VFSStat: a stat object.
### Response:
def _GetStat(self):
"""Retrieves information about the file entry.
Returns:
VFSStat: a stat object.
"""
stat_object = super(A... |
def _expectation(p, mean, none, kern, feat, nghp=None):
"""
Compute the expectation:
expectation[n] = <x_n K_{x_n, Z}>_p(x_n)
- K_{.,.} :: RBF kernel
:return: NxDxM
"""
Xmu, Xcov = p.mu, p.cov
with tf.control_dependencies([tf.assert_equal(
tf.shape(Xmu)[1], tf.constant(... | Compute the expectation:
expectation[n] = <x_n K_{x_n, Z}>_p(x_n)
- K_{.,.} :: RBF kernel
:return: NxDxM | Below is the the instruction that describes the task:
### Input:
Compute the expectation:
expectation[n] = <x_n K_{x_n, Z}>_p(x_n)
- K_{.,.} :: RBF kernel
:return: NxDxM
### Response:
def _expectation(p, mean, none, kern, feat, nghp=None):
"""
Compute the expectation:
expectation[n] = ... |
def get_metrics(self, from_time=None, to_time=None, metrics=None,
ifs=[], storageIds=[], view=None):
"""
This endpoint is not supported as of v6. Use the timeseries API
instead. To get all metrics for a host with the timeseries API use
the query:
'select * where hostId = $HOST_ID'.
To ge... | This endpoint is not supported as of v6. Use the timeseries API
instead. To get all metrics for a host with the timeseries API use
the query:
'select * where hostId = $HOST_ID'.
To get specific metrics for a host use a comma-separated list of
the metric names as follows:
'select $METRIC_NAME1... | Below is the the instruction that describes the task:
### Input:
This endpoint is not supported as of v6. Use the timeseries API
instead. To get all metrics for a host with the timeseries API use
the query:
'select * where hostId = $HOST_ID'.
To get specific metrics for a host use a comma-separate... |
def get_csv_rows_for_installed(
old_csv_rows, # type: Iterable[List[str]]
installed, # type: Dict[str, str]
changed, # type: set
generated, # type: List[str]
lib_dir, # type: str
):
# type: (...) -> List[InstalledCSVRow]
"""
:param installed: A map from archive RECORD path to instal... | :param installed: A map from archive RECORD path to installation RECORD
path. | Below is the the instruction that describes the task:
### Input:
:param installed: A map from archive RECORD path to installation RECORD
path.
### Response:
def get_csv_rows_for_installed(
old_csv_rows, # type: Iterable[List[str]]
installed, # type: Dict[str, str]
changed, # type: set
ge... |
def disambiguate_url(url, location=None):
"""turn multi-ip interfaces '0.0.0.0' and '*' into connectable
ones, based on the location (default interpretation is localhost).
This is for zeromq urls, such as tcp://*:10101."""
try:
proto,ip,port = split_url(url)
except AssertionError:
... | turn multi-ip interfaces '0.0.0.0' and '*' into connectable
ones, based on the location (default interpretation is localhost).
This is for zeromq urls, such as tcp://*:10101. | Below is the the instruction that describes the task:
### Input:
turn multi-ip interfaces '0.0.0.0' and '*' into connectable
ones, based on the location (default interpretation is localhost).
This is for zeromq urls, such as tcp://*:10101.
### Response:
def disambiguate_url(url, location=None):
""... |
def resize(im, short, max_size):
"""
only resize input image to target size and return scale
:param im: BGR image input by opencv
:param short: one dimensional size (the short side)
:param max_size: one dimensional max size (the long side)
:return: resized image (NDArray) and scale (float)
"... | only resize input image to target size and return scale
:param im: BGR image input by opencv
:param short: one dimensional size (the short side)
:param max_size: one dimensional max size (the long side)
:return: resized image (NDArray) and scale (float) | Below is the the instruction that describes the task:
### Input:
only resize input image to target size and return scale
:param im: BGR image input by opencv
:param short: one dimensional size (the short side)
:param max_size: one dimensional max size (the long side)
:return: resized image (NDArray)... |
def run(host=DEFAULT_HOST, port=DEFAULT_PORT, path='.'):
"""Run the development server
"""
path = abspath(path)
c = Clay(path)
c.run(host=host, port=port) | Run the development server | Below is the the instruction that describes the task:
### Input:
Run the development server
### Response:
def run(host=DEFAULT_HOST, port=DEFAULT_PORT, path='.'):
"""Run the development server
"""
path = abspath(path)
c = Clay(path)
c.run(host=host, port=port) |
def from_whypo(cls, xml, encoding='utf-8'):
"""Constructor from xml element *WHYPO*
:param xml.etree.ElementTree xml: the xml *WHYPO* element
:param string encoding: encoding of the xml
"""
word = unicode(xml.get('WORD'), encoding)
confidence = float(xml.get('CM'))
... | Constructor from xml element *WHYPO*
:param xml.etree.ElementTree xml: the xml *WHYPO* element
:param string encoding: encoding of the xml | Below is the the instruction that describes the task:
### Input:
Constructor from xml element *WHYPO*
:param xml.etree.ElementTree xml: the xml *WHYPO* element
:param string encoding: encoding of the xml
### Response:
def from_whypo(cls, xml, encoding='utf-8'):
"""Constructor from xml elem... |
def from_iso_time(timestring, use_dateutil=True):
"""Parse an ISO8601-formatted datetime string and return a datetime.time
object.
"""
if not _iso8601_time_re.match(timestring):
raise ValueError('Not a valid ISO8601-formatted time string')
if dateutil_available and use_dateutil:
retu... | Parse an ISO8601-formatted datetime string and return a datetime.time
object. | Below is the the instruction that describes the task:
### Input:
Parse an ISO8601-formatted datetime string and return a datetime.time
object.
### Response:
def from_iso_time(timestring, use_dateutil=True):
"""Parse an ISO8601-formatted datetime string and return a datetime.time
object.
"""
if ... |
def joint_probabilities_nn(
neighbors,
distances,
perplexities,
symmetrize=True,
normalization="pair-wise",
n_reference_samples=None,
n_jobs=1,
):
"""Compute the conditional probability matrix P_{j|i}.
This method computes an approximation to P using the nearest neighbors.
Para... | Compute the conditional probability matrix P_{j|i}.
This method computes an approximation to P using the nearest neighbors.
Parameters
----------
neighbors: np.ndarray
A `n_samples * k_neighbors` matrix containing the indices to each
points" nearest neighbors in descending order.
d... | Below is the the instruction that describes the task:
### Input:
Compute the conditional probability matrix P_{j|i}.
This method computes an approximation to P using the nearest neighbors.
Parameters
----------
neighbors: np.ndarray
A `n_samples * k_neighbors` matrix containing the indices... |
def sam_iter(handle, start_line=None, headers=False):
"""Iterate over SAM file and return SAM entries
Args:
handle (file): SAM file handle, can be any iterator so long as it
it returns subsequent "lines" of a SAM entry
start_line (str): Next SAM entry, if 'handle' has been partiall... | Iterate over SAM file and return SAM entries
Args:
handle (file): SAM file handle, can be any iterator so long as it
it returns subsequent "lines" of a SAM entry
start_line (str): Next SAM entry, if 'handle' has been partially read
and you want to start iterating at the nex... | Below is the the instruction that describes the task:
### Input:
Iterate over SAM file and return SAM entries
Args:
handle (file): SAM file handle, can be any iterator so long as it
it returns subsequent "lines" of a SAM entry
start_line (str): Next SAM entry, if 'handle' has been ... |
def get_request_mock():
"""Build a ``request`` mock up for tests"""
from django.test.client import RequestFactory
from django.core.handlers.base import BaseHandler
factory = RequestFactory()
request = factory.get('/')
class FakeUser():
is_authenticated = False
is_staff = Fa... | Build a ``request`` mock up for tests | Below is the the instruction that describes the task:
### Input:
Build a ``request`` mock up for tests
### Response:
def get_request_mock():
"""Build a ``request`` mock up for tests"""
from django.test.client import RequestFactory
from django.core.handlers.base import BaseHandler
factory = RequestF... |
def coding_sequence(self):
"""
cDNA coding sequence (from start codon to stop codon, without
any introns)
"""
if self.sequence is None:
return None
start = self.first_start_codon_spliced_offset
end = self.last_stop_codon_spliced_offset
# If s... | cDNA coding sequence (from start codon to stop codon, without
any introns) | Below is the the instruction that describes the task:
### Input:
cDNA coding sequence (from start codon to stop codon, without
any introns)
### Response:
def coding_sequence(self):
"""
cDNA coding sequence (from start codon to stop codon, without
any introns)
"""
if ... |
def receive_trial_result(self, parameter_id, parameters, value):
'''
Record an observation of the objective function
parameter_id : int
parameters : dict of parameters
value: final metrics of the trial, including reward
'''
logger.debug('acquiring lock for param {... | Record an observation of the objective function
parameter_id : int
parameters : dict of parameters
value: final metrics of the trial, including reward | Below is the the instruction that describes the task:
### Input:
Record an observation of the objective function
parameter_id : int
parameters : dict of parameters
value: final metrics of the trial, including reward
### Response:
def receive_trial_result(self, parameter_id, parameters, valu... |
def enable_gui(gui, kernel=None):
"""Enable integration with a given GUI"""
if gui not in loop_map:
raise ValueError("GUI %r not supported" % gui)
if kernel is None:
if Application.initialized():
kernel = getattr(Application.instance(), 'kernel', None)
if kernel is None:
... | Enable integration with a given GUI | Below is the the instruction that describes the task:
### Input:
Enable integration with a given GUI
### Response:
def enable_gui(gui, kernel=None):
"""Enable integration with a given GUI"""
if gui not in loop_map:
raise ValueError("GUI %r not supported" % gui)
if kernel is None:
if App... |
def SVD_sim(sp, lowcut, highcut, samp_rate,
amp_range=np.arange(-10, 10, 0.01)):
"""
Generate basis vectors of a set of simulated seismograms.
Inputs should have a range of S-P amplitude ratios, in theory to simulate \
a range of focal mechanisms.
:type sp: int
:param sp: S-P time ... | Generate basis vectors of a set of simulated seismograms.
Inputs should have a range of S-P amplitude ratios, in theory to simulate \
a range of focal mechanisms.
:type sp: int
:param sp: S-P time in seconds - will be converted to samples according \
to samp_rate.
:type lowcut: float
:... | Below is the the instruction that describes the task:
### Input:
Generate basis vectors of a set of simulated seismograms.
Inputs should have a range of S-P amplitude ratios, in theory to simulate \
a range of focal mechanisms.
:type sp: int
:param sp: S-P time in seconds - will be converted to sa... |
def _init_ui(self):
"""Initial the first UI page.
- load html from '/' endpoint
- if <title> is defined, use as windows title
"""
(content, mimetype) = make_response(self._url_map_to_function('/'))
try:
beautifulsoup = BeautifulSoup(content)
self.w... | Initial the first UI page.
- load html from '/' endpoint
- if <title> is defined, use as windows title | Below is the the instruction that describes the task:
### Input:
Initial the first UI page.
- load html from '/' endpoint
- if <title> is defined, use as windows title
### Response:
def _init_ui(self):
"""Initial the first UI page.
- load html from '/' endpoint
- if <title> ... |
def generate_xhtml(path, dirs, files):
"""Return a XHTML document listing the directories and files."""
# Prepare the path to display.
if path != '/':
dirs.insert(0, '..')
if not path.endswith('/'):
path += '/'
def itemize(item):
return '<a href="%s">%s</a>' % (item... | Return a XHTML document listing the directories and files. | Below is the the instruction that describes the task:
### Input:
Return a XHTML document listing the directories and files.
### Response:
def generate_xhtml(path, dirs, files):
"""Return a XHTML document listing the directories and files."""
# Prepare the path to display.
if path != '/':
di... |
def metadata(self, name):
"""Return value and metadata associated with the named value
Parameters
----------
name : str
name to retrieve. If the name contains '.'s it will be retrieved recursively
Raises
------
KeyError
if name is not def... | Return value and metadata associated with the named value
Parameters
----------
name : str
name to retrieve. If the name contains '.'s it will be retrieved recursively
Raises
------
KeyError
if name is not defined in the ConfigTree | Below is the the instruction that describes the task:
### Input:
Return value and metadata associated with the named value
Parameters
----------
name : str
name to retrieve. If the name contains '.'s it will be retrieved recursively
Raises
------
KeyErro... |
def as_proximal_lang_operator(op, norm_bound=None):
"""Wrap ``op`` as a ``proximal.BlackBox``.
This is intended to be used with the `ProxImaL language solvers.
<https://github.com/comp-imaging/proximal>`_
For documentation on the proximal language (ProxImaL) see [Hei+2016].
Parameters
-------... | Wrap ``op`` as a ``proximal.BlackBox``.
This is intended to be used with the `ProxImaL language solvers.
<https://github.com/comp-imaging/proximal>`_
For documentation on the proximal language (ProxImaL) see [Hei+2016].
Parameters
----------
op : `Operator`
Linear operator to be wrapp... | Below is the the instruction that describes the task:
### Input:
Wrap ``op`` as a ``proximal.BlackBox``.
This is intended to be used with the `ProxImaL language solvers.
<https://github.com/comp-imaging/proximal>`_
For documentation on the proximal language (ProxImaL) see [Hei+2016].
Parameters
... |
def get_config(network, data_shape, **kwargs):
"""Configuration factory for various networks
Parameters
----------
network : str
base network name, such as vgg_reduced, inceptionv3, resnet...
data_shape : int
input data dimension
kwargs : dict
extra arguments
"""
... | Configuration factory for various networks
Parameters
----------
network : str
base network name, such as vgg_reduced, inceptionv3, resnet...
data_shape : int
input data dimension
kwargs : dict
extra arguments | Below is the the instruction that describes the task:
### Input:
Configuration factory for various networks
Parameters
----------
network : str
base network name, such as vgg_reduced, inceptionv3, resnet...
data_shape : int
input data dimension
kwargs : dict
extra argume... |
def load_python_bindings(python_input):
"""
Custom key bindings.
"""
bindings = KeyBindings()
sidebar_visible = Condition(lambda: python_input.show_sidebar)
handle = bindings.add
@handle('c-l')
def _(event):
"""
Clear whole screen and render again -- also when the sideb... | Custom key bindings. | Below is the the instruction that describes the task:
### Input:
Custom key bindings.
### Response:
def load_python_bindings(python_input):
"""
Custom key bindings.
"""
bindings = KeyBindings()
sidebar_visible = Condition(lambda: python_input.show_sidebar)
handle = bindings.add
@handl... |
def create_host(factories, value):
"""Use the factories to create a host object.
:param factories: a list of functions that return host objects
(Hostname, IPv4Address, IPv6Address) for valid arguments
:param value: a value to be passed as argument to factories
:returns: an object representing the v... | Use the factories to create a host object.
:param factories: a list of functions that return host objects
(Hostname, IPv4Address, IPv6Address) for valid arguments
:param value: a value to be passed as argument to factories
:returns: an object representing the value, created by one of
the factories.... | Below is the the instruction that describes the task:
### Input:
Use the factories to create a host object.
:param factories: a list of functions that return host objects
(Hostname, IPv4Address, IPv6Address) for valid arguments
:param value: a value to be passed as argument to factories
:returns: a... |
def get_sorted_series_files(self, startpath="", series_number=None, return_files_with_info=False,
sort_keys="SliceLocation", return_files=True, remove_doubled_slice_locations=True):
"""
Function returns sorted list of dicom files. File paths are organized
by Serie... | Function returns sorted list of dicom files. File paths are organized
by SeriesUID, StudyUID and FrameUID
:param startpath: path prefix. E.g. "~/data"
:param series_number: ID of series used for filtering the data
:param return_files_with_info: return more complex information about sor... | Below is the the instruction that describes the task:
### Input:
Function returns sorted list of dicom files. File paths are organized
by SeriesUID, StudyUID and FrameUID
:param startpath: path prefix. E.g. "~/data"
:param series_number: ID of series used for filtering the data
:pa... |
def text(cls, text, *, resize=None, single_use=None, selective=None):
"""
Creates a new button with the given text.
Args:
resize (`bool`):
If present, the entire keyboard will be reconfigured to
be resized and be smaller if there are not many buttons.... | Creates a new button with the given text.
Args:
resize (`bool`):
If present, the entire keyboard will be reconfigured to
be resized and be smaller if there are not many buttons.
single_use (`bool`):
If present, the entire keyboard will be... | Below is the the instruction that describes the task:
### Input:
Creates a new button with the given text.
Args:
resize (`bool`):
If present, the entire keyboard will be reconfigured to
be resized and be smaller if there are not many buttons.
single_... |
def uniq(args):
"""
%prog uniq gffile cdsfasta
Remove overlapping gene models. Similar to formats.gff.uniq(), overlapping
'piles' are processed, one by one.
Here, we use a different algorithm, that retains the best non-overlapping
subset witin each pile, rather than single best model. Scoring ... | %prog uniq gffile cdsfasta
Remove overlapping gene models. Similar to formats.gff.uniq(), overlapping
'piles' are processed, one by one.
Here, we use a different algorithm, that retains the best non-overlapping
subset witin each pile, rather than single best model. Scoring function is
also differe... | Below is the the instruction that describes the task:
### Input:
%prog uniq gffile cdsfasta
Remove overlapping gene models. Similar to formats.gff.uniq(), overlapping
'piles' are processed, one by one.
Here, we use a different algorithm, that retains the best non-overlapping
subset witin each pile... |
def export(self):
"""
Run the export process
Returns:
(list of str): The path of the exported disks.
"""
if self._with_threads:
utils.invoke_different_funcs_in_parallel(
*map(lambda mgr: mgr.export, self._get_export_mgr())
)
... | Run the export process
Returns:
(list of str): The path of the exported disks. | Below is the the instruction that describes the task:
### Input:
Run the export process
Returns:
(list of str): The path of the exported disks.
### Response:
def export(self):
"""
Run the export process
Returns:
(list of str): The path of the exported disks.
... |
def hpo_genes(context, hpo_term):
"""Export a list of genes based on hpo terms"""
LOG.info("Running scout export hpo_genes")
adapter = context.obj['adapter']
header = ["#Gene_id\tCount"]
if not hpo_term:
LOG.warning("Please use at least one hpo term")
context.abort()
for l... | Export a list of genes based on hpo terms | Below is the the instruction that describes the task:
### Input:
Export a list of genes based on hpo terms
### Response:
def hpo_genes(context, hpo_term):
"""Export a list of genes based on hpo terms"""
LOG.info("Running scout export hpo_genes")
adapter = context.obj['adapter']
header = ["#Gen... |
def report_score_vs_rmsd_funnels(designs, path):
"""
Create a PDF showing the score vs. RMSD funnels for all the reasonable
designs. This method was copied from an old version of this script, and
does not currently work.
"""
from matplotlib.backends.backend_pdf import PdfPages
import matplo... | Create a PDF showing the score vs. RMSD funnels for all the reasonable
designs. This method was copied from an old version of this script, and
does not currently work. | Below is the the instruction that describes the task:
### Input:
Create a PDF showing the score vs. RMSD funnels for all the reasonable
designs. This method was copied from an old version of this script, and
does not currently work.
### Response:
def report_score_vs_rmsd_funnels(designs, path):
"""
... |
def run_python_module(modulename, args):
"""Run a python module, as though with ``python -m name args...``.
`modulename` is the name of the module, possibly a dot-separated name.
`args` is the argument array to present as sys.argv, including the first
element naming the module being executed.
"""
... | Run a python module, as though with ``python -m name args...``.
`modulename` is the name of the module, possibly a dot-separated name.
`args` is the argument array to present as sys.argv, including the first
element naming the module being executed. | Below is the the instruction that describes the task:
### Input:
Run a python module, as though with ``python -m name args...``.
`modulename` is the name of the module, possibly a dot-separated name.
`args` is the argument array to present as sys.argv, including the first
element naming the module bein... |
def predict(self, X):
"""
Assign classes to test data.
Parameters
----------
X : array
Test data, of dimension N times d (rows are examples, columns
are data dimensions)
Returns
-------
y_predicted : array
A vector of ... | Assign classes to test data.
Parameters
----------
X : array
Test data, of dimension N times d (rows are examples, columns
are data dimensions)
Returns
-------
y_predicted : array
A vector of length N containing assigned classes. If n... | Below is the the instruction that describes the task:
### Input:
Assign classes to test data.
Parameters
----------
X : array
Test data, of dimension N times d (rows are examples, columns
are data dimensions)
Returns
-------
y_predicted : arr... |
def apply_Mueller(I,Q,U,V, gain_offsets, phase_offsets, chan_per_coarse, feedtype='l'):
'''
Returns calibrated Stokes parameters for an observation given an array
of differential gains and phase differences.
'''
#Find shape of data arrays and calculate number of coarse channels
shape = I.shape
... | Returns calibrated Stokes parameters for an observation given an array
of differential gains and phase differences. | Below is the the instruction that describes the task:
### Input:
Returns calibrated Stokes parameters for an observation given an array
of differential gains and phase differences.
### Response:
def apply_Mueller(I,Q,U,V, gain_offsets, phase_offsets, chan_per_coarse, feedtype='l'):
'''
Returns calibrat... |
def yesno(question, default=None):
"""Asks a yes/no question
Args:
question: string **without** the question mark and without the options.
Example: 'Create links'
default: default option. Accepted values are 'Y', 'YES', 'N', 'NO' or lowercase versions of
these val... | Asks a yes/no question
Args:
question: string **without** the question mark and without the options.
Example: 'Create links'
default: default option. Accepted values are 'Y', 'YES', 'N', 'NO' or lowercase versions of
these valus (this argument is case-insensitive)
... | Below is the the instruction that describes the task:
### Input:
Asks a yes/no question
Args:
question: string **without** the question mark and without the options.
Example: 'Create links'
default: default option. Accepted values are 'Y', 'YES', 'N', 'NO' or lowercase versions... |
def copy_any(src, dst, only_missing=False): # pragma: no cover
"""Copy a file or a directory tree, deleting the destination before processing"""
if not only_missing:
remove_if_exist(dst)
if os.path.exists(src):
if os.path.isdir(src):
if not only_missing:
shutil.c... | Copy a file or a directory tree, deleting the destination before processing | Below is the the instruction that describes the task:
### Input:
Copy a file or a directory tree, deleting the destination before processing
### Response:
def copy_any(src, dst, only_missing=False): # pragma: no cover
"""Copy a file or a directory tree, deleting the destination before processing"""
if not... |
def _clear_queue(to_clear):
"""Clear all items from a queue safely."""
while not to_clear.empty():
try:
to_clear.get(False)
to_clear.task_done()
except queue.Empty:
continue | Clear all items from a queue safely. | Below is the the instruction that describes the task:
### Input:
Clear all items from a queue safely.
### Response:
def _clear_queue(to_clear):
"""Clear all items from a queue safely."""
while not to_clear.empty():
try:
to_clear.get(False)
to_clear.task_done()
excep... |
def load(path_or_file, validate=True, strict=True, fmt='auto'):
r"""Load a JAMS Annotation from a file.
Parameters
----------
path_or_file : str or file-like
Path to the JAMS file to load
OR
An open file handle to load from.
validate : bool
Attempt to validate the ... | r"""Load a JAMS Annotation from a file.
Parameters
----------
path_or_file : str or file-like
Path to the JAMS file to load
OR
An open file handle to load from.
validate : bool
Attempt to validate the JAMS object
strict : bool
if `validate == True`, enforc... | Below is the the instruction that describes the task:
### Input:
r"""Load a JAMS Annotation from a file.
Parameters
----------
path_or_file : str or file-like
Path to the JAMS file to load
OR
An open file handle to load from.
validate : bool
Attempt to validate the... |
def slugs_navigation_encode(self, u_m, phi_c, theta_c, psiDot_c, ay_body, totalDist, dist2Go, fromWP, toWP, h_c):
'''
Data used in the navigation algorithm.
u_m : Measured Airspeed prior to the nav filter in m/s (float)
phi_c ... | Data used in the navigation algorithm.
u_m : Measured Airspeed prior to the nav filter in m/s (float)
phi_c : Commanded Roll (float)
theta_c : Commanded Pitch (float)
psiDot_c : ... | Below is the the instruction that describes the task:
### Input:
Data used in the navigation algorithm.
u_m : Measured Airspeed prior to the nav filter in m/s (float)
phi_c : Commanded Roll (float)
theta_c :... |
def ne(name, value):
'''
Only succeed if the value in the given register location is not equal to
the given value
USAGE:
.. code-block:: yaml
foo:
check.ne:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
... | Only succeed if the value in the given register location is not equal to
the given value
USAGE:
.. code-block:: yaml
foo:
check.ne:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
... | Below is the the instruction that describes the task:
### Input:
Only succeed if the value in the given register location is not equal to
the given value
USAGE:
.. code-block:: yaml
foo:
check.ne:
- value: 42
run_remote_ex:
local.cmd:
- tgt... |
def in_config(self, key):
"""Check to see if the given key (or an alias) is in the config file.
"""
# if the requested key is an alias, then return the proper key
key = self._real_key(key)
exists = self._config.get(key)
return exists | Check to see if the given key (or an alias) is in the config file. | Below is the the instruction that describes the task:
### Input:
Check to see if the given key (or an alias) is in the config file.
### Response:
def in_config(self, key):
"""Check to see if the given key (or an alias) is in the config file.
"""
# if the requested key is an alias, then retu... |
def disable_svc_event_handler(self, service):
"""Disable event handlers for a service
Format of the line that triggers function call::
DISABLE_SVC_EVENT_HANDLER;<host_name>;<service_description>
:param service: service to edit
:type service: alignak.objects.service.Service
... | Disable event handlers for a service
Format of the line that triggers function call::
DISABLE_SVC_EVENT_HANDLER;<host_name>;<service_description>
:param service: service to edit
:type service: alignak.objects.service.Service
:return: None | Below is the the instruction that describes the task:
### Input:
Disable event handlers for a service
Format of the line that triggers function call::
DISABLE_SVC_EVENT_HANDLER;<host_name>;<service_description>
:param service: service to edit
:type service: alignak.objects.service.... |
def get_vcs_details_output_vcs_details_principal_switch_wwn(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vcs_details = ET.Element("get_vcs_details")
config = get_vcs_details
output = ET.SubElement(get_vcs_details, "output")
vcs_det... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def get_vcs_details_output_vcs_details_principal_switch_wwn(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vcs_details = ET.Element("get_vcs_details")
... |
def download_segmentation_image_file(self, mapobject_type_name,
plate_name, well_name, well_pos_y, well_pos_x, tpoint, zplane, align,
directory):
'''Downloads a segmentation image and writes it to a *PNG* file on disk.
Parameters
----------
mapobject_type_name: s... | Downloads a segmentation image and writes it to a *PNG* file on disk.
Parameters
----------
mapobject_type_name: str
name of the segmented objects
plate_name: str
name of the plate
well_name: str
name of the well in which the image is located
... | Below is the the instruction that describes the task:
### Input:
Downloads a segmentation image and writes it to a *PNG* file on disk.
Parameters
----------
mapobject_type_name: str
name of the segmented objects
plate_name: str
name of the plate
well_... |
def blend_rect(self, x0, y0, x1, y1, dx, dy, destination, alpha=0xff):
"""Blend a rectangle onto the image"""
x0, y0, x1, y1 = self.rect_helper(x0, y0, x1, y1)
for x in range(x0, x1 + 1):
for y in range(y0, y1 + 1):
o = self._offset(x, y)
rgba = self.c... | Blend a rectangle onto the image | Below is the the instruction that describes the task:
### Input:
Blend a rectangle onto the image
### Response:
def blend_rect(self, x0, y0, x1, y1, dx, dy, destination, alpha=0xff):
"""Blend a rectangle onto the image"""
x0, y0, x1, y1 = self.rect_helper(x0, y0, x1, y1)
for x in range(x0, ... |
def add_member(self, container_id, member_id):
"""AddMember.
[Preview API]
:param str container_id:
:param str member_id:
:rtype: bool
"""
route_values = {}
if container_id is not None:
route_values['containerId'] = self._serialize.url('contain... | AddMember.
[Preview API]
:param str container_id:
:param str member_id:
:rtype: bool | Below is the the instruction that describes the task:
### Input:
AddMember.
[Preview API]
:param str container_id:
:param str member_id:
:rtype: bool
### Response:
def add_member(self, container_id, member_id):
"""AddMember.
[Preview API]
:param str container... |
def get_choice(value):
"""Gets a key to choose a choice from any value."""
if value is None:
return 'null'
for attr in ['__name__', 'name']:
if hasattr(value, attr):
return getattr(value, attr)
return str(value) | Gets a key to choose a choice from any value. | Below is the the instruction that describes the task:
### Input:
Gets a key to choose a choice from any value.
### Response:
def get_choice(value):
"""Gets a key to choose a choice from any value."""
if value is None:
return 'null'
for attr in ['__name__', 'name']:
if hasattr(value, att... |
def add_item_to_basket(self, item, variant=VARIANT.MEDIUM, quantity=1):
'''
Add an item to the current basket.
:param Item item: Item from menu.
:param int variant: Item SKU id. Ignored if the item is a side.
:param int quantity: The quantity of item to be added.
:return... | Add an item to the current basket.
:param Item item: Item from menu.
:param int variant: Item SKU id. Ignored if the item is a side.
:param int quantity: The quantity of item to be added.
:return: A response having added an item to the current basket.
:rtype: requests.Response | Below is the the instruction that describes the task:
### Input:
Add an item to the current basket.
:param Item item: Item from menu.
:param int variant: Item SKU id. Ignored if the item is a side.
:param int quantity: The quantity of item to be added.
:return: A response having add... |
def p_if_expr_header(p):
""" if_header : IF expr
"""
global ENABLED
IFDEFS.append((ENABLED, p.lineno(1)))
ENABLED = bool(int(p[2])) if p[2].isdigit() else ID_TABLE.defined(p[2]) | if_header : IF expr | Below is the the instruction that describes the task:
### Input:
if_header : IF expr
### Response:
def p_if_expr_header(p):
""" if_header : IF expr
"""
global ENABLED
IFDEFS.append((ENABLED, p.lineno(1)))
ENABLED = bool(int(p[2])) if p[2].isdigit() else ID_TABLE.defined(p[2]) |
def deleteThreads(self, thread_ids):
"""
Deletes threads
:param thread_ids: Thread IDs to delete. See :ref:`intro_threads`
:return: Whether the request was successful
:raises: FBchatException if request failed
"""
thread_ids = require_list(thread_ids)
da... | Deletes threads
:param thread_ids: Thread IDs to delete. See :ref:`intro_threads`
:return: Whether the request was successful
:raises: FBchatException if request failed | Below is the the instruction that describes the task:
### Input:
Deletes threads
:param thread_ids: Thread IDs to delete. See :ref:`intro_threads`
:return: Whether the request was successful
:raises: FBchatException if request failed
### Response:
def deleteThreads(self, thread_ids):
... |
def getThirdpartyLibs(self, libs, configuration = 'Development', includePlatformDefaults = True):
"""
Retrieves the ThirdPartyLibraryDetails instance for Unreal-bundled versions of the specified third-party libraries
"""
if includePlatformDefaults == True:
libs = self._defaultThirdpartyLibs() + libs
interr... | Retrieves the ThirdPartyLibraryDetails instance for Unreal-bundled versions of the specified third-party libraries | Below is the the instruction that describes the task:
### Input:
Retrieves the ThirdPartyLibraryDetails instance for Unreal-bundled versions of the specified third-party libraries
### Response:
def getThirdpartyLibs(self, libs, configuration = 'Development', includePlatformDefaults = True):
"""
Retrieves the T... |
def update_database(self, server_name, name, new_database_name=None,
service_objective_id=None, edition=None,
max_size_bytes=None):
'''
Updates existing database details.
server_name:
Name of the server to contain the new database.
... | Updates existing database details.
server_name:
Name of the server to contain the new database.
name:
Required. The name for the new database. See Naming Requirements
in Azure SQL Database General Guidelines and Limitations and
Database Identifiers for mo... | Below is the the instruction that describes the task:
### Input:
Updates existing database details.
server_name:
Name of the server to contain the new database.
name:
Required. The name for the new database. See Naming Requirements
in Azure SQL Database General G... |
def all(self, order_by=None, limit=0):
"""
Fetch all items.
:param limit: How many rows to fetch.
:param order_by: column on which to order the results. \
To change the sort, prepend with < or >.
"""
with rconnect() as conn:
try:
... | Fetch all items.
:param limit: How many rows to fetch.
:param order_by: column on which to order the results. \
To change the sort, prepend with < or >. | Below is the the instruction that describes the task:
### Input:
Fetch all items.
:param limit: How many rows to fetch.
:param order_by: column on which to order the results. \
To change the sort, prepend with < or >.
### Response:
def all(self, order_by=None, limit=0):
... |
def head_orifice(Diam, RatioVCOrifice, FlowRate):
"""Return the head of the orifice."""
#Checking input validity
ut.check_range([Diam, ">0", "Diameter"], [FlowRate, ">0", "Flow rate"],
[RatioVCOrifice, "0-1", "VC orifice ratio"])
return ((FlowRate
/ (RatioVCOrifice * area... | Return the head of the orifice. | Below is the the instruction that describes the task:
### Input:
Return the head of the orifice.
### Response:
def head_orifice(Diam, RatioVCOrifice, FlowRate):
"""Return the head of the orifice."""
#Checking input validity
ut.check_range([Diam, ">0", "Diameter"], [FlowRate, ">0", "Flow rate"],
... |
def offset(self, heading_initial, distance, ellipse = 'WGS84'):
'''
Offset a LatLon object by a heading (in degrees) and distance (in km)
to return a new LatLon object
'''
lat1, lon1 = self.lat.decimal_degree, self.lon.decimal_degree
g = pyproj.Geod(ellps = ellipse)
... | Offset a LatLon object by a heading (in degrees) and distance (in km)
to return a new LatLon object | Below is the the instruction that describes the task:
### Input:
Offset a LatLon object by a heading (in degrees) and distance (in km)
to return a new LatLon object
### Response:
def offset(self, heading_initial, distance, ellipse = 'WGS84'):
'''
Offset a LatLon object by a heading (in degr... |
def generate_all_deps(self, target: Target):
"""Generate all dependencies of `target` (the target nodes)."""
yield from (self.targets[dep_name]
for dep_name in self.generate_dep_names(target)) | Generate all dependencies of `target` (the target nodes). | Below is the the instruction that describes the task:
### Input:
Generate all dependencies of `target` (the target nodes).
### Response:
def generate_all_deps(self, target: Target):
"""Generate all dependencies of `target` (the target nodes)."""
yield from (self.targets[dep_name]
... |
def find_ent_endurance_tier_price(package, tier_level):
"""Find the price in the given package with the specified tier level
:param package: The Enterprise (Endurance) product package
:param tier_level: The endurance tier for which a price is desired
:return: Returns the price for the given tier, or an... | Find the price in the given package with the specified tier level
:param package: The Enterprise (Endurance) product package
:param tier_level: The endurance tier for which a price is desired
:return: Returns the price for the given tier, or an error if not found | Below is the the instruction that describes the task:
### Input:
Find the price in the given package with the specified tier level
:param package: The Enterprise (Endurance) product package
:param tier_level: The endurance tier for which a price is desired
:return: Returns the price for the given tier,... |
def is_parent_of(self, parent, child):
"""Return whether ``child`` is a branch descended from ``parent`` at
any remove.
"""
if parent == 'trunk':
return True
if child == 'trunk':
return False
if child not in self._branches:
raise Value... | Return whether ``child`` is a branch descended from ``parent`` at
any remove. | Below is the the instruction that describes the task:
### Input:
Return whether ``child`` is a branch descended from ``parent`` at
any remove.
### Response:
def is_parent_of(self, parent, child):
"""Return whether ``child`` is a branch descended from ``parent`` at
any remove.
"""
... |
def getOverlayMouseScale(self, ulOverlayHandle):
"""
Gets the mouse scaling factor that is used for mouse events. The actual texture may be a different size, but this is
typically the size of the underlying UI in pixels.
"""
fn = self.function_table.getOverlayMouseScale
... | Gets the mouse scaling factor that is used for mouse events. The actual texture may be a different size, but this is
typically the size of the underlying UI in pixels. | Below is the the instruction that describes the task:
### Input:
Gets the mouse scaling factor that is used for mouse events. The actual texture may be a different size, but this is
typically the size of the underlying UI in pixels.
### Response:
def getOverlayMouseScale(self, ulOverlayHandle):
"""... |
def _getPayload(self, record):
"""
The data that will be sent to the RESTful API
"""
try:
# top level payload items
d = record.__dict__
pid = d.pop('process', 'nopid')
tid = d.pop('thread', 'notid')
payload = {
... | The data that will be sent to the RESTful API | Below is the the instruction that describes the task:
### Input:
The data that will be sent to the RESTful API
### Response:
def _getPayload(self, record):
"""
The data that will be sent to the RESTful API
"""
try:
# top level payload items
d = record.__dict... |
def searchResults(self, REQUEST=None, used=None, **kw):
"""Search the catalog
Search terms can be passed in the REQUEST or as keyword
arguments.
The used argument is now deprecated and ignored
"""
if REQUEST and REQUEST.get('getRequestUID') \
and self.id == CATALOG_ANALYSIS_LISTING... | Search the catalog
Search terms can be passed in the REQUEST or as keyword
arguments.
The used argument is now deprecated and ignored | Below is the the instruction that describes the task:
### Input:
Search the catalog
Search terms can be passed in the REQUEST or as keyword
arguments.
The used argument is now deprecated and ignored
### Response:
def searchResults(self, REQUEST=None, used=None, **kw):
"""Search the catalog
S... |
def chunk_list(l, n):
"""Return `n` size lists from a given list `l`"""
return [l[i:i + n] for i in range(0, len(l), n)] | Return `n` size lists from a given list `l` | Below is the the instruction that describes the task:
### Input:
Return `n` size lists from a given list `l`
### Response:
def chunk_list(l, n):
"""Return `n` size lists from a given list `l`"""
return [l[i:i + n] for i in range(0, len(l), n)] |
def push(self):
""" create a github repo and push the local repo into it
"""
self.github_repo.create_and_push()
self._repo = self.github_repo.repo
return self._repo | create a github repo and push the local repo into it | Below is the the instruction that describes the task:
### Input:
create a github repo and push the local repo into it
### Response:
def push(self):
""" create a github repo and push the local repo into it
"""
self.github_repo.create_and_push()
self._repo = self.github_repo.repo
... |
def add_section(self, section_name):
"""Add an empty section.
"""
if section_name == "DEFAULT":
raise Exception("'DEFAULT' is reserved section name.")
if section_name in self._sections:
raise Exception(
"Error! %s is already one of the sections" %... | Add an empty section. | Below is the the instruction that describes the task:
### Input:
Add an empty section.
### Response:
def add_section(self, section_name):
"""Add an empty section.
"""
if section_name == "DEFAULT":
raise Exception("'DEFAULT' is reserved section name.")
if section_name in... |
def get_season(self, season_key, card_type="micro_card"):
"""
Calling Season API.
Arg:
season_key: key of the season
card_type: optional, default to micro_card. Accepted values are
micro_card & summary_card
Return:
json data
"""
... | Calling Season API.
Arg:
season_key: key of the season
card_type: optional, default to micro_card. Accepted values are
micro_card & summary_card
Return:
json data | Below is the the instruction that describes the task:
### Input:
Calling Season API.
Arg:
season_key: key of the season
card_type: optional, default to micro_card. Accepted values are
micro_card & summary_card
Return:
json data
### Response:
def get_se... |
def add_request_init_listener(self, fn, *args, **kwargs):
"""
Adds a callback with arguments to be called when any request is created.
It will be invoked as `fn(response_future, *args, **kwargs)` after each client request is created,
and before the request is sent\*. This can be used to... | Adds a callback with arguments to be called when any request is created.
It will be invoked as `fn(response_future, *args, **kwargs)` after each client request is created,
and before the request is sent\*. This can be used to create extensions by adding result callbacks to the
response future.
... | Below is the the instruction that describes the task:
### Input:
Adds a callback with arguments to be called when any request is created.
It will be invoked as `fn(response_future, *args, **kwargs)` after each client request is created,
and before the request is sent\*. This can be used to create e... |
def complete_multipart_upload(self, bucket, object_name, upload_id,
parts_list, content_type=None, metadata={}):
"""
Complete a multipart upload.
N.B. This can be possibly be a slow operation.
@param bucket: The bucket name
@param object_name: ... | Complete a multipart upload.
N.B. This can be possibly be a slow operation.
@param bucket: The bucket name
@param object_name: The object name
@param upload_id: The multipart upload id
@param parts_list: A List of all the parts
(2-tuples of part sequence number and ... | Below is the the instruction that describes the task:
### Input:
Complete a multipart upload.
N.B. This can be possibly be a slow operation.
@param bucket: The bucket name
@param object_name: The object name
@param upload_id: The multipart upload id
@param parts_list: A Lis... |
def filter_traceback(error, tb, ignore_pkg=CURRENT_PACKAGE):
"""Filtered out all parent stacktraces starting with the given stacktrace that has
a given variable name in its globals.
"""
if not isinstance(tb, types.TracebackType):
return tb
def in_namespace(n):
return n and (n.starts... | Filtered out all parent stacktraces starting with the given stacktrace that has
a given variable name in its globals. | Below is the the instruction that describes the task:
### Input:
Filtered out all parent stacktraces starting with the given stacktrace that has
a given variable name in its globals.
### Response:
def filter_traceback(error, tb, ignore_pkg=CURRENT_PACKAGE):
"""Filtered out all parent stacktraces starting w... |
def fcoe_get_login_output_fcoe_login_list_fcoe_login_connected_peer_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcoe_get_login = ET.Element("fcoe_get_login")
config = fcoe_get_login
output = ET.SubElement(fcoe_get_login, "output")
... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def fcoe_get_login_output_fcoe_login_list_fcoe_login_connected_peer_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcoe_get_login = ET.Element("fcoe_get... |
def load_at2_file(cls, filename):
"""Read an AT2 formatted time series.
Parameters
----------
filename: str
Filename to open.
"""
with open(filename) as fp:
next(fp)
description = next(fp).strip()
next(fp)
part... | Read an AT2 formatted time series.
Parameters
----------
filename: str
Filename to open. | Below is the the instruction that describes the task:
### Input:
Read an AT2 formatted time series.
Parameters
----------
filename: str
Filename to open.
### Response:
def load_at2_file(cls, filename):
"""Read an AT2 formatted time series.
Parameters
--... |
def save(self, filename, encoding ='ISO-8859-1', standalone='no'):
"""
Stores any element in a svg file (including header).
Calling this method only makes sense if the root element is an svg elemnt
"""
f = codecs.open(filename, 'w', encoding)
s = self.wrap_xml(self.getXM... | Stores any element in a svg file (including header).
Calling this method only makes sense if the root element is an svg elemnt | Below is the the instruction that describes the task:
### Input:
Stores any element in a svg file (including header).
Calling this method only makes sense if the root element is an svg elemnt
### Response:
def save(self, filename, encoding ='ISO-8859-1', standalone='no'):
"""
Stores any el... |
def _search_env(keys):
"""
Search the environment for the supplied keys, returning the first
one found or None if none was found.
"""
matches = (os.environ[key] for key in keys if key in os.environ)
return next(matches, None) | Search the environment for the supplied keys, returning the first
one found or None if none was found. | Below is the the instruction that describes the task:
### Input:
Search the environment for the supplied keys, returning the first
one found or None if none was found.
### Response:
def _search_env(keys):
"""
Search the environment for the supplied keys, returning the first
one found or None if none was fo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.