code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def update_free_shipping_coupon_by_id(cls, free_shipping_coupon_id, free_shipping_coupon, **kwargs):
"""Update FreeShippingCoupon
Update attributes of FreeShippingCoupon
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True... | Update FreeShippingCoupon
Update attributes of FreeShippingCoupon
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_free_shipping_coupon_by_id(free_shipping_coupon_id, free_shipping_coupon, async... | Below is the the instruction that describes the task:
### Input:
Update FreeShippingCoupon
Update attributes of FreeShippingCoupon
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_free_shipp... |
def insert_statement(table, columns, values):
"""Generate an insert statement string for dumping to text file or MySQL execution."""
if not all(isinstance(r, (list, set, tuple)) for r in values):
values = [[r] for r in values]
rows = []
for row in values:
new_row = []
for col in ... | Generate an insert statement string for dumping to text file or MySQL execution. | Below is the the instruction that describes the task:
### Input:
Generate an insert statement string for dumping to text file or MySQL execution.
### Response:
def insert_statement(table, columns, values):
"""Generate an insert statement string for dumping to text file or MySQL execution."""
if not all(isi... |
def get_edit_handler(self):
'''TODO: Fix add-to-field'''
# just a flag
self.generic = 'false'
return '''
<span class="input-group-btn">
<a href="#" id="item-edit-%(id)s" data-add-to-field="id_file" class="btn btn-default disabled"><span class="fa fa-pencil"></span><... | TODO: Fix add-to-field | Below is the the instruction that describes the task:
### Input:
TODO: Fix add-to-field
### Response:
def get_edit_handler(self):
'''TODO: Fix add-to-field'''
# just a flag
self.generic = 'false'
return '''
<span class="input-group-btn">
<a href="#" id="item-ed... |
def create_service_network(self, tenant_name, network, subnet,
dhcp_range=True):
"""Create network on the DCNM.
:param tenant_name: name of tenant the network belongs to
:param network: network parameters
:param subnet: subnet parameters of the network
... | Create network on the DCNM.
:param tenant_name: name of tenant the network belongs to
:param network: network parameters
:param subnet: subnet parameters of the network | Below is the the instruction that describes the task:
### Input:
Create network on the DCNM.
:param tenant_name: name of tenant the network belongs to
:param network: network parameters
:param subnet: subnet parameters of the network
### Response:
def create_service_network(self, tenant_na... |
def canonical_name(sgf_name):
"""Keep filename and some date folders"""
sgf_name = os.path.normpath(sgf_name)
assert sgf_name.endswith('.sgf'), sgf_name
# Strip off '.sgf'
sgf_name = sgf_name[:-4]
# Often eval is inside a folder with the run name.
# include from folder before /eval/ if part... | Keep filename and some date folders | Below is the the instruction that describes the task:
### Input:
Keep filename and some date folders
### Response:
def canonical_name(sgf_name):
"""Keep filename and some date folders"""
sgf_name = os.path.normpath(sgf_name)
assert sgf_name.endswith('.sgf'), sgf_name
# Strip off '.sgf'
sgf_name... |
def Cmatrix(x, y, sx, sy, theta):
"""
Construct a correlation matrix corresponding to the data.
The matrix assumes a gaussian correlation function.
Parameters
----------
x, y : array-like
locations at which to evaluate the correlation matirx
sx, sy : float
major/minor axes o... | Construct a correlation matrix corresponding to the data.
The matrix assumes a gaussian correlation function.
Parameters
----------
x, y : array-like
locations at which to evaluate the correlation matirx
sx, sy : float
major/minor axes of the gaussian correlation function (sigmas)
... | Below is the the instruction that describes the task:
### Input:
Construct a correlation matrix corresponding to the data.
The matrix assumes a gaussian correlation function.
Parameters
----------
x, y : array-like
locations at which to evaluate the correlation matirx
sx, sy : float
... |
def fromvector(cls, v):
"""Initialize from euclidean vector"""
w = v.normalized()
return cls(w.x, w.y, w.z) | Initialize from euclidean vector | Below is the the instruction that describes the task:
### Input:
Initialize from euclidean vector
### Response:
def fromvector(cls, v):
"""Initialize from euclidean vector"""
w = v.normalized()
return cls(w.x, w.y, w.z) |
def index_to_widget(self, idx):
"""Returns child corresponding to `idx`"""
nchild = self.mdi_w.get_nth_page(idx)
return self._native_to_child(nchild) | Returns child corresponding to `idx` | Below is the the instruction that describes the task:
### Input:
Returns child corresponding to `idx`
### Response:
def index_to_widget(self, idx):
"""Returns child corresponding to `idx`"""
nchild = self.mdi_w.get_nth_page(idx)
return self._native_to_child(nchild) |
def __clean_rouge_args(self, rouge_args):
"""
Remove enclosing quotation marks, if any.
"""
if not rouge_args:
return
quot_mark_pattern = re.compile('"(.+)"')
match = quot_mark_pattern.match(rouge_args)
if match:
cleaned_args = match.group... | Remove enclosing quotation marks, if any. | Below is the the instruction that describes the task:
### Input:
Remove enclosing quotation marks, if any.
### Response:
def __clean_rouge_args(self, rouge_args):
"""
Remove enclosing quotation marks, if any.
"""
if not rouge_args:
return
quot_mark_pattern = re.... |
def get_class(self, name):
"""
Return a specific class
:param name: the name of the class
:rtype: a :class:`ClassDefItem` object
"""
for i in self.get_classes():
if i.get_name() == name:
return i
return None | Return a specific class
:param name: the name of the class
:rtype: a :class:`ClassDefItem` object | Below is the the instruction that describes the task:
### Input:
Return a specific class
:param name: the name of the class
:rtype: a :class:`ClassDefItem` object
### Response:
def get_class(self, name):
"""
Return a specific class
:param name: the name of the class
... |
def to_dictionary(self):
"""Serialize an object into dictionary form. Useful if you have to
serialize an array of objects into JSON. Otherwise, if you call the
:meth:`to_json` method on each object in the list and then try to
dump the array, you end up with an array with one string."""... | Serialize an object into dictionary form. Useful if you have to
serialize an array of objects into JSON. Otherwise, if you call the
:meth:`to_json` method on each object in the list and then try to
dump the array, you end up with an array with one string. | Below is the the instruction that describes the task:
### Input:
Serialize an object into dictionary form. Useful if you have to
serialize an array of objects into JSON. Otherwise, if you call the
:meth:`to_json` method on each object in the list and then try to
dump the array, you end up ... |
def keybinding(attr):
"""Return keybinding"""
ks = getattr(QKeySequence, attr)
return from_qvariant(QKeySequence.keyBindings(ks)[0], str) | Return keybinding | Below is the the instruction that describes the task:
### Input:
Return keybinding
### Response:
def keybinding(attr):
"""Return keybinding"""
ks = getattr(QKeySequence, attr)
return from_qvariant(QKeySequence.keyBindings(ks)[0], str) |
def get_settings(self):
"""Returns a mapping of UID -> setting
"""
settings = self.context.getAnalysisServicesSettings()
mapping = dict(map(lambda s: (s.get("uid"), s), settings))
return mapping | Returns a mapping of UID -> setting | Below is the the instruction that describes the task:
### Input:
Returns a mapping of UID -> setting
### Response:
def get_settings(self):
"""Returns a mapping of UID -> setting
"""
settings = self.context.getAnalysisServicesSettings()
mapping = dict(map(lambda s: (s.get("uid"), s),... |
def similarity(self, other):
"""Get similarity as a ratio of the two texts."""
ratio = SequenceMatcher(a=self.value, b=other.value).ratio()
similarity = self.Similarity(ratio)
return similarity | Get similarity as a ratio of the two texts. | Below is the the instruction that describes the task:
### Input:
Get similarity as a ratio of the two texts.
### Response:
def similarity(self, other):
"""Get similarity as a ratio of the two texts."""
ratio = SequenceMatcher(a=self.value, b=other.value).ratio()
similarity = self.Similarity... |
def get_subparser(parser, command):
'''
Retrieve the given subparser from parser
'''
# pylint: disable=protected-access
subparsers_actions = [action for action in parser._actions
if isinstance(action, argparse._SubParsersAction)]
# there will probably only be one subparser_action,
... | Retrieve the given subparser from parser | Below is the the instruction that describes the task:
### Input:
Retrieve the given subparser from parser
### Response:
def get_subparser(parser, command):
'''
Retrieve the given subparser from parser
'''
# pylint: disable=protected-access
subparsers_actions = [action for action in parser._actions
... |
def to_query(self):
"""
Returns a json-serializable representation.
"""
query = {}
for field_instance in self.fields:
query.update(field_instance.to_query())
return query | Returns a json-serializable representation. | Below is the the instruction that describes the task:
### Input:
Returns a json-serializable representation.
### Response:
def to_query(self):
"""
Returns a json-serializable representation.
"""
query = {}
for field_instance in self.fields:
query.update(field_in... |
def potcar_symbols(self):
"""
List of POTCAR symbols.
"""
elements = self.poscar.site_symbols
potcar_symbols = []
settings = self._config_dict["POTCAR"]
if isinstance(settings[elements[-1]], dict):
for el in elements:
potcar_symbols.ap... | List of POTCAR symbols. | Below is the the instruction that describes the task:
### Input:
List of POTCAR symbols.
### Response:
def potcar_symbols(self):
"""
List of POTCAR symbols.
"""
elements = self.poscar.site_symbols
potcar_symbols = []
settings = self._config_dict["POTCAR"]
if... |
def write_image_to_disk(self, msg, result, fh):
"""Decode message to PNG and write to disk."""
cairosvg.svg2png(bytestring=msg.encode('utf-8'), write_to=fh) | Decode message to PNG and write to disk. | Below is the the instruction that describes the task:
### Input:
Decode message to PNG and write to disk.
### Response:
def write_image_to_disk(self, msg, result, fh):
"""Decode message to PNG and write to disk."""
cairosvg.svg2png(bytestring=msg.encode('utf-8'), write_to=fh) |
def ppo_original_world_model():
"""Atari parameters with world model as policy."""
hparams = ppo_original_params()
hparams.policy_network = "next_frame_basic_deterministic"
hparams_keys = hparams.values().keys()
video_hparams = basic_deterministic_params.next_frame_basic_deterministic()
for (name, value) in... | Atari parameters with world model as policy. | Below is the the instruction that describes the task:
### Input:
Atari parameters with world model as policy.
### Response:
def ppo_original_world_model():
"""Atari parameters with world model as policy."""
hparams = ppo_original_params()
hparams.policy_network = "next_frame_basic_deterministic"
hparams_ke... |
def _crc16_checksum(bytes):
"""Returns the CRC-16 checksum of bytearray bytes
Ported from Java implementation at: http://introcs.cs.princeton.edu/java/61data/CRC16CCITT.java.html
Initial value changed to 0x0000 to match Stellar configuration.
"""
crc = 0x0000
polynomial = 0x1021
for byte ... | Returns the CRC-16 checksum of bytearray bytes
Ported from Java implementation at: http://introcs.cs.princeton.edu/java/61data/CRC16CCITT.java.html
Initial value changed to 0x0000 to match Stellar configuration. | Below is the the instruction that describes the task:
### Input:
Returns the CRC-16 checksum of bytearray bytes
Ported from Java implementation at: http://introcs.cs.princeton.edu/java/61data/CRC16CCITT.java.html
Initial value changed to 0x0000 to match Stellar configuration.
### Response:
def _crc16_che... |
def _compute_signature(self, body):
"""
Computes the signature.
Described at:
http://crossbar.io/docs/HTTP-Bridge-Services-Caller/
Reference code is at:
https://github.com/crossbario/crossbar/blob/master/crossbar/adapter/rest/common.py
:return: (signature, none... | Computes the signature.
Described at:
http://crossbar.io/docs/HTTP-Bridge-Services-Caller/
Reference code is at:
https://github.com/crossbario/crossbar/blob/master/crossbar/adapter/rest/common.py
:return: (signature, none, timestamp) | Below is the the instruction that describes the task:
### Input:
Computes the signature.
Described at:
http://crossbar.io/docs/HTTP-Bridge-Services-Caller/
Reference code is at:
https://github.com/crossbario/crossbar/blob/master/crossbar/adapter/rest/common.py
:return: (si... |
def parseWord(word):
"""
Split given attribute word to key, value pair.
Values are casted to python equivalents.
:param word: API word.
:returns: Key, value pair.
"""
mapping = {'yes': True, 'true': True, 'no': False, 'false': False}
_, key, value = word.split('=', 2)
try:
... | Split given attribute word to key, value pair.
Values are casted to python equivalents.
:param word: API word.
:returns: Key, value pair. | Below is the the instruction that describes the task:
### Input:
Split given attribute word to key, value pair.
Values are casted to python equivalents.
:param word: API word.
:returns: Key, value pair.
### Response:
def parseWord(word):
"""
Split given attribute word to key, value pair.
... |
def _hash_categorical(c, encoding, hash_key):
"""
Hash a Categorical by hashing its categories, and then mapping the codes
to the hashes
Parameters
----------
c : Categorical
encoding : string, default 'utf8'
hash_key : string key to encode, default to _default_hash_key
Returns
... | Hash a Categorical by hashing its categories, and then mapping the codes
to the hashes
Parameters
----------
c : Categorical
encoding : string, default 'utf8'
hash_key : string key to encode, default to _default_hash_key
Returns
-------
ndarray of hashed values array, same size as ... | Below is the the instruction that describes the task:
### Input:
Hash a Categorical by hashing its categories, and then mapping the codes
to the hashes
Parameters
----------
c : Categorical
encoding : string, default 'utf8'
hash_key : string key to encode, default to _default_hash_key
... |
def _from_deprecated_string(cls, serialized):
"""
Return an instance of `cls` parsed from its deprecated `serialized` form.
This will be called only if :meth:`OpaqueKey.from_string` is unable to
parse a key out of `serialized`, and only if `set_deprecated_fallback` has
been call... | Return an instance of `cls` parsed from its deprecated `serialized` form.
This will be called only if :meth:`OpaqueKey.from_string` is unable to
parse a key out of `serialized`, and only if `set_deprecated_fallback` has
been called to register a fallback class.
Args:
cls: T... | Below is the the instruction that describes the task:
### Input:
Return an instance of `cls` parsed from its deprecated `serialized` form.
This will be called only if :meth:`OpaqueKey.from_string` is unable to
parse a key out of `serialized`, and only if `set_deprecated_fallback` has
been c... |
def positive_directional_movement(high_data, low_data):
"""
Positive Directional Movement (+DM).
Formula:
+DM: if UPMOVE > DWNMOVE and UPMOVE > 0 then +DM = UPMOVE else +DM = 0
"""
catch_errors.check_for_input_len_diff(high_data, low_data)
up_moves = calculate_up_moves(high_data)
down_m... | Positive Directional Movement (+DM).
Formula:
+DM: if UPMOVE > DWNMOVE and UPMOVE > 0 then +DM = UPMOVE else +DM = 0 | Below is the the instruction that describes the task:
### Input:
Positive Directional Movement (+DM).
Formula:
+DM: if UPMOVE > DWNMOVE and UPMOVE > 0 then +DM = UPMOVE else +DM = 0
### Response:
def positive_directional_movement(high_data, low_data):
"""
Positive Directional Movement (+DM).
... |
def filepaths(self) -> List[str]:
"""Absolute path names of the files contained in the current
working directory.
Files names starting with underscores are ignored:
>>> from hydpy.core.filetools import FileManager
>>> filemanager = FileManager()
>>> filemanager.BASEDIR ... | Absolute path names of the files contained in the current
working directory.
Files names starting with underscores are ignored:
>>> from hydpy.core.filetools import FileManager
>>> filemanager = FileManager()
>>> filemanager.BASEDIR = 'basename'
>>> filemanager.projectd... | Below is the the instruction that describes the task:
### Input:
Absolute path names of the files contained in the current
working directory.
Files names starting with underscores are ignored:
>>> from hydpy.core.filetools import FileManager
>>> filemanager = FileManager()
... |
def getNumPhones(isleDict, word, maxFlag):
'''
Get the number of syllables and phones in this word
If maxFlag=True, use the longest pronunciation. Otherwise, take the
average length.
'''
phoneCount = 0
syllableCount = 0
syllableCountList = []
phoneCountList = []
w... | Get the number of syllables and phones in this word
If maxFlag=True, use the longest pronunciation. Otherwise, take the
average length. | Below is the the instruction that describes the task:
### Input:
Get the number of syllables and phones in this word
If maxFlag=True, use the longest pronunciation. Otherwise, take the
average length.
### Response:
def getNumPhones(isleDict, word, maxFlag):
'''
Get the number of syllables and... |
def validate_param_completion(self, param, leftover_args):
""" validates that a param should be completed """
# validates param starts with unfinished word
completes = self.validate_completion(param)
# show parameter completions when started
full_param = self.unfinished_word.sta... | validates that a param should be completed | Below is the the instruction that describes the task:
### Input:
validates that a param should be completed
### Response:
def validate_param_completion(self, param, leftover_args):
""" validates that a param should be completed """
# validates param starts with unfinished word
completes = s... |
def from_json(cls, data):
"""Create an analysis period from a dictionary.
Args:
data: {
st_month: An integer between 1-12 for starting month (default = 1)
st_day: An integer between 1-31 for starting day (default = 1).
Note that some months are sho... | Create an analysis period from a dictionary.
Args:
data: {
st_month: An integer between 1-12 for starting month (default = 1)
st_day: An integer between 1-31 for starting day (default = 1).
Note that some months are shorter than 31 days.
st_hou... | Below is the the instruction that describes the task:
### Input:
Create an analysis period from a dictionary.
Args:
data: {
st_month: An integer between 1-12 for starting month (default = 1)
st_day: An integer between 1-31 for starting day (default = 1).
... |
def bind(topic, signal=None, kind=MIDDLE, nice=-1):
"""
This is a decorator function, so you should use it as:
@bind('init')
def process_init(a, b):
...
"""
def f(func):
if not topic in _receivers:
receivers = _receivers[topic] = []
... | This is a decorator function, so you should use it as:
@bind('init')
def process_init(a, b):
... | Below is the the instruction that describes the task:
### Input:
This is a decorator function, so you should use it as:
@bind('init')
def process_init(a, b):
...
### Response:
def bind(topic, signal=None, kind=MIDDLE, nice=-1):
"""
This is a decorator function, so... |
def resplit(prev, pattern, *args, **kw):
"""The resplit pipe split previous pipe input by regular expression.
Use 'maxsplit' keyword argument to limit the number of split.
:param prev: The previous iterator of pipe.
:type prev: Pipe
:param pattern: The pattern which used to split string.
:type... | The resplit pipe split previous pipe input by regular expression.
Use 'maxsplit' keyword argument to limit the number of split.
:param prev: The previous iterator of pipe.
:type prev: Pipe
:param pattern: The pattern which used to split string.
:type pattern: str|unicode | Below is the the instruction that describes the task:
### Input:
The resplit pipe split previous pipe input by regular expression.
Use 'maxsplit' keyword argument to limit the number of split.
:param prev: The previous iterator of pipe.
:type prev: Pipe
:param pattern: The pattern which used to sp... |
def _prepare_request(self, url, method, headers, data):
"""Prepare HTTP request.
:param str url: request URL.
:param str method: request method.
:param dict headers: request headers.
:param object data: JSON-encodable object.
:rtype: httpclient.HTTPRequest
"""
... | Prepare HTTP request.
:param str url: request URL.
:param str method: request method.
:param dict headers: request headers.
:param object data: JSON-encodable object.
:rtype: httpclient.HTTPRequest | Below is the the instruction that describes the task:
### Input:
Prepare HTTP request.
:param str url: request URL.
:param str method: request method.
:param dict headers: request headers.
:param object data: JSON-encodable object.
:rtype: httpclient.HTTPRequest
### Respons... |
def p_kw_args_update(self, p):
"""kw_args : kw_args COMMA kw_arg"""
p[0] = p[1]
for key in p[3]:
if key in p[1]:
msg = "Keyword argument '%s' defined more than once." % key
self.errors.append((msg, p.lineno(2), self.path))
p[0].update(p[3]) | kw_args : kw_args COMMA kw_arg | Below is the the instruction that describes the task:
### Input:
kw_args : kw_args COMMA kw_arg
### Response:
def p_kw_args_update(self, p):
"""kw_args : kw_args COMMA kw_arg"""
p[0] = p[1]
for key in p[3]:
if key in p[1]:
msg = "Keyword argument '%s' defined mor... |
def is_indexed(self, dataset):
""" Returns True if dataset is already indexed. Otherwise returns False. """
with self.index.searcher() as searcher:
result = searcher.search(Term('vid', dataset.vid))
return bool(result) | Returns True if dataset is already indexed. Otherwise returns False. | Below is the the instruction that describes the task:
### Input:
Returns True if dataset is already indexed. Otherwise returns False.
### Response:
def is_indexed(self, dataset):
""" Returns True if dataset is already indexed. Otherwise returns False. """
with self.index.searcher() as searcher:
... |
def elapsed(self):
"""
:return: duration in seconds spent in the context.
:rtype: float
"""
if self.end is None:
return self() - self.end
return self.end - self.start | :return: duration in seconds spent in the context.
:rtype: float | Below is the the instruction that describes the task:
### Input:
:return: duration in seconds spent in the context.
:rtype: float
### Response:
def elapsed(self):
"""
:return: duration in seconds spent in the context.
:rtype: float
"""
if self.end is None:
... |
def main(argv=None):
"""
The entry point of the script.
"""
from vsgen import VSGSuite
from vsgen import VSGLogger
# Special case to use the sys.argv when main called without a list.
if argv is None:
argv = sys.argv
# Initialize the application logger
pylogger = VSGLogger()... | The entry point of the script. | Below is the the instruction that describes the task:
### Input:
The entry point of the script.
### Response:
def main(argv=None):
"""
The entry point of the script.
"""
from vsgen import VSGSuite
from vsgen import VSGLogger
# Special case to use the sys.argv when main called without a lis... |
def _parse_binary(v, header_d):
""" Parses binary string.
Note:
<str> for py2 and <binary> for py3.
"""
# This is often a no-op, but it ocassionally converts numbers into strings
v = nullify(v)
if v is None:
return None
if six.PY2:
try:
return six.bi... | Parses binary string.
Note:
<str> for py2 and <binary> for py3. | Below is the the instruction that describes the task:
### Input:
Parses binary string.
Note:
<str> for py2 and <binary> for py3.
### Response:
def _parse_binary(v, header_d):
""" Parses binary string.
Note:
<str> for py2 and <binary> for py3.
"""
# This is often a no-op, but... |
def _add_numeric_methods_binary(cls):
""" add in numeric methods, specialized to RangeIndex """
def _make_evaluate_binop(op, step=False):
"""
Parameters
----------
op : callable that accepts 2 parms
perform the binary op
step :... | add in numeric methods, specialized to RangeIndex | Below is the the instruction that describes the task:
### Input:
add in numeric methods, specialized to RangeIndex
### Response:
def _add_numeric_methods_binary(cls):
""" add in numeric methods, specialized to RangeIndex """
def _make_evaluate_binop(op, step=False):
"""
Par... |
def rotatable_count(mol):
"""Rotatable bond count """
mol.require("Rotatable")
return sum(1 for _, _, b in mol.bonds_iter() if b.rotatable) | Rotatable bond count | Below is the the instruction that describes the task:
### Input:
Rotatable bond count
### Response:
def rotatable_count(mol):
"""Rotatable bond count """
mol.require("Rotatable")
return sum(1 for _, _, b in mol.bonds_iter() if b.rotatable) |
def discover_remote_results(self, response, name):
"""
Create a new remote server resource for each valid discover response.
:param response: the response to the discovery request
:param name: the server name
"""
host, port = response.source
if response.code == ... | Create a new remote server resource for each valid discover response.
:param response: the response to the discovery request
:param name: the server name | Below is the the instruction that describes the task:
### Input:
Create a new remote server resource for each valid discover response.
:param response: the response to the discovery request
:param name: the server name
### Response:
def discover_remote_results(self, response, name):
"""
... |
def load():
""" Check available plugins and attempt to import them """
# Code is based on beaker-client's command.py script
plugins = []
for filename in os.listdir(PLUGINS_PATH):
if not filename.endswith(".py") or filename.startswith("_"):
continue
if not os.path.isfile(os.pa... | Check available plugins and attempt to import them | Below is the the instruction that describes the task:
### Input:
Check available plugins and attempt to import them
### Response:
def load():
""" Check available plugins and attempt to import them """
# Code is based on beaker-client's command.py script
plugins = []
for filename in os.listdir(PLUGI... |
def datasetScalarTimeStepChunk(lines, numberColumns, numberCells):
"""
Process the time step chunks for scalar datasets
"""
END_DATASET_TAG = 'ENDDS'
# Define the result object
result = {'iStatus': None,
'timestamp': None,
'cellArray': None,
'rasterText... | Process the time step chunks for scalar datasets | Below is the the instruction that describes the task:
### Input:
Process the time step chunks for scalar datasets
### Response:
def datasetScalarTimeStepChunk(lines, numberColumns, numberCells):
"""
Process the time step chunks for scalar datasets
"""
END_DATASET_TAG = 'ENDDS'
# Define the res... |
def get_generator():
""" construct and return generator """
g_net = gluon.nn.Sequential()
with g_net.name_scope():
g_net.add(gluon.nn.Conv2DTranspose(
channels=512, kernel_size=4, strides=1, padding=0, use_bias=False))
g_net.add(gluon.nn.BatchNorm())
g_net.add(gluon.nn.L... | construct and return generator | Below is the the instruction that describes the task:
### Input:
construct and return generator
### Response:
def get_generator():
""" construct and return generator """
g_net = gluon.nn.Sequential()
with g_net.name_scope():
g_net.add(gluon.nn.Conv2DTranspose(
channels=512, kernel_... |
def reference(self):
"""A :class:`~google.cloud.bigquery.model.ModelReference` pointing to
this model.
Read-only.
Returns:
google.cloud.bigquery.model.ModelReference: pointer to this model.
"""
ref = ModelReference()
ref._proto = self._proto.model_re... | A :class:`~google.cloud.bigquery.model.ModelReference` pointing to
this model.
Read-only.
Returns:
google.cloud.bigquery.model.ModelReference: pointer to this model. | Below is the the instruction that describes the task:
### Input:
A :class:`~google.cloud.bigquery.model.ModelReference` pointing to
this model.
Read-only.
Returns:
google.cloud.bigquery.model.ModelReference: pointer to this model.
### Response:
def reference(self):
"""... |
def identify_needed_data(curr_exe_job, link_job_instance=None):
""" This function will identify the length of data that a specific executable
needs to analyse and what part of that data is valid (ie. inspiral doesn't
analyse the first or last 64+8s of data it reads in).
In addition you can supply a sec... | This function will identify the length of data that a specific executable
needs to analyse and what part of that data is valid (ie. inspiral doesn't
analyse the first or last 64+8s of data it reads in).
In addition you can supply a second job instance to "link" to, which will
ensure that the two jobs w... | Below is the the instruction that describes the task:
### Input:
This function will identify the length of data that a specific executable
needs to analyse and what part of that data is valid (ie. inspiral doesn't
analyse the first or last 64+8s of data it reads in).
In addition you can supply a second... |
def merge_rdf_list(rdf_list):
""" takes an rdf list and merges it into a python list
args:
rdf_list: the RdfDataset object with the list values
returns:
list of values
"""
# pdb.set_trace()
if isinstance(rdf_list, list):
rdf_list = rdf_list[0]
rtn_list = []
# fo... | takes an rdf list and merges it into a python list
args:
rdf_list: the RdfDataset object with the list values
returns:
list of values | Below is the the instruction that describes the task:
### Input:
takes an rdf list and merges it into a python list
args:
rdf_list: the RdfDataset object with the list values
returns:
list of values
### Response:
def merge_rdf_list(rdf_list):
""" takes an rdf list and merges it into a... |
def print_splits(cliques, next_cliques):
"""Print shifts for new forks."""
splits = 0
for i, clique in enumerate(cliques):
parent, _ = clique
# If this fork continues
if parent in next_cliques:
# If there is a new fork, print a split
if len(next_cliques[paren... | Print shifts for new forks. | Below is the the instruction that describes the task:
### Input:
Print shifts for new forks.
### Response:
def print_splits(cliques, next_cliques):
"""Print shifts for new forks."""
splits = 0
for i, clique in enumerate(cliques):
parent, _ = clique
# If this fork continues
if p... |
def put(self, todo_id):
"""
This is an example
---
tags:
- restful
parameters:
- in: body
name: body
schema:
$ref: '#/definitions/Task'
- in: path
name: todo_id
required: true
... | This is an example
---
tags:
- restful
parameters:
- in: body
name: body
schema:
$ref: '#/definitions/Task'
- in: path
name: todo_id
required: true
description: The ID of the task, try 42!
... | Below is the the instruction that describes the task:
### Input:
This is an example
---
tags:
- restful
parameters:
- in: body
name: body
schema:
$ref: '#/definitions/Task'
- in: path
name: todo_id
re... |
def _mk_client():
'''
Create a file client and add it to the context.
Each file client needs to correspond to a unique copy
of the opts dictionary, therefore it's hashed by the
id of the __opts__ dict
'''
if 'cp.fileclient_{0}'.format(id(__opts__)) not in __context__:
__context__['c... | Create a file client and add it to the context.
Each file client needs to correspond to a unique copy
of the opts dictionary, therefore it's hashed by the
id of the __opts__ dict | Below is the the instruction that describes the task:
### Input:
Create a file client and add it to the context.
Each file client needs to correspond to a unique copy
of the opts dictionary, therefore it's hashed by the
id of the __opts__ dict
### Response:
def _mk_client():
'''
Create a file ... |
def _set_as_cached(self, item, cacher):
"""Set the _cacher attribute on the calling object with a weakref to
cacher.
"""
self._cacher = (item, weakref.ref(cacher)) | Set the _cacher attribute on the calling object with a weakref to
cacher. | Below is the the instruction that describes the task:
### Input:
Set the _cacher attribute on the calling object with a weakref to
cacher.
### Response:
def _set_as_cached(self, item, cacher):
"""Set the _cacher attribute on the calling object with a weakref to
cacher.
"""
s... |
def get_mst(points):
"""
Parameters
----------
points : list of points (geometry.Point)
The first element of the list is the center of the bounding box of the
first stroke, the second one belongs to the seconds stroke, ...
Returns
-------
mst : square matrix
0 nodes ... | Parameters
----------
points : list of points (geometry.Point)
The first element of the list is the center of the bounding box of the
first stroke, the second one belongs to the seconds stroke, ...
Returns
-------
mst : square matrix
0 nodes the edges are not connected, > 0 ... | Below is the the instruction that describes the task:
### Input:
Parameters
----------
points : list of points (geometry.Point)
The first element of the list is the center of the bounding box of the
first stroke, the second one belongs to the seconds stroke, ...
Returns
-------
... |
def walk_data(cls, dist, path='/'):
"""Yields filename, stream for files identified as data in the distribution"""
for rel_fn in filter(None, dist.resource_listdir(path)):
full_fn = os.path.join(path, rel_fn)
if dist.resource_isdir(full_fn):
for fn, stream in cls.walk_data(dist, full_fn):
... | Yields filename, stream for files identified as data in the distribution | Below is the the instruction that describes the task:
### Input:
Yields filename, stream for files identified as data in the distribution
### Response:
def walk_data(cls, dist, path='/'):
"""Yields filename, stream for files identified as data in the distribution"""
for rel_fn in filter(None, dist.resource... |
def collect_usage_pieces(self, ctx):
"""Prepend "[--]" before "[ARGV]..."."""
pieces = super(ProfilingCommand, self).collect_usage_pieces(ctx)
assert pieces[-1] == '[ARGV]...'
pieces.insert(-1, 'SCRIPT')
pieces.insert(-1, '[--]')
return pieces | Prepend "[--]" before "[ARGV]...". | Below is the the instruction that describes the task:
### Input:
Prepend "[--]" before "[ARGV]...".
### Response:
def collect_usage_pieces(self, ctx):
"""Prepend "[--]" before "[ARGV]..."."""
pieces = super(ProfilingCommand, self).collect_usage_pieces(ctx)
assert pieces[-1] == '[ARGV]...'
... |
def python_console(namespace=None):
"""Start a interactive python console with caller's stack"""
if namespace is None:
import inspect
frame = inspect.currentframe()
caller = frame.f_back
if not caller:
logging.error("can't find caller who start this console.")
... | Start a interactive python console with caller's stack | Below is the the instruction that describes the task:
### Input:
Start a interactive python console with caller's stack
### Response:
def python_console(namespace=None):
"""Start a interactive python console with caller's stack"""
if namespace is None:
import inspect
frame = inspect.curren... |
def save(self, foldername: str, path_to_folder: str=None) -> None:
''' Saves entities into multiple files within the same folder because of pickle-recursive
errors that would happen if squeezed into one '''
self.create_pickle((self.g.namespaces, ))
self.df.to_pickle(output) | Saves entities into multiple files within the same folder because of pickle-recursive
errors that would happen if squeezed into one | Below is the the instruction that describes the task:
### Input:
Saves entities into multiple files within the same folder because of pickle-recursive
errors that would happen if squeezed into one
### Response:
def save(self, foldername: str, path_to_folder: str=None) -> None:
''' Saves entitie... |
def integrate(self, fluxunits='photlam'):
"""Integrate the flux in given unit.
Integration is done using :meth:`~Integrator.trapezoidIntegration`
with ``x=wave`` and ``y=flux``, where flux has been
convert to given unit first.
.. math::
\\textnormal{result} = \\int... | Integrate the flux in given unit.
Integration is done using :meth:`~Integrator.trapezoidIntegration`
with ``x=wave`` and ``y=flux``, where flux has been
convert to given unit first.
.. math::
\\textnormal{result} = \\int F_{\\lambda} d\\lambda
Parameters
-... | Below is the the instruction that describes the task:
### Input:
Integrate the flux in given unit.
Integration is done using :meth:`~Integrator.trapezoidIntegration`
with ``x=wave`` and ``y=flux``, where flux has been
convert to given unit first.
.. math::
\\textnormal... |
def _should_remove(self, i, name):
"""Look ahead for a parameter with the same name, but hidden.
If one exists, we should remove the given one rather than blanking it.
"""
if self.params[i].showkey:
following = self.params[i + 1:]
better_matches = [after.name.str... | Look ahead for a parameter with the same name, but hidden.
If one exists, we should remove the given one rather than blanking it. | Below is the the instruction that describes the task:
### Input:
Look ahead for a parameter with the same name, but hidden.
If one exists, we should remove the given one rather than blanking it.
### Response:
def _should_remove(self, i, name):
"""Look ahead for a parameter with the same name, but ... |
def _merge_states(self, states):
"""
Merges a list of states.
:param states: the states to merge
:returns SimState: the resulting state
"""
if self._hierarchy:
optimal, common_history, others = self._hierarchy.most_mergeable(states)
else:
... | Merges a list of states.
:param states: the states to merge
:returns SimState: the resulting state | Below is the the instruction that describes the task:
### Input:
Merges a list of states.
:param states: the states to merge
:returns SimState: the resulting state
### Response:
def _merge_states(self, states):
"""
Merges a list of states.
:param states: the sta... |
def get_dict_for_class(self, class_name, state=None, base_name='View'):
"""The style dict for a given class and state.
This collects the style attributes from parent classes
and the class of the given object and gives precedence
to values thereof to the children.
The state attr... | The style dict for a given class and state.
This collects the style attributes from parent classes
and the class of the given object and gives precedence
to values thereof to the children.
The state attribute of the view instance is taken as
the current state if state is None.
... | Below is the the instruction that describes the task:
### Input:
The style dict for a given class and state.
This collects the style attributes from parent classes
and the class of the given object and gives precedence
to values thereof to the children.
The state attribute of the v... |
def remove_file_ident_desc_by_name(self, name, logical_block_size):
# type: (bytes, int) -> int
'''
A method to remove a UDF File Identifier Descriptor from this UDF File
Entry.
Parameters:
name - The name of the UDF File Identifier Descriptor to remove.
logica... | A method to remove a UDF File Identifier Descriptor from this UDF File
Entry.
Parameters:
name - The name of the UDF File Identifier Descriptor to remove.
logical_block_size - The logical block size to use.
Returns:
The number of extents removed due to removing this F... | Below is the the instruction that describes the task:
### Input:
A method to remove a UDF File Identifier Descriptor from this UDF File
Entry.
Parameters:
name - The name of the UDF File Identifier Descriptor to remove.
logical_block_size - The logical block size to use.
R... |
def update(self, data=values.unset, ttl=values.unset, item_ttl=values.unset,
collection_ttl=values.unset):
"""
Update the SyncMapItemInstance
:param dict data: Contains an arbitrary JSON object to be stored in this Map Item.
:param unicode ttl: Alias for item_ttl
... | Update the SyncMapItemInstance
:param dict data: Contains an arbitrary JSON object to be stored in this Map Item.
:param unicode ttl: Alias for item_ttl
:param unicode item_ttl: Time-to-live of this item in seconds, defaults to no expiration.
:param unicode collection_ttl: Time-to-live ... | Below is the the instruction that describes the task:
### Input:
Update the SyncMapItemInstance
:param dict data: Contains an arbitrary JSON object to be stored in this Map Item.
:param unicode ttl: Alias for item_ttl
:param unicode item_ttl: Time-to-live of this item in seconds, defaults t... |
def switch_to_frame(driver, frame, timeout=settings.SMALL_TIMEOUT):
"""
Wait for an iframe to appear, and switch to it. This should be usable
as a drop-in replacement for driver.switch_to.frame().
@Params
driver - the webdriver object (required)
frame - the frame element, name, or index
time... | Wait for an iframe to appear, and switch to it. This should be usable
as a drop-in replacement for driver.switch_to.frame().
@Params
driver - the webdriver object (required)
frame - the frame element, name, or index
timeout - the time to wait for the alert in seconds | Below is the the instruction that describes the task:
### Input:
Wait for an iframe to appear, and switch to it. This should be usable
as a drop-in replacement for driver.switch_to.frame().
@Params
driver - the webdriver object (required)
frame - the frame element, name, or index
timeout - the t... |
def up(self):
"""
Move this object up one position.
"""
self.swap(self.get_ordering_queryset().filter(order__lt=self.order).order_by('-order')) | Move this object up one position. | Below is the the instruction that describes the task:
### Input:
Move this object up one position.
### Response:
def up(self):
"""
Move this object up one position.
"""
self.swap(self.get_ordering_queryset().filter(order__lt=self.order).order_by('-order')) |
def try_acquire(self, permits=1, timeout=0):
"""
Tries to acquire one or the given number of permits, if they are available, and returns immediately, with the
value ``true``, reducing the number of available permits by the given amount.
If there are insufficient permits and a timeout is... | Tries to acquire one or the given number of permits, if they are available, and returns immediately, with the
value ``true``, reducing the number of available permits by the given amount.
If there are insufficient permits and a timeout is provided, the current thread becomes disabled for thread
... | Below is the the instruction that describes the task:
### Input:
Tries to acquire one or the given number of permits, if they are available, and returns immediately, with the
value ``true``, reducing the number of available permits by the given amount.
If there are insufficient permits and a timeou... |
def fingerprint(self, phrase, qval=2, start_stop='', joiner=''):
"""Return Q-Gram fingerprint.
Parameters
----------
phrase : str
The string from which to calculate the q-gram fingerprint
qval : int
The length of each q-gram (by default 2)
start_s... | Return Q-Gram fingerprint.
Parameters
----------
phrase : str
The string from which to calculate the q-gram fingerprint
qval : int
The length of each q-gram (by default 2)
start_stop : str
The start & stop symbol(s) to concatenate on either en... | Below is the the instruction that describes the task:
### Input:
Return Q-Gram fingerprint.
Parameters
----------
phrase : str
The string from which to calculate the q-gram fingerprint
qval : int
The length of each q-gram (by default 2)
start_stop : s... |
def imsi(number):
'''
Printable International Mobile Subscriber Identity (IMSI) numbers. Mind
that there is no validation done on the actual correctness of the MCC/MNC.
If you wish to validate IMSI numbers, take a look at `python-stdnum`_.
:param number: string or int
>>> print(imsi(2042312345... | Printable International Mobile Subscriber Identity (IMSI) numbers. Mind
that there is no validation done on the actual correctness of the MCC/MNC.
If you wish to validate IMSI numbers, take a look at `python-stdnum`_.
:param number: string or int
>>> print(imsi(2042312345))
204-23-12345
.. _p... | Below is the the instruction that describes the task:
### Input:
Printable International Mobile Subscriber Identity (IMSI) numbers. Mind
that there is no validation done on the actual correctness of the MCC/MNC.
If you wish to validate IMSI numbers, take a look at `python-stdnum`_.
:param number: strin... |
async def wait(self, name):
"""
:py:func:`asyncio.coroutine`
Wait for all throttles
:param name: name of throttle to acquire ("read" or "write")
:type name: :py:class:`str`
"""
waiters = []
for throttle in self.throttles.values():
curr_thrott... | :py:func:`asyncio.coroutine`
Wait for all throttles
:param name: name of throttle to acquire ("read" or "write")
:type name: :py:class:`str` | Below is the the instruction that describes the task:
### Input:
:py:func:`asyncio.coroutine`
Wait for all throttles
:param name: name of throttle to acquire ("read" or "write")
:type name: :py:class:`str`
### Response:
async def wait(self, name):
"""
:py:func:`asyncio.cor... |
def bind(self, *args, **kw):
"""
Bind environment variables into this object's scope.
"""
new_self = self.copy()
new_scopes = Object.translate_to_scopes(*args, **kw)
new_self._scopes = tuple(reversed(new_scopes)) + new_self._scopes
return new_self | Bind environment variables into this object's scope. | Below is the the instruction that describes the task:
### Input:
Bind environment variables into this object's scope.
### Response:
def bind(self, *args, **kw):
"""
Bind environment variables into this object's scope.
"""
new_self = self.copy()
new_scopes = Object.translate_to_scopes(*args, *... |
def _getApplication(self):
"""Get the base application UIElement.
If the UIElement is a child of the application, it will try
to get the AXParent until it reaches the top application level
element.
"""
app = self
while True:
try:
app =... | Get the base application UIElement.
If the UIElement is a child of the application, it will try
to get the AXParent until it reaches the top application level
element. | Below is the the instruction that describes the task:
### Input:
Get the base application UIElement.
If the UIElement is a child of the application, it will try
to get the AXParent until it reaches the top application level
element.
### Response:
def _getApplication(self):
"""Get t... |
def proceed(self, *,
action=adhoc_xso.ActionType.EXECUTE,
payload=None):
"""
Proceed command execution to the next stage.
:param action: Action type for proceeding
:type action: :class:`~.ActionTyp`
:param payload: Payload for the request, or :dat... | Proceed command execution to the next stage.
:param action: Action type for proceeding
:type action: :class:`~.ActionTyp`
:param payload: Payload for the request, or :data:`None`
:return: The :attr:`~.xso.Command.first_payload` of the response
`action` must be one of the action... | Below is the the instruction that describes the task:
### Input:
Proceed command execution to the next stage.
:param action: Action type for proceeding
:type action: :class:`~.ActionTyp`
:param payload: Payload for the request, or :data:`None`
:return: The :attr:`~.xso.Command.first... |
def ensure_dim(core, dim, dim_):
"""Ensure that dim is correct."""
if dim is None:
dim = dim_
if not dim:
return core, 1
if dim_ == dim:
return core, int(dim)
if dim > dim_:
key_convert = lambda vari: vari[:dim_]
else:
key_convert = lambda vari: vari + (0... | Ensure that dim is correct. | Below is the the instruction that describes the task:
### Input:
Ensure that dim is correct.
### Response:
def ensure_dim(core, dim, dim_):
"""Ensure that dim is correct."""
if dim is None:
dim = dim_
if not dim:
return core, 1
if dim_ == dim:
return core, int(dim)
if d... |
def schedule(self, schedule_time):
"""Add a specific enqueue time to the message.
:param schedule_time: The scheduled time to enqueue the message.
:type schedule_time: ~datetime.datetime
"""
if not self.properties.message_id:
self.properties.message_id = str(uuid.uui... | Add a specific enqueue time to the message.
:param schedule_time: The scheduled time to enqueue the message.
:type schedule_time: ~datetime.datetime | Below is the the instruction that describes the task:
### Input:
Add a specific enqueue time to the message.
:param schedule_time: The scheduled time to enqueue the message.
:type schedule_time: ~datetime.datetime
### Response:
def schedule(self, schedule_time):
"""Add a specific enqueue t... |
def GET(self, mid=None):
'''
Show the list of minion keys or detail on a specific key
.. versionadded:: 2014.7.0
.. http:get:: /keys/(mid)
List all keys or show a specific key
:reqheader X-Auth-Token: |req_token|
:reqheader Accept: |req_accept|
... | Show the list of minion keys or detail on a specific key
.. versionadded:: 2014.7.0
.. http:get:: /keys/(mid)
List all keys or show a specific key
:reqheader X-Auth-Token: |req_token|
:reqheader Accept: |req_accept|
:status 200: |200|
:sta... | Below is the the instruction that describes the task:
### Input:
Show the list of minion keys or detail on a specific key
.. versionadded:: 2014.7.0
.. http:get:: /keys/(mid)
List all keys or show a specific key
:reqheader X-Auth-Token: |req_token|
:reqheader ... |
def new_pos(self, html_div):
"""factory method pattern"""
pos = self.Position(self, html_div)
pos.bind_mov()
self.positions.append(pos)
return pos | factory method pattern | Below is the the instruction that describes the task:
### Input:
factory method pattern
### Response:
def new_pos(self, html_div):
"""factory method pattern"""
pos = self.Position(self, html_div)
pos.bind_mov()
self.positions.append(pos)
return pos |
def get_root_banks(self):
"""Gets the root banks in this bank hierarchy.
return: (osid.assessment.BankList) - the root banks
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure occurred
*compliance: mandatory -- This method is mu... | Gets the root banks in this bank hierarchy.
return: (osid.assessment.BankList) - the root banks
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure occurred
*compliance: mandatory -- This method is must be implemented.* | Below is the the instruction that describes the task:
### Input:
Gets the root banks in this bank hierarchy.
return: (osid.assessment.BankList) - the root banks
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure occurred
*compliance... |
def update(m, k, f, *args):
"""Updates the value for key k in associative data structure m with the return value from
calling f(old_v, *args). If m is None, use an empty map. If k is not in m, old_v will be
None."""
if m is None:
return lmap.Map.empty().assoc(k, f(None, *args))
if isinstance... | Updates the value for key k in associative data structure m with the return value from
calling f(old_v, *args). If m is None, use an empty map. If k is not in m, old_v will be
None. | Below is the the instruction that describes the task:
### Input:
Updates the value for key k in associative data structure m with the return value from
calling f(old_v, *args). If m is None, use an empty map. If k is not in m, old_v will be
None.
### Response:
def update(m, k, f, *args):
"""Updates the... |
def listrecycle(self, start = 0, limit = 1000):
''' Usage: listrecycle [start] [limit] - \
list the recycle contents
start - starting point, default: 0
limit - maximum number of items to display. default: 1000
'''
pars = {
'method' : 'listrecycle',
'start' : str2int(start),
'limit' : str2int(limit) }... | Usage: listrecycle [start] [limit] - \
list the recycle contents
start - starting point, default: 0
limit - maximum number of items to display. default: 1000 | Below is the the instruction that describes the task:
### Input:
Usage: listrecycle [start] [limit] - \
list the recycle contents
start - starting point, default: 0
limit - maximum number of items to display. default: 1000
### Response:
def listrecycle(self, start = 0, limit = 1000):
''' Usage: listrecycle [... |
def _iter_path(pointer):
"""Take a cairo_path_t * pointer
and yield ``(path_operation, coordinates)`` tuples.
See :meth:`Context.copy_path` for the data structure.
"""
_check_status(pointer.status)
data = pointer.data
num_data = pointer.num_data
points_per_type = PATH_POINTS_PER_TYPE
... | Take a cairo_path_t * pointer
and yield ``(path_operation, coordinates)`` tuples.
See :meth:`Context.copy_path` for the data structure. | Below is the the instruction that describes the task:
### Input:
Take a cairo_path_t * pointer
and yield ``(path_operation, coordinates)`` tuples.
See :meth:`Context.copy_path` for the data structure.
### Response:
def _iter_path(pointer):
"""Take a cairo_path_t * pointer
and yield ``(path_operati... |
def _is_at_ref_end(self, nucmer_hit):
'''Returns True iff the hit is "close enough" to the end of the reference sequence'''
hit_coords = nucmer_hit.ref_coords()
return hit_coords.end >= nucmer_hit.ref_length - self.ref_end_tolerance | Returns True iff the hit is "close enough" to the end of the reference sequence | Below is the the instruction that describes the task:
### Input:
Returns True iff the hit is "close enough" to the end of the reference sequence
### Response:
def _is_at_ref_end(self, nucmer_hit):
'''Returns True iff the hit is "close enough" to the end of the reference sequence'''
hit_coords = nuc... |
def emd_model(prediction, fm):
"""
wraps emd functionality for model evaluation
requires:
OpenCV python bindings
input:
prediction: the model salience map
fm : fixmat filtered for the image corresponding to the prediction
"""
(_, r_x) = calc_resize_factor(prediction, fm... | wraps emd functionality for model evaluation
requires:
OpenCV python bindings
input:
prediction: the model salience map
fm : fixmat filtered for the image corresponding to the prediction | Below is the the instruction that describes the task:
### Input:
wraps emd functionality for model evaluation
requires:
OpenCV python bindings
input:
prediction: the model salience map
fm : fixmat filtered for the image corresponding to the prediction
### Response:
def emd_model(p... |
def list_policy_versions(policyName,
region=None, key=None, keyid=None, profile=None):
'''
List the versions available for the given policy.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.list_policy_versions mypolicy
Example Return:
.. code-block:: yaml
... | List the versions available for the given policy.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.list_policy_versions mypolicy
Example Return:
.. code-block:: yaml
policyVersions:
- {...}
- {...} | Below is the the instruction that describes the task:
### Input:
List the versions available for the given policy.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.list_policy_versions mypolicy
Example Return:
.. code-block:: yaml
policyVersions:
- {...}
... |
def validate_read_preference_tags(name, value):
"""Parse readPreferenceTags if passed as a client kwarg.
"""
if not isinstance(value, list):
value = [value]
tag_sets = []
for tag_set in value:
if tag_set == '':
tag_sets.append({})
continue
try:
... | Parse readPreferenceTags if passed as a client kwarg. | Below is the the instruction that describes the task:
### Input:
Parse readPreferenceTags if passed as a client kwarg.
### Response:
def validate_read_preference_tags(name, value):
"""Parse readPreferenceTags if passed as a client kwarg.
"""
if not isinstance(value, list):
value = [value]
... |
def create_new_database(request):
"""Create a New Mongo Database by adding a single document."""
name = "Create a New MongoDB Database"
if request.method == 'POST':
form = CreateDatabaseForm(request.POST)
if form.is_valid():
result = form.save()
if "error" in result... | Create a New Mongo Database by adding a single document. | Below is the the instruction that describes the task:
### Input:
Create a New Mongo Database by adding a single document.
### Response:
def create_new_database(request):
"""Create a New Mongo Database by adding a single document."""
name = "Create a New MongoDB Database"
if request.method == 'POST':
... |
def set(self, k, v, obj='override'):
'obj is a Sheet instance, or a Sheet [sub]class. obj="override" means override all; obj="default" means last resort.'
if k not in self:
self[k] = dict()
self[k][self.objname(obj)] = v
return v | obj is a Sheet instance, or a Sheet [sub]class. obj="override" means override all; obj="default" means last resort. | Below is the the instruction that describes the task:
### Input:
obj is a Sheet instance, or a Sheet [sub]class. obj="override" means override all; obj="default" means last resort.
### Response:
def set(self, k, v, obj='override'):
'obj is a Sheet instance, or a Sheet [sub]class. obj="override" means ove... |
def save_function(self, obj, name=None):
""" Registered with the dispatch to handle all function types.
Determines what kind of function obj is (e.g. lambda, defined at
interactive prompt, etc) and handles the pickling appropriately.
"""
try:
should_special_case = ob... | Registered with the dispatch to handle all function types.
Determines what kind of function obj is (e.g. lambda, defined at
interactive prompt, etc) and handles the pickling appropriately. | Below is the the instruction that describes the task:
### Input:
Registered with the dispatch to handle all function types.
Determines what kind of function obj is (e.g. lambda, defined at
interactive prompt, etc) and handles the pickling appropriately.
### Response:
def save_function(self, obj, n... |
def past_participle(self):
"""
Strong verbs
I
>>> verb = StrongOldNorseVerb()
>>> verb.set_canonic_forms(["líta", "lítr", "leit", "litu", "litinn"])
>>> verb.past_participle()
[['litinn', 'litinn', 'litnum', 'litins', 'litnir', 'litna', 'litnum', 'litinna'], ['li... | Strong verbs
I
>>> verb = StrongOldNorseVerb()
>>> verb.set_canonic_forms(["líta", "lítr", "leit", "litu", "litinn"])
>>> verb.past_participle()
[['litinn', 'litinn', 'litnum', 'litins', 'litnir', 'litna', 'litnum', 'litinna'], ['litin', 'litna', 'litinni', 'litinnar', 'litnar',... | Below is the the instruction that describes the task:
### Input:
Strong verbs
I
>>> verb = StrongOldNorseVerb()
>>> verb.set_canonic_forms(["líta", "lítr", "leit", "litu", "litinn"])
>>> verb.past_participle()
[['litinn', 'litinn', 'litnum', 'litins', 'litnir', 'litna', 'lit... |
def timesince(d, now=None, pos=True, flag=False):
"""
pos means calculate which direction, pos = True, now - d, pos = False, d - now
flag means return value type, True will return since, message and Flase return message
>>> d = datetime.datetime(2009, 10, 1, 12, 23, 19)
>>> timesince(d, d, True)
... | pos means calculate which direction, pos = True, now - d, pos = False, d - now
flag means return value type, True will return since, message and Flase return message
>>> d = datetime.datetime(2009, 10, 1, 12, 23, 19)
>>> timesince(d, d, True)
>>> now = datetime.datetime(2009, 10, 1, 12, 24, 19)
>>> ... | Below is the the instruction that describes the task:
### Input:
pos means calculate which direction, pos = True, now - d, pos = False, d - now
flag means return value type, True will return since, message and Flase return message
>>> d = datetime.datetime(2009, 10, 1, 12, 23, 19)
>>> timesince(d, d, Tr... |
def anyopen(datasource, mode='rt', reset=True):
"""Open datasource (gzipped, bzipped, uncompressed) and return a stream.
`datasource` can be a filename or a stream (see :func:`isstream`). By
default, a stream is reset to its start if possible (via
:meth:`~io.IOBase.seek` or :meth:`~cString.StringIO.res... | Open datasource (gzipped, bzipped, uncompressed) and return a stream.
`datasource` can be a filename or a stream (see :func:`isstream`). By
default, a stream is reset to its start if possible (via
:meth:`~io.IOBase.seek` or :meth:`~cString.StringIO.reset`).
If possible, the attribute ``stream.name`` i... | Below is the the instruction that describes the task:
### Input:
Open datasource (gzipped, bzipped, uncompressed) and return a stream.
`datasource` can be a filename or a stream (see :func:`isstream`). By
default, a stream is reset to its start if possible (via
:meth:`~io.IOBase.seek` or :meth:`~cStrin... |
def create_model_table(self, model):
"""Creates the table for the given model.
Args:
model: A StatikModel instance.
Returns:
A SQLAlchemy model instance for the table corresponding to this
particular model.
"""
try:
return db_mode... | Creates the table for the given model.
Args:
model: A StatikModel instance.
Returns:
A SQLAlchemy model instance for the table corresponding to this
particular model. | Below is the the instruction that describes the task:
### Input:
Creates the table for the given model.
Args:
model: A StatikModel instance.
Returns:
A SQLAlchemy model instance for the table corresponding to this
particular model.
### Response:
def create_mode... |
def find_agent(self, desc):
'''Gives medium class of the agent if the agency hosts it.'''
agent_id = (desc.doc_id
if IDocument.providedBy(desc)
else desc)
self.log("I'm trying to find the agent with id: %s", agent_id)
result = first(x for x in self... | Gives medium class of the agent if the agency hosts it. | Below is the the instruction that describes the task:
### Input:
Gives medium class of the agent if the agency hosts it.
### Response:
def find_agent(self, desc):
'''Gives medium class of the agent if the agency hosts it.'''
agent_id = (desc.doc_id
if IDocument.providedBy(desc)
... |
def unix_domain_socket_server(sock_path):
"""
Create UNIX-domain socket on specified path.
Listen on it, and delete it after the generated context is over.
"""
log.debug('serving on %s', sock_path)
remove_file(sock_path)
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
server... | Create UNIX-domain socket on specified path.
Listen on it, and delete it after the generated context is over. | Below is the the instruction that describes the task:
### Input:
Create UNIX-domain socket on specified path.
Listen on it, and delete it after the generated context is over.
### Response:
def unix_domain_socket_server(sock_path):
"""
Create UNIX-domain socket on specified path.
Listen on it, and... |
def maskname(self) -> Optional[str]:
"""Name of the mask matrix file."""
mask = self._data['geometry']['mask']
if os.path.abspath(mask):
mask = os.path.split(mask)[-1]
return mask | Name of the mask matrix file. | Below is the the instruction that describes the task:
### Input:
Name of the mask matrix file.
### Response:
def maskname(self) -> Optional[str]:
"""Name of the mask matrix file."""
mask = self._data['geometry']['mask']
if os.path.abspath(mask):
mask = os.path.split(mask)[-1]
... |
def toggle_input(self):
"""Change behaviour of radio button based on input."""
current_index = self.input.currentIndex()
# If current input is not a radio button enabler, disable radio button.
if self.input.itemData(current_index, Qt.UserRole) != (
self.radio_button_enabl... | Change behaviour of radio button based on input. | Below is the the instruction that describes the task:
### Input:
Change behaviour of radio button based on input.
### Response:
def toggle_input(self):
"""Change behaviour of radio button based on input."""
current_index = self.input.currentIndex()
# If current input is not a radio button e... |
def show_default_popup(self, pos):
'''show default popup menu'''
state = self.state
if state.default_popup.popup is not None:
wx_menu = state.default_popup.popup.wx_menu()
state.frame.PopupMenu(wx_menu, pos) | show default popup menu | Below is the the instruction that describes the task:
### Input:
show default popup menu
### Response:
def show_default_popup(self, pos):
'''show default popup menu'''
state = self.state
if state.default_popup.popup is not None:
wx_menu = state.default_popup.popup.wx_menu()
... |
def grok(cls, value, value_type, visitor):
"""Like :py:meth:`normalize.visitor.VisitorPattern.unpack` but called
for ``cast`` operations. Expects to work with dictionaries and lists
instead of Record objects.
Reverses the transform performed in
:py:meth:`normalize.visitor.Visit... | Like :py:meth:`normalize.visitor.VisitorPattern.unpack` but called
for ``cast`` operations. Expects to work with dictionaries and lists
instead of Record objects.
Reverses the transform performed in
:py:meth:`normalize.visitor.VisitorPattern.reduce` for collections with
propert... | Below is the the instruction that describes the task:
### Input:
Like :py:meth:`normalize.visitor.VisitorPattern.unpack` but called
for ``cast`` operations. Expects to work with dictionaries and lists
instead of Record objects.
Reverses the transform performed in
:py:meth:`normaliz... |
def check(self):
"""
Type check this object.
"""
try:
si, uninterp = self.interpolate()
# TODO(wickman) This should probably be pushed out to the interpolate leaves.
except (Object.CoercionError, MustacheParser.Uninterpolatable) as e:
return TypeCheck(False, "Unable to interpolate:... | Type check this object. | Below is the the instruction that describes the task:
### Input:
Type check this object.
### Response:
def check(self):
"""
Type check this object.
"""
try:
si, uninterp = self.interpolate()
# TODO(wickman) This should probably be pushed out to the interpolate leaves.
except (Object... |
def start(self):
"""Start the schedule."""
zones = [{"id": data[0], "duration": data[1], "sortOrder": count}
for (count, data) in enumerate(self._zones, 1)]
self._api.startMultiple(zones) | Start the schedule. | Below is the the instruction that describes the task:
### Input:
Start the schedule.
### Response:
def start(self):
"""Start the schedule."""
zones = [{"id": data[0], "duration": data[1], "sortOrder": count}
for (count, data) in enumerate(self._zones, 1)]
self._api.startMul... |
def revoke(self, fail_on_found=False, **kwargs):
"""Remove a user or a team from a role. Required information:
1) Type of the role
2) Resource of the role, inventory, credential, or any other
3) A user or a team to add to the role
=====API DOCS=====
Remove a user or a te... | Remove a user or a team from a role. Required information:
1) Type of the role
2) Resource of the role, inventory, credential, or any other
3) A user or a team to add to the role
=====API DOCS=====
Remove a user or a team from a role. Required information:
* Type of the ... | Below is the the instruction that describes the task:
### Input:
Remove a user or a team from a role. Required information:
1) Type of the role
2) Resource of the role, inventory, credential, or any other
3) A user or a team to add to the role
=====API DOCS=====
Remove a use... |
def register_default_dimensions(cube, slvr_cfg):
""" Register the default dimensions for a RIME solver """
import montblanc.src_types as mbs
# Pull out the configuration options for the basics
autocor = slvr_cfg['auto_correlations']
ntime = 10
na = 7
nbands = 1
nchan = 16
npol = 4... | Register the default dimensions for a RIME solver | Below is the the instruction that describes the task:
### Input:
Register the default dimensions for a RIME solver
### Response:
def register_default_dimensions(cube, slvr_cfg):
""" Register the default dimensions for a RIME solver """
import montblanc.src_types as mbs
# Pull out the configuration op... |
def list_containers(self, stack=None, service=None):
"""列出容器列表
列出应用内所有部署的容器, 返回一组容器IP。
Args:
- stack: 要列出容器的服务组名(可不填,表示默认列出所有)
- service: 要列出容器服务的服务名(可不填,表示默认列出所有)
Returns:
返回一个tuple对象,其格式为(<result>, <ResponseInfo>)
- result ... | 列出容器列表
列出应用内所有部署的容器, 返回一组容器IP。
Args:
- stack: 要列出容器的服务组名(可不填,表示默认列出所有)
- service: 要列出容器服务的服务名(可不填,表示默认列出所有)
Returns:
返回一个tuple对象,其格式为(<result>, <ResponseInfo>)
- result 成功返回容器的ip数组,失败返回{"error": "<errMsg string>"}
- Resp... | Below is the the instruction that describes the task:
### Input:
列出容器列表
列出应用内所有部署的容器, 返回一组容器IP。
Args:
- stack: 要列出容器的服务组名(可不填,表示默认列出所有)
- service: 要列出容器服务的服务名(可不填,表示默认列出所有)
Returns:
返回一个tuple对象,其格式为(<result>, <ResponseInfo>)
- result ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.