code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def clean_csvs(dialogpath=None):
""" Translate non-ASCII characters to spaces or equivalent ASCII characters """
dialogdir = os.dirname(dialogpath) if os.path.isfile(dialogpath) else dialogpath
filenames = [dialogpath.split(os.path.sep)[-1]] if os.path.isfile(dialogpath) else os.listdir(dialogpath)
for ... | Translate non-ASCII characters to spaces or equivalent ASCII characters | Below is the the instruction that describes the task:
### Input:
Translate non-ASCII characters to spaces or equivalent ASCII characters
### Response:
def clean_csvs(dialogpath=None):
""" Translate non-ASCII characters to spaces or equivalent ASCII characters """
dialogdir = os.dirname(dialogpath) if os.pa... |
def create_key(self, title, key):
"""
:calls: `POST /user/keys <http://developer.github.com/v3/users/keys>`_
:param title: string
:param key: string
:rtype: :class:`github.UserKey.UserKey`
"""
assert isinstance(title, (str, unicode)), title
assert isinstan... | :calls: `POST /user/keys <http://developer.github.com/v3/users/keys>`_
:param title: string
:param key: string
:rtype: :class:`github.UserKey.UserKey` | Below is the the instruction that describes the task:
### Input:
:calls: `POST /user/keys <http://developer.github.com/v3/users/keys>`_
:param title: string
:param key: string
:rtype: :class:`github.UserKey.UserKey`
### Response:
def create_key(self, title, key):
"""
:calls:... |
def _from_dict(cls, _dict):
"""Initialize a IdentifiableLanguages object from a json dictionary."""
args = {}
if 'languages' in _dict:
args['languages'] = [
IdentifiableLanguage._from_dict(x)
for x in (_dict.get('languages'))
]
else... | Initialize a IdentifiableLanguages object from a json dictionary. | Below is the the instruction that describes the task:
### Input:
Initialize a IdentifiableLanguages object from a json dictionary.
### Response:
def _from_dict(cls, _dict):
"""Initialize a IdentifiableLanguages object from a json dictionary."""
args = {}
if 'languages' in _dict:
... |
def add_container_output_args(argument_parser):
"""Define command-line arguments for output of a container (result files).
@param argument_parser: an argparse parser instance
"""
argument_parser.add_argument("--output-directory", metavar="DIR", default="output.files",
help="target directory for ... | Define command-line arguments for output of a container (result files).
@param argument_parser: an argparse parser instance | Below is the the instruction that describes the task:
### Input:
Define command-line arguments for output of a container (result files).
@param argument_parser: an argparse parser instance
### Response:
def add_container_output_args(argument_parser):
"""Define command-line arguments for output of a contain... |
def update_environment(self, **kwargs):
"""
Set environment variables for future git invocations. Return all changed
values in a format that can be passed back into this function to revert
the changes:
``Examples``::
old_env = self.update_environment(PWD='/tmp')
... | Set environment variables for future git invocations. Return all changed
values in a format that can be passed back into this function to revert
the changes:
``Examples``::
old_env = self.update_environment(PWD='/tmp')
self.update_environment(**old_env)
:param ... | Below is the the instruction that describes the task:
### Input:
Set environment variables for future git invocations. Return all changed
values in a format that can be passed back into this function to revert
the changes:
``Examples``::
old_env = self.update_environment(PWD='/... |
def sendFragmentStart(self, data):
"""
Send the start of a data fragment stream to a websocket client.
Subsequent data should be sent using sendFragment().
A fragment stream is completed when sendFragmentEnd() is called.
If data is a unicode object then the frame is ... | Send the start of a data fragment stream to a websocket client.
Subsequent data should be sent using sendFragment().
A fragment stream is completed when sendFragmentEnd() is called.
If data is a unicode object then the frame is sent as Text.
If the data is a bytearray objec... | Below is the the instruction that describes the task:
### Input:
Send the start of a data fragment stream to a websocket client.
Subsequent data should be sent using sendFragment().
A fragment stream is completed when sendFragmentEnd() is called.
If data is a unicode object then t... |
def loads(self, data):
"""
Deserialize the data into it's original python object.
:param bytes data: The serialized object to load.
:return: The original python object.
"""
if not isinstance(data, bytes):
raise TypeError("loads() argument 1 must be bytes, not {0}".format(type(data).__name__))
if self.... | Deserialize the data into it's original python object.
:param bytes data: The serialized object to load.
:return: The original python object. | Below is the the instruction that describes the task:
### Input:
Deserialize the data into it's original python object.
:param bytes data: The serialized object to load.
:return: The original python object.
### Response:
def loads(self, data):
"""
Deserialize the data into it's original python object.
... |
def toString(self):
"""
Returns almost original string.
If you want prettified string, try :meth:`.prettify`.
Returns:
str: Complete representation of the element with childs, endtag \
and so on.
"""
output = ""
if self.childs or se... | Returns almost original string.
If you want prettified string, try :meth:`.prettify`.
Returns:
str: Complete representation of the element with childs, endtag \
and so on. | Below is the the instruction that describes the task:
### Input:
Returns almost original string.
If you want prettified string, try :meth:`.prettify`.
Returns:
str: Complete representation of the element with childs, endtag \
and so on.
### Response:
def toString(self... |
def run_command_on_event(self, command, phase=phases.ASAP):
"""Run the given command on a given phase.
:param str|unicode command:
:param str|unicode phase: See constants in ``Phases`` class.
"""
self._set('exec-%s' % phase, command, multi=True)
return self._section | Run the given command on a given phase.
:param str|unicode command:
:param str|unicode phase: See constants in ``Phases`` class. | Below is the the instruction that describes the task:
### Input:
Run the given command on a given phase.
:param str|unicode command:
:param str|unicode phase: See constants in ``Phases`` class.
### Response:
def run_command_on_event(self, command, phase=phases.ASAP):
"""Run the given comm... |
def continuous_subpaths(self):
"""Breaks self into its continuous components, returning a list of
continuous subpaths.
I.e.
(all(subpath.iscontinuous() for subpath in self.continuous_subpaths())
and self == concatpaths(self.continuous_subpaths()))
)
"""
s... | Breaks self into its continuous components, returning a list of
continuous subpaths.
I.e.
(all(subpath.iscontinuous() for subpath in self.continuous_subpaths())
and self == concatpaths(self.continuous_subpaths()))
) | Below is the the instruction that describes the task:
### Input:
Breaks self into its continuous components, returning a list of
continuous subpaths.
I.e.
(all(subpath.iscontinuous() for subpath in self.continuous_subpaths())
and self == concatpaths(self.continuous_subpaths()))
... |
def check_argument_type(dtype, kernel_argument, i):
"""check if the numpy.dtype matches the type used in the code"""
types_map = {"uint8": ["uchar", "unsigned char", "uint8_t"],
"int8": ["char", "int8_t"],
"uint16": ["ushort", "unsigned short", "uint16_t"],
"in... | check if the numpy.dtype matches the type used in the code | Below is the the instruction that describes the task:
### Input:
check if the numpy.dtype matches the type used in the code
### Response:
def check_argument_type(dtype, kernel_argument, i):
"""check if the numpy.dtype matches the type used in the code"""
types_map = {"uint8": ["uchar", "unsigned char", "ui... |
def get_cn(self, structure, n, use_weights=False):
"""
Get coordination number, CN, of site with index n in structure.
Args:
structure (Structure): input structure.
n (integer): index of site for which to determine CN.
use_weights (boolean): flag indicating w... | Get coordination number, CN, of site with index n in structure.
Args:
structure (Structure): input structure.
n (integer): index of site for which to determine CN.
use_weights (boolean): flag indicating whether (True)
to use weights for computing the coordina... | Below is the the instruction that describes the task:
### Input:
Get coordination number, CN, of site with index n in structure.
Args:
structure (Structure): input structure.
n (integer): index of site for which to determine CN.
use_weights (boolean): flag indicating whe... |
def tree_view_keypress_callback(self, widget, event):
"""Tab back and forward tab-key motion in list widget and the scrollbar motion to follow key cursor motions
The method introduce motion and edit functionality by using "tab"- or "shift-tab"-key for a Gtk.TreeView.
It is designed to work wi... | Tab back and forward tab-key motion in list widget and the scrollbar motion to follow key cursor motions
The method introduce motion and edit functionality by using "tab"- or "shift-tab"-key for a Gtk.TreeView.
It is designed to work with a Gtk.TreeView which model is a Gtk.ListStore and only uses te... | Below is the the instruction that describes the task:
### Input:
Tab back and forward tab-key motion in list widget and the scrollbar motion to follow key cursor motions
The method introduce motion and edit functionality by using "tab"- or "shift-tab"-key for a Gtk.TreeView.
It is designed to wor... |
def elem_add(self, idx=None, name=None, **kwargs):
"""
Add an element of this model
:param idx: element idx
:param name: element name
:param kwargs: keyword arguments of the parameters
:return: allocated idx
"""
idx = self.system.devman.register_element(... | Add an element of this model
:param idx: element idx
:param name: element name
:param kwargs: keyword arguments of the parameters
:return: allocated idx | Below is the the instruction that describes the task:
### Input:
Add an element of this model
:param idx: element idx
:param name: element name
:param kwargs: keyword arguments of the parameters
:return: allocated idx
### Response:
def elem_add(self, idx=None, name=None, **kwargs):... |
def fit(self, X, y=None):
"""
Fits the RFECV with the wrapped model to the specified data and draws
the rfecv curve with the optimal number of features found.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training vector, where n_samples... | Fits the RFECV with the wrapped model to the specified data and draws
the rfecv curve with the optimal number of features found.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training vector, where n_samples is the number of samples and
n_fe... | Below is the the instruction that describes the task:
### Input:
Fits the RFECV with the wrapped model to the specified data and draws
the rfecv curve with the optimal number of features found.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training ... |
def _create_clone_schema_function(self):
"""
Creates a postgres function `clone_schema` that copies a schema and its
contents. Will replace any existing `clone_schema` functions owned by the
`postgres` superuser.
"""
cursor = connection.cursor()
cursor.execute(CLO... | Creates a postgres function `clone_schema` that copies a schema and its
contents. Will replace any existing `clone_schema` functions owned by the
`postgres` superuser. | Below is the the instruction that describes the task:
### Input:
Creates a postgres function `clone_schema` that copies a schema and its
contents. Will replace any existing `clone_schema` functions owned by the
`postgres` superuser.
### Response:
def _create_clone_schema_function(self):
"""... |
def domain_delete(auth=None, **kwargs):
'''
Delete a domain
CLI Example:
.. code-block:: bash
salt '*' keystoneng.domain_delete name=domain1
salt '*' keystoneng.domain_delete name=b62e76fbeeff4e8fb77073f591cf211e
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(... | Delete a domain
CLI Example:
.. code-block:: bash
salt '*' keystoneng.domain_delete name=domain1
salt '*' keystoneng.domain_delete name=b62e76fbeeff4e8fb77073f591cf211e | Below is the the instruction that describes the task:
### Input:
Delete a domain
CLI Example:
.. code-block:: bash
salt '*' keystoneng.domain_delete name=domain1
salt '*' keystoneng.domain_delete name=b62e76fbeeff4e8fb77073f591cf211e
### Response:
def domain_delete(auth=None, **kwargs):
... |
def s3_keys_from_env():
'''Retrieve S3 access keys from the environment, or None if not present.'''
env = os.environ
if S3_ACCESS_KEY_NAME in env and S3_SECRET_KEY_NAME in env:
keys = (env[S3_ACCESS_KEY_NAME], env[S3_SECRET_KEY_NAME])
debug("read S3 keys from environment")
return keys
... | Retrieve S3 access keys from the environment, or None if not present. | Below is the the instruction that describes the task:
### Input:
Retrieve S3 access keys from the environment, or None if not present.
### Response:
def s3_keys_from_env():
'''Retrieve S3 access keys from the environment, or None if not present.'''
env = os.environ
if S3_ACCESS_KEY_NAME in env and S3_S... |
def logCellActivity_noisyFeature_varyNumColumns(name="cellActivity"):
"""
Run the experiment, varying the column counts, and save each
[# correctly active cells, # incorrectly active cells]
pair to a JSON file that can be visualized.
"""
noiseLevels = [0.0, 0.30, 0.40, 0.45, 0.50, 0.55, 0.60, 0.65, 0.70, ... | Run the experiment, varying the column counts, and save each
[# correctly active cells, # incorrectly active cells]
pair to a JSON file that can be visualized. | Below is the the instruction that describes the task:
### Input:
Run the experiment, varying the column counts, and save each
[# correctly active cells, # incorrectly active cells]
pair to a JSON file that can be visualized.
### Response:
def logCellActivity_noisyFeature_varyNumColumns(name="cellActivity"):
... |
def print_last(limit=None, file=None):
"""This is a shorthand for 'print_exception(sys.last_type,
sys.last_value, sys.last_traceback, limit, file)'."""
if not hasattr(sys, "last_type"):
raise ValueError("no last exception")
if file is None:
file = sys.stderr
print_exception(sys.last_... | This is a shorthand for 'print_exception(sys.last_type,
sys.last_value, sys.last_traceback, limit, file)'. | Below is the the instruction that describes the task:
### Input:
This is a shorthand for 'print_exception(sys.last_type,
sys.last_value, sys.last_traceback, limit, file)'.
### Response:
def print_last(limit=None, file=None):
"""This is a shorthand for 'print_exception(sys.last_type,
sys.last_value, sys... |
def do_zero(self, params):
"""
\x1b[1mNAME\x1b[0m
zero - Set the znode's to None (no bytes)
\x1b[1mSYNOPSIS\x1b[0m
zero <path> [version]
\x1b[1mOPTIONS\x1b[0m
* version: only update if version matches (default: -1)
\x1b[1mEXAMPLES\x1b[0m
> zero /foo
> zero /foo 3
... | \x1b[1mNAME\x1b[0m
zero - Set the znode's to None (no bytes)
\x1b[1mSYNOPSIS\x1b[0m
zero <path> [version]
\x1b[1mOPTIONS\x1b[0m
* version: only update if version matches (default: -1)
\x1b[1mEXAMPLES\x1b[0m
> zero /foo
> zero /foo 3 | Below is the the instruction that describes the task:
### Input:
\x1b[1mNAME\x1b[0m
zero - Set the znode's to None (no bytes)
\x1b[1mSYNOPSIS\x1b[0m
zero <path> [version]
\x1b[1mOPTIONS\x1b[0m
* version: only update if version matches (default: -1)
\x1b[1mEXAMPLES\x1b[0m
> zero /f... |
def identifier(self, mask: str = '##-##/##') -> str:
"""Generate a random identifier by mask.
With this method you can generate any identifiers that
you need. Simply select the mask that you need.
:param mask:
The mask. Here ``@`` is a placeholder for characters and ``#`` i... | Generate a random identifier by mask.
With this method you can generate any identifiers that
you need. Simply select the mask that you need.
:param mask:
The mask. Here ``@`` is a placeholder for characters and ``#`` is
placeholder for digits.
:return: An identi... | Below is the the instruction that describes the task:
### Input:
Generate a random identifier by mask.
With this method you can generate any identifiers that
you need. Simply select the mask that you need.
:param mask:
The mask. Here ``@`` is a placeholder for characters and ``... |
def draw_2d(self, width=300, height=300, Hs=False): # pragma: no cover
r'''Interface for drawing a 2D image of the molecule.
Requires an HTML5 browser, and the libraries RDKit and
IPython. An exception is raised if either of these libraries is
absent.
Parameters
--------... | r'''Interface for drawing a 2D image of the molecule.
Requires an HTML5 browser, and the libraries RDKit and
IPython. An exception is raised if either of these libraries is
absent.
Parameters
----------
width : int
Number of pixels wide for the view
h... | Below is the the instruction that describes the task:
### Input:
r'''Interface for drawing a 2D image of the molecule.
Requires an HTML5 browser, and the libraries RDKit and
IPython. An exception is raised if either of these libraries is
absent.
Parameters
----------
... |
def check_shell_encoding(cls):
"""
Check whether ``sys.stdin`` and ``sys.stdout`` are UTF-8 encoded.
Return ``True`` on failure and ``False`` on success.
:rtype: bool
"""
is_in_utf8 = True
is_out_utf8 = True
if sys.stdin.encoding not in ["UTF-8", "UTF8"]... | Check whether ``sys.stdin`` and ``sys.stdout`` are UTF-8 encoded.
Return ``True`` on failure and ``False`` on success.
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Check whether ``sys.stdin`` and ``sys.stdout`` are UTF-8 encoded.
Return ``True`` on failure and ``False`` on success.
:rtype: bool
### Response:
def check_shell_encoding(cls):
"""
Check whether ``sys.stdin`` and ``s... |
def read_properties(self):
"""
Read properties from the ndata file reference
:param reference: the reference from which to read
:return: a tuple of the item_uuid and a dict of the properties
"""
with self.__lock:
absolute_file_path = self.__file_p... | Read properties from the ndata file reference
:param reference: the reference from which to read
:return: a tuple of the item_uuid and a dict of the properties | Below is the the instruction that describes the task:
### Input:
Read properties from the ndata file reference
:param reference: the reference from which to read
:return: a tuple of the item_uuid and a dict of the properties
### Response:
def read_properties(self):
"""
... |
def _ConvertFloat(value):
"""Convert an floating point number."""
if value == 'nan':
raise ParseError('Couldn\'t parse float "nan", use "NaN" instead.')
try:
# Assume Python compatible syntax.
return float(value)
except ValueError:
# Check alternative spellings.
if value == _NEG_INFINITY:
... | Convert an floating point number. | Below is the the instruction that describes the task:
### Input:
Convert an floating point number.
### Response:
def _ConvertFloat(value):
"""Convert an floating point number."""
if value == 'nan':
raise ParseError('Couldn\'t parse float "nan", use "NaN" instead.')
try:
# Assume Python compatible syn... |
def __parse_dict(self) -> OrderedDict:
"""Returns an Ordered Dictionary of nested bencode elements."""
self.idx += 1
d = OrderedDict()
key_name = None
while self.data[self.idx: self.idx + 1] != b'e':
if key_name is None:
key_name = self.__parse()
... | Returns an Ordered Dictionary of nested bencode elements. | Below is the the instruction that describes the task:
### Input:
Returns an Ordered Dictionary of nested bencode elements.
### Response:
def __parse_dict(self) -> OrderedDict:
"""Returns an Ordered Dictionary of nested bencode elements."""
self.idx += 1
d = OrderedDict()
key_name = ... |
def edit(self, invoice_id, data={}, **kwargs):
""""
Update an invoice
In draft state all the attributes are allowed.
Args:
invoice_id : Id for delete the invoice
data : Dictionary having keys using which invoice have to be updated
Returns:
Its... | Update an invoice
In draft state all the attributes are allowed.
Args:
invoice_id : Id for delete the invoice
data : Dictionary having keys using which invoice have to be updated
Returns:
Its response is the invoice entity, similar to create/update API respon... | Below is the the instruction that describes the task:
### Input:
Update an invoice
In draft state all the attributes are allowed.
Args:
invoice_id : Id for delete the invoice
data : Dictionary having keys using which invoice have to be updated
Returns:
It... |
def main(args=None):
""" Performs an action against a Streaming Analytics service.
"""
streamsx._streams._version._mismatch_check('streamsx.topology.context')
try:
sr = run_cmd(args)
sr['return_code'] = 0
except:
sr = {'return_code':1, 'error': sys.exc_info()}
return sr | Performs an action against a Streaming Analytics service. | Below is the the instruction that describes the task:
### Input:
Performs an action against a Streaming Analytics service.
### Response:
def main(args=None):
""" Performs an action against a Streaming Analytics service.
"""
streamsx._streams._version._mismatch_check('streamsx.topology.context')
try... |
def _enable_session_activity(self, app):
"""Enable session activity."""
user_logged_in.connect(login_listener, app)
user_logged_out.connect(logout_listener, app)
from .views.settings import blueprint
from .views.security import security, revoke_session
blueprint.route('/s... | Enable session activity. | Below is the the instruction that describes the task:
### Input:
Enable session activity.
### Response:
def _enable_session_activity(self, app):
"""Enable session activity."""
user_logged_in.connect(login_listener, app)
user_logged_out.connect(logout_listener, app)
from .views.setti... |
def md5sum(content):
'''Calculate and returns an MD5 checksum for the specified content.
:param content: text content
:returns: hex-digest formatted MD5 checksum as a string
'''
md5 = hashlib.md5()
md5.update(force_bytes(content))
return md5.hexdigest() | Calculate and returns an MD5 checksum for the specified content.
:param content: text content
:returns: hex-digest formatted MD5 checksum as a string | Below is the the instruction that describes the task:
### Input:
Calculate and returns an MD5 checksum for the specified content.
:param content: text content
:returns: hex-digest formatted MD5 checksum as a string
### Response:
def md5sum(content):
'''Calculate and returns an MD5 checksum for the spe... |
def issamedoc(self):
"""Return :const:`True` if this is a same-document reference."""
return (self.scheme is None and self.authority is None and
not self.path and self.query is None) | Return :const:`True` if this is a same-document reference. | Below is the the instruction that describes the task:
### Input:
Return :const:`True` if this is a same-document reference.
### Response:
def issamedoc(self):
"""Return :const:`True` if this is a same-document reference."""
return (self.scheme is None and self.authority is None and
... |
def get_egg_info(cfg, verbose=False):
"""Call 'setup egg_info' and return the parsed meta-data."""
result = Bunch()
setup_py = cfg.rootjoin('setup.py')
if not os.path.exists(setup_py):
return result
egg_info = shell.capture("python {} egg_info".format(setup_py), echo=True if verbose else No... | Call 'setup egg_info' and return the parsed meta-data. | Below is the the instruction that describes the task:
### Input:
Call 'setup egg_info' and return the parsed meta-data.
### Response:
def get_egg_info(cfg, verbose=False):
"""Call 'setup egg_info' and return the parsed meta-data."""
result = Bunch()
setup_py = cfg.rootjoin('setup.py')
if not os.pat... |
def get_general_case_info(adapter, institute_id=None, slice_query=None):
"""Return general information about cases
Args:
adapter(adapter.MongoAdapter)
institute_id(str)
slice_query(str): Query to filter cases to obtain statistics for.
Returns:
general(dict)
"""
g... | Return general information about cases
Args:
adapter(adapter.MongoAdapter)
institute_id(str)
slice_query(str): Query to filter cases to obtain statistics for.
Returns:
general(dict) | Below is the the instruction that describes the task:
### Input:
Return general information about cases
Args:
adapter(adapter.MongoAdapter)
institute_id(str)
slice_query(str): Query to filter cases to obtain statistics for.
Returns:
general(dict)
### Response:
def get_g... |
async def deserialize(data: dict):
"""
Create a credential object from a previously serialized credential object
:param data: JSON data from a serialized object.
:return: A created credential
Example:
credential = await Credential.create(source_id, offer)
data = a... | Create a credential object from a previously serialized credential object
:param data: JSON data from a serialized object.
:return: A created credential
Example:
credential = await Credential.create(source_id, offer)
data = await credential.serialize()
credential2 = await... | Below is the the instruction that describes the task:
### Input:
Create a credential object from a previously serialized credential object
:param data: JSON data from a serialized object.
:return: A created credential
Example:
credential = await Credential.create(source_id, offer)
... |
def _absolute_position_to_relative_position_unmasked(x):
"""Helper function for dot_product_unmasked_self_attention_relative_v2.
Rearrange an attention logits or weights Tensor.
The dimensions of the input represent:
[batch, heads, query_position, memory_position]
The dimensions of the output represent:
... | Helper function for dot_product_unmasked_self_attention_relative_v2.
Rearrange an attention logits or weights Tensor.
The dimensions of the input represent:
[batch, heads, query_position, memory_position]
The dimensions of the output represent:
[batch, heads, query_position, memory_position - query_positio... | Below is the the instruction that describes the task:
### Input:
Helper function for dot_product_unmasked_self_attention_relative_v2.
Rearrange an attention logits or weights Tensor.
The dimensions of the input represent:
[batch, heads, query_position, memory_position]
The dimensions of the output repres... |
def interpolate(self, factor, minLayer, maxLayer, round=True,
suppressError=True):
"""
Interpolate all possible data in the layer. ::
>>> layer.interpolate(0.5, otherLayer1, otherLayer2)
>>> layer.interpolate((0.5, 2.0), otherLayer1, otherLayer2, round=False)... | Interpolate all possible data in the layer. ::
>>> layer.interpolate(0.5, otherLayer1, otherLayer2)
>>> layer.interpolate((0.5, 2.0), otherLayer1, otherLayer2, round=False)
The interpolation occurs on a 0 to 1.0 range where **minLayer**
is located at 0 and **maxLayer** is locat... | Below is the the instruction that describes the task:
### Input:
Interpolate all possible data in the layer. ::
>>> layer.interpolate(0.5, otherLayer1, otherLayer2)
>>> layer.interpolate((0.5, 2.0), otherLayer1, otherLayer2, round=False)
The interpolation occurs on a 0 to 1.0 range... |
def plot_gross_leverage(returns, positions, ax=None, **kwargs):
"""
Plots gross leverage versus date.
Gross leverage is the sum of long and short exposure per share
divided by net asset value.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
... | Plots gross leverage versus date.
Gross leverage is the sum of long and short exposure per share
divided by net asset value.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
position... | Below is the the instruction that describes the task:
### Input:
Plots gross leverage versus date.
Gross leverage is the sum of long and short exposure per share
divided by net asset value.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
... |
def data(self, column, role):
"""Return the data for the specified column and role
The column addresses one attribute of the data.
:param column: the data column
:type column: int
:param role: the data role
:type role: QtCore.Qt.ItemDataRole
:returns: data depen... | Return the data for the specified column and role
The column addresses one attribute of the data.
:param column: the data column
:type column: int
:param role: the data role
:type role: QtCore.Qt.ItemDataRole
:returns: data depending on the role
:rtype:
... | Below is the the instruction that describes the task:
### Input:
Return the data for the specified column and role
The column addresses one attribute of the data.
:param column: the data column
:type column: int
:param role: the data role
:type role: QtCore.Qt.ItemDataRole
... |
def createURL(self, word, mode="phonefy"):
"""
Method to create the URL replacing the word in the appropriate URL.
Args:
-----
word: Word to be searched.
mode: Mode to be executed.
Return:
-------
The URL to be queried.
"""
... | Method to create the URL replacing the word in the appropriate URL.
Args:
-----
word: Word to be searched.
mode: Mode to be executed.
Return:
-------
The URL to be queried. | Below is the the instruction that describes the task:
### Input:
Method to create the URL replacing the word in the appropriate URL.
Args:
-----
word: Word to be searched.
mode: Mode to be executed.
Return:
-------
The URL to be queried.
### Resp... |
def index_data(self):
'''Generate and return a dictionary of default fields to be
indexed for searching (e.g., in Solr). Includes top-level
object properties, Content Model URIs, and Dublin Core
fields.
This method is intended to be customized and extended in order
to e... | Generate and return a dictionary of default fields to be
indexed for searching (e.g., in Solr). Includes top-level
object properties, Content Model URIs, and Dublin Core
fields.
This method is intended to be customized and extended in order
to easily modify the fields that shou... | Below is the the instruction that describes the task:
### Input:
Generate and return a dictionary of default fields to be
indexed for searching (e.g., in Solr). Includes top-level
object properties, Content Model URIs, and Dublin Core
fields.
This method is intended to be customize... |
def tags_published():
"""
Return the published tags.
"""
from tagging.models import Tag
from zinnia.models.entry import Entry
tags_entry_published = Tag.objects.usage_for_queryset(
Entry.published.all())
# Need to do that until the issue #44 of django-tagging is fixed
return Tag.... | Return the published tags. | Below is the the instruction that describes the task:
### Input:
Return the published tags.
### Response:
def tags_published():
"""
Return the published tags.
"""
from tagging.models import Tag
from zinnia.models.entry import Entry
tags_entry_published = Tag.objects.usage_for_queryset(
... |
def matrix_to_timeseries( image, matrix, mask=None ):
"""
converts a matrix to a ND image.
ANTsR function: `matrix2timeseries`
Arguments
---------
image: reference ND image
matrix: matrix to convert to image
mask: mask image defining voxels of interest
Returns
-------
... | converts a matrix to a ND image.
ANTsR function: `matrix2timeseries`
Arguments
---------
image: reference ND image
matrix: matrix to convert to image
mask: mask image defining voxels of interest
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> img... | Below is the the instruction that describes the task:
### Input:
converts a matrix to a ND image.
ANTsR function: `matrix2timeseries`
Arguments
---------
image: reference ND image
matrix: matrix to convert to image
mask: mask image defining voxels of interest
Returns
-------
... |
def search(self, fields=None, query=None, filters=None):
"""Search for entities.
At its simplest, this method searches for all entities of a given kind.
For example, to ask for all
:class:`nailgun.entities.LifecycleEnvironment` entities::
LifecycleEnvironment().search()
... | Search for entities.
At its simplest, this method searches for all entities of a given kind.
For example, to ask for all
:class:`nailgun.entities.LifecycleEnvironment` entities::
LifecycleEnvironment().search()
Values on an entity are used to generate a search query, and t... | Below is the the instruction that describes the task:
### Input:
Search for entities.
At its simplest, this method searches for all entities of a given kind.
For example, to ask for all
:class:`nailgun.entities.LifecycleEnvironment` entities::
LifecycleEnvironment().search()
... |
def markdown(doc, title=True, template='short_documentation.md'):
"""Markdown, specifically for the Notes field in a CKAN dataset"""
from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(
loader=PackageLoader('metapack', 'support/templates')
#autoescape=select_a... | Markdown, specifically for the Notes field in a CKAN dataset | Below is the the instruction that describes the task:
### Input:
Markdown, specifically for the Notes field in a CKAN dataset
### Response:
def markdown(doc, title=True, template='short_documentation.md'):
"""Markdown, specifically for the Notes field in a CKAN dataset"""
from jinja2 import Environment, P... |
def write_sampler_metadata(self, sampler):
"""Adds writing ntemps to file.
"""
super(MultiTemperedMetadataIO, self).write_sampler_metadata(sampler)
self[self.sampler_group].attrs["ntemps"] = sampler.ntemps | Adds writing ntemps to file. | Below is the the instruction that describes the task:
### Input:
Adds writing ntemps to file.
### Response:
def write_sampler_metadata(self, sampler):
"""Adds writing ntemps to file.
"""
super(MultiTemperedMetadataIO, self).write_sampler_metadata(sampler)
self[self.sampler_group].at... |
def _corrupt(self, data, dpos):
"""Corruption from SHA1 core."""
ws = list(self._BLK_BE.unpack_from(data, dpos))
for t in range(16, 80):
tmp = ws[(t - 3) & 15] ^ ws[(t - 8) & 15] ^ ws[(t - 14) & 15] ^ ws[(t - 16) & 15]
ws[t & 15] = ((tmp << 1) | (tmp >> (32 - 1))) & 0xFFF... | Corruption from SHA1 core. | Below is the the instruction that describes the task:
### Input:
Corruption from SHA1 core.
### Response:
def _corrupt(self, data, dpos):
"""Corruption from SHA1 core."""
ws = list(self._BLK_BE.unpack_from(data, dpos))
for t in range(16, 80):
tmp = ws[(t - 3) & 15] ^ ws[(t - 8) ... |
def to_dict(self):
"""Dump show to a dictionary.
:return: Show dictionary
:rtype: :class:`~python:dict`
"""
result = self.to_identifier()
result['seasons'] = [
season.to_dict()
for season in self.seasons.values()
]
result['in_wa... | Dump show to a dictionary.
:return: Show dictionary
:rtype: :class:`~python:dict` | Below is the the instruction that describes the task:
### Input:
Dump show to a dictionary.
:return: Show dictionary
:rtype: :class:`~python:dict`
### Response:
def to_dict(self):
"""Dump show to a dictionary.
:return: Show dictionary
:rtype: :class:`~python:dict`
... |
def parse_fields(cls, formatter):
"Returns the format fields otherwise raise exception"
if formatter is None: return []
try:
parse = list(string.Formatter().parse(formatter))
return set(f for f in list(zip(*parse))[1] if f is not None)
except:
raise S... | Returns the format fields otherwise raise exception | Below is the the instruction that describes the task:
### Input:
Returns the format fields otherwise raise exception
### Response:
def parse_fields(cls, formatter):
"Returns the format fields otherwise raise exception"
if formatter is None: return []
try:
parse = list(string.For... |
def verify_server(self, server_name, srv_type = 'xmpp-client'):
"""Verify certificate for a server.
:Parameters:
- `server_name`: name of the server presenting the cerificate
- `srv_type`: service type requested, as used in the SRV record
:Types:
- `server_na... | Verify certificate for a server.
:Parameters:
- `server_name`: name of the server presenting the cerificate
- `srv_type`: service type requested, as used in the SRV record
:Types:
- `server_name`: `unicode` or `JID`
- `srv_type`: `unicode`
:Retur... | Below is the the instruction that describes the task:
### Input:
Verify certificate for a server.
:Parameters:
- `server_name`: name of the server presenting the cerificate
- `srv_type`: service type requested, as used in the SRV record
:Types:
- `server_name`: `... |
def remove_item(self, item):
"""
Remove (and un-index) an object
:param item: object to remove
:type item: alignak.objects.item.Item
:return: None
"""
self.unindex_item(item)
self.items.pop(item.uuid, None) | Remove (and un-index) an object
:param item: object to remove
:type item: alignak.objects.item.Item
:return: None | Below is the the instruction that describes the task:
### Input:
Remove (and un-index) an object
:param item: object to remove
:type item: alignak.objects.item.Item
:return: None
### Response:
def remove_item(self, item):
"""
Remove (and un-index) an object
:param ... |
def send_message(self, text, user_ids, thread_id=None):
"""
:param self: bot
:param text: text of message
:param user_ids: list of user_ids for creating group or one user_id for send to one person
:param thread_id: thread_id
"""
user_ids = _get_user_ids(self, user_ids)
if not isinstance(... | :param self: bot
:param text: text of message
:param user_ids: list of user_ids for creating group or one user_id for send to one person
:param thread_id: thread_id | Below is the the instruction that describes the task:
### Input:
:param self: bot
:param text: text of message
:param user_ids: list of user_ids for creating group or one user_id for send to one person
:param thread_id: thread_id
### Response:
def send_message(self, text, user_ids, thread_id=None):
... |
def plot_factors(U, plots='line', fig=None, axes=None, scatter_kw=dict(),
line_kw=dict(), bar_kw=dict(), **kwargs):
"""Plots a KTensor.
Note: Each keyword option is broadcast to all modes of the KTensor. For
example, if `U` is a 3rd-order tensor (i.e. `U.ndim == 3`) then
`plot_factors(... | Plots a KTensor.
Note: Each keyword option is broadcast to all modes of the KTensor. For
example, if `U` is a 3rd-order tensor (i.e. `U.ndim == 3`) then
`plot_factors(U, plots=['line','bar','scatter'])` plots all factors for the
first mode as a line plot, the second as a bar plot, and the third mode as... | Below is the the instruction that describes the task:
### Input:
Plots a KTensor.
Note: Each keyword option is broadcast to all modes of the KTensor. For
example, if `U` is a 3rd-order tensor (i.e. `U.ndim == 3`) then
`plot_factors(U, plots=['line','bar','scatter'])` plots all factors for the
first... |
def i3():
'''Install and customize the tiling window manager i3.'''
install_package('i3')
install_file_legacy(path='~/.i3/config', username=env.user, repos_dir='repos')
# setup: hide the mouse if not in use
# in ~/.i3/config: 'exec /home/<USERNAME>/repos/hhpc/hhpc -i 10 &'
install_packages(['ma... | Install and customize the tiling window manager i3. | Below is the the instruction that describes the task:
### Input:
Install and customize the tiling window manager i3.
### Response:
def i3():
'''Install and customize the tiling window manager i3.'''
install_package('i3')
install_file_legacy(path='~/.i3/config', username=env.user, repos_dir='repos')
... |
def _guess_next_poll_interval(self):
"""
Determine when to query the progress status next.
This function is used if the external progress function did not return time interval for when it should be
queried next.
"""
time_elapsed = self._progress_data[-1][0] - self._progr... | Determine when to query the progress status next.
This function is used if the external progress function did not return time interval for when it should be
queried next. | Below is the the instruction that describes the task:
### Input:
Determine when to query the progress status next.
This function is used if the external progress function did not return time interval for when it should be
queried next.
### Response:
def _guess_next_poll_interval(self):
"""... |
def convert_file(filename, renderer):
"""
Parse a Markdown file and dump the output to stdout.
"""
try:
with open(filename, 'r') as fin:
rendered = mistletoe.markdown(fin, renderer)
print(rendered, end='')
except OSError:
sys.exit('Cannot open file "{}".'.form... | Parse a Markdown file and dump the output to stdout. | Below is the the instruction that describes the task:
### Input:
Parse a Markdown file and dump the output to stdout.
### Response:
def convert_file(filename, renderer):
"""
Parse a Markdown file and dump the output to stdout.
"""
try:
with open(filename, 'r') as fin:
rendered =... |
def retrieve_review(self, reviewer, product):
"""Retrieve review that the given reviewer put the given product.
Args:
reviewer: An instance of Reviewer.
product: An instance of Product.
Returns:
A review object.
Raises:
TypeError: when given rev... | Retrieve review that the given reviewer put the given product.
Args:
reviewer: An instance of Reviewer.
product: An instance of Product.
Returns:
A review object.
Raises:
TypeError: when given reviewer and product aren't instance of
specifie... | Below is the the instruction that describes the task:
### Input:
Retrieve review that the given reviewer put the given product.
Args:
reviewer: An instance of Reviewer.
product: An instance of Product.
Returns:
A review object.
Raises:
TypeError: wh... |
def finite_datetimes(self, finite_start, finite_stop):
"""
Simply returns the points in time that correspond to turn of month.
"""
start_date = self._align(finite_start)
aligned_stop = self._align(finite_stop)
dates = []
for m in itertools.count():
t =... | Simply returns the points in time that correspond to turn of month. | Below is the the instruction that describes the task:
### Input:
Simply returns the points in time that correspond to turn of month.
### Response:
def finite_datetimes(self, finite_start, finite_stop):
"""
Simply returns the points in time that correspond to turn of month.
"""
start... |
def kill_all_jobs():
'''
Sends a kill signal (SIGKILL 9) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_all_jobs
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system ... | Sends a kill signal (SIGKILL 9) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_all_jobs | Below is the the instruction that describes the task:
### Input:
Sends a kill signal (SIGKILL 9) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_all_jobs
### Response:
def kill_all_jobs():
'''
Sends a kill signal (SIGKILL 9) to all currently running... |
def sep_dist_clay(ConcClay, material):
"""Return the separation distance between clay particles."""
return ((material.Density/ConcClay)*((np.pi
* material.Diameter ** 3)/6))**(1/3) | Return the separation distance between clay particles. | Below is the the instruction that describes the task:
### Input:
Return the separation distance between clay particles.
### Response:
def sep_dist_clay(ConcClay, material):
"""Return the separation distance between clay particles."""
return ((material.Density/ConcClay)*((np.pi
*... |
def evals_get(self, service_staff_id, start_date, end_date, session):
'''taobao.wangwang.eservice.evals.get 获取评价详细
根据用户id查询用户对应的评价详细情况, 主账号id可以查询店铺内子账号的评价 组管理员可以查询组内账号的评价 非管理员的子账号可以查自己的评价'''
request = TOPRequest('taobao.wangwang.eservice.evals.get')
request['service_staff_id'] =... | taobao.wangwang.eservice.evals.get 获取评价详细
根据用户id查询用户对应的评价详细情况, 主账号id可以查询店铺内子账号的评价 组管理员可以查询组内账号的评价 非管理员的子账号可以查自己的评价 | Below is the the instruction that describes the task:
### Input:
taobao.wangwang.eservice.evals.get 获取评价详细
根据用户id查询用户对应的评价详细情况, 主账号id可以查询店铺内子账号的评价 组管理员可以查询组内账号的评价 非管理员的子账号可以查自己的评价
### Response:
def evals_get(self, service_staff_id, start_date, end_date, session):
'''taobao.wangwang.eservic... |
def shape(self):
"""Copy the shape from TCMPS as a new numpy ndarray."""
# Create C variables that will serve as out parameters for TCMPS.
shape_ptr = _ctypes.POINTER(_ctypes.c_size_t)() # size_t* shape_ptr
dim = _ctypes.c_size_t() # size_t dim
# Obtain... | Copy the shape from TCMPS as a new numpy ndarray. | Below is the the instruction that describes the task:
### Input:
Copy the shape from TCMPS as a new numpy ndarray.
### Response:
def shape(self):
"""Copy the shape from TCMPS as a new numpy ndarray."""
# Create C variables that will serve as out parameters for TCMPS.
shape_ptr = _ctypes.PO... |
def generateSummary(self, extraLapse = TYPICAL_LAPSE):
'''Generates a summary of the status of the expected scripts broken based on the log.
This summary (a list of strings) is returned as well as a list with the dates (which
can be used to index the log)of the most recent attempts at the failed jobs.
'''
... | Generates a summary of the status of the expected scripts broken based on the log.
This summary (a list of strings) is returned as well as a list with the dates (which
can be used to index the log)of the most recent attempts at the failed jobs. | Below is the the instruction that describes the task:
### Input:
Generates a summary of the status of the expected scripts broken based on the log.
This summary (a list of strings) is returned as well as a list with the dates (which
can be used to index the log)of the most recent attempts at the failed jobs.
... |
def fir_remez_lpf(f_pass, f_stop, d_pass, d_stop, fs = 1.0, N_bump=5):
"""
Design an FIR lowpass filter using remez with order
determination. The filter order is determined based on
f_pass Hz, fstop Hz, and the desired passband ripple
d_pass dB and stopband attenuation d_stop dB all
rel... | Design an FIR lowpass filter using remez with order
determination. The filter order is determined based on
f_pass Hz, fstop Hz, and the desired passband ripple
d_pass dB and stopband attenuation d_stop dB all
relative to a sampling rate of fs Hz.
Mark Wickert October 2016, updated October ... | Below is the the instruction that describes the task:
### Input:
Design an FIR lowpass filter using remez with order
determination. The filter order is determined based on
f_pass Hz, fstop Hz, and the desired passband ripple
d_pass dB and stopband attenuation d_stop dB all
relative to a sampl... |
def compile_action_bound_constraints(self,
state: Sequence[tf.Tensor]) -> Dict[str, Bounds]:
'''Compiles all actions bounds for the given `state`.
Args:
state (Sequence[tf.Tensor]): The current state fluents.
Returns:
A mapping from action names to a pair of... | Compiles all actions bounds for the given `state`.
Args:
state (Sequence[tf.Tensor]): The current state fluents.
Returns:
A mapping from action names to a pair of
:obj:`rddl2tf.fluent.TensorFluent` representing
its lower and upper bounds. | Below is the the instruction that describes the task:
### Input:
Compiles all actions bounds for the given `state`.
Args:
state (Sequence[tf.Tensor]): The current state fluents.
Returns:
A mapping from action names to a pair of
:obj:`rddl2tf.fluent.TensorFluent`... |
def on_comment_posted(sender, comment, request, **kwargs):
"""
Send email notification of a new comment to site staff when email notifications have been requested.
"""
content_object = comment.content_object
moderator = moderation.get_model_moderator(content_object.__class__)
if moderator is No... | Send email notification of a new comment to site staff when email notifications have been requested. | Below is the the instruction that describes the task:
### Input:
Send email notification of a new comment to site staff when email notifications have been requested.
### Response:
def on_comment_posted(sender, comment, request, **kwargs):
"""
Send email notification of a new comment to site staff when emai... |
def get_times(self):
"""return an array of times (in sec) of all APs."""
self.ensureDetection()
times=[]
for ap in self.APs:
times.append(ap["T"])
return np.array(sorted(times)) | return an array of times (in sec) of all APs. | Below is the the instruction that describes the task:
### Input:
return an array of times (in sec) of all APs.
### Response:
def get_times(self):
"""return an array of times (in sec) of all APs."""
self.ensureDetection()
times=[]
for ap in self.APs:
times.append(ap["T"])... |
def get_unpack_filter(cls, unpackable_target):
"""Calculate a filter function from the include/exclude patterns of a Target.
:param ImportRemoteSourcesMixin unpackable_target: A target with include_patterns and
exclude_patterns attributes.
"""
# TO... | Calculate a filter function from the include/exclude patterns of a Target.
:param ImportRemoteSourcesMixin unpackable_target: A target with include_patterns and
exclude_patterns attributes. | Below is the the instruction that describes the task:
### Input:
Calculate a filter function from the include/exclude patterns of a Target.
:param ImportRemoteSourcesMixin unpackable_target: A target with include_patterns and
exclude_patterns attributes.
#... |
def check_for_connection(self):
""" Scan arguments for a `@name` one.
"""
for idx, arg in enumerate(self.args):
if arg.startswith('@'):
if arg[1:] not in config.connections:
self.parser.error("Undefined connection '{}'!".format(arg[1:]))
... | Scan arguments for a `@name` one. | Below is the the instruction that describes the task:
### Input:
Scan arguments for a `@name` one.
### Response:
def check_for_connection(self):
""" Scan arguments for a `@name` one.
"""
for idx, arg in enumerate(self.args):
if arg.startswith('@'):
if arg[1:] not... |
def get_md_device(self, line, personalities=[]):
"""Return a dict of md device define in the line."""
ret = {}
splitted = split('\W+', line)
# Raid status
# Active or 'started'. An inactive array is usually faulty.
# Stopped arrays aren't visible here.
ret['statu... | Return a dict of md device define in the line. | Below is the the instruction that describes the task:
### Input:
Return a dict of md device define in the line.
### Response:
def get_md_device(self, line, personalities=[]):
"""Return a dict of md device define in the line."""
ret = {}
splitted = split('\W+', line)
# Raid status
... |
def filter(ol,test_func,*args,**kwargs):
'''
from elist.elist import *
def test_func(ele,x):
cond = (ele > x)
return(cond)
ol = [1,2,3,4]
id(ol)
new = filter(ol,test_func,3)
new
id(new)
#####
ol = [10,20,30,40]
... | from elist.elist import *
def test_func(ele,x):
cond = (ele > x)
return(cond)
ol = [1,2,3,4]
id(ol)
new = filter(ol,test_func,3)
new
id(new)
#####
ol = [10,20,30,40]
id(ol)
rslt = filter(ol,test_func,3,mode=... | Below is the the instruction that describes the task:
### Input:
from elist.elist import *
def test_func(ele,x):
cond = (ele > x)
return(cond)
ol = [1,2,3,4]
id(ol)
new = filter(ol,test_func,3)
new
id(new)
#####
ol = [1... |
def me(self):
"""Get the details of the person accessing the API.
Raises:
ApiError: If the Webex Teams cloud returns an error.
"""
# API request
json_data = self._session.get(API_ENDPOINT + '/me')
# Return a person object created from the response JSON data... | Get the details of the person accessing the API.
Raises:
ApiError: If the Webex Teams cloud returns an error. | Below is the the instruction that describes the task:
### Input:
Get the details of the person accessing the API.
Raises:
ApiError: If the Webex Teams cloud returns an error.
### Response:
def me(self):
"""Get the details of the person accessing the API.
Raises:
Ap... |
def make_report(self, session, *levels):
"""
Prepares the report at the requested level(s)
"""
if not levels:
levels = ["full"]
try:
# List the methods to call, avoiding double-calls
methods = set()
for level in levels:
... | Prepares the report at the requested level(s) | Below is the the instruction that describes the task:
### Input:
Prepares the report at the requested level(s)
### Response:
def make_report(self, session, *levels):
"""
Prepares the report at the requested level(s)
"""
if not levels:
levels = ["full"]
try:
... |
def glob(self, node, path):
"""
Return instances at `path` supporting wildcards.
Behaves identical to :any:`get`, but accepts wildcards and returns
a list of found nodes.
* `*` matches any characters, except '/'.
* `?` matches a single character, except '/'.
An... | Return instances at `path` supporting wildcards.
Behaves identical to :any:`get`, but accepts wildcards and returns
a list of found nodes.
* `*` matches any characters, except '/'.
* `?` matches a single character, except '/'.
An example module tree:
>>> from anytree ... | Below is the the instruction that describes the task:
### Input:
Return instances at `path` supporting wildcards.
Behaves identical to :any:`get`, but accepts wildcards and returns
a list of found nodes.
* `*` matches any characters, except '/'.
* `?` matches a single character, ex... |
def scan(cls, filter_builder=None, **scan_filter):
"""High level scan API.
:param filter_builder: filter expression builder.
:type filter_builder: :class:`~bynamodb.filterexps.Operator`
"""
scan_kwargs = {'scan_filter': build_condition(scan_filter)}
if filter_builder:
... | High level scan API.
:param filter_builder: filter expression builder.
:type filter_builder: :class:`~bynamodb.filterexps.Operator` | Below is the the instruction that describes the task:
### Input:
High level scan API.
:param filter_builder: filter expression builder.
:type filter_builder: :class:`~bynamodb.filterexps.Operator`
### Response:
def scan(cls, filter_builder=None, **scan_filter):
"""High level scan API.
... |
def dir_tails_top(self, rr_id) -> str:
"""
Return top of tails tree for input rev reg id.
:param rr_id: revocation registry identifier
:return: top of tails tree
"""
return join(self.dir_tails_hopper, rr_id) if self.external else self.dir_tails | Return top of tails tree for input rev reg id.
:param rr_id: revocation registry identifier
:return: top of tails tree | Below is the the instruction that describes the task:
### Input:
Return top of tails tree for input rev reg id.
:param rr_id: revocation registry identifier
:return: top of tails tree
### Response:
def dir_tails_top(self, rr_id) -> str:
"""
Return top of tails tree for input rev re... |
def parse_user_params(user_params):
"""
Parse the user params (-p/--params) and them as a dict.
"""
if user_params:
params = {}
try:
for param in options.params.split(','):
param_key, param_value = param.split('=', 1)
params[param_key] = param_... | Parse the user params (-p/--params) and them as a dict. | Below is the the instruction that describes the task:
### Input:
Parse the user params (-p/--params) and them as a dict.
### Response:
def parse_user_params(user_params):
"""
Parse the user params (-p/--params) and them as a dict.
"""
if user_params:
params = {}
try:
for... |
def _get_peer_connection(self, blacklist=None):
"""Find a peer and connect to it.
Returns a ``(peer, connection)`` tuple.
Raises ``NoAvailablePeerError`` if no healthy peers are found.
:param blacklist:
If given, a set of hostports for peers that we must not try.
"... | Find a peer and connect to it.
Returns a ``(peer, connection)`` tuple.
Raises ``NoAvailablePeerError`` if no healthy peers are found.
:param blacklist:
If given, a set of hostports for peers that we must not try. | Below is the the instruction that describes the task:
### Input:
Find a peer and connect to it.
Returns a ``(peer, connection)`` tuple.
Raises ``NoAvailablePeerError`` if no healthy peers are found.
:param blacklist:
If given, a set of hostports for peers that we must not try.... |
def get(self, count=None, since_id=None, silent=False):
"""
Get all photos from the user or members of the list
:param count: Number of tweets to try and retrieve. If None, return
all photos since `since_id`
:param since_id: An integer specifying the oldest tweet id
"... | Get all photos from the user or members of the list
:param count: Number of tweets to try and retrieve. If None, return
all photos since `since_id`
:param since_id: An integer specifying the oldest tweet id | Below is the the instruction that describes the task:
### Input:
Get all photos from the user or members of the list
:param count: Number of tweets to try and retrieve. If None, return
all photos since `since_id`
:param since_id: An integer specifying the oldest tweet id
### Response:
d... |
def compliance_uri(self):
"""Compliance URI based on api_version.
Value is based on api_version and complicance_level, will be
None if either are unset/unrecognized. The assumption here is
that the api_version and level are orthogonal, override this
method if that isn't true.
... | Compliance URI based on api_version.
Value is based on api_version and complicance_level, will be
None if either are unset/unrecognized. The assumption here is
that the api_version and level are orthogonal, override this
method if that isn't true. | Below is the the instruction that describes the task:
### Input:
Compliance URI based on api_version.
Value is based on api_version and complicance_level, will be
None if either are unset/unrecognized. The assumption here is
that the api_version and level are orthogonal, override this
... |
def floating_ip_create(self, pool=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ip = nt_ks.floating_ips.create(pool)
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,... | Allocate a floating IP
.. versionadded:: 2016.3.0 | Below is the the instruction that describes the task:
### Input:
Allocate a floating IP
.. versionadded:: 2016.3.0
### Response:
def floating_ip_create(self, pool=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
flo... |
def qwe(rtol, atol, maxint, inp, intervals, lambd=None, off=None,
factAng=None):
r"""Quadrature-With-Extrapolation.
This is the kernel of the QWE method, used for the Hankel (``hqwe``) and
the Fourier (``fqwe``) Transforms. See ``hqwe`` for an extensive
description.
This function is based ... | r"""Quadrature-With-Extrapolation.
This is the kernel of the QWE method, used for the Hankel (``hqwe``) and
the Fourier (``fqwe``) Transforms. See ``hqwe`` for an extensive
description.
This function is based on ``qwe.m`` from the source code distributed with
[Key12]_. | Below is the the instruction that describes the task:
### Input:
r"""Quadrature-With-Extrapolation.
This is the kernel of the QWE method, used for the Hankel (``hqwe``) and
the Fourier (``fqwe``) Transforms. See ``hqwe`` for an extensive
description.
This function is based on ``qwe.m`` from the so... |
def configure(self, src_dir, build_dir, **kwargs):
"""This function builds the cmake configure command."""
del kwargs
ex_path = self._ex_args.get("project_path")
if ex_path:
src_dir = os.path.join(src_dir, ex_path)
return [{"args": ["cmake", src_dir] + self._config_a... | This function builds the cmake configure command. | Below is the the instruction that describes the task:
### Input:
This function builds the cmake configure command.
### Response:
def configure(self, src_dir, build_dir, **kwargs):
"""This function builds the cmake configure command."""
del kwargs
ex_path = self._ex_args.get("project_path")
... |
def __generate_indexed_requirements(dut_count, basekeys, requirements):
"""
Generate indexed requirements from general requirements.
:param dut_count: Amount of duts
:param basekeys: base keys as dict
:param requirements: requirements
:return: Indexed requirements as dic... | Generate indexed requirements from general requirements.
:param dut_count: Amount of duts
:param basekeys: base keys as dict
:param requirements: requirements
:return: Indexed requirements as dict. | Below is the the instruction that describes the task:
### Input:
Generate indexed requirements from general requirements.
:param dut_count: Amount of duts
:param basekeys: base keys as dict
:param requirements: requirements
:return: Indexed requirements as dict.
### Response:
def _... |
def save_state(self):
"""Save the current state of the ui to an internal class member.
The saved state can be restored again easily using
:func:`restore_state`
"""
state = {
'hazard': self.hazard_layer_combo.currentText(),
'exposure': self.exposure_layer_... | Save the current state of the ui to an internal class member.
The saved state can be restored again easily using
:func:`restore_state` | Below is the the instruction that describes the task:
### Input:
Save the current state of the ui to an internal class member.
The saved state can be restored again easily using
:func:`restore_state`
### Response:
def save_state(self):
"""Save the current state of the ui to an internal cla... |
def _add_notice_to_docstring(doc, no_doc_str, notice):
"""Adds a deprecation notice to a docstring."""
if not doc:
lines = [no_doc_str]
else:
lines = _normalize_docstring(doc).splitlines()
notice = [''] + notice
if len(lines) > 1:
# Make sure that we keep our distance from... | Adds a deprecation notice to a docstring. | Below is the the instruction that describes the task:
### Input:
Adds a deprecation notice to a docstring.
### Response:
def _add_notice_to_docstring(doc, no_doc_str, notice):
"""Adds a deprecation notice to a docstring."""
if not doc:
lines = [no_doc_str]
else:
lines = _normalize_docs... |
def get_auth_context(hostname, username, password, auth_mech):
"""
Returns an AuthContext used in the CredSSP authentication process and to
wrap/unwrap tokens sent to and from the client. This step get's the context
based on the auth_mech configured and what is available on the server. It
tries to f... | Returns an AuthContext used in the CredSSP authentication process and to
wrap/unwrap tokens sent to and from the client. This step get's the context
based on the auth_mech configured and what is available on the server. It
tries to favour system libraries like SSPI (Windows) or GSSAPI (Unix) if
possible... | Below is the the instruction that describes the task:
### Input:
Returns an AuthContext used in the CredSSP authentication process and to
wrap/unwrap tokens sent to and from the client. This step get's the context
based on the auth_mech configured and what is available on the server. It
tries to favour ... |
def eta_from_tau0_tau3(tau0, tau3, f_lower):
r"""Returns symmetric mass ratio from :math:`\tau_0, \tau_3`."""
mtotal = mtotal_from_tau0_tau3(tau0, tau3, f_lower,
in_seconds=True)
eta = mtotal**(-2./3.) * (_a3(f_lower) / tau3)
return eta | r"""Returns symmetric mass ratio from :math:`\tau_0, \tau_3`. | Below is the the instruction that describes the task:
### Input:
r"""Returns symmetric mass ratio from :math:`\tau_0, \tau_3`.
### Response:
def eta_from_tau0_tau3(tau0, tau3, f_lower):
r"""Returns symmetric mass ratio from :math:`\tau_0, \tau_3`."""
mtotal = mtotal_from_tau0_tau3(tau0, tau3, f_lower,
... |
def get_objective_form_for_create(self, objective_record_types=None):
"""Gets the objective form for creating new objectives.
A new form should be requested for each create transaction.
arg: objectiveRecordTypes (osid.type.Type): array of
objective record types
return:... | Gets the objective form for creating new objectives.
A new form should be requested for each create transaction.
arg: objectiveRecordTypes (osid.type.Type): array of
objective record types
return: (osid.learning.ObjectiveForm) - the objective form
raise: NullArgument ... | Below is the the instruction that describes the task:
### Input:
Gets the objective form for creating new objectives.
A new form should be requested for each create transaction.
arg: objectiveRecordTypes (osid.type.Type): array of
objective record types
return: (osid.learn... |
def add_user_to_group(group, role, email):
"""Add a user to a group the caller owns
Args:
group (str): Group name
role (str) : Role of user for group; either 'member' or 'admin'
email (str): Email of user or group to add
Swagger:
https://api.firecloud.org/#!/Groups/addU... | Add a user to a group the caller owns
Args:
group (str): Group name
role (str) : Role of user for group; either 'member' or 'admin'
email (str): Email of user or group to add
Swagger:
https://api.firecloud.org/#!/Groups/addUserToGroup | Below is the the instruction that describes the task:
### Input:
Add a user to a group the caller owns
Args:
group (str): Group name
role (str) : Role of user for group; either 'member' or 'admin'
email (str): Email of user or group to add
Swagger:
https://api.firecloud... |
def update(self, stats):
"""Update stats to a server.
The method builds two lists: names and values
and calls the export method to export the stats.
Note: this class can be overwrite (for example in CSV and Graph).
"""
if not self.export_enable:
return False... | Update stats to a server.
The method builds two lists: names and values
and calls the export method to export the stats.
Note: this class can be overwrite (for example in CSV and Graph). | Below is the the instruction that describes the task:
### Input:
Update stats to a server.
The method builds two lists: names and values
and calls the export method to export the stats.
Note: this class can be overwrite (for example in CSV and Graph).
### Response:
def update(self, stats)... |
def plot_clicked(self, mouse_event):
"""
gets activated when the user clicks on a plot
Args:
mouse_event:
"""
if isinstance(self.current_script, SelectPoints) and self.current_script.is_running:
if (not (mouse_event.xdata == None)):
if (mou... | gets activated when the user clicks on a plot
Args:
mouse_event: | Below is the the instruction that describes the task:
### Input:
gets activated when the user clicks on a plot
Args:
mouse_event:
### Response:
def plot_clicked(self, mouse_event):
"""
gets activated when the user clicks on a plot
Args:
mouse_event:
"... |
def _connect(self):
"""
Connect to a RabbitMQ instance
:returns: Boolean corresponding to success of connection
:rtype: bool
"""
logger.info("Connecting to rabbit")
for url in self._urls:
try:
self._connection = pika.BlockingConnectio... | Connect to a RabbitMQ instance
:returns: Boolean corresponding to success of connection
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Connect to a RabbitMQ instance
:returns: Boolean corresponding to success of connection
:rtype: bool
### Response:
def _connect(self):
"""
Connect to a RabbitMQ instance
:returns: Boolean corresponding to suc... |
def import_module(module, pass_errors=False):
"""
Function imports a module given module name
Args
----
module (string): the module name
pass_errors(boolean): the switch for function
to skip errors or not.
Returns
-------
module (module): the module object.
Raises
----... | Function imports a module given module name
Args
----
module (string): the module name
pass_errors(boolean): the switch for function
to skip errors or not.
Returns
-------
module (module): the module object.
Raises
------
exception (Exception): any kind of exceptions durin... | Below is the the instruction that describes the task:
### Input:
Function imports a module given module name
Args
----
module (string): the module name
pass_errors(boolean): the switch for function
to skip errors or not.
Returns
-------
module (module): the module object.
Rais... |
def compile_results(self):
"""Compile all results for the current test
"""
self._init_dataframes()
self.total_transactions = len(self.main_results['raw'])
self._init_dates() | Compile all results for the current test | Below is the the instruction that describes the task:
### Input:
Compile all results for the current test
### Response:
def compile_results(self):
"""Compile all results for the current test
"""
self._init_dataframes()
self.total_transactions = len(self.main_results['raw'])
... |
def set(self, value):
"""
Sets the value of the string
:param value:
A unicode string
"""
if not isinstance(value, str_cls):
raise TypeError(unwrap(
'''
%s value must be a unicode string, not %s
''',
... | Sets the value of the string
:param value:
A unicode string | Below is the the instruction that describes the task:
### Input:
Sets the value of the string
:param value:
A unicode string
### Response:
def set(self, value):
"""
Sets the value of the string
:param value:
A unicode string
"""
if not isin... |
def aoi_projection(surface_tilt, surface_azimuth, solar_zenith, solar_azimuth):
"""
Calculates the dot product of the sun position unit vector and the surface
normal unit vector; in other words, the cosine of the angle of incidence.
Usage note: When the sun is behind the surface the value returned is
... | Calculates the dot product of the sun position unit vector and the surface
normal unit vector; in other words, the cosine of the angle of incidence.
Usage note: When the sun is behind the surface the value returned is
negative. For many uses negative values must be set to zero.
Input all angles in de... | Below is the the instruction that describes the task:
### Input:
Calculates the dot product of the sun position unit vector and the surface
normal unit vector; in other words, the cosine of the angle of incidence.
Usage note: When the sun is behind the surface the value returned is
negative. For many ... |
def close(
self,
nonce: Nonce,
balance_hash: BalanceHash,
additional_hash: AdditionalHash,
signature: Signature,
block_identifier: BlockSpecification,
):
""" Closes the channel using the provided balance proof. """
self.token_ne... | Closes the channel using the provided balance proof. | Below is the the instruction that describes the task:
### Input:
Closes the channel using the provided balance proof.
### Response:
def close(
self,
nonce: Nonce,
balance_hash: BalanceHash,
additional_hash: AdditionalHash,
signature: Signature,
... |
def return_labels_numpy(self, original=False):
"""
Returns a 2d numpy array of labels
Parameters
----------
original : if True, will return original labels, if False, will return transformed labels (as defined by
label_dict), default value: False
Returns
... | Returns a 2d numpy array of labels
Parameters
----------
original : if True, will return original labels, if False, will return transformed labels (as defined by
label_dict), default value: False
Returns
-------
A numpy array of labels, each row corresponds to a... | Below is the the instruction that describes the task:
### Input:
Returns a 2d numpy array of labels
Parameters
----------
original : if True, will return original labels, if False, will return transformed labels (as defined by
label_dict), default value: False
Returns
... |
def register_package(module=None, package=None, separator='.', ignore=[],
strict=True):
"""
This is a helper function that takes the concept of Actionscript packages
and registers all the classes in the supplied Python module under that
package. It auto-aliased all classes in C{modu... | This is a helper function that takes the concept of Actionscript packages
and registers all the classes in the supplied Python module under that
package. It auto-aliased all classes in C{module} based on the parent
C{package}.
@param module: The Python module that will contain all the classes to
... | Below is the the instruction that describes the task:
### Input:
This is a helper function that takes the concept of Actionscript packages
and registers all the classes in the supplied Python module under that
package. It auto-aliased all classes in C{module} based on the parent
C{package}.
@param ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.