code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def isolate_element(self, x):
"""Isolates `x` from its equivalence class."""
members = list(self.members(x))
self.delete_set(x)
self.union(*(v for v in members if v != x)) | Isolates `x` from its equivalence class. | Below is the the instruction that describes the task:
### Input:
Isolates `x` from its equivalence class.
### Response:
def isolate_element(self, x):
"""Isolates `x` from its equivalence class."""
members = list(self.members(x))
self.delete_set(x)
self.union(*(v for v in members if ... |
def markWatched(self):
""" Mark video as watched. """
key = '/:/scrobble?key=%s&identifier=com.plexapp.plugins.library' % self.ratingKey
self._server.query(key)
self.reload() | Mark video as watched. | Below is the the instruction that describes the task:
### Input:
Mark video as watched.
### Response:
def markWatched(self):
""" Mark video as watched. """
key = '/:/scrobble?key=%s&identifier=com.plexapp.plugins.library' % self.ratingKey
self._server.query(key)
self.reload() |
def get_meta_rdf(self, fmt='n3'):
"""Get the metadata for this Point in rdf fmt
Advanced users who want to manipulate the RDF for this Point directly without the
[PointMeta](PointMeta.m.html#IoticAgent.IOT.PointMeta.PointMeta) helper object
Returns the RDF in the format you specify. - ... | Get the metadata for this Point in rdf fmt
Advanced users who want to manipulate the RDF for this Point directly without the
[PointMeta](PointMeta.m.html#IoticAgent.IOT.PointMeta.PointMeta) helper object
Returns the RDF in the format you specify. - OR -
Raises [IOTException](./Excepti... | Below is the the instruction that describes the task:
### Input:
Get the metadata for this Point in rdf fmt
Advanced users who want to manipulate the RDF for this Point directly without the
[PointMeta](PointMeta.m.html#IoticAgent.IOT.PointMeta.PointMeta) helper object
Returns the RDF in th... |
def parse_all(self, sources, path, package_name, root_dir):
"""Parse all the model dictionaries in sources.
:param List[dict] sources: The `sources` section of the schema.yml, as
a list of dicts.
:param str path: The path to the schema.yml file
:param str package_name: The n... | Parse all the model dictionaries in sources.
:param List[dict] sources: The `sources` section of the schema.yml, as
a list of dicts.
:param str path: The path to the schema.yml file
:param str package_name: The name of the current package
:param str root_dir: The root direct... | Below is the the instruction that describes the task:
### Input:
Parse all the model dictionaries in sources.
:param List[dict] sources: The `sources` section of the schema.yml, as
a list of dicts.
:param str path: The path to the schema.yml file
:param str package_name: The nam... |
def upload_superfile(self, remote_path, block_list, ondup=None, **kwargs):
"""分片上传—合并分片文件.
与分片文件上传的 ``upload_tmpfile`` 方法配合使用,
可实现超大文件(>2G)上传,同时也可用于断点续传的场景。
:param remote_path: 网盘中文件的保存路径(包含文件名)。
必须以 /apps/ 开头。
.. warning::
... | 分片上传—合并分片文件.
与分片文件上传的 ``upload_tmpfile`` 方法配合使用,
可实现超大文件(>2G)上传,同时也可用于断点续传的场景。
:param remote_path: 网盘中文件的保存路径(包含文件名)。
必须以 /apps/ 开头。
.. warning::
* 路径长度限制为1000;
* 径中不能包含以下字符... | Below is the the instruction that describes the task:
### Input:
分片上传—合并分片文件.
与分片文件上传的 ``upload_tmpfile`` 方法配合使用,
可实现超大文件(>2G)上传,同时也可用于断点续传的场景。
:param remote_path: 网盘中文件的保存路径(包含文件名)。
必须以 /apps/ 开头。
.. warning::
... |
def check_yaafe():
"Check Aubio availability"
try:
import yaafelib
except ImportError:
warnings.warn('Yaafe librairy is not available', ImportWarning,
stacklevel=2)
_WITH_YAAFE = False
else:
_WITH_YAAFE = True
del yaafelib
return _WITH_YA... | Check Aubio availability | Below is the the instruction that describes the task:
### Input:
Check Aubio availability
### Response:
def check_yaafe():
"Check Aubio availability"
try:
import yaafelib
except ImportError:
warnings.warn('Yaafe librairy is not available', ImportWarning,
stacklevel... |
def kill_tweens(self, obj = None):
"""Stop tweening an object, without completing the motion or firing the
on_complete"""
if obj is not None:
try:
del self.current_tweens[obj]
except:
pass
else:
self.current_tweens = col... | Stop tweening an object, without completing the motion or firing the
on_complete | Below is the the instruction that describes the task:
### Input:
Stop tweening an object, without completing the motion or firing the
on_complete
### Response:
def kill_tweens(self, obj = None):
"""Stop tweening an object, without completing the motion or firing the
on_complete"""
i... |
def do_metric_list(mc, args):
'''List metrics for this tenant.'''
fields = {}
if args.name:
fields['name'] = args.name
if args.dimensions:
fields['dimensions'] = utils.format_dimensions_query(args.dimensions)
if args.limit:
fields['limit'] = args.limit
if args.offset:
... | List metrics for this tenant. | Below is the the instruction that describes the task:
### Input:
List metrics for this tenant.
### Response:
def do_metric_list(mc, args):
'''List metrics for this tenant.'''
fields = {}
if args.name:
fields['name'] = args.name
if args.dimensions:
fields['dimensions'] = utils.format... |
def value_after(self, x):
"""Returns value of argument after given found argument (or list thereof)."""
try:
try:
i = self.all.index(x)
except ValueError:
return None
return self.all[i + 1]
except IndexError:
retu... | Returns value of argument after given found argument (or list thereof). | Below is the the instruction that describes the task:
### Input:
Returns value of argument after given found argument (or list thereof).
### Response:
def value_after(self, x):
"""Returns value of argument after given found argument (or list thereof)."""
try:
try:
i = s... |
def make_unique_str(num_chars=20):
"""make a random string of characters for a temp filename"""
chars = 'abcdefghigklmnopqrstuvwxyz'
all_chars = chars + chars.upper() + '01234567890'
picks = list(all_chars)
return ''.join([choice(picks) for i in range(num_chars)]) | make a random string of characters for a temp filename | Below is the the instruction that describes the task:
### Input:
make a random string of characters for a temp filename
### Response:
def make_unique_str(num_chars=20):
"""make a random string of characters for a temp filename"""
chars = 'abcdefghigklmnopqrstuvwxyz'
all_chars = chars + chars.upper() + ... |
def _convert_value(self, item):
"""
Handle different value types for XLS. Item is a cell object.
"""
# Types:
# 0 = empty u''
# 1 = unicode text
# 2 = float (convert to int if possible, then convert to string)
# 3 = date (convert to unambiguous date/time s... | Handle different value types for XLS. Item is a cell object. | Below is the the instruction that describes the task:
### Input:
Handle different value types for XLS. Item is a cell object.
### Response:
def _convert_value(self, item):
"""
Handle different value types for XLS. Item is a cell object.
"""
# Types:
# 0 = empty u''
#... |
def convert_filename(txtfilename, outdir='.'):
"""Convert a .TXT filename to a Therion .TH filename"""
return os.path.join(outdir, os.path.basename(txtfilename)).rsplit('.', 1)[0] + '.th' | Convert a .TXT filename to a Therion .TH filename | Below is the the instruction that describes the task:
### Input:
Convert a .TXT filename to a Therion .TH filename
### Response:
def convert_filename(txtfilename, outdir='.'):
"""Convert a .TXT filename to a Therion .TH filename"""
return os.path.join(outdir, os.path.basename(txtfilename)).rsplit('.', 1)[0... |
def get_cachesim(self, cores=1):
"""
Return a cachesim.CacheSimulator object based on the machine description.
:param cores: core count (default: 1)
"""
cache_dict = {}
for c in self['memory hierarchy']:
# Skip main memory
if 'cache per group' not... | Return a cachesim.CacheSimulator object based on the machine description.
:param cores: core count (default: 1) | Below is the the instruction that describes the task:
### Input:
Return a cachesim.CacheSimulator object based on the machine description.
:param cores: core count (default: 1)
### Response:
def get_cachesim(self, cores=1):
"""
Return a cachesim.CacheSimulator object based on the machine d... |
def _asdict_anything(val, filter, dict_factory, retain_collection_types):
"""
``asdict`` only works on attrs instances, this works on anything.
"""
if getattr(val.__class__, "__attrs_attrs__", None) is not None:
# Attrs class.
rv = asdict(val, True, filter, dict_factory, retain_collectio... | ``asdict`` only works on attrs instances, this works on anything. | Below is the the instruction that describes the task:
### Input:
``asdict`` only works on attrs instances, this works on anything.
### Response:
def _asdict_anything(val, filter, dict_factory, retain_collection_types):
"""
``asdict`` only works on attrs instances, this works on anything.
"""
if get... |
def get_lead(self, lead_id):
"""
Get a specific lead saved on your account.
:param lead_id: Id of the lead to search. Must be defined.
:return: Lead found as a dict.
"""
params = self.base_params
endpoint = self.base_endpoint.format('leads/' + str(lead_id))
... | Get a specific lead saved on your account.
:param lead_id: Id of the lead to search. Must be defined.
:return: Lead found as a dict. | Below is the the instruction that describes the task:
### Input:
Get a specific lead saved on your account.
:param lead_id: Id of the lead to search. Must be defined.
:return: Lead found as a dict.
### Response:
def get_lead(self, lead_id):
"""
Get a specific lead saved on your ac... |
def open(self):
"""Open receiver connection and authenticate session.
If the receiver is already open, this operation will do nothing.
This method will be called automatically when one starts to iterate
messages in the receiver, so there should be no need to call it directly.
A ... | Open receiver connection and authenticate session.
If the receiver is already open, this operation will do nothing.
This method will be called automatically when one starts to iterate
messages in the receiver, so there should be no need to call it directly.
A receiver opened with this m... | Below is the the instruction that describes the task:
### Input:
Open receiver connection and authenticate session.
If the receiver is already open, this operation will do nothing.
This method will be called automatically when one starts to iterate
messages in the receiver, so there should ... |
def to_directed(self):
"""Return a directed representation of the graph.
Returns
-------
G : DynDiGraph
A dynamic directed graph with the same name, same nodes, and with
each edge (u,v,data) replaced by two directed edges
(u,v,data) and (v,u,data).
... | Return a directed representation of the graph.
Returns
-------
G : DynDiGraph
A dynamic directed graph with the same name, same nodes, and with
each edge (u,v,data) replaced by two directed edges
(u,v,data) and (v,u,data).
Notes
-----
... | Below is the the instruction that describes the task:
### Input:
Return a directed representation of the graph.
Returns
-------
G : DynDiGraph
A dynamic directed graph with the same name, same nodes, and with
each edge (u,v,data) replaced by two directed edges
... |
def isopoly_to_gdf(collec_poly, levels, field_name="levels"):
"""
Convert a collection of matplotlib.contour.QuadContourSet to a GeoDataFrame
Set an attribute `field_name` on each feature, according to `levels` values
(`levels` must have the same number of features as the collection of contours)
Pa... | Convert a collection of matplotlib.contour.QuadContourSet to a GeoDataFrame
Set an attribute `field_name` on each feature, according to `levels` values
(`levels` must have the same number of features as the collection of contours)
Parameters
----------
collection_polygons : matplotlib.contour.QuadC... | Below is the the instruction that describes the task:
### Input:
Convert a collection of matplotlib.contour.QuadContourSet to a GeoDataFrame
Set an attribute `field_name` on each feature, according to `levels` values
(`levels` must have the same number of features as the collection of contours)
Paramet... |
def find_out_attribs(self):
"""
Get all out attributes in the shader source.
:return: List of attribute names
"""
names = []
for line in self.lines:
if line.strip().startswith("out "):
names.append(line.split()[2].replace(';', ''))
... | Get all out attributes in the shader source.
:return: List of attribute names | Below is the the instruction that describes the task:
### Input:
Get all out attributes in the shader source.
:return: List of attribute names
### Response:
def find_out_attribs(self):
"""
Get all out attributes in the shader source.
:return: List of attribute names
... |
def WriteMessageHandlerRequests(self, requests):
"""Writes a list of message handler requests to the database."""
now = rdfvalue.RDFDatetime.Now()
for r in requests:
flow_dict = self.message_handler_requests.setdefault(r.handler_name, {})
cloned_request = r.Copy()
cloned_request.timestamp ... | Writes a list of message handler requests to the database. | Below is the the instruction that describes the task:
### Input:
Writes a list of message handler requests to the database.
### Response:
def WriteMessageHandlerRequests(self, requests):
"""Writes a list of message handler requests to the database."""
now = rdfvalue.RDFDatetime.Now()
for r in requests:... |
def topic_command():
'''command line tool for jps
'''
parser = argparse.ArgumentParser(description='json pub/sub tool')
pub_common_parser = jps.ArgumentParser(subscriber=False, add_help=False)
sub_common_parser = jps.ArgumentParser(publisher=False, add_help=False)
command_parsers = parser.add_su... | command line tool for jps | Below is the the instruction that describes the task:
### Input:
command line tool for jps
### Response:
def topic_command():
'''command line tool for jps
'''
parser = argparse.ArgumentParser(description='json pub/sub tool')
pub_common_parser = jps.ArgumentParser(subscriber=False, add_help=False)
... |
def _createGaVariant(self):
"""
Convenience method to set the common fields in a GA Variant
object from this variant set.
"""
ret = protocol.Variant()
if self._creationTime:
ret.created = self._creationTime
if self._updatedTime:
ret.updated... | Convenience method to set the common fields in a GA Variant
object from this variant set. | Below is the the instruction that describes the task:
### Input:
Convenience method to set the common fields in a GA Variant
object from this variant set.
### Response:
def _createGaVariant(self):
"""
Convenience method to set the common fields in a GA Variant
object from this varia... |
def get_links_of_type(self, s_type=''):
"""Return the `s_type` satellite list (eg. schedulers)
If s_type is None, returns a dictionary of all satellites, else returns the dictionary
of the s_type satellites
The returned dict is indexed with the satellites uuid.
:param s_type: ... | Return the `s_type` satellite list (eg. schedulers)
If s_type is None, returns a dictionary of all satellites, else returns the dictionary
of the s_type satellites
The returned dict is indexed with the satellites uuid.
:param s_type: satellite type
:type s_type: str
:r... | Below is the the instruction that describes the task:
### Input:
Return the `s_type` satellite list (eg. schedulers)
If s_type is None, returns a dictionary of all satellites, else returns the dictionary
of the s_type satellites
The returned dict is indexed with the satellites uuid.
... |
def reload(self):
""" Function reload
Reload the full object to ensure sync
"""
realData = self.load()
self.clear()
self.update(realData) | Function reload
Reload the full object to ensure sync | Below is the the instruction that describes the task:
### Input:
Function reload
Reload the full object to ensure sync
### Response:
def reload(self):
""" Function reload
Reload the full object to ensure sync
"""
realData = self.load()
self.clear()
self.updat... |
def _lmder1_rosenbrock():
"""Rosenbrock function (lmder test #4)"""
def func(params, vec):
vec[0] = 10 * (params[1] - params[0]**2)
vec[1] = 1 - params[0]
def jac(params, jac):
jac[0,0] = -20 * params[0]
jac[0,1] = -1
jac[1,0] = 10
jac[1,1] = 0
guess = ... | Rosenbrock function (lmder test #4) | Below is the the instruction that describes the task:
### Input:
Rosenbrock function (lmder test #4)
### Response:
def _lmder1_rosenbrock():
"""Rosenbrock function (lmder test #4)"""
def func(params, vec):
vec[0] = 10 * (params[1] - params[0]**2)
vec[1] = 1 - params[0]
def jac(params,... |
def which(program):
"""
returns the path to an executable or None if it can't be found
"""
def is_exe(_fpath):
return os.path.isfile(_fpath) and os.access(_fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
... | returns the path to an executable or None if it can't be found | Below is the the instruction that describes the task:
### Input:
returns the path to an executable or None if it can't be found
### Response:
def which(program):
"""
returns the path to an executable or None if it can't be found
"""
def is_exe(_fpath):
return os.path.isfile(_fpath) and os.a... |
def stamp(directory=None, revision='head', sql=False, tag=None):
"""'stamp' the revision table with the given revision; don't run any
migrations"""
config = current_app.extensions['migrate'].migrate.get_config(directory)
command.stamp(config, revision, sql=sql, tag=tag) | stamp' the revision table with the given revision; don't run any
migrations | Below is the the instruction that describes the task:
### Input:
stamp' the revision table with the given revision; don't run any
migrations
### Response:
def stamp(directory=None, revision='head', sql=False, tag=None):
"""'stamp' the revision table with the given revision; don't run any
migrations"""
... |
def path_compute(
p: tcod.path.AStar, ox: int, oy: int, dx: int, dy: int
) -> bool:
"""Find a path from (ox, oy) to (dx, dy). Return True if path is found.
Args:
p (AStar): An AStar instance.
ox (int): Starting x position.
oy (int): Starting y position.
dx (int): Destinatio... | Find a path from (ox, oy) to (dx, dy). Return True if path is found.
Args:
p (AStar): An AStar instance.
ox (int): Starting x position.
oy (int): Starting y position.
dx (int): Destination x position.
dy (int): Destination y position.
Returns:
bool: True if a va... | Below is the the instruction that describes the task:
### Input:
Find a path from (ox, oy) to (dx, dy). Return True if path is found.
Args:
p (AStar): An AStar instance.
ox (int): Starting x position.
oy (int): Starting y position.
dx (int): Destination x position.
dy (... |
def setImage(self, image=None, autoLevels=None, **kargs):
"""
Same this as ImageItem.setImage, but we don't update the drawing
"""
profile = debug.Profiler()
gotNewData = False
if image is None:
if self.image is None:
return
e... | Same this as ImageItem.setImage, but we don't update the drawing | Below is the the instruction that describes the task:
### Input:
Same this as ImageItem.setImage, but we don't update the drawing
### Response:
def setImage(self, image=None, autoLevels=None, **kargs):
"""
Same this as ImageItem.setImage, but we don't update the drawing
"""
... |
def ParseAutofillRow(
self, parser_mediator, query, row, **unused_kwargs):
"""Parses an autofill entry row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
r... | Parses an autofill entry row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.Row): row. | Below is the the instruction that describes the task:
### Input:
Parses an autofill entry row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.Row): r... |
def encodeIntoArray(self, x, output):
""" See method description in base.py """
if x is not None and not isinstance(x, numbers.Number):
raise TypeError(
"Expected a scalar input but got input of type %s" % type(x))
# Get the bucket index to use
bucketIdx = self.getBucketIndices(x)[0]
... | See method description in base.py | Below is the the instruction that describes the task:
### Input:
See method description in base.py
### Response:
def encodeIntoArray(self, x, output):
""" See method description in base.py """
if x is not None and not isinstance(x, numbers.Number):
raise TypeError(
"Expected a scalar input... |
def from_usi(cls, usi):
'''
Parses an USI string.
Raises `ValueError` if the USI string is invalid.
'''
if usi == '0000':
return cls.null()
elif len(usi) == 4:
if usi[1] == '*':
piece = Piece.from_symbol(usi[0])
retu... | Parses an USI string.
Raises `ValueError` if the USI string is invalid. | Below is the the instruction that describes the task:
### Input:
Parses an USI string.
Raises `ValueError` if the USI string is invalid.
### Response:
def from_usi(cls, usi):
'''
Parses an USI string.
Raises `ValueError` if the USI string is invalid.
'''
if usi == '0... |
def _patch_original_class(self):
"""
Apply accumulated methods and return the class.
"""
cls = self._cls
base_names = self._base_names
# Clean class of attribute definitions (`attr.ib()`s).
if self._delete_attribs:
for name in self._attr_names:
... | Apply accumulated methods and return the class. | Below is the the instruction that describes the task:
### Input:
Apply accumulated methods and return the class.
### Response:
def _patch_original_class(self):
"""
Apply accumulated methods and return the class.
"""
cls = self._cls
base_names = self._base_names
# Cl... |
def references(self, datatrees, whole=False):
"""
Reference name resolver (eg. /a/b/c/d@.x.y or /a/b/c/@y will search data in .x.y or y nodes)
there are used regular expressions (re.search) to match names
it uses simple references schema, do not use references to another references,
... | Reference name resolver (eg. /a/b/c/d@.x.y or /a/b/c/@y will search data in .x.y or y nodes)
there are used regular expressions (re.search) to match names
it uses simple references schema, do not use references to another references,
avoid usind / in reference because actual solution creates als... | Below is the the instruction that describes the task:
### Input:
Reference name resolver (eg. /a/b/c/d@.x.y or /a/b/c/@y will search data in .x.y or y nodes)
there are used regular expressions (re.search) to match names
it uses simple references schema, do not use references to another references,
... |
def write_config_from_api(self, api, config_file=None, profile=None):
'''
Create/update the config file from a DataAPI object
Parameters
----------
api : object
The :py:class:`datafs.DataAPI` object from which
to create the config profile
profil... | Create/update the config file from a DataAPI object
Parameters
----------
api : object
The :py:class:`datafs.DataAPI` object from which
to create the config profile
profile : str
Name of the profile to use in the config file
(default "de... | Below is the the instruction that describes the task:
### Input:
Create/update the config file from a DataAPI object
Parameters
----------
api : object
The :py:class:`datafs.DataAPI` object from which
to create the config profile
profile : str
N... |
def delete(self, params, args, data):
# type: (str, dict, dict) -> None
"""
DELETE /resource/model_cls/[params]?[args]
delete resource/s
"""
ctx = self._create_context(params, args, data)
row_id = ctx.get_row_id()
if row_id is not None:
retur... | DELETE /resource/model_cls/[params]?[args]
delete resource/s | Below is the the instruction that describes the task:
### Input:
DELETE /resource/model_cls/[params]?[args]
delete resource/s
### Response:
def delete(self, params, args, data):
# type: (str, dict, dict) -> None
"""
DELETE /resource/model_cls/[params]?[args]
delete resourc... |
def console(session, database=None, user=None, password=None, server=None):
"""An interactive Python API console for MyGeotab
If IPython is installed, it will launch an interactive IPython console instead of the built-in Python console. The
IPython console has numerous advantages over the stock Python cons... | An interactive Python API console for MyGeotab
If IPython is installed, it will launch an interactive IPython console instead of the built-in Python console. The
IPython console has numerous advantages over the stock Python console, including: colors, pretty printing,
command auto-completion, and more.
... | Below is the the instruction that describes the task:
### Input:
An interactive Python API console for MyGeotab
If IPython is installed, it will launch an interactive IPython console instead of the built-in Python console. The
IPython console has numerous advantages over the stock Python console, including... |
def _escape(self, bits):
"""
value: 'foobar {' -> 'foobar {{'
value: 'x}' -> 'x}}'
"""
# for value, field_name, format_spec, conversion in bits:
while True:
try:
value, field_name, format_spec, conversion = next(bits)
if value:
... | value: 'foobar {' -> 'foobar {{'
value: 'x}' -> 'x}}' | Below is the the instruction that describes the task:
### Input:
value: 'foobar {' -> 'foobar {{'
value: 'x}' -> 'x}}'
### Response:
def _escape(self, bits):
"""
value: 'foobar {' -> 'foobar {{'
value: 'x}' -> 'x}}'
"""
# for value, field_name, format_spec, conversio... |
def ext_pillar(minion_id, pillar, *args, **kwargs):
'''
Query NetBox API for minion data
'''
if minion_id == '*':
log.info('There\'s no data to collect from NetBox for the Master')
return {}
# Pull settings from kwargs
api_url = kwargs['api_url'].rstrip('/')
api_token = kwarg... | Query NetBox API for minion data | Below is the the instruction that describes the task:
### Input:
Query NetBox API for minion data
### Response:
def ext_pillar(minion_id, pillar, *args, **kwargs):
'''
Query NetBox API for minion data
'''
if minion_id == '*':
log.info('There\'s no data to collect from NetBox for the Master'... |
def new_message(self, body=''):
"""
Create new message of appropriate class.
:type body: message body
:param body: The body of the newly created message (optional).
:rtype: :class:`boto.sqs.message.Message`
:return: A new Message object
"""
m = self.mess... | Create new message of appropriate class.
:type body: message body
:param body: The body of the newly created message (optional).
:rtype: :class:`boto.sqs.message.Message`
:return: A new Message object | Below is the the instruction that describes the task:
### Input:
Create new message of appropriate class.
:type body: message body
:param body: The body of the newly created message (optional).
:rtype: :class:`boto.sqs.message.Message`
:return: A new Message object
### Response:
d... |
def items_for_result(cl, result, form):
"""
Generates the actual list of data.
@jjdelc:
This has been shamelessly copied from original
django.contrib.admin.templatetags.admin_list.items_for_result
in order to alter the dispay for the first element
"""
first = True
pk = cl.lookup_opt... | Generates the actual list of data.
@jjdelc:
This has been shamelessly copied from original
django.contrib.admin.templatetags.admin_list.items_for_result
in order to alter the dispay for the first element | Below is the the instruction that describes the task:
### Input:
Generates the actual list of data.
@jjdelc:
This has been shamelessly copied from original
django.contrib.admin.templatetags.admin_list.items_for_result
in order to alter the dispay for the first element
### Response:
def items_for_r... |
def picknthweekday(year, month, dayofweek, hour, minute, whichweek):
"""dayofweek == 0 means Sunday, whichweek 5 means last instance"""
first = datetime.datetime(year, month, 1, hour, minute)
weekdayone = first.replace(day=((dayofweek-first.isoweekday())%7+1))
for n in range(whichweek):
dt = wee... | dayofweek == 0 means Sunday, whichweek 5 means last instance | Below is the the instruction that describes the task:
### Input:
dayofweek == 0 means Sunday, whichweek 5 means last instance
### Response:
def picknthweekday(year, month, dayofweek, hour, minute, whichweek):
"""dayofweek == 0 means Sunday, whichweek 5 means last instance"""
first = datetime.datetime(year,... |
def h_boiling_Yan_Lin(m, x, Dh, rhol, rhog, mul, kl, Hvap, Cpl, q,
A_channel_flow):
r'''Calculates the two-phase boiling heat transfer coefficient of a
liquid and gas flowing inside a plate and frame heat exchanger, as
developed in [1]_. Reviewed in [2]_, [3]_, [4]_, and [5]_.
... | r'''Calculates the two-phase boiling heat transfer coefficient of a
liquid and gas flowing inside a plate and frame heat exchanger, as
developed in [1]_. Reviewed in [2]_, [3]_, [4]_, and [5]_.
.. math::
h = 1.926\left(\frac{k_l}{D_h}\right) Re_{eq} Pr_l^{1/3} Bo_{eq}^{0.3}
Re^{-0.5}
... | Below is the the instruction that describes the task:
### Input:
r'''Calculates the two-phase boiling heat transfer coefficient of a
liquid and gas flowing inside a plate and frame heat exchanger, as
developed in [1]_. Reviewed in [2]_, [3]_, [4]_, and [5]_.
.. math::
h = 1.926\left(\frac{... |
def generate_captcha(self):
"""Generated a fresh captcha
This method randomly generates a simple captcha question. It then
generates a timestamp for the current time, and signs the answer
cryptographically to protect against tampering and replay attacks.
"""
# Generate a... | Generated a fresh captcha
This method randomly generates a simple captcha question. It then
generates a timestamp for the current time, and signs the answer
cryptographically to protect against tampering and replay attacks. | Below is the the instruction that describes the task:
### Input:
Generated a fresh captcha
This method randomly generates a simple captcha question. It then
generates a timestamp for the current time, and signs the answer
cryptographically to protect against tampering and replay attacks.
##... |
def J(*args, **kwargs):
"""Wrapper around jsonify that sets the Content-Type of the response to
application/vnd.api+json.
"""
response = jsonify(*args, **kwargs)
response.mimetype = 'application/vnd.api+json'
return response | Wrapper around jsonify that sets the Content-Type of the response to
application/vnd.api+json. | Below is the the instruction that describes the task:
### Input:
Wrapper around jsonify that sets the Content-Type of the response to
application/vnd.api+json.
### Response:
def J(*args, **kwargs):
"""Wrapper around jsonify that sets the Content-Type of the response to
application/vnd.api+json.
"""... |
def read(self, size=None):
"""
Read at most ``size`` bytes from the file (less if we hit the end of the
file first). If the ``size`` argument is negative or omitted, read all
the remaining data in the file.
.. note::
``'b'`` mode flag is ignored (``self.FLAG_BINARY`... | Read at most ``size`` bytes from the file (less if we hit the end of the
file first). If the ``size`` argument is negative or omitted, read all
the remaining data in the file.
.. note::
``'b'`` mode flag is ignored (``self.FLAG_BINARY`` in
``self._flags``), because SSH ... | Below is the the instruction that describes the task:
### Input:
Read at most ``size`` bytes from the file (less if we hit the end of the
file first). If the ``size`` argument is negative or omitted, read all
the remaining data in the file.
.. note::
``'b'`` mode flag is ignore... |
def worker_config(queue, s3_key, period, verbose):
"""daemon queue worker for config notifications"""
logging.basicConfig(level=(verbose and logging.DEBUG or logging.INFO))
logging.getLogger('botocore').setLevel(logging.WARNING)
logging.getLogger('s3transfer').setLevel(logging.WARNING)
queue, regio... | daemon queue worker for config notifications | Below is the the instruction that describes the task:
### Input:
daemon queue worker for config notifications
### Response:
def worker_config(queue, s3_key, period, verbose):
"""daemon queue worker for config notifications"""
logging.basicConfig(level=(verbose and logging.DEBUG or logging.INFO))
loggin... |
def reverse_readline(m_file, blk_size=4096, max_mem=4000000):
"""
Generator method to read a file line-by-line, but backwards. This allows
one to efficiently get data at the end of a file.
Based on code by Peter Astrand <astrand@cendio.se>, using modifications by
Raymond Hettinger and Kevin German.... | Generator method to read a file line-by-line, but backwards. This allows
one to efficiently get data at the end of a file.
Based on code by Peter Astrand <astrand@cendio.se>, using modifications by
Raymond Hettinger and Kevin German.
http://code.activestate.com/recipes/439045-read-a-text-file-backwards... | Below is the the instruction that describes the task:
### Input:
Generator method to read a file line-by-line, but backwards. This allows
one to efficiently get data at the end of a file.
Based on code by Peter Astrand <astrand@cendio.se>, using modifications by
Raymond Hettinger and Kevin German.
... |
def rr_cache(max_size=128):
"""
Random Replacement cache decorator, implementing :class:`faste.caches.RRCache`
:keyword int max_size: max cache size
"""
def actual_decorator(func):
return _cached_func(func, caches.RRCache, max_size)
return actual_decorator | Random Replacement cache decorator, implementing :class:`faste.caches.RRCache`
:keyword int max_size: max cache size | Below is the the instruction that describes the task:
### Input:
Random Replacement cache decorator, implementing :class:`faste.caches.RRCache`
:keyword int max_size: max cache size
### Response:
def rr_cache(max_size=128):
"""
Random Replacement cache decorator, implementing :class:`faste.caches.RRCa... |
def makeCustomSpecificationsMapping(func):
'''
Creates the "pickleable" dictionary that will be used with
:data:`~exhale.configs.customSpecificationsMapping` supplied to ``exhale_args`` in
your ``conf.py``.
**Parameters**
``func`` (types.FunctionType)
A callable function that ta... | Creates the "pickleable" dictionary that will be used with
:data:`~exhale.configs.customSpecificationsMapping` supplied to ``exhale_args`` in
your ``conf.py``.
**Parameters**
``func`` (types.FunctionType)
A callable function that takes as input a string from
:data:`~exhale.u... | Below is the the instruction that describes the task:
### Input:
Creates the "pickleable" dictionary that will be used with
:data:`~exhale.configs.customSpecificationsMapping` supplied to ``exhale_args`` in
your ``conf.py``.
**Parameters**
``func`` (types.FunctionType)
A callable fu... |
def help(*args):
"""Prints help."""
from . import commands
parser = argparse.ArgumentParser(prog="%s %s" % (__package__, help.__name__), description=help.__doc__)
parser.add_argument('COMMAND', help="command to show help for", nargs="?", choices=__all__)
args = parser.parse_args(args)
if args.CO... | Prints help. | Below is the the instruction that describes the task:
### Input:
Prints help.
### Response:
def help(*args):
"""Prints help."""
from . import commands
parser = argparse.ArgumentParser(prog="%s %s" % (__package__, help.__name__), description=help.__doc__)
parser.add_argument('COMMAND', help="command... |
def DeserializeTX(buffer):
"""
Deserialize the stream into a Transaction object.
Args:
buffer (BytesIO): stream to deserialize the Transaction from.
Returns:
neo.Core.TX.Transaction:
"""
mstream = MemoryStream(buffer)
reader = BinaryReade... | Deserialize the stream into a Transaction object.
Args:
buffer (BytesIO): stream to deserialize the Transaction from.
Returns:
neo.Core.TX.Transaction: | Below is the the instruction that describes the task:
### Input:
Deserialize the stream into a Transaction object.
Args:
buffer (BytesIO): stream to deserialize the Transaction from.
Returns:
neo.Core.TX.Transaction:
### Response:
def DeserializeTX(buffer):
"""
... |
def parse_status_line(cls, data):
'''Parse the status line bytes.
Returns:
tuple: An tuple representing the version, code, and reason.
'''
match = re.match(
br'(HTTP/\d+\.\d+)[ \t]+([0-9]{1,3})[ \t]*([^\r\n]*)',
data
)
if match:
... | Parse the status line bytes.
Returns:
tuple: An tuple representing the version, code, and reason. | Below is the the instruction that describes the task:
### Input:
Parse the status line bytes.
Returns:
tuple: An tuple representing the version, code, and reason.
### Response:
def parse_status_line(cls, data):
'''Parse the status line bytes.
Returns:
tuple: An tup... |
def get_cmd_epilog(self):
"""
Get the trailing, multi-line description of this command.
:returns:
``self.epilog``, if defined
:returns:
A substring of the class docstring between the string ``@EPILOG``
and the end of the docstring, if defined
... | Get the trailing, multi-line description of this command.
:returns:
``self.epilog``, if defined
:returns:
A substring of the class docstring between the string ``@EPILOG``
and the end of the docstring, if defined
:returns:
None, otherwise
... | Below is the the instruction that describes the task:
### Input:
Get the trailing, multi-line description of this command.
:returns:
``self.epilog``, if defined
:returns:
A substring of the class docstring between the string ``@EPILOG``
and the end of the docstri... |
def add_all_database_reactions(model, compartments):
"""Add all reactions from database that occur in given compartments.
Args:
model: :class:`psamm.metabolicmodel.MetabolicModel`.
"""
added = set()
for rxnid in model.database.reactions:
reaction = model.database.get_reaction(rxnid... | Add all reactions from database that occur in given compartments.
Args:
model: :class:`psamm.metabolicmodel.MetabolicModel`. | Below is the the instruction that describes the task:
### Input:
Add all reactions from database that occur in given compartments.
Args:
model: :class:`psamm.metabolicmodel.MetabolicModel`.
### Response:
def add_all_database_reactions(model, compartments):
"""Add all reactions from database that o... |
def get_redirect_args(self, request, callback):
"""Get request parameters for redirect url."""
callback = force_text(request.build_absolute_uri(callback))
raw_token = self.get_request_token(request, callback)
token, secret, _ = self.parse_raw_token(raw_token)
if token is not None... | Get request parameters for redirect url. | Below is the the instruction that describes the task:
### Input:
Get request parameters for redirect url.
### Response:
def get_redirect_args(self, request, callback):
"""Get request parameters for redirect url."""
callback = force_text(request.build_absolute_uri(callback))
raw_token = self... |
def parse_secondary_types(self, request):
"""
Return secondary event types that occurrences must belong to, or `None`
if there is no constraint on secondary type.
"""
if request.GET.getlist('secondary_types'):
return EventType.objects.filter(
slug__in=... | Return secondary event types that occurrences must belong to, or `None`
if there is no constraint on secondary type. | Below is the the instruction that describes the task:
### Input:
Return secondary event types that occurrences must belong to, or `None`
if there is no constraint on secondary type.
### Response:
def parse_secondary_types(self, request):
"""
Return secondary event types that occurrences mus... |
def select(cls, **context):
"""
Selects records for the class based on the inputted \
options. If no db is specified, then the current \
global database will be used. If the inflated flag is specified, then \
the results will be inflated to class instances.
If the flag... | Selects records for the class based on the inputted \
options. If no db is specified, then the current \
global database will be used. If the inflated flag is specified, then \
the results will be inflated to class instances.
If the flag is left as None, then results will be auto-infl... | Below is the the instruction that describes the task:
### Input:
Selects records for the class based on the inputted \
options. If no db is specified, then the current \
global database will be used. If the inflated flag is specified, then \
the results will be inflated to class instances.... |
def get_comments(self, sharekey=None):
"""
Retrieve comments on a SharedFile
Args:
sharekey (str): Sharekey for the file from which you want to return
the set of comments.
Returns:
List of Comment objects.
"""
if not sharekey:
... | Retrieve comments on a SharedFile
Args:
sharekey (str): Sharekey for the file from which you want to return
the set of comments.
Returns:
List of Comment objects. | Below is the the instruction that describes the task:
### Input:
Retrieve comments on a SharedFile
Args:
sharekey (str): Sharekey for the file from which you want to return
the set of comments.
Returns:
List of Comment objects.
### Response:
def get_comment... |
def get_all(resource):
''' Return all of a single resource '''
QUERYSETS = {
settings.PEOPLE: PeopleQuerySet,
settings.PLANETS: PlanetQuerySet,
settings.STARSHIPS: StarshipQuerySet,
settings.VEHICLES: VehicleQuerySet,
settings.SPECIES: SpeciesQuerySet,
settings.FI... | Return all of a single resource | Below is the the instruction that describes the task:
### Input:
Return all of a single resource
### Response:
def get_all(resource):
''' Return all of a single resource '''
QUERYSETS = {
settings.PEOPLE: PeopleQuerySet,
settings.PLANETS: PlanetQuerySet,
settings.STARSHIPS: Starship... |
def zoom_out_frag(self, curr_frag):
"""
:param curr_frag:
"""
level = curr_frag[1]
frag = curr_frag[0]
output = []
if level > 0:
str_level = str(level)
high_frag = self.spec_level[str_level]["fragments_dict"][frag][
"super_i... | :param curr_frag: | Below is the the instruction that describes the task:
### Input:
:param curr_frag:
### Response:
def zoom_out_frag(self, curr_frag):
"""
:param curr_frag:
"""
level = curr_frag[1]
frag = curr_frag[0]
output = []
if level > 0:
str_level = str(level... |
def escape_quotes(self, val):
"""
Escape any quotes in a value
"""
if self.is_string(val) and self._in_quotes(val, self.quote):
# make sure any previously escaped quotes are not re-escaped
middle = self.remove_quotes(val).replace("\\" + self.quote, self.quote)
... | Escape any quotes in a value | Below is the the instruction that describes the task:
### Input:
Escape any quotes in a value
### Response:
def escape_quotes(self, val):
"""
Escape any quotes in a value
"""
if self.is_string(val) and self._in_quotes(val, self.quote):
# make sure any previously escaped ... |
def check_pre_approval_notification(self, code):
""" check a notification by its code """
response = self.get(
url=self.config.PRE_APPROVAL_NOTIFICATION_URL % code)
return PagSeguroPreApprovalNotificationResponse(
response.content, self.config) | check a notification by its code | Below is the the instruction that describes the task:
### Input:
check a notification by its code
### Response:
def check_pre_approval_notification(self, code):
""" check a notification by its code """
response = self.get(
url=self.config.PRE_APPROVAL_NOTIFICATION_URL % code)
re... |
def insert_dict(self, value_dict, commit=False):
"""
Execute an INSERT statement using a python dict
:value_dict: A dictionary representing all the columns(keys) and
values that should be part of the INSERT statement
:commit: Whether to automatically commit the t... | Execute an INSERT statement using a python dict
:value_dict: A dictionary representing all the columns(keys) and
values that should be part of the INSERT statement
:commit: Whether to automatically commit the transaction
:returns: Psycopg2 result | Below is the the instruction that describes the task:
### Input:
Execute an INSERT statement using a python dict
:value_dict: A dictionary representing all the columns(keys) and
values that should be part of the INSERT statement
:commit: Whether to automatically commit the tr... |
def dispatch(self, receiver):
''' Dispatch handling of this event to a receiver.
This method will invoke ``receiver._columns_streamed`` if it exists.
'''
super(ColumnsStreamedEvent, self).dispatch(receiver)
if hasattr(receiver, '_columns_streamed'):
receiver._column... | Dispatch handling of this event to a receiver.
This method will invoke ``receiver._columns_streamed`` if it exists. | Below is the the instruction that describes the task:
### Input:
Dispatch handling of this event to a receiver.
This method will invoke ``receiver._columns_streamed`` if it exists.
### Response:
def dispatch(self, receiver):
''' Dispatch handling of this event to a receiver.
This method w... |
def dead(name,
enable=None,
sig=None,
init_delay=None,
**kwargs):
'''
Ensure that the named service is dead by stopping the service if it is running
name
The name of the init or rc script used to manage the service
enable
Set the service to be enable... | Ensure that the named service is dead by stopping the service if it is running
name
The name of the init or rc script used to manage the service
enable
Set the service to be enabled at boot time, ``True`` sets the service
to be enabled, ``False`` sets the named service to be disabled. ... | Below is the the instruction that describes the task:
### Input:
Ensure that the named service is dead by stopping the service if it is running
name
The name of the init or rc script used to manage the service
enable
Set the service to be enabled at boot time, ``True`` sets the service
... |
def service_name_from_scope_name(scope_name):
"""Translate scope name to service name which can be used in dns.
230 = 253 - len('replica.') - len('.service.consul')
"""
def replace_char(match):
c = match.group(0)
return '-' if c in '. _' else "u{:04d}".format(ord(c))
service_name ... | Translate scope name to service name which can be used in dns.
230 = 253 - len('replica.') - len('.service.consul') | Below is the the instruction that describes the task:
### Input:
Translate scope name to service name which can be used in dns.
230 = 253 - len('replica.') - len('.service.consul')
### Response:
def service_name_from_scope_name(scope_name):
"""Translate scope name to service name which can be used in dns.... |
def dump_with_fn(dump_fn, data, stream, **options):
"""
Dump 'data' to a string if 'stream' is None, or dump 'data' to a file or
file-like object 'stream'.
:param dump_fn: Callable to dump data
:param data: Data to dump
:param stream: File or file like object or None
:param options: option... | Dump 'data' to a string if 'stream' is None, or dump 'data' to a file or
file-like object 'stream'.
:param dump_fn: Callable to dump data
:param data: Data to dump
:param stream: File or file like object or None
:param options: optional keyword parameters
:return: String represents data if st... | Below is the the instruction that describes the task:
### Input:
Dump 'data' to a string if 'stream' is None, or dump 'data' to a file or
file-like object 'stream'.
:param dump_fn: Callable to dump data
:param data: Data to dump
:param stream: File or file like object or None
:param options: o... |
def _render_name(self):
"""Render data name.
The rendering is based on name template (`process.data_name`) and
input context.
"""
if not self.process.data_name or self.named_by_user: # pylint: disable=no-member
return
inputs = copy.deepcopy(self.input)
... | Render data name.
The rendering is based on name template (`process.data_name`) and
input context. | Below is the the instruction that describes the task:
### Input:
Render data name.
The rendering is based on name template (`process.data_name`) and
input context.
### Response:
def _render_name(self):
"""Render data name.
The rendering is based on name template (`process.data_nam... |
def _push_condition(predicate):
"""As we enter new conditions, this pushes them on the predicate stack."""
global _depth
_check_under_condition()
_depth += 1
if predicate is not otherwise and len(predicate) > 1:
raise PyrtlError('all predicates for conditional assignments must wirevectors of... | As we enter new conditions, this pushes them on the predicate stack. | Below is the the instruction that describes the task:
### Input:
As we enter new conditions, this pushes them on the predicate stack.
### Response:
def _push_condition(predicate):
"""As we enter new conditions, this pushes them on the predicate stack."""
global _depth
_check_under_condition()
_dept... |
def run_class(class_name, args=None, properties=None, classpath=None,
hadoop_conf_dir=None, logger=None, keep_streams=True):
"""
Run a Java class with Hadoop (equivalent of running ``hadoop
<class_name>`` from the command line).
Additional ``HADOOP_CLASSPATH`` elements can be provided via... | Run a Java class with Hadoop (equivalent of running ``hadoop
<class_name>`` from the command line).
Additional ``HADOOP_CLASSPATH`` elements can be provided via
``classpath`` (either as a non-string sequence where each element
is a classpath element or as a ``':'``-separated string). Other
argumen... | Below is the the instruction that describes the task:
### Input:
Run a Java class with Hadoop (equivalent of running ``hadoop
<class_name>`` from the command line).
Additional ``HADOOP_CLASSPATH`` elements can be provided via
``classpath`` (either as a non-string sequence where each element
is a cl... |
def update_course(self, course, enterprise_customer, enterprise_context):
"""
Update course metadata of the given course and return updated course.
Arguments:
course (dict): Course Metadata returned by course catalog API
enterprise_customer (EnterpriseCustomer): enterpri... | Update course metadata of the given course and return updated course.
Arguments:
course (dict): Course Metadata returned by course catalog API
enterprise_customer (EnterpriseCustomer): enterprise customer instance.
enterprise_context (dict): Enterprise context to be added to... | Below is the the instruction that describes the task:
### Input:
Update course metadata of the given course and return updated course.
Arguments:
course (dict): Course Metadata returned by course catalog API
enterprise_customer (EnterpriseCustomer): enterprise customer instance.
... |
def image(self, data, cmap='cubehelix', clim='auto', fg_color=None):
"""Show an image
Parameters
----------
data : ndarray
Should have shape (N, M), (N, M, 3) or (N, M, 4).
cmap : str
Colormap name.
clim : str | tuple
Colormap limits. ... | Show an image
Parameters
----------
data : ndarray
Should have shape (N, M), (N, M, 3) or (N, M, 4).
cmap : str
Colormap name.
clim : str | tuple
Colormap limits. Should be ``'auto'`` or a two-element tuple of
min and max values.
... | Below is the the instruction that describes the task:
### Input:
Show an image
Parameters
----------
data : ndarray
Should have shape (N, M), (N, M, 3) or (N, M, 4).
cmap : str
Colormap name.
clim : str | tuple
Colormap limits. Should be `... |
def main():
"""The main function of the script"""
desc = 'Generate files to benchmark'
parser = argparse.ArgumentParser(description=desc)
parser.add_argument(
'--src',
dest='src_dir',
default='src',
help='The directory containing the templates'
)
parser.add_argume... | The main function of the script | Below is the the instruction that describes the task:
### Input:
The main function of the script
### Response:
def main():
"""The main function of the script"""
desc = 'Generate files to benchmark'
parser = argparse.ArgumentParser(description=desc)
parser.add_argument(
'--src',
dest... |
def _fix_perms(perm_obj):
"""
:param perm_obj: A permissions object, as given by os.stat()
:type perm_obj: integer
:returns: A permissions object that is the result of "chmod a+rX" on the
given permission object. This is defined to be the permission object
bitwise or-ed with... | :param perm_obj: A permissions object, as given by os.stat()
:type perm_obj: integer
:returns: A permissions object that is the result of "chmod a+rX" on the
given permission object. This is defined to be the permission object
bitwise or-ed with all stat.S_IR*, and if the stat.S_IXU... | Below is the the instruction that describes the task:
### Input:
:param perm_obj: A permissions object, as given by os.stat()
:type perm_obj: integer
:returns: A permissions object that is the result of "chmod a+rX" on the
given permission object. This is defined to be the permission object
... |
def search_blogs(q, start=0, wait=10, asynchronous=False, cached=False):
""" Returns a Google blogs query formatted as a GoogleSearch list object.
"""
service = GOOGLE_BLOGS
return GoogleSearch(q, start, service, "", wait, asynchronous, cached) | Returns a Google blogs query formatted as a GoogleSearch list object. | Below is the the instruction that describes the task:
### Input:
Returns a Google blogs query formatted as a GoogleSearch list object.
### Response:
def search_blogs(q, start=0, wait=10, asynchronous=False, cached=False):
""" Returns a Google blogs query formatted as a GoogleSearch list object.
"""
... |
def accelerator_experiments(self, key, value):
"""Populate the ``accelerator_experiments`` key."""
result = []
a_value = force_single_element(value.get('a'))
e_values = [el for el in force_list(value.get('e')) if el != '-']
zero_values = force_list(value.get('0'))
if a_value and not e_values:
... | Populate the ``accelerator_experiments`` key. | Below is the the instruction that describes the task:
### Input:
Populate the ``accelerator_experiments`` key.
### Response:
def accelerator_experiments(self, key, value):
"""Populate the ``accelerator_experiments`` key."""
result = []
a_value = force_single_element(value.get('a'))
e_values = [el ... |
def execute(self):
"""Execute the PEX.
This function makes assumptions that it is the last function called by
the interpreter.
"""
teardown_verbosity = self._vars.PEX_TEARDOWN_VERBOSE
try:
pex_inherit_path = self._vars.PEX_INHERIT_PATH
if pex_inherit_path == "false":
pex_inh... | Execute the PEX.
This function makes assumptions that it is the last function called by
the interpreter. | Below is the the instruction that describes the task:
### Input:
Execute the PEX.
This function makes assumptions that it is the last function called by
the interpreter.
### Response:
def execute(self):
"""Execute the PEX.
This function makes assumptions that it is the last function called by
... |
def parse_vmware_file(path):
"""
Parses a VMware file (VMX, preferences or inventory).
:param path: path to the VMware file
:returns: dict
"""
pairs = OrderedDict()
encoding = "utf-8"
# get the first line to read the .encoding value
with open(pa... | Parses a VMware file (VMX, preferences or inventory).
:param path: path to the VMware file
:returns: dict | Below is the the instruction that describes the task:
### Input:
Parses a VMware file (VMX, preferences or inventory).
:param path: path to the VMware file
:returns: dict
### Response:
def parse_vmware_file(path):
"""
Parses a VMware file (VMX, preferences or inventory).
... |
def master_pub(self):
'''
Return the master publish port
'''
return _get_master_uri(self.opts['master_ip'],
self.publish_port,
source_ip=self.opts.get('source_ip'),
source_port=self.opts.get('sou... | Return the master publish port | Below is the the instruction that describes the task:
### Input:
Return the master publish port
### Response:
def master_pub(self):
'''
Return the master publish port
'''
return _get_master_uri(self.opts['master_ip'],
self.publish_port,
... |
def Overlay_setSuspended(self, suspended):
"""
Function path: Overlay.setSuspended
Domain: Overlay
Method name: setSuspended
Parameters:
Required arguments:
'suspended' (type: boolean) -> Whether overlay should be suspended and not consume any resources until resumed.
No return value.
"... | Function path: Overlay.setSuspended
Domain: Overlay
Method name: setSuspended
Parameters:
Required arguments:
'suspended' (type: boolean) -> Whether overlay should be suspended and not consume any resources until resumed.
No return value. | Below is the the instruction that describes the task:
### Input:
Function path: Overlay.setSuspended
Domain: Overlay
Method name: setSuspended
Parameters:
Required arguments:
'suspended' (type: boolean) -> Whether overlay should be suspended and not consume any resources until resumed.
No re... |
def _fetchAllChildren(self):
""" Fetches all fields that this variable contains.
Only variables with a structured data type can have fields.
"""
assert self.canFetchChildren(), "canFetchChildren must be True"
childItems = []
# Add fields
if self._isStructure... | Fetches all fields that this variable contains.
Only variables with a structured data type can have fields. | Below is the the instruction that describes the task:
### Input:
Fetches all fields that this variable contains.
Only variables with a structured data type can have fields.
### Response:
def _fetchAllChildren(self):
""" Fetches all fields that this variable contains.
Only variables ... |
def _get_base(group, **conn):
"""Fetch the base IAM Group."""
group['_version'] = 1
# Get the initial group details (only needed if we didn't grab the users):
group.update(get_group_api(group['GroupName'], users=False, **conn)['Group'])
# Cast CreateDate from a datetime to something JSON serializa... | Fetch the base IAM Group. | Below is the the instruction that describes the task:
### Input:
Fetch the base IAM Group.
### Response:
def _get_base(group, **conn):
"""Fetch the base IAM Group."""
group['_version'] = 1
# Get the initial group details (only needed if we didn't grab the users):
group.update(get_group_api(group['... |
def apply_docstr(docstr_func):
"""
Changes docstr of one functio to that of another
"""
def docstr_applier(func):
#docstr = meta_util_six.get_funcdoc(docstr_func)
#meta_util_six.set_funcdoc(func, docstr)
if isinstance(docstr_func, six.string_types):
olddoc = meta_util... | Changes docstr of one functio to that of another | Below is the the instruction that describes the task:
### Input:
Changes docstr of one functio to that of another
### Response:
def apply_docstr(docstr_func):
"""
Changes docstr of one functio to that of another
"""
def docstr_applier(func):
#docstr = meta_util_six.get_funcdoc(docstr_func)
... |
def available_edbg_ports(self):
"""
Finds available EDBG COM ports.
:return: list of available ports
"""
ports_available = sorted(list(list_ports.comports()))
edbg_ports = []
for iport in ports_available:
port = iport[0]
desc = iport[1]
... | Finds available EDBG COM ports.
:return: list of available ports | Below is the the instruction that describes the task:
### Input:
Finds available EDBG COM ports.
:return: list of available ports
### Response:
def available_edbg_ports(self):
"""
Finds available EDBG COM ports.
:return: list of available ports
"""
ports_available ... |
def base64_b64encode(instr):
'''
Encode a string as base64 using the "modern" Python interface.
Among other possible differences, the "modern" encoder does not include
newline ('\\n') characters in the encoded output.
'''
return salt.utils.stringutils.to_unicode(
base64.b64encode(salt.u... | Encode a string as base64 using the "modern" Python interface.
Among other possible differences, the "modern" encoder does not include
newline ('\\n') characters in the encoded output. | Below is the the instruction that describes the task:
### Input:
Encode a string as base64 using the "modern" Python interface.
Among other possible differences, the "modern" encoder does not include
newline ('\\n') characters in the encoded output.
### Response:
def base64_b64encode(instr):
'''
E... |
def get(self, request, format=None):
"""
Get list of bots
---
serializer: BotSerializer
responseMessages:
- code: 401
message: Not authenticated
"""
bots = Bot.objects.filter(owner=request.user)
serializer = BotSerializer(bots, ma... | Get list of bots
---
serializer: BotSerializer
responseMessages:
- code: 401
message: Not authenticated | Below is the the instruction that describes the task:
### Input:
Get list of bots
---
serializer: BotSerializer
responseMessages:
- code: 401
message: Not authenticated
### Response:
def get(self, request, format=None):
"""
Get list of bots
... |
def validate_user_email(self, value):
"""
Validates the user_email, if given, to see if an existing EnterpriseCustomerUser exists for it.
If it does not, it does not fail validation, unlike for the other field validation methods above.
"""
enterprise_customer = self.context.get(... | Validates the user_email, if given, to see if an existing EnterpriseCustomerUser exists for it.
If it does not, it does not fail validation, unlike for the other field validation methods above. | Below is the the instruction that describes the task:
### Input:
Validates the user_email, if given, to see if an existing EnterpriseCustomerUser exists for it.
If it does not, it does not fail validation, unlike for the other field validation methods above.
### Response:
def validate_user_email(self, val... |
def emit(self, key, value):
"""\
Handle an output key/value pair.
Reporting progress is strictly necessary only when using a Python
record writer, because sending an output key/value pair is an implicit
progress report. To take advantage of this, however, we would be
for... | \
Handle an output key/value pair.
Reporting progress is strictly necessary only when using a Python
record writer, because sending an output key/value pair is an implicit
progress report. To take advantage of this, however, we would be
forced to flush the uplink stream at every... | Below is the the instruction that describes the task:
### Input:
\
Handle an output key/value pair.
Reporting progress is strictly necessary only when using a Python
record writer, because sending an output key/value pair is an implicit
progress report. To take advantage of this, ho... |
def putURL(self, url, headers, body=None):
"""
Request a URL using the HTTP method PUT.
"""
return self._load_resource("PUT", url, headers, body) | Request a URL using the HTTP method PUT. | Below is the the instruction that describes the task:
### Input:
Request a URL using the HTTP method PUT.
### Response:
def putURL(self, url, headers, body=None):
"""
Request a URL using the HTTP method PUT.
"""
return self._load_resource("PUT", url, headers, body) |
def get_node_size(node):
"""
Get size of memory on C{node}.
@param node: node idx
@type node: C{int}
@return: free memory/total memory
@rtype: C{tuple}(C{int}, C{int})
"""
free = c_longlong()
if node < 0 or node > get_max_node():
raise ValueError(node)
size = libnuma.... | Get size of memory on C{node}.
@param node: node idx
@type node: C{int}
@return: free memory/total memory
@rtype: C{tuple}(C{int}, C{int}) | Below is the the instruction that describes the task:
### Input:
Get size of memory on C{node}.
@param node: node idx
@type node: C{int}
@return: free memory/total memory
@rtype: C{tuple}(C{int}, C{int})
### Response:
def get_node_size(node):
"""
Get size of memory on C{node}.
@param ... |
def setup_website_module(self, command):
"""Create stacker configuration for website module."""
name = self.options.get('name') if self.options.get('name') else self.options.get('path') # noqa pylint: disable=line-too-long
ensure_valid_environment_config(
name,
self.opti... | Create stacker configuration for website module. | Below is the the instruction that describes the task:
### Input:
Create stacker configuration for website module.
### Response:
def setup_website_module(self, command):
"""Create stacker configuration for website module."""
name = self.options.get('name') if self.options.get('name') else self.optio... |
def _find_input_files(var, out):
"""Find input files within the given CWL object.
"""
if isinstance(var, (list, tuple)):
for x in var:
out = _find_input_files(x, out)
elif isinstance(var, dict):
if var.get("class") == "File":
out.append(var["path"])
ou... | Find input files within the given CWL object. | Below is the the instruction that describes the task:
### Input:
Find input files within the given CWL object.
### Response:
def _find_input_files(var, out):
"""Find input files within the given CWL object.
"""
if isinstance(var, (list, tuple)):
for x in var:
out = _find_input_files... |
def __as_list(value: List[JsonObjTypes]) -> List[JsonTypes]:
""" Return a json array as a list
:param value: array
:return: array with JsonObj instances removed
"""
return [e._as_dict if isinstance(e, JsonObj) else e for e in value] | Return a json array as a list
:param value: array
:return: array with JsonObj instances removed | Below is the the instruction that describes the task:
### Input:
Return a json array as a list
:param value: array
:return: array with JsonObj instances removed
### Response:
def __as_list(value: List[JsonObjTypes]) -> List[JsonTypes]:
""" Return a json array as a list
:param valu... |
def find_comments(fname, ch):
"""
Find the comments for a function.
fname: filename
ch: CppHeaderParser parse tree
The function must look like
/*
* comments
* comments
*/
template<class I, ...>
void somefunc(...){
-or-
/*
* comments
* comments
... | Find the comments for a function.
fname: filename
ch: CppHeaderParser parse tree
The function must look like
/*
* comments
* comments
*/
template<class I, ...>
void somefunc(...){
-or-
/*
* comments
* comments
*/
void somefunc(...){
-or-
... | Below is the the instruction that describes the task:
### Input:
Find the comments for a function.
fname: filename
ch: CppHeaderParser parse tree
The function must look like
/*
* comments
* comments
*/
template<class I, ...>
void somefunc(...){
-or-
/*
* co... |
def guess_payload_class(self, payload):
# type: (str) -> base_classes.Packet_metaclass
""" guess_payload_class returns the Class object to use for parsing a payload
This function uses the H2Frame.type field value to decide which payload to parse. The implement cannot be # noqa: E501
per... | guess_payload_class returns the Class object to use for parsing a payload
This function uses the H2Frame.type field value to decide which payload to parse. The implement cannot be # noqa: E501
performed using the simple bind_layers helper because sometimes the selection of which Class object to return ... | Below is the the instruction that describes the task:
### Input:
guess_payload_class returns the Class object to use for parsing a payload
This function uses the H2Frame.type field value to decide which payload to parse. The implement cannot be # noqa: E501
performed using the simple bind_layers he... |
def GamePlayFinder(**kwargs):
""" Docstring will be filled in by __init__.py """
querystring = _kwargs_to_qs(**kwargs)
url = '{}?{}'.format(GPF_URL, querystring)
# if verbose, print url
if kwargs.get('verbose', False):
print(url)
html = utils.get_html(url)
doc = pq(html)
# pars... | Docstring will be filled in by __init__.py | Below is the the instruction that describes the task:
### Input:
Docstring will be filled in by __init__.py
### Response:
def GamePlayFinder(**kwargs):
""" Docstring will be filled in by __init__.py """
querystring = _kwargs_to_qs(**kwargs)
url = '{}?{}'.format(GPF_URL, querystring)
# if verbose, ... |
def map_expression(expr):
"""
Returns a function that maps a dict to a new dict with unique keys and
values, kind of like a SQL SELECT clause, e.g.:
>>> map_expression("foo=bar")({'bar': 1})
{'foo': 1}
>>> map_expression("foo=bar+1")({'bar': 1})
{'foo': 2}
"""
if callable(expr):
... | Returns a function that maps a dict to a new dict with unique keys and
values, kind of like a SQL SELECT clause, e.g.:
>>> map_expression("foo=bar")({'bar': 1})
{'foo': 1}
>>> map_expression("foo=bar+1")({'bar': 1})
{'foo': 2} | Below is the the instruction that describes the task:
### Input:
Returns a function that maps a dict to a new dict with unique keys and
values, kind of like a SQL SELECT clause, e.g.:
>>> map_expression("foo=bar")({'bar': 1})
{'foo': 1}
>>> map_expression("foo=bar+1")({'bar': 1})
{'foo': 2}
###... |
def write_globalattrs(self, globalAttrs):
'''
Writes the global attributes.
Parameters
----------
globalAttrs: dict
Global attribute name(s) and their value(s) pair(s).
The value(s) is a dictionary of entry number and value pair(s).
For examp... | Writes the global attributes.
Parameters
----------
globalAttrs: dict
Global attribute name(s) and their value(s) pair(s).
The value(s) is a dictionary of entry number and value pair(s).
For example::
globalAttrs={}
globalAtt... | Below is the the instruction that describes the task:
### Input:
Writes the global attributes.
Parameters
----------
globalAttrs: dict
Global attribute name(s) and their value(s) pair(s).
The value(s) is a dictionary of entry number and value pair(s).
Fo... |
def import_(path):
"""
Import string format module, e.g. 'uliweb.orm' or an object
return module object and object
"""
if isinstance(path, str):
v = path.split(':')
if len(v) == 1:
x = path.rsplit('.', 1)
if len(x) == 2:
module, func = x
... | Import string format module, e.g. 'uliweb.orm' or an object
return module object and object | Below is the the instruction that describes the task:
### Input:
Import string format module, e.g. 'uliweb.orm' or an object
return module object and object
### Response:
def import_(path):
"""
Import string format module, e.g. 'uliweb.orm' or an object
return module object and object
"""
i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.