code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def show_toast(self, msg, long=True):
""" Show a toast message for the given duration.
This is an android specific api.
Parameters
-----------
msg: str
Text to display in the toast message
long: bool
Display for a long or short (system defined) du... | Show a toast message for the given duration.
This is an android specific api.
Parameters
-----------
msg: str
Text to display in the toast message
long: bool
Display for a long or short (system defined) duration | Below is the the instruction that describes the task:
### Input:
Show a toast message for the given duration.
This is an android specific api.
Parameters
-----------
msg: str
Text to display in the toast message
long: bool
Display for a long or short ... |
def set_fallback(self, target):
"""Sets a fallback configuration for section.
Re-exec uWSGI with the specified config when exit code is 1.
:param str|unicode|Section target: File path or Section to include.
"""
if isinstance(target, Section):
target = ':' + target.n... | Sets a fallback configuration for section.
Re-exec uWSGI with the specified config when exit code is 1.
:param str|unicode|Section target: File path or Section to include. | Below is the the instruction that describes the task:
### Input:
Sets a fallback configuration for section.
Re-exec uWSGI with the specified config when exit code is 1.
:param str|unicode|Section target: File path or Section to include.
### Response:
def set_fallback(self, target):
"""Set... |
def _init_all_stages(self, config):
'''Create stages that are used for the pipeline.
:param dict config: `streamcorpus_pipeline` configuration
:return: tuple of (reader, incremental transforms, batch
transforms, post-batch incremental transforms, writers,
temporary directory... | Create stages that are used for the pipeline.
:param dict config: `streamcorpus_pipeline` configuration
:return: tuple of (reader, incremental transforms, batch
transforms, post-batch incremental transforms, writers,
temporary directory) | Below is the the instruction that describes the task:
### Input:
Create stages that are used for the pipeline.
:param dict config: `streamcorpus_pipeline` configuration
:return: tuple of (reader, incremental transforms, batch
transforms, post-batch incremental transforms, writers,
... |
def absolute_magnitude(self, richness=1, steps=1e4):
"""
Calculate the absolute visual magnitude (Mv) from the richness
by transforming the isochrone in the SDSS system and using the
g,r -> V transform equations from Jester 2005
[astro-ph/0506022].
Parameters:
-... | Calculate the absolute visual magnitude (Mv) from the richness
by transforming the isochrone in the SDSS system and using the
g,r -> V transform equations from Jester 2005
[astro-ph/0506022].
Parameters:
-----------
richness : isochrone normalization parameter
s... | Below is the the instruction that describes the task:
### Input:
Calculate the absolute visual magnitude (Mv) from the richness
by transforming the isochrone in the SDSS system and using the
g,r -> V transform equations from Jester 2005
[astro-ph/0506022].
Parameters:
-----... |
def write_const_tpl(name, tpl_file, suffix, zn_array=None, shape=None, spatial_reference=None,
longnames=False):
""" write a constant (uniform) template file
Parameters
----------
name : str
the base parameter name
tpl_file : str
the template file to write - incl... | write a constant (uniform) template file
Parameters
----------
name : str
the base parameter name
tpl_file : str
the template file to write - include path
zn_array : numpy.ndarray
an array used to skip inactive cells
Returns
-------
df : pandas.DataFrame
... | Below is the the instruction that describes the task:
### Input:
write a constant (uniform) template file
Parameters
----------
name : str
the base parameter name
tpl_file : str
the template file to write - include path
zn_array : numpy.ndarray
an array used to skip inac... |
def _calculate_column_widths(self):
"""Calculate width of column automatically based on data."""
table_width = self.get_table_width()
lpw, rpw = self._left_padding_widths, self._right_padding_widths
pad_widths = [(lpw[i] + rpw[i]) for i in range(self._column_count)]
max_widths = ... | Calculate width of column automatically based on data. | Below is the the instruction that describes the task:
### Input:
Calculate width of column automatically based on data.
### Response:
def _calculate_column_widths(self):
"""Calculate width of column automatically based on data."""
table_width = self.get_table_width()
lpw, rpw = self._left_p... |
def fill_gaps(list_dicts):
"""
Fill gaps in a list of dictionaries. Add empty keys to dictionaries in
the list that don't contain other entries' keys
:param list_dicts: A list of dictionaries
:return: A list of field names, a list of dictionaries with identical keys
"""
field_name... | Fill gaps in a list of dictionaries. Add empty keys to dictionaries in
the list that don't contain other entries' keys
:param list_dicts: A list of dictionaries
:return: A list of field names, a list of dictionaries with identical keys | Below is the the instruction that describes the task:
### Input:
Fill gaps in a list of dictionaries. Add empty keys to dictionaries in
the list that don't contain other entries' keys
:param list_dicts: A list of dictionaries
:return: A list of field names, a list of dictionaries with identical key... |
def set_field(self, field_name, data):
"""Set property into the Dataset.
Parameters
----------
field_name : string
The field name of the information.
data : list, numpy 1-D array, pandas Series or None
The array of data to be set.
Returns
... | Set property into the Dataset.
Parameters
----------
field_name : string
The field name of the information.
data : list, numpy 1-D array, pandas Series or None
The array of data to be set.
Returns
-------
self : Dataset
Datase... | Below is the the instruction that describes the task:
### Input:
Set property into the Dataset.
Parameters
----------
field_name : string
The field name of the information.
data : list, numpy 1-D array, pandas Series or None
The array of data to be set.
... |
def _schemaPrepareInsert(self, store):
"""
Prepare each attribute in my schema for insertion into a given store,
either by upgrade or by creation. This makes sure all references point
to this store and all relative paths point to this store's files
directory.
"""
... | Prepare each attribute in my schema for insertion into a given store,
either by upgrade or by creation. This makes sure all references point
to this store and all relative paths point to this store's files
directory. | Below is the the instruction that describes the task:
### Input:
Prepare each attribute in my schema for insertion into a given store,
either by upgrade or by creation. This makes sure all references point
to this store and all relative paths point to this store's files
directory.
### Respo... |
def AddFilesWithUnknownHashes(
client_path_blob_refs,
use_external_stores = True
):
"""Adds new files consisting of given blob references.
Args:
client_path_blob_refs: A dictionary mapping `db.ClientPath` instances to
lists of blob references.
use_external_stores: A flag indicating if the fil... | Adds new files consisting of given blob references.
Args:
client_path_blob_refs: A dictionary mapping `db.ClientPath` instances to
lists of blob references.
use_external_stores: A flag indicating if the files should also be added to
external file stores.
Returns:
A dictionary mapping `db.C... | Below is the the instruction that describes the task:
### Input:
Adds new files consisting of given blob references.
Args:
client_path_blob_refs: A dictionary mapping `db.ClientPath` instances to
lists of blob references.
use_external_stores: A flag indicating if the files should also be added to
... |
def setup_psd_pregenerated(workflow, tags=None):
'''
Setup CBC workflow to use pregenerated psd files.
The file given in cp.get('workflow','pregenerated-psd-file-(ifo)') will
be used as the --psd-file argument to geom_nonspinbank, geom_aligned_bank
and pycbc_plot_psd_file.
Parameters
------... | Setup CBC workflow to use pregenerated psd files.
The file given in cp.get('workflow','pregenerated-psd-file-(ifo)') will
be used as the --psd-file argument to geom_nonspinbank, geom_aligned_bank
and pycbc_plot_psd_file.
Parameters
----------
workflow: pycbc.workflow.core.Workflow
An in... | Below is the the instruction that describes the task:
### Input:
Setup CBC workflow to use pregenerated psd files.
The file given in cp.get('workflow','pregenerated-psd-file-(ifo)') will
be used as the --psd-file argument to geom_nonspinbank, geom_aligned_bank
and pycbc_plot_psd_file.
Parameters
... |
def list_databases(self, like=None):
"""
List databases in the Clickhouse cluster.
Like the SHOW DATABASES command in the clickhouse-shell.
Parameters
----------
like : string, default None
e.g. 'foo*' to match all tables starting with 'foo'
Returns
... | List databases in the Clickhouse cluster.
Like the SHOW DATABASES command in the clickhouse-shell.
Parameters
----------
like : string, default None
e.g. 'foo*' to match all tables starting with 'foo'
Returns
-------
databases : list of strings | Below is the the instruction that describes the task:
### Input:
List databases in the Clickhouse cluster.
Like the SHOW DATABASES command in the clickhouse-shell.
Parameters
----------
like : string, default None
e.g. 'foo*' to match all tables starting with 'foo'
... |
def put(self, job, result):
"Perform a job by a member in the pool and return the result."
self.job.put(job)
r = result.get()
return r | Perform a job by a member in the pool and return the result. | Below is the the instruction that describes the task:
### Input:
Perform a job by a member in the pool and return the result.
### Response:
def put(self, job, result):
"Perform a job by a member in the pool and return the result."
self.job.put(job)
r = result.get()
return r |
def create():
"""Create a new post for the current user."""
if request.method == "POST":
title = request.form["title"]
body = request.form["body"]
error = None
if not title:
error = "Title is required."
if error is not None:
flash(error)
... | Create a new post for the current user. | Below is the the instruction that describes the task:
### Input:
Create a new post for the current user.
### Response:
def create():
"""Create a new post for the current user."""
if request.method == "POST":
title = request.form["title"]
body = request.form["body"]
error = None
... |
def pop_context(self):
"""Pops the last set of keyword arguments provided to the processor."""
processor = getattr(self, 'processor', None)
if processor is not None:
pop_context = getattr(processor, 'pop_context', None)
if pop_context is None:
pop_context ... | Pops the last set of keyword arguments provided to the processor. | Below is the the instruction that describes the task:
### Input:
Pops the last set of keyword arguments provided to the processor.
### Response:
def pop_context(self):
"""Pops the last set of keyword arguments provided to the processor."""
processor = getattr(self, 'processor', None)
if pro... |
def guess_content_type_and_encoding(path):
"""Guess the content type of a path, using ``mimetypes``.
Falls back to "application/binary" if no content type is found.
Args:
path (str): the path to guess the mimetype of
Returns:
str: the content type of the file
"""
for ext, con... | Guess the content type of a path, using ``mimetypes``.
Falls back to "application/binary" if no content type is found.
Args:
path (str): the path to guess the mimetype of
Returns:
str: the content type of the file | Below is the the instruction that describes the task:
### Input:
Guess the content type of a path, using ``mimetypes``.
Falls back to "application/binary" if no content type is found.
Args:
path (str): the path to guess the mimetype of
Returns:
str: the content type of the file
### Re... |
def load_variable(self, var=None, start_date=None, end_date=None,
time_offset=None, grid_attrs=None, **DataAttrs):
"""Load a DataArray for requested variable and time range.
Automatically renames all grid attributes to match aospy conventions.
Parameters
---------... | Load a DataArray for requested variable and time range.
Automatically renames all grid attributes to match aospy conventions.
Parameters
----------
var : Var
aospy Var object
start_date : datetime.datetime
start date for interval
end_date : datet... | Below is the the instruction that describes the task:
### Input:
Load a DataArray for requested variable and time range.
Automatically renames all grid attributes to match aospy conventions.
Parameters
----------
var : Var
aospy Var object
start_date : datetime.... |
def breakfast(self, message="Breakfast is ready", shout: bool = False):
"""Say something in the morning"""
return self.helper.output(message, shout) | Say something in the morning | Below is the the instruction that describes the task:
### Input:
Say something in the morning
### Response:
def breakfast(self, message="Breakfast is ready", shout: bool = False):
"""Say something in the morning"""
return self.helper.output(message, shout) |
def _index_range(self, version, symbol, date_range=None, **kwargs):
""" Given a version, read the segment_index and return the chunks associated
with the date_range. As the segment index is (id -> last datetime)
we need to take care in choosing the correct chunks. """
if date_range and '... | Given a version, read the segment_index and return the chunks associated
with the date_range. As the segment index is (id -> last datetime)
we need to take care in choosing the correct chunks. | Below is the the instruction that describes the task:
### Input:
Given a version, read the segment_index and return the chunks associated
with the date_range. As the segment index is (id -> last datetime)
we need to take care in choosing the correct chunks.
### Response:
def _index_range(self, vers... |
def render_template(self, plain, rich = None, **context):
'''Render the body of the message from a template. The plain
body will be rendered from a template named ``plain`` or
``plain + '.txt'`` (in that order of preference). The rich
body will be rendered from ``rich`` if given, or el... | Render the body of the message from a template. The plain
body will be rendered from a template named ``plain`` or
``plain + '.txt'`` (in that order of preference). The rich
body will be rendered from ``rich`` if given, or else from
``plain + '.html'``. If neither exists, then the mes... | Below is the the instruction that describes the task:
### Input:
Render the body of the message from a template. The plain
body will be rendered from a template named ``plain`` or
``plain + '.txt'`` (in that order of preference). The rich
body will be rendered from ``rich`` if given, or el... |
def stop(self, key):
"""
Stop a concurrent operation.
This gets the concurrency limiter for the given key (creating it if
necessary) and stops a concurrent operation on it. If the concurrency
limiter is empty, it is deleted.
"""
self._get_limiter(key).stop()
... | Stop a concurrent operation.
This gets the concurrency limiter for the given key (creating it if
necessary) and stops a concurrent operation on it. If the concurrency
limiter is empty, it is deleted. | Below is the the instruction that describes the task:
### Input:
Stop a concurrent operation.
This gets the concurrency limiter for the given key (creating it if
necessary) and stops a concurrent operation on it. If the concurrency
limiter is empty, it is deleted.
### Response:
def stop(se... |
def setname(self, dim_name):
"""Set the dimension name.
Args::
dim_name dimension name; setting 2 dimensions to the same
name make the dimensions "shared"; in order to be
shared, the dimesions must be deined similarly.
Returns::
... | Set the dimension name.
Args::
dim_name dimension name; setting 2 dimensions to the same
name make the dimensions "shared"; in order to be
shared, the dimesions must be deined similarly.
Returns::
None
C library equivalent :... | Below is the the instruction that describes the task:
### Input:
Set the dimension name.
Args::
dim_name dimension name; setting 2 dimensions to the same
name make the dimensions "shared"; in order to be
shared, the dimesions must be deined similarl... |
def pack_ihex(type_, address, size, data):
"""Create a Intel HEX record of given data.
"""
line = '{:02X}{:04X}{:02X}'.format(size, address, type_)
if data:
line += binascii.hexlify(data).decode('ascii').upper()
return ':{}{:02X}'.format(line, crc_ihex(line)) | Create a Intel HEX record of given data. | Below is the the instruction that describes the task:
### Input:
Create a Intel HEX record of given data.
### Response:
def pack_ihex(type_, address, size, data):
"""Create a Intel HEX record of given data.
"""
line = '{:02X}{:04X}{:02X}'.format(size, address, type_)
if data:
line += bin... |
def get_model(self, opt_fn, emb_sz, n_hid, n_layers, **kwargs):
""" Method returns a RNN_Learner object, that wraps an instance of the RNN_Encoder module.
Args:
opt_fn (Optimizer): the torch optimizer function to use
emb_sz (int): embedding size
n_hid (int): number o... | Method returns a RNN_Learner object, that wraps an instance of the RNN_Encoder module.
Args:
opt_fn (Optimizer): the torch optimizer function to use
emb_sz (int): embedding size
n_hid (int): number of hidden inputs
n_layers (int): number of hidden layers
... | Below is the the instruction that describes the task:
### Input:
Method returns a RNN_Learner object, that wraps an instance of the RNN_Encoder module.
Args:
opt_fn (Optimizer): the torch optimizer function to use
emb_sz (int): embedding size
n_hid (int): number of hidde... |
def tokens(self, si, k):
'''`si` is a stream item and `k` is a key in this feature. The purpose
of this method is to dereference the token pointers with
respect to the given stream item. That is, it translates each
sequence of token pointers to a sequence of `Token`.
'''
... | `si` is a stream item and `k` is a key in this feature. The purpose
of this method is to dereference the token pointers with
respect to the given stream item. That is, it translates each
sequence of token pointers to a sequence of `Token`. | Below is the the instruction that describes the task:
### Input:
`si` is a stream item and `k` is a key in this feature. The purpose
of this method is to dereference the token pointers with
respect to the given stream item. That is, it translates each
sequence of token pointers to a sequence... |
def _parse_plt_segment(self, fptr):
"""Parse the PLT segment.
The packet headers are not parsed, i.e. they remain uninterpreted raw
data buffers.
Parameters
----------
fptr : file
Open file object.
Returns
-------
PLTSegment
... | Parse the PLT segment.
The packet headers are not parsed, i.e. they remain uninterpreted raw
data buffers.
Parameters
----------
fptr : file
Open file object.
Returns
-------
PLTSegment
The current PLT segment. | Below is the the instruction that describes the task:
### Input:
Parse the PLT segment.
The packet headers are not parsed, i.e. they remain uninterpreted raw
data buffers.
Parameters
----------
fptr : file
Open file object.
Returns
-------
... |
def in_download_archive(track):
"""
Returns True if a track_id exists in the download archive
"""
global arguments
if not arguments['--download-archive']:
return
archive_filename = arguments.get('--download-archive')
try:
with open(archive_filename, 'a+', encoding='utf-8') a... | Returns True if a track_id exists in the download archive | Below is the the instruction that describes the task:
### Input:
Returns True if a track_id exists in the download archive
### Response:
def in_download_archive(track):
"""
Returns True if a track_id exists in the download archive
"""
global arguments
if not arguments['--download-archive']:
... |
def CountHuntLogEntries(self, hunt_id, cursor=None):
"""Returns number of hunt log entries of a given hunt."""
hunt_id_int = db_utils.HuntIDToInt(hunt_id)
query = ("SELECT COUNT(*) FROM flow_log_entries "
"FORCE INDEX(flow_log_entries_by_hunt) "
"WHERE hunt_id = %s AND flow_id = h... | Returns number of hunt log entries of a given hunt. | Below is the the instruction that describes the task:
### Input:
Returns number of hunt log entries of a given hunt.
### Response:
def CountHuntLogEntries(self, hunt_id, cursor=None):
"""Returns number of hunt log entries of a given hunt."""
hunt_id_int = db_utils.HuntIDToInt(hunt_id)
query = ("SELECT... |
def plot_ebands(self, **kwargs):
"""
Plot the band structure. kwargs are passed to the plot method of :class:`ElectronBands`.
Returns:
`matplotlib` figure
"""
with self.nscf_task.open_gsr() as gsr:
return gsr.ebands.plot(**kwargs) | Plot the band structure. kwargs are passed to the plot method of :class:`ElectronBands`.
Returns:
`matplotlib` figure | Below is the the instruction that describes the task:
### Input:
Plot the band structure. kwargs are passed to the plot method of :class:`ElectronBands`.
Returns:
`matplotlib` figure
### Response:
def plot_ebands(self, **kwargs):
"""
Plot the band structure. kwargs are passed t... |
def enable_node(self, service_name, node_name):
"""
Enables a given node name for the given service name via the
"enable server" HAProxy command.
"""
logger.info("Enabling server %s/%s", service_name, node_name)
return self.send_command(
"enable server %s/%s" ... | Enables a given node name for the given service name via the
"enable server" HAProxy command. | Below is the the instruction that describes the task:
### Input:
Enables a given node name for the given service name via the
"enable server" HAProxy command.
### Response:
def enable_node(self, service_name, node_name):
"""
Enables a given node name for the given service name via the
... |
def linkage(self):
"""Return the linkage of this cursor."""
if not hasattr(self, '_linkage'):
self._linkage = conf.lib.clang_getCursorLinkage(self)
return LinkageKind.from_id(self._linkage) | Return the linkage of this cursor. | Below is the the instruction that describes the task:
### Input:
Return the linkage of this cursor.
### Response:
def linkage(self):
"""Return the linkage of this cursor."""
if not hasattr(self, '_linkage'):
self._linkage = conf.lib.clang_getCursorLinkage(self)
return LinkageKi... |
def context(self, line):
"""
Return the context for a given 1-offset line number.
"""
# XXX due to a limitation in Visitor,
# non-python code after the last python code
# in a file is not added to self.lines, so we
# have to guard against IndexErrors.
idx ... | Return the context for a given 1-offset line number. | Below is the the instruction that describes the task:
### Input:
Return the context for a given 1-offset line number.
### Response:
def context(self, line):
"""
Return the context for a given 1-offset line number.
"""
# XXX due to a limitation in Visitor,
# non-python code a... |
def max_size(self):
"""
Gets the largest size of the object over all timesteps.
Returns:
Maximum size of the object in pixels
"""
sizes = np.array([m.sum() for m in self.masks])
return sizes.max() | Gets the largest size of the object over all timesteps.
Returns:
Maximum size of the object in pixels | Below is the the instruction that describes the task:
### Input:
Gets the largest size of the object over all timesteps.
Returns:
Maximum size of the object in pixels
### Response:
def max_size(self):
"""
Gets the largest size of the object over all timesteps.
... |
def ip_to_geojson(ipaddress, name="Point"):
"""Generate GeoJSON for given IP address"""
geo = ip_to_geo(ipaddress)
point = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"name": name
... | Generate GeoJSON for given IP address | Below is the the instruction that describes the task:
### Input:
Generate GeoJSON for given IP address
### Response:
def ip_to_geojson(ipaddress, name="Point"):
"""Generate GeoJSON for given IP address"""
geo = ip_to_geo(ipaddress)
point = {
"type": "FeatureCollection",
"features": [
... |
def match(self, table, nomatch=0):
"""
Make a vector of the positions of (first) matches of its first argument in its second.
Only applicable to single-column categorical/string frames.
:param List table: the list of items to match against
:param int nomatch: value that should ... | Make a vector of the positions of (first) matches of its first argument in its second.
Only applicable to single-column categorical/string frames.
:param List table: the list of items to match against
:param int nomatch: value that should be returned when there is no match.
:returns: a... | Below is the the instruction that describes the task:
### Input:
Make a vector of the positions of (first) matches of its first argument in its second.
Only applicable to single-column categorical/string frames.
:param List table: the list of items to match against
:param int nomatch: valu... |
def copy(self):
"""Make a copy of this instance.
Copies the local data stored as simple types and copies the client
attached to this instance.
:rtype: :class:`~google.cloud.spanner_v1.instance.Instance`
:returns: A copy of the current instance.
"""
new_client = ... | Make a copy of this instance.
Copies the local data stored as simple types and copies the client
attached to this instance.
:rtype: :class:`~google.cloud.spanner_v1.instance.Instance`
:returns: A copy of the current instance. | Below is the the instruction that describes the task:
### Input:
Make a copy of this instance.
Copies the local data stored as simple types and copies the client
attached to this instance.
:rtype: :class:`~google.cloud.spanner_v1.instance.Instance`
:returns: A copy of the current i... |
def readQuotes(self, start, end):
''' read quotes from Yahoo Financial'''
if self.symbol is None:
LOG.debug('Symbol is None')
return []
return self.__yf.getQuotes(self.symbol, start, end) | read quotes from Yahoo Financial | Below is the the instruction that describes the task:
### Input:
read quotes from Yahoo Financial
### Response:
def readQuotes(self, start, end):
''' read quotes from Yahoo Financial'''
if self.symbol is None:
LOG.debug('Symbol is None')
return []
return self.... |
def send_reset_password_instructions(self, user):
"""
Sends the reset password instructions email for the specified user.
Sends signal `reset_password_instructions_sent`.
:param user: The user to send the instructions to.
"""
token = self.security_utils_service.generate... | Sends the reset password instructions email for the specified user.
Sends signal `reset_password_instructions_sent`.
:param user: The user to send the instructions to. | Below is the the instruction that describes the task:
### Input:
Sends the reset password instructions email for the specified user.
Sends signal `reset_password_instructions_sent`.
:param user: The user to send the instructions to.
### Response:
def send_reset_password_instructions(self, user):
... |
def as_xml(self, parent = None):
"""Make an XML element from self.
:Parameters:
- `parent`: Parent element
:Types:
- `parent`: :etree:`ElementTree.Element`
"""
if parent is not None:
element = ElementTree.SubElement(parent, ITEM_TAG)
e... | Make an XML element from self.
:Parameters:
- `parent`: Parent element
:Types:
- `parent`: :etree:`ElementTree.Element` | Below is the the instruction that describes the task:
### Input:
Make an XML element from self.
:Parameters:
- `parent`: Parent element
:Types:
- `parent`: :etree:`ElementTree.Element`
### Response:
def as_xml(self, parent = None):
"""Make an XML element from self.
... |
def compose(*fs):
"""
Compose functions together in order:
compose(f, g, h) = lambda n: f(g(h(n)))
"""
# Pull the iterator out into a tuple so we can call `composed`
# more than once.
rs = tuple(reversed(fs))
def composed(n):
return reduce(lambda a, b: b(a), rs, n)
# Attem... | Compose functions together in order:
compose(f, g, h) = lambda n: f(g(h(n))) | Below is the the instruction that describes the task:
### Input:
Compose functions together in order:
compose(f, g, h) = lambda n: f(g(h(n)))
### Response:
def compose(*fs):
"""
Compose functions together in order:
compose(f, g, h) = lambda n: f(g(h(n)))
"""
# Pull the iterator out into a... |
def search_manager_from_config(config, **default_init):
"""Get a `SearchManager` instance dynamically based on config.
`config` is a dictionary containing ``class`` and ``init`` keys as defined
in :mod:`birding.config`.
"""
manager_cls = import_name(config['class'], default_ns='birding.search')
... | Get a `SearchManager` instance dynamically based on config.
`config` is a dictionary containing ``class`` and ``init`` keys as defined
in :mod:`birding.config`. | Below is the the instruction that describes the task:
### Input:
Get a `SearchManager` instance dynamically based on config.
`config` is a dictionary containing ``class`` and ``init`` keys as defined
in :mod:`birding.config`.
### Response:
def search_manager_from_config(config, **default_init):
"""Get... |
def _replace_with_specific_page(page, menu_item):
"""
If ``page`` is a vanilla ``Page` object, replace it with a 'specific'
version of itself. Also update ``menu_item``, depending on whether it's
a ``MenuItem`` object or a ``Page`` object.
"""
if type(page) is Page:
... | If ``page`` is a vanilla ``Page` object, replace it with a 'specific'
version of itself. Also update ``menu_item``, depending on whether it's
a ``MenuItem`` object or a ``Page`` object. | Below is the the instruction that describes the task:
### Input:
If ``page`` is a vanilla ``Page` object, replace it with a 'specific'
version of itself. Also update ``menu_item``, depending on whether it's
a ``MenuItem`` object or a ``Page`` object.
### Response:
def _replace_with_specific_page(pa... |
def _key_question(self, text):
"""Action for '?'"""
if self.get_current_line_to_cursor():
last_obj = self.get_last_obj()
if last_obj and not last_obj.isdigit():
self.show_object_info(last_obj)
self.insert_text(text)
# In case calltip and com... | Action for '? | Below is the the instruction that describes the task:
### Input:
Action for '?
### Response:
def _key_question(self, text):
"""Action for '?'"""
if self.get_current_line_to_cursor():
last_obj = self.get_last_obj()
if last_obj and not last_obj.isdigit():
... |
def get_means_and_scales_from_q(self):
"""
Gets the mean and scales for normal approximating parameters
"""
means = np.zeros(len(self.q))
scale = np.zeros(len(self.q))
for i in range(len(self.q)):
means[i] = self.q[i].mu0
scale[i] = self.q[i].sigma... | Gets the mean and scales for normal approximating parameters | Below is the the instruction that describes the task:
### Input:
Gets the mean and scales for normal approximating parameters
### Response:
def get_means_and_scales_from_q(self):
"""
Gets the mean and scales for normal approximating parameters
"""
means = np.zeros(len(self.q))
... |
def wrapper(vertices_resources, vertices_applications,
nets, net_keys,
machine, constraints=[],
reserve_monitor=True, align_sdram=True,
place=default_place, place_kwargs={},
allocate=default_allocate, allocate_kwargs={},
route=default_route, route_... | Wrapper for core place-and-route tasks for the common case.
At a high level this function essentially takes a set of vertices and nets
and produces placements, memory allocations, routing tables and application
loading information.
.. warning::
This function is deprecated. New users should use... | Below is the the instruction that describes the task:
### Input:
Wrapper for core place-and-route tasks for the common case.
At a high level this function essentially takes a set of vertices and nets
and produces placements, memory allocations, routing tables and application
loading information.
..... |
def get_word_from_offset(self, offset):
"""Return the word value at the given file offset. (little endian)"""
if offset+2 > len(self.__data__):
return None
return self.get_word_from_data(self.__data__[offset:offset+2], 0) | Return the word value at the given file offset. (little endian) | Below is the the instruction that describes the task:
### Input:
Return the word value at the given file offset. (little endian)
### Response:
def get_word_from_offset(self, offset):
"""Return the word value at the given file offset. (little endian)"""
if offset+2 > len(self.__data__):
... |
def main(dbg=None, sys_argv=list(sys.argv)):
"""Routine which gets run if we were invoked directly"""
global __title__
# Save the original just for use in the restart that works via exec.
orig_sys_argv = list(sys_argv)
opts, dbg_opts, sys_argv = Moptions.process_options(__title__,
... | Routine which gets run if we were invoked directly | Below is the the instruction that describes the task:
### Input:
Routine which gets run if we were invoked directly
### Response:
def main(dbg=None, sys_argv=list(sys.argv)):
"""Routine which gets run if we were invoked directly"""
global __title__
# Save the original just for use in the restart that ... |
def parse(self, fn):
"""
Parses a file into a lxml.etree structure with namespaces remove. This tree is added to self.iocs.
:param fn: File to parse.
:return:
"""
ioc_xml = xmlutils.read_xml_no_ns(fn)
if not ioc_xml:
return False
root = ioc_x... | Parses a file into a lxml.etree structure with namespaces remove. This tree is added to self.iocs.
:param fn: File to parse.
:return: | Below is the the instruction that describes the task:
### Input:
Parses a file into a lxml.etree structure with namespaces remove. This tree is added to self.iocs.
:param fn: File to parse.
:return:
### Response:
def parse(self, fn):
"""
Parses a file into a lxml.etree structure w... |
def parallel_assimilate(self, rootpath):
"""
Assimilate the entire subdirectory structure in rootpath.
"""
logger.info('Scanning for valid paths...')
valid_paths = []
for (parent, subdirs, files) in os.walk(rootpath):
valid_paths.extend(self._drone.get_valid_p... | Assimilate the entire subdirectory structure in rootpath. | Below is the the instruction that describes the task:
### Input:
Assimilate the entire subdirectory structure in rootpath.
### Response:
def parallel_assimilate(self, rootpath):
"""
Assimilate the entire subdirectory structure in rootpath.
"""
logger.info('Scanning for valid paths..... |
def usaheatindex(temp, humidity, dew=None):
"""Calculate Heat Index as per USA National Weather Service Standards
See http://en.wikipedia.org/wiki/Heat_index, formula 1. The
formula is not valid for T < 26.7C, Dew Point < 12C, or RH < 40%
"""
if temp is None or humidity is None:
return Non... | Calculate Heat Index as per USA National Weather Service Standards
See http://en.wikipedia.org/wiki/Heat_index, formula 1. The
formula is not valid for T < 26.7C, Dew Point < 12C, or RH < 40% | Below is the the instruction that describes the task:
### Input:
Calculate Heat Index as per USA National Weather Service Standards
See http://en.wikipedia.org/wiki/Heat_index, formula 1. The
formula is not valid for T < 26.7C, Dew Point < 12C, or RH < 40%
### Response:
def usaheatindex(temp, humidity, de... |
def get_table(table, table_file, path=None, target=None, key=None, key_items=None,
filters=None, template_args=None):
'''
Retrieve data from a Junos device using Tables/Views
table (required)
Name of PyEZ Table
table_file (required)
YAML file that has the table specified ... | Retrieve data from a Junos device using Tables/Views
table (required)
Name of PyEZ Table
table_file (required)
YAML file that has the table specified in table parameter
path:
Path of location of the YAML file.
defaults to op directory in jnpr.junos.op
target:
... | Below is the the instruction that describes the task:
### Input:
Retrieve data from a Junos device using Tables/Views
table (required)
Name of PyEZ Table
table_file (required)
YAML file that has the table specified in table parameter
path:
Path of location of the YAML file.
... |
def cluster_resources(self):
"""Get the current total cluster resources.
Note that this information can grow stale as nodes are added to or
removed from the cluster.
Returns:
A dictionary mapping resource name to the total quantity of that
resource in the cl... | Get the current total cluster resources.
Note that this information can grow stale as nodes are added to or
removed from the cluster.
Returns:
A dictionary mapping resource name to the total quantity of that
resource in the cluster. | Below is the the instruction that describes the task:
### Input:
Get the current total cluster resources.
Note that this information can grow stale as nodes are added to or
removed from the cluster.
Returns:
A dictionary mapping resource name to the total quantity of that
... |
def rest_verbs(http_method_names=None):
"""
Decorator that converts a function-based view into an RestView subclass.
Takes a list of allowed methods for the view as an argument.
"""
http_method_names = ['GET'] if (http_method_names is None) else http_method_names
def decorator(func):
... | Decorator that converts a function-based view into an RestView subclass.
Takes a list of allowed methods for the view as an argument. | Below is the the instruction that describes the task:
### Input:
Decorator that converts a function-based view into an RestView subclass.
Takes a list of allowed methods for the view as an argument.
### Response:
def rest_verbs(http_method_names=None):
"""
Decorator that converts a function-based view... |
def plot(self, sig_style='', title=None, figsize=None,
return_fig=False):
"""
Plot the comparison of two sets of annotations, possibly
overlaid on their original signal.
Parameters
----------
sig_style : str, optional
The matplotlib style of the ... | Plot the comparison of two sets of annotations, possibly
overlaid on their original signal.
Parameters
----------
sig_style : str, optional
The matplotlib style of the signal
title : str, optional
The title of the plot
figsize: tuple, optional
... | Below is the the instruction that describes the task:
### Input:
Plot the comparison of two sets of annotations, possibly
overlaid on their original signal.
Parameters
----------
sig_style : str, optional
The matplotlib style of the signal
title : str, optional
... |
def alignment_to_partials(alignment, missing_data=None):
""" Generate a partials dictionary from a treeCl.Alignment """
partials_dict = {}
for (name, sequence) in alignment.get_sequences():
datatype = 'dna' if alignment.is_dna() else 'protein'
partials_dict[name] = seq_to_partials(sequence, ... | Generate a partials dictionary from a treeCl.Alignment | Below is the the instruction that describes the task:
### Input:
Generate a partials dictionary from a treeCl.Alignment
### Response:
def alignment_to_partials(alignment, missing_data=None):
""" Generate a partials dictionary from a treeCl.Alignment """
partials_dict = {}
for (name, sequence) in alignm... |
def wait(self=None, period=10, callback=None, *args, **kwargs):
"""Wait until task is complete
:param period: Time in seconds between reloads
:param callback: Function to call after the task has finished,
arguments and keyword arguments can be provided for it
:return: Return ... | Wait until task is complete
:param period: Time in seconds between reloads
:param callback: Function to call after the task has finished,
arguments and keyword arguments can be provided for it
:return: Return value of provided callback function or None if a
callback funct... | Below is the the instruction that describes the task:
### Input:
Wait until task is complete
:param period: Time in seconds between reloads
:param callback: Function to call after the task has finished,
arguments and keyword arguments can be provided for it
:return: Return value ... |
def writeInfo(self, stream):
""" Write information about diffs into a file stream for use later. """
for (fromUUID, size) in Diff.theKnownSizes[self.uuid].iteritems():
self.writeInfoLine(stream, fromUUID, size) | Write information about diffs into a file stream for use later. | Below is the the instruction that describes the task:
### Input:
Write information about diffs into a file stream for use later.
### Response:
def writeInfo(self, stream):
""" Write information about diffs into a file stream for use later. """
for (fromUUID, size) in Diff.theKnownSizes[self.uuid].i... |
def pop_back(self):
'''Remove the last element from the :class:`Sequence`.'''
backend = self.backend
return backend.execute(backend.structure(self).pop_back(),
self.value_pickler.loads) | Remove the last element from the :class:`Sequence`. | Below is the the instruction that describes the task:
### Input:
Remove the last element from the :class:`Sequence`.
### Response:
def pop_back(self):
'''Remove the last element from the :class:`Sequence`.'''
backend = self.backend
return backend.execute(backend.structure(self).pop_back(... |
def _add_path(dir_name, payload_info_list):
"""Add a key with the path to each payload_info_dict."""
for payload_info_dict in payload_info_list:
file_name = payload_info_dict['filename'] or payload_info_dict['pid']
payload_info_dict['path'] = d1_common.utils.filesystem.gen_safe_path(
... | Add a key with the path to each payload_info_dict. | Below is the the instruction that describes the task:
### Input:
Add a key with the path to each payload_info_dict.
### Response:
def _add_path(dir_name, payload_info_list):
"""Add a key with the path to each payload_info_dict."""
for payload_info_dict in payload_info_list:
file_name = payload_info... |
def escape_latex(s):
r"""Escape characters that are special in latex.
Args
----
s : `str`, `NoEscape` or anything that can be converted to string
The string to be escaped. If this is not a string, it will be converted
to a string using `str`. If it is a `NoEscape` string, it will pass
... | r"""Escape characters that are special in latex.
Args
----
s : `str`, `NoEscape` or anything that can be converted to string
The string to be escaped. If this is not a string, it will be converted
to a string using `str`. If it is a `NoEscape` string, it will pass
through unchanged.... | Below is the the instruction that describes the task:
### Input:
r"""Escape characters that are special in latex.
Args
----
s : `str`, `NoEscape` or anything that can be converted to string
The string to be escaped. If this is not a string, it will be converted
to a string using `str`. ... |
def fetch_post_data(self):
'''
fetch post accessed data. post_data, and ext_dic.
'''
post_data = {}
ext_dic = {}
for key in self.request.arguments:
if key.startswith('ext_') or key.startswith('tag_'):
ext_dic[key] = self.get_argument(key)
... | fetch post accessed data. post_data, and ext_dic. | Below is the the instruction that describes the task:
### Input:
fetch post accessed data. post_data, and ext_dic.
### Response:
def fetch_post_data(self):
'''
fetch post accessed data. post_data, and ext_dic.
'''
post_data = {}
ext_dic = {}
for key in self.request.a... |
def pop_identity(self):
"""
:returns: SimpleIdentifierCollection
"""
popped = None
stack = self.get_run_as_identifiers_stack()
if (stack):
popped = stack.pop()
if (stack):
# persist the changed stack to the session
... | :returns: SimpleIdentifierCollection | Below is the the instruction that describes the task:
### Input:
:returns: SimpleIdentifierCollection
### Response:
def pop_identity(self):
"""
:returns: SimpleIdentifierCollection
"""
popped = None
stack = self.get_run_as_identifiers_stack()
if (stack):
... |
def chrome_getdata_view(request):
"""Get the data of the last notification sent to the current user.
This is needed because Chrome, as of version 44, doesn't support
sending a data payload to a notification. Thus, information on what
the notification is actually for must be manually fetched.
"""
... | Get the data of the last notification sent to the current user.
This is needed because Chrome, as of version 44, doesn't support
sending a data payload to a notification. Thus, information on what
the notification is actually for must be manually fetched. | Below is the the instruction that describes the task:
### Input:
Get the data of the last notification sent to the current user.
This is needed because Chrome, as of version 44, doesn't support
sending a data payload to a notification. Thus, information on what
the notification is actually for must be ... |
def parse_str(self, s):
"""
Parse string and return relevant object
:param s: string to parse
:type s: str
:return: Parsed object
"""
self.object = self.parsed_class()
in_section = None # Holds name of FEH file section while traversing through file.
... | Parse string and return relevant object
:param s: string to parse
:type s: str
:return: Parsed object | Below is the the instruction that describes the task:
### Input:
Parse string and return relevant object
:param s: string to parse
:type s: str
:return: Parsed object
### Response:
def parse_str(self, s):
"""
Parse string and return relevant object
:param s: string... |
def AddKeys(self, key_list):
"""Mark additional columns as being part of the superkey.
Supplements the Keys already extracted from the FSM template.
Useful when adding new columns to existing tables.
Note: This will impact attempts to further 'extend' the table as the
superkey must be common bet... | Mark additional columns as being part of the superkey.
Supplements the Keys already extracted from the FSM template.
Useful when adding new columns to existing tables.
Note: This will impact attempts to further 'extend' the table as the
superkey must be common between tables for successful extension.
... | Below is the the instruction that describes the task:
### Input:
Mark additional columns as being part of the superkey.
Supplements the Keys already extracted from the FSM template.
Useful when adding new columns to existing tables.
Note: This will impact attempts to further 'extend' the table as the
... |
def parse_cookie(cookie: str) -> Dict[str, str]:
"""Parse a ``Cookie`` HTTP header into a dict of name/value pairs.
This function attempts to mimic browser cookie parsing behavior;
it specifically does not follow any of the cookie-related RFCs
(because browsers don't either).
The algorithm used is... | Parse a ``Cookie`` HTTP header into a dict of name/value pairs.
This function attempts to mimic browser cookie parsing behavior;
it specifically does not follow any of the cookie-related RFCs
(because browsers don't either).
The algorithm used is identical to that used by Django version 1.9.10.
.... | Below is the the instruction that describes the task:
### Input:
Parse a ``Cookie`` HTTP header into a dict of name/value pairs.
This function attempts to mimic browser cookie parsing behavior;
it specifically does not follow any of the cookie-related RFCs
(because browsers don't either).
The algo... |
def addToDefinition(self, json_dict):
"""
The addToDefinition operation supports adding a definition
property to a hosted feature service. The result of this
operation is a response indicating success or failure with error
code and description.
This functi... | The addToDefinition operation supports adding a definition
property to a hosted feature service. The result of this
operation is a response indicating success or failure with error
code and description.
This function will allow users to change add additional values
... | Below is the the instruction that describes the task:
### Input:
The addToDefinition operation supports adding a definition
property to a hosted feature service. The result of this
operation is a response indicating success or failure with error
code and description.
Thi... |
def diff(
cobertura_file1, cobertura_file2,
color, format, output, source1, source2,
source_prefix1, source_prefix2, source):
"""compare coverage of two Cobertura reports"""
cobertura1 = Cobertura(
cobertura_file1,
source=source1,
source_prefix=source_prefix1
... | compare coverage of two Cobertura reports | Below is the the instruction that describes the task:
### Input:
compare coverage of two Cobertura reports
### Response:
def diff(
cobertura_file1, cobertura_file2,
color, format, output, source1, source2,
source_prefix1, source_prefix2, source):
"""compare coverage of two Cobertura rep... |
def send_document(self, *args, **kwargs):
"""See :func:`send_document`"""
return send_document(*args, **self._merge_overrides(**kwargs)).run() | See :func:`send_document` | Below is the the instruction that describes the task:
### Input:
See :func:`send_document`
### Response:
def send_document(self, *args, **kwargs):
"""See :func:`send_document`"""
return send_document(*args, **self._merge_overrides(**kwargs)).run() |
def printrdf(wflow, ctx, style): # type: (Process, ContextType, Text) -> Text
"""Serialize the CWL document into a string, ready for printing."""
rdf = gather(wflow, ctx).serialize(format=style, encoding='utf-8')
if not rdf:
return u""
return rdf.decode('utf-8') | Serialize the CWL document into a string, ready for printing. | Below is the the instruction that describes the task:
### Input:
Serialize the CWL document into a string, ready for printing.
### Response:
def printrdf(wflow, ctx, style): # type: (Process, ContextType, Text) -> Text
"""Serialize the CWL document into a string, ready for printing."""
rdf = gather(wflow,... |
def str_to_inet(address):
"""Convert an a string IP address to a inet struct
Args:
address (str): String representation of address
Returns:
inet: Inet network address
"""
# First try ipv4 and then ipv6
try:
return socket.inet_pton(socket.AF_INET, address)... | Convert an a string IP address to a inet struct
Args:
address (str): String representation of address
Returns:
inet: Inet network address | Below is the the instruction that describes the task:
### Input:
Convert an a string IP address to a inet struct
Args:
address (str): String representation of address
Returns:
inet: Inet network address
### Response:
def str_to_inet(address):
"""Convert an a string IP a... |
def eval_function(value):
""" Evaluate a timestamp function """
name, args = value[0], value[1:]
if name == "NOW":
return datetime.utcnow().replace(tzinfo=tzutc())
elif name in ["TIMESTAMP", "TS"]:
return parse(unwrap(args[0])).replace(tzinfo=tzlocal())
elif name in ["UTCTIMESTAMP", ... | Evaluate a timestamp function | Below is the the instruction that describes the task:
### Input:
Evaluate a timestamp function
### Response:
def eval_function(value):
""" Evaluate a timestamp function """
name, args = value[0], value[1:]
if name == "NOW":
return datetime.utcnow().replace(tzinfo=tzutc())
elif name in ["TIM... |
def _parse_version_reply(self):
"waiting for a version reply"
if len(self._data) >= 2:
reply = self._data[:2]
self._data = self._data[2:]
(version, method) = struct.unpack('BB', reply)
if version == 5 and method in [0x00, 0x02]:
self.versio... | waiting for a version reply | Below is the the instruction that describes the task:
### Input:
waiting for a version reply
### Response:
def _parse_version_reply(self):
"waiting for a version reply"
if len(self._data) >= 2:
reply = self._data[:2]
self._data = self._data[2:]
(version, method) ... |
def _static_value(
self,
serie_node,
value,
x,
y,
metadata,
align_text='left',
classes=None
):
"""Write the print value"""
label = metadata and metadata.get('label')
classes = classes and [classes... | Write the print value | Below is the the instruction that describes the task:
### Input:
Write the print value
### Response:
def _static_value(
self,
serie_node,
value,
x,
y,
metadata,
align_text='left',
classes=None
):
"""Write th... |
def _visit_value_and_its_immediate_references(obj, visitor):
''' Recurse down Models, HasProps, and Python containers
The ordering in this function is to optimize performance. We check the
most comomn types (int, float, str) first so that we can quickly return in
the common case. We avoid isinstance ... | Recurse down Models, HasProps, and Python containers
The ordering in this function is to optimize performance. We check the
most comomn types (int, float, str) first so that we can quickly return in
the common case. We avoid isinstance and issubclass checks in a couple
places with `type` checks becau... | Below is the the instruction that describes the task:
### Input:
Recurse down Models, HasProps, and Python containers
The ordering in this function is to optimize performance. We check the
most comomn types (int, float, str) first so that we can quickly return in
the common case. We avoid isinstance ... |
def profile_config_get(name, config_key, remote_addr=None,
cert=None, key=None, verify_cert=True):
''' Get a profile config item.
name :
The name of the profile to get the config item from.
config_key :
The key for the item to retrieve.
remot... | Get a profile config item.
name :
The name of the profile to get the config item from.
config_key :
The key for the item to retrieve.
remote_addr :
An URL to a remote Server, you also have to give cert and key if
you provide remote_addr and its ... | Below is the the instruction that describes the task:
### Input:
Get a profile config item.
name :
The name of the profile to get the config item from.
config_key :
The key for the item to retrieve.
remote_addr :
An URL to a remote Server, you also have... |
def import_class(import_str):
"""Returns a class from a string including module and class."""
mod_str, _sep, class_str = import_str.rpartition(".")
__import__(mod_str)
return getattr(sys.modules[mod_str], class_str) | Returns a class from a string including module and class. | Below is the the instruction that describes the task:
### Input:
Returns a class from a string including module and class.
### Response:
def import_class(import_str):
"""Returns a class from a string including module and class."""
mod_str, _sep, class_str = import_str.rpartition(".")
__import__(mod_str... |
def cut_action_callback(self, *event):
"""Add a copy and cut all selected row dict value pairs to the clipboard"""
if react_to_event(self.view, self.tree_view, event) and self.active_entry_widget is None:
_, dict_paths = self.get_view_selection()
stored_data_list = []
... | Add a copy and cut all selected row dict value pairs to the clipboard | Below is the the instruction that describes the task:
### Input:
Add a copy and cut all selected row dict value pairs to the clipboard
### Response:
def cut_action_callback(self, *event):
"""Add a copy and cut all selected row dict value pairs to the clipboard"""
if react_to_event(self.view, self.t... |
def add_workflow(self, workflow, commit=False):
"""
Add a new workflow and optionally commit it to the database
:param workflow: The workflow
:param commit: Whether to commit the workflow to the database
:type workflow: Workflow
:type commit: bool
:return: None
... | Add a new workflow and optionally commit it to the database
:param workflow: The workflow
:param commit: Whether to commit the workflow to the database
:type workflow: Workflow
:type commit: bool
:return: None | Below is the the instruction that describes the task:
### Input:
Add a new workflow and optionally commit it to the database
:param workflow: The workflow
:param commit: Whether to commit the workflow to the database
:type workflow: Workflow
:type commit: bool
:return: None
#... |
def collect_population_best(self, best_chromosome, best_fitness_function):
"""!
@brief Stores the best chromosome for current specific iteration and its fitness function's value.
@param[in] best_chromosome (list): The best chromosome on specific iteration.
@param[in] best_fitnes... | !
@brief Stores the best chromosome for current specific iteration and its fitness function's value.
@param[in] best_chromosome (list): The best chromosome on specific iteration.
@param[in] best_fitness_function (float): Fitness function value of the chromosome. | Below is the the instruction that describes the task:
### Input:
!
@brief Stores the best chromosome for current specific iteration and its fitness function's value.
@param[in] best_chromosome (list): The best chromosome on specific iteration.
@param[in] best_fitness_function (float... |
def strike(channel, nick, rest):
"Strike last <n> statements from the record"
yield NoLog
rest = rest.strip()
if not rest:
count = 1
else:
if not rest.isdigit():
yield "Strike how many? Argument must be a positive integer."
raise StopIteration
count = int(rest)
try:
struck = Logger.store.strike(cha... | Strike last <n> statements from the record | Below is the the instruction that describes the task:
### Input:
Strike last <n> statements from the record
### Response:
def strike(channel, nick, rest):
"Strike last <n> statements from the record"
yield NoLog
rest = rest.strip()
if not rest:
count = 1
else:
if not rest.isdigit():
yield "Strike how m... |
def get_library_value(self, key: str) -> typing.Any:
"""Get the library value for the given key.
Please consult the developer documentation for a list of valid keys.
.. versionadded:: 1.0
Scriptable: Yes
"""
desc = Metadata.session_key_map.get(key)
if desc is n... | Get the library value for the given key.
Please consult the developer documentation for a list of valid keys.
.. versionadded:: 1.0
Scriptable: Yes | Below is the the instruction that describes the task:
### Input:
Get the library value for the given key.
Please consult the developer documentation for a list of valid keys.
.. versionadded:: 1.0
Scriptable: Yes
### Response:
def get_library_value(self, key: str) -> typing.Any:
... |
def accountable_date(self):
'''Accountable date of transaction, localized as America/Santiago
'''
fecha_transaccion = self.data['TBK_FECHA_CONTABLE']
m = int(fecha_transaccion[:2])
d = int(fecha_transaccion[2:])
santiago = pytz.timezone('America/Santiago')
today =... | Accountable date of transaction, localized as America/Santiago | Below is the the instruction that describes the task:
### Input:
Accountable date of transaction, localized as America/Santiago
### Response:
def accountable_date(self):
'''Accountable date of transaction, localized as America/Santiago
'''
fecha_transaccion = self.data['TBK_FECHA_CONTABLE']... |
def features(sender=''):
'''Returns a list of signature features.'''
return [
# This one isn't from paper.
# Meant to match companies names, sender's names, address.
many_capitalized_words,
# This one is not from paper.
# Line is too long.
# This one is less aggre... | Returns a list of signature features. | Below is the the instruction that describes the task:
### Input:
Returns a list of signature features.
### Response:
def features(sender=''):
'''Returns a list of signature features.'''
return [
# This one isn't from paper.
# Meant to match companies names, sender's names, address.
... |
def _define_case(self):
''' Identify case '''
lonBool = self._map_center(
'long', self.lonM) != self._map_center('long', self.lonm)
latBool = self._map_center(
'lat', self.latM) != self._map_center('lat', self.latm)
if not lonBool and not latBool:
pr... | Identify case | Below is the the instruction that describes the task:
### Input:
Identify case
### Response:
def _define_case(self):
''' Identify case '''
lonBool = self._map_center(
'long', self.lonM) != self._map_center('long', self.lonm)
latBool = self._map_center(
'lat', self.l... |
def submit_influxdb_measurement(self):
"""Submit a measurement for a message to InfluxDB"""
measurement = influxdb.Measurement(*self.influxdb)
measurement.set_timestamp(time.time())
for key, value in self.measurement.counters.items():
measurement.set_field(key, value)
... | Submit a measurement for a message to InfluxDB | Below is the the instruction that describes the task:
### Input:
Submit a measurement for a message to InfluxDB
### Response:
def submit_influxdb_measurement(self):
"""Submit a measurement for a message to InfluxDB"""
measurement = influxdb.Measurement(*self.influxdb)
measurement.set_timest... |
def is_memoized(self, k):
'''
lmap.is_memoized(k) yields True if k is a key in the given lazy map lmap that is both lazy
and already memoized.
'''
v = ps.PMap.__getitem__(self, k)
if not isinstance(v, (types.FunctionType, partial)):
return False
else:
... | lmap.is_memoized(k) yields True if k is a key in the given lazy map lmap that is both lazy
and already memoized. | Below is the the instruction that describes the task:
### Input:
lmap.is_memoized(k) yields True if k is a key in the given lazy map lmap that is both lazy
and already memoized.
### Response:
def is_memoized(self, k):
'''
lmap.is_memoized(k) yields True if k is a key in the given lazy map l... |
def set_provenance_to_project_variables(provenances):
"""Helper method to update / create provenance in project variables.
:param provenances: Keys and values from provenances.
:type provenances: dict
"""
def write_project_variable(key, value):
"""Helper to write project variable for base_k... | Helper method to update / create provenance in project variables.
:param provenances: Keys and values from provenances.
:type provenances: dict | Below is the the instruction that describes the task:
### Input:
Helper method to update / create provenance in project variables.
:param provenances: Keys and values from provenances.
:type provenances: dict
### Response:
def set_provenance_to_project_variables(provenances):
"""Helper method to updat... |
def _formatNumbers(self, line):
"""
Format the numbers so that there are commas inserted.
For example: 1200300 becomes 1,200,300.
"""
# below thousands separator syntax only works for
# python 2.7, skip for 2.6
if sys.version_info < (2, 7):
return lin... | Format the numbers so that there are commas inserted.
For example: 1200300 becomes 1,200,300. | Below is the the instruction that describes the task:
### Input:
Format the numbers so that there are commas inserted.
For example: 1200300 becomes 1,200,300.
### Response:
def _formatNumbers(self, line):
"""
Format the numbers so that there are commas inserted.
For example: 12003... |
def load_drp(self, name, entry_point='numina.pipeline.1'):
"""Load all available DRPs in 'entry_point'."""
for drpins in self.iload(entry_point):
if drpins.name == name:
return drpins
else:
raise KeyError('{}'.format(name)) | Load all available DRPs in 'entry_point'. | Below is the the instruction that describes the task:
### Input:
Load all available DRPs in 'entry_point'.
### Response:
def load_drp(self, name, entry_point='numina.pipeline.1'):
"""Load all available DRPs in 'entry_point'."""
for drpins in self.iload(entry_point):
if drpins.name == n... |
def write_out(self, page, xml_subpages, output):
"""Banana banana
"""
# pylint: disable=missing-docstring
def subpages(_):
return xml_subpages
namespace = etree.FunctionNamespace('uri:hotdoc')
namespace['subpages'] = subpages
html_output = os.path.joi... | Banana banana | Below is the the instruction that describes the task:
### Input:
Banana banana
### Response:
def write_out(self, page, xml_subpages, output):
"""Banana banana
"""
# pylint: disable=missing-docstring
def subpages(_):
return xml_subpages
namespace = etree.Function... |
def _redirect_edge(self, u_id, v_id, new_v_id):
"""Redirect the layer to a new node.
Change the edge originally from `u_id` to `v_id` into an edge from `u_id` to `new_v_id`
while keeping all other property of the edge the same.
"""
layer_id = None
for index, edge_tuple in... | Redirect the layer to a new node.
Change the edge originally from `u_id` to `v_id` into an edge from `u_id` to `new_v_id`
while keeping all other property of the edge the same. | Below is the the instruction that describes the task:
### Input:
Redirect the layer to a new node.
Change the edge originally from `u_id` to `v_id` into an edge from `u_id` to `new_v_id`
while keeping all other property of the edge the same.
### Response:
def _redirect_edge(self, u_id, v_id, new_v_... |
def can_import(self, file_uris, current_doc=None):
"""
Check that the specified file looks like a PDF
"""
if len(file_uris) <= 0:
return False
for uri in file_uris:
uri = self.fs.safe(uri)
if not self.check_file_type(uri):
retur... | Check that the specified file looks like a PDF | Below is the the instruction that describes the task:
### Input:
Check that the specified file looks like a PDF
### Response:
def can_import(self, file_uris, current_doc=None):
"""
Check that the specified file looks like a PDF
"""
if len(file_uris) <= 0:
return False
... |
def save_form(self, request, form, change):
"""
Don't show links in the sitemap.
"""
obj = form.save(commit=False)
if not obj.id and "in_sitemap" not in form.fields:
obj.in_sitemap = False
return super(LinkAdmin, self).save_form(request, form, change) | Don't show links in the sitemap. | Below is the the instruction that describes the task:
### Input:
Don't show links in the sitemap.
### Response:
def save_form(self, request, form, change):
"""
Don't show links in the sitemap.
"""
obj = form.save(commit=False)
if not obj.id and "in_sitemap" not in form.field... |
def parse_cli_args():
"""parse args from the CLI and return a dict"""
parser = argparse.ArgumentParser(description='2048 in your terminal')
parser.add_argument('--mode', dest='mode', type=str,
default=None, help='colors mode (dark or light)')
parser.add_argument('--az', dest='azm... | parse args from the CLI and return a dict | Below is the the instruction that describes the task:
### Input:
parse args from the CLI and return a dict
### Response:
def parse_cli_args():
"""parse args from the CLI and return a dict"""
parser = argparse.ArgumentParser(description='2048 in your terminal')
parser.add_argument('--mode', dest='mode',... |
def key(self):
"""
Returns a tuple that identifies the task instance uniquely
"""
return self.dag_id, self.task_id, self.execution_date, self.try_number | Returns a tuple that identifies the task instance uniquely | Below is the the instruction that describes the task:
### Input:
Returns a tuple that identifies the task instance uniquely
### Response:
def key(self):
"""
Returns a tuple that identifies the task instance uniquely
"""
return self.dag_id, self.task_id, self.execution_date, self.try... |
def help(rest):
"""Help (this command)"""
rs = rest.strip()
if rs:
# give help for matching commands
for handler in Handler._registry:
if handler.name == rs.lower():
yield '!%s: %s' % (handler.name, handler.doc)
break
else:
yield "command not found"
return
# give help for all commands
def mk... | Help (this command) | Below is the the instruction that describes the task:
### Input:
Help (this command)
### Response:
def help(rest):
"""Help (this command)"""
rs = rest.strip()
if rs:
# give help for matching commands
for handler in Handler._registry:
if handler.name == rs.lower():
yield '!%s: %s' % (handler.name, han... |
def normalize_value(val):
"""
Normalize strings with booleans into Python types.
"""
if val is not None:
if val.lower() == 'false':
val = False
elif val.lower() == 'true':
val = True
return val | Normalize strings with booleans into Python types. | Below is the the instruction that describes the task:
### Input:
Normalize strings with booleans into Python types.
### Response:
def normalize_value(val):
"""
Normalize strings with booleans into Python types.
"""
if val is not None:
if val.lower() == 'false':
val = False
... |
def the_gui(gui_queue):
"""
Starts and executes the GUI
Reads data from a Queue and displays the data to the window
Returns when the user exits / closes the window
(that means it does NOT return until the user exits the window)
:param gui_queue: Queue the GUI should read from
:return:
... | Starts and executes the GUI
Reads data from a Queue and displays the data to the window
Returns when the user exits / closes the window
(that means it does NOT return until the user exits the window)
:param gui_queue: Queue the GUI should read from
:return: | Below is the the instruction that describes the task:
### Input:
Starts and executes the GUI
Reads data from a Queue and displays the data to the window
Returns when the user exits / closes the window
(that means it does NOT return until the user exits the window)
:param gui_queue: Queue the GUI... |
def get_first_recipient_with_address(self):
""" Returns the first recipient found with a non blank address
:return: First Recipient
:rtype: Recipient
"""
recipients_with_address = [recipient for recipient in self._recipients
if recipient.addres... | Returns the first recipient found with a non blank address
:return: First Recipient
:rtype: Recipient | Below is the the instruction that describes the task:
### Input:
Returns the first recipient found with a non blank address
:return: First Recipient
:rtype: Recipient
### Response:
def get_first_recipient_with_address(self):
""" Returns the first recipient found with a non blank address
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.