code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def decoration(self):
""" The displayed icon.
Shows open icon when node was visited (children are fetched). This allows users
for instance to collapse a directory node but still see that it was visited, which
may be useful if there is a huge list of directories.
"""
... | The displayed icon.
Shows open icon when node was visited (children are fetched). This allows users
for instance to collapse a directory node but still see that it was visited, which
may be useful if there is a huge list of directories. | Below is the the instruction that describes the task:
### Input:
The displayed icon.
Shows open icon when node was visited (children are fetched). This allows users
for instance to collapse a directory node but still see that it was visited, which
may be useful if there is a hug... |
def find_actual_caller(self):
"""
Returns the full-qualified module name, full pathname, line number, and
function in which `StreamTeeLogger.write()` was called. For example,
if this instance is used to replace `sys.stdout`, this will return the
location of any print statement.
... | Returns the full-qualified module name, full pathname, line number, and
function in which `StreamTeeLogger.write()` was called. For example,
if this instance is used to replace `sys.stdout`, this will return the
location of any print statement. | Below is the the instruction that describes the task:
### Input:
Returns the full-qualified module name, full pathname, line number, and
function in which `StreamTeeLogger.write()` was called. For example,
if this instance is used to replace `sys.stdout`, this will return the
location of an... |
def add_page(self, slug):
'''
Add new page.
'''
post_data = self.get_post_data()
post_data['user_name'] = self.userinfo.user_name
if MWiki.get_by_uid(slug):
self.set_status(400)
return False
else:
MWiki.create_page(slug, post... | Add new page. | Below is the the instruction that describes the task:
### Input:
Add new page.
### Response:
def add_page(self, slug):
'''
Add new page.
'''
post_data = self.get_post_data()
post_data['user_name'] = self.userinfo.user_name
if MWiki.get_by_uid(slug):
se... |
def _update_segmentation_mask_if_overlap(toupdate, other, id, otherid):
"""
Merges the segments specified by `id` (found in `toupdate`) and `otherid`
(found in `other`) if they overlap at all. Updates `toupdate` accordingly.
"""
# If there is any overlap or touching, merge the two, otherwise just re... | Merges the segments specified by `id` (found in `toupdate`) and `otherid`
(found in `other`) if they overlap at all. Updates `toupdate` accordingly. | Below is the the instruction that describes the task:
### Input:
Merges the segments specified by `id` (found in `toupdate`) and `otherid`
(found in `other`) if they overlap at all. Updates `toupdate` accordingly.
### Response:
def _update_segmentation_mask_if_overlap(toupdate, other, id, otherid):
"""
... |
def _group_kwargs_to_options(cls, obj, kwargs):
"Format option group kwargs into canonical options format"
groups = Options._option_groups
if set(kwargs.keys()) - set(groups):
raise Exception("Keyword options %s must be one of %s" % (groups,
','.join(repr... | Format option group kwargs into canonical options format | Below is the the instruction that describes the task:
### Input:
Format option group kwargs into canonical options format
### Response:
def _group_kwargs_to_options(cls, obj, kwargs):
"Format option group kwargs into canonical options format"
groups = Options._option_groups
if set(kwargs.ke... |
def _connect_mitogen_su(spec):
"""
Return ContextService arguments for su as a first class connection.
"""
return {
'method': 'su',
'kwargs': {
'username': spec.remote_user(),
'password': spec.password(),
'python_path': spec.python_path(),
... | Return ContextService arguments for su as a first class connection. | Below is the the instruction that describes the task:
### Input:
Return ContextService arguments for su as a first class connection.
### Response:
def _connect_mitogen_su(spec):
"""
Return ContextService arguments for su as a first class connection.
"""
return {
'method': 'su',
'kwa... |
def connect(self, taskspec):
"""
Connect the *following* task to this one. In other words, the
given task is added as an output task.
:type taskspec: TaskSpec
:param taskspec: The new output task.
"""
self.outputs.append(taskspec)
taskspec._connect_notif... | Connect the *following* task to this one. In other words, the
given task is added as an output task.
:type taskspec: TaskSpec
:param taskspec: The new output task. | Below is the the instruction that describes the task:
### Input:
Connect the *following* task to this one. In other words, the
given task is added as an output task.
:type taskspec: TaskSpec
:param taskspec: The new output task.
### Response:
def connect(self, taskspec):
"""
... |
def makeMigrator(context, portal_type, remove_old_value=True):
""" generate a migrator for the given at-based portal type """
meta_type = portal_type
class BlobMigrator(BaseInlineMigrator):
"""in-place migrator for archetypes based content that copies
file/image data from old non-blob field... | generate a migrator for the given at-based portal type | Below is the the instruction that describes the task:
### Input:
generate a migrator for the given at-based portal type
### Response:
def makeMigrator(context, portal_type, remove_old_value=True):
""" generate a migrator for the given at-based portal type """
meta_type = portal_type
class BlobMigrator... |
def top2_full(votes):
"""
Description:
Top 2 alternatives 16 moment conditions values calculation
Parameters:
votes: ordinal preference data (numpy ndarray of integers)
"""
res = np.zeros(16)
for vote in votes:
# the top ranked alternative is in vote[0][0], second in vote... | Description:
Top 2 alternatives 16 moment conditions values calculation
Parameters:
votes: ordinal preference data (numpy ndarray of integers) | Below is the the instruction that describes the task:
### Input:
Description:
Top 2 alternatives 16 moment conditions values calculation
Parameters:
votes: ordinal preference data (numpy ndarray of integers)
### Response:
def top2_full(votes):
"""
Description:
Top 2 alternatives... |
def deserialize_frame(stream, header, verifier=None):
"""Deserializes a frame from a body.
:param stream: Source data stream
:type stream: io.BytesIO
:param header: Deserialized header
:type header: aws_encryption_sdk.structures.MessageHeader
:param verifier: Signature verifier object (optional... | Deserializes a frame from a body.
:param stream: Source data stream
:type stream: io.BytesIO
:param header: Deserialized header
:type header: aws_encryption_sdk.structures.MessageHeader
:param verifier: Signature verifier object (optional)
:type verifier: aws_encryption_sdk.internal.crypto.Veri... | Below is the the instruction that describes the task:
### Input:
Deserializes a frame from a body.
:param stream: Source data stream
:type stream: io.BytesIO
:param header: Deserialized header
:type header: aws_encryption_sdk.structures.MessageHeader
:param verifier: Signature verifier object (... |
def install(
engine,
n_creatures=5,
n_sickles=3,
malaria_chance=.05,
mate_chance=.05,
mapsize=(1, 1),
startpos=(0, 0)
):
"""Natural Selection on Sickle Cell Anemia
If anyone carries a pair of sickle betaglobin genes, they die of
sickle cell anemia.
... | Natural Selection on Sickle Cell Anemia
If anyone carries a pair of sickle betaglobin genes, they die of
sickle cell anemia.
Individuals with 1x betaglobin, 1x sickle betaglobin are immune to
malaria. | Below is the the instruction that describes the task:
### Input:
Natural Selection on Sickle Cell Anemia
If anyone carries a pair of sickle betaglobin genes, they die of
sickle cell anemia.
Individuals with 1x betaglobin, 1x sickle betaglobin are immune to
malaria.
### Response:
def install(
... |
def RelaxNGValidateCtxt(self, reader, options):
"""Use RelaxNG schema context to validate the document as it
is processed. Activation is only possible before the first
Read(). If @ctxt is None, then RelaxNG schema validation is
deactivated. """
if reader is None: reader__o... | Use RelaxNG schema context to validate the document as it
is processed. Activation is only possible before the first
Read(). If @ctxt is None, then RelaxNG schema validation is
deactivated. | Below is the the instruction that describes the task:
### Input:
Use RelaxNG schema context to validate the document as it
is processed. Activation is only possible before the first
Read(). If @ctxt is None, then RelaxNG schema validation is
deactivated.
### Response:
def RelaxNGVali... |
def _iter_unfolded_lines(self):
"""Iter input unfoled lines. Skip comments."""
line = self._input_file.readline()
while line:
self.line_counter += 1
self.byte_counter += len(line)
line = self._strip_line_sep(line)
nextline = self._input_file.read... | Iter input unfoled lines. Skip comments. | Below is the the instruction that describes the task:
### Input:
Iter input unfoled lines. Skip comments.
### Response:
def _iter_unfolded_lines(self):
"""Iter input unfoled lines. Skip comments."""
line = self._input_file.readline()
while line:
self.line_counter += 1
... |
def get_select_items(items):
"""Return list of possible select items."""
option_items = list()
for item in items:
if isinstance(item, dict) and defs.VALUE in item and defs.LABEL in item:
option_items.append(item[defs.VALUE])
else:
raise exceptions.ParametersFieldError... | Return list of possible select items. | Below is the the instruction that describes the task:
### Input:
Return list of possible select items.
### Response:
def get_select_items(items):
"""Return list of possible select items."""
option_items = list()
for item in items:
if isinstance(item, dict) and defs.VALUE in item and defs.LABEL ... |
def _set_name_server(self, v, load=False):
"""
Setter method for name_server, mapped from YANG variable /ip/dns/name_server (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_name_server is considered as a private
method. Backends looking to populate this variabl... | Setter method for name_server, mapped from YANG variable /ip/dns/name_server (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_name_server is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_name_server... | Below is the the instruction that describes the task:
### Input:
Setter method for name_server, mapped from YANG variable /ip/dns/name_server (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_name_server is considered as a private
method. Backends looking to populat... |
def visitLexerBlock(self, ctx: jsgParser.LexerBlockContext):
""" lexerBlock: OPREN lexeraltList CPREN """
self._rulePattern += '('
self.visitChildren(ctx)
self._rulePattern += ')' | lexerBlock: OPREN lexeraltList CPREN | Below is the the instruction that describes the task:
### Input:
lexerBlock: OPREN lexeraltList CPREN
### Response:
def visitLexerBlock(self, ctx: jsgParser.LexerBlockContext):
""" lexerBlock: OPREN lexeraltList CPREN """
self._rulePattern += '('
self.visitChildren(ctx)
self._rulePa... |
def from_cif_string(cif_string, transformations=None, primitive=True,
occupancy_tolerance=1.):
"""
Generates TransformedStructure from a cif string.
Args:
cif_string (str): Input cif string. Should contain only one
structure. For cifs containi... | Generates TransformedStructure from a cif string.
Args:
cif_string (str): Input cif string. Should contain only one
structure. For cifs containing multiple structures, please use
CifTransmuter.
transformations ([Transformations]): Sequence of transformati... | Below is the the instruction that describes the task:
### Input:
Generates TransformedStructure from a cif string.
Args:
cif_string (str): Input cif string. Should contain only one
structure. For cifs containing multiple structures, please use
CifTransmuter.
... |
def crypto_kx_seed_keypair(seed):
"""
Generate a keypair with a given seed.
This is functionally the same as crypto_box_seed_keypair, however
it uses the blake2b hash primitive instead of sha512.
It is included mainly for api consistency when using crypto_kx.
:param seed: random seed
:type s... | Generate a keypair with a given seed.
This is functionally the same as crypto_box_seed_keypair, however
it uses the blake2b hash primitive instead of sha512.
It is included mainly for api consistency when using crypto_kx.
:param seed: random seed
:type seed: bytes
:return: (public_key, secret_ke... | Below is the the instruction that describes the task:
### Input:
Generate a keypair with a given seed.
This is functionally the same as crypto_box_seed_keypair, however
it uses the blake2b hash primitive instead of sha512.
It is included mainly for api consistency when using crypto_kx.
:param seed: ... |
def input_loop():
'''wait for user input'''
while mpstate.status.exit != True:
try:
if mpstate.status.exit != True:
line = input(mpstate.rl.prompt)
except EOFError:
mpstate.status.exit = True
sys.exit(1)
mpstate.input_queue.put(line) | wait for user input | Below is the the instruction that describes the task:
### Input:
wait for user input
### Response:
def input_loop():
'''wait for user input'''
while mpstate.status.exit != True:
try:
if mpstate.status.exit != True:
line = input(mpstate.rl.prompt)
except EOFError:... |
def merge_deployment_data(dict1: DeployedContracts, dict2: DeployedContracts) -> DeployedContracts:
""" Take contents of two deployment JSON files and merge them
The dictionary under 'contracts' key will be merged. The 'contracts'
contents from different JSON files must not overlap. The contents
under ... | Take contents of two deployment JSON files and merge them
The dictionary under 'contracts' key will be merged. The 'contracts'
contents from different JSON files must not overlap. The contents
under other keys must be identical. | Below is the the instruction that describes the task:
### Input:
Take contents of two deployment JSON files and merge them
The dictionary under 'contracts' key will be merged. The 'contracts'
contents from different JSON files must not overlap. The contents
under other keys must be identical.
### Respo... |
def transpose(self, name=None):
"""Returns matching `Conv1D` module.
Args:
name: Optional string assigning name of transpose module. The default name
is constructed by appending "_transpose" to `self.name`.
Returns:
`Conv1D` module.
"""
if name is None:
name = self.module... | Returns matching `Conv1D` module.
Args:
name: Optional string assigning name of transpose module. The default name
is constructed by appending "_transpose" to `self.name`.
Returns:
`Conv1D` module. | Below is the the instruction that describes the task:
### Input:
Returns matching `Conv1D` module.
Args:
name: Optional string assigning name of transpose module. The default name
is constructed by appending "_transpose" to `self.name`.
Returns:
`Conv1D` module.
### Response:
def tran... |
def _mul8(ins):
""" Multiplies 2 las values from the stack.
Optimizations:
* If any of the ops is ZERO,
then do A = 0 ==> XOR A, cause A * 0 = 0 * A = 0
* If any ot the ops is ONE, do NOTHING
A * 1 = 1 * A = A
"""
op1, op2 = tuple(ins.quad[2:])
if _int_ops(op1, op2) is... | Multiplies 2 las values from the stack.
Optimizations:
* If any of the ops is ZERO,
then do A = 0 ==> XOR A, cause A * 0 = 0 * A = 0
* If any ot the ops is ONE, do NOTHING
A * 1 = 1 * A = A | Below is the the instruction that describes the task:
### Input:
Multiplies 2 las values from the stack.
Optimizations:
* If any of the ops is ZERO,
then do A = 0 ==> XOR A, cause A * 0 = 0 * A = 0
* If any ot the ops is ONE, do NOTHING
A * 1 = 1 * A = A
### Response:
def _mul8(in... |
def create_iopub_stream(self, kernel_id):
"""Create a new iopub stream."""
self._check_kernel_id(kernel_id)
return super(MappingKernelManager, self).create_iopub_stream(kernel_id) | Create a new iopub stream. | Below is the the instruction that describes the task:
### Input:
Create a new iopub stream.
### Response:
def create_iopub_stream(self, kernel_id):
"""Create a new iopub stream."""
self._check_kernel_id(kernel_id)
return super(MappingKernelManager, self).create_iopub_stream(kernel_id) |
def dotplot(adata, var_names, groupby=None, use_raw=None, log=False, num_categories=7,
expression_cutoff=0., mean_only_expressed=False, color_map='Reds', dot_max=None,
dot_min=None, figsize=None, dendrogram=False, gene_symbols=None,
var_group_positions=None, standard_scale=None, smal... | \
Makes a *dot plot* of the expression values of `var_names`.
For each var_name and each `groupby` category a dot is plotted. Each dot
represents two values: mean expression within each category (visualized by
color) and fraction of cells expressing the var_name in the
category (visualized by the s... | Below is the the instruction that describes the task:
### Input:
\
Makes a *dot plot* of the expression values of `var_names`.
For each var_name and each `groupby` category a dot is plotted. Each dot
represents two values: mean expression within each category (visualized by
color) and fraction of c... |
def iter_starred(self, login=None, sort=None, direction=None, number=-1,
etag=None):
"""Iterate over repositories starred by ``login`` or the authenticated
user.
.. versionchanged:: 0.5
Added sort and direction parameters (optional) as per the change in
... | Iterate over repositories starred by ``login`` or the authenticated
user.
.. versionchanged:: 0.5
Added sort and direction parameters (optional) as per the change in
GitHub's API.
:param str login: (optional), name of user whose stars you want to see
:param str so... | Below is the the instruction that describes the task:
### Input:
Iterate over repositories starred by ``login`` or the authenticated
user.
.. versionchanged:: 0.5
Added sort and direction parameters (optional) as per the change in
GitHub's API.
:param str login: (opti... |
def set_consistent(self, consistent_config):
""" Indicates that the stream is the start of a consistent region.
Args:
consistent_config(consistent.ConsistentRegionConfig): the configuration of the consistent region.
Returns:
Stream: Returns this stream.
.. vers... | Indicates that the stream is the start of a consistent region.
Args:
consistent_config(consistent.ConsistentRegionConfig): the configuration of the consistent region.
Returns:
Stream: Returns this stream.
.. versionadded:: 1.11 | Below is the the instruction that describes the task:
### Input:
Indicates that the stream is the start of a consistent region.
Args:
consistent_config(consistent.ConsistentRegionConfig): the configuration of the consistent region.
Returns:
Stream: Returns this stream.
... |
def delete_variable(self, name):
"""Deletes a variable from a DataFrame."""
del self.variables[name]
self.signal_variable_changed.emit(self, name, "delete") | Deletes a variable from a DataFrame. | Below is the the instruction that describes the task:
### Input:
Deletes a variable from a DataFrame.
### Response:
def delete_variable(self, name):
"""Deletes a variable from a DataFrame."""
del self.variables[name]
self.signal_variable_changed.emit(self, name, "delete") |
def audit_1_1(self):
"""1.1 Avoid the use of the "root" account (Scored)"""
for row in self.credential_report:
if row["user"] == "<root_account>":
for field in "password_last_used", "access_key_1_last_used_date", "access_key_2_last_used_date":
if row[field... | 1.1 Avoid the use of the "root" account (Scored) | Below is the the instruction that describes the task:
### Input:
1.1 Avoid the use of the "root" account (Scored)
### Response:
def audit_1_1(self):
"""1.1 Avoid the use of the "root" account (Scored)"""
for row in self.credential_report:
if row["user"] == "<root_account>":
... |
def add_lines(self, txt, indent=0):
"""Adds a list of lines.
The list can be indented with the optional argument 'indent'.
"""
for line in txt:
self.add_line(line, indent) | Adds a list of lines.
The list can be indented with the optional argument 'indent'. | Below is the the instruction that describes the task:
### Input:
Adds a list of lines.
The list can be indented with the optional argument 'indent'.
### Response:
def add_lines(self, txt, indent=0):
"""Adds a list of lines.
The list can be indented with the optional argument 'indent'.
... |
def generate_message_doc(message_descriptor, locations, path, name_prefix=''):
"""Generate docs for message and nested messages and enums.
Args:
message_descriptor: descriptor_pb2.DescriptorProto instance for message
to generate docs for.
locations: Dictionary of location paths tupl... | Generate docs for message and nested messages and enums.
Args:
message_descriptor: descriptor_pb2.DescriptorProto instance for message
to generate docs for.
locations: Dictionary of location paths tuples to
descriptor_pb2.SourceCodeInfo.Location instances.
path: Path... | Below is the the instruction that describes the task:
### Input:
Generate docs for message and nested messages and enums.
Args:
message_descriptor: descriptor_pb2.DescriptorProto instance for message
to generate docs for.
locations: Dictionary of location paths tuples to
... |
def is_access_granted(self, agreement_id, did, consumer_address):
"""
Check permission for the agreement.
Verify on-chain that the `consumer_address` has permission to access the given asset `did`
according to the `agreement_id`.
:param agreement_id: id of the agreement, hex st... | Check permission for the agreement.
Verify on-chain that the `consumer_address` has permission to access the given asset `did`
according to the `agreement_id`.
:param agreement_id: id of the agreement, hex str
:param did: DID, str
:param consumer_address: ethereum account addre... | Below is the the instruction that describes the task:
### Input:
Check permission for the agreement.
Verify on-chain that the `consumer_address` has permission to access the given asset `did`
according to the `agreement_id`.
:param agreement_id: id of the agreement, hex str
:param ... |
def as_sql(self):
"""Gets report as json
:return: json-formatted report
"""
labels, data = self._get_table()
table = SqlTable(labels, data, "{:.3f}", "\n")
return str(table) | Gets report as json
:return: json-formatted report | Below is the the instruction that describes the task:
### Input:
Gets report as json
:return: json-formatted report
### Response:
def as_sql(self):
"""Gets report as json
:return: json-formatted report
"""
labels, data = self._get_table()
table = SqlTable(labels, ... |
def discover_base_dir(start_dir):
'''Return start_dir or the parent dir that has the s2 marker.
Starting from the specified directory, and going up the parent
chain, check each directory to see if it's a base_dir (contains
the "marker" directory *s2*) and return it. Otherwise, return
the start_dir.... | Return start_dir or the parent dir that has the s2 marker.
Starting from the specified directory, and going up the parent
chain, check each directory to see if it's a base_dir (contains
the "marker" directory *s2*) and return it. Otherwise, return
the start_dir. | Below is the the instruction that describes the task:
### Input:
Return start_dir or the parent dir that has the s2 marker.
Starting from the specified directory, and going up the parent
chain, check each directory to see if it's a base_dir (contains
the "marker" directory *s2*) and return it. Otherwis... |
def login():
""" Enables the user to login to the remote GMQL service.
If both username and password are None, the user will be connected as guest.
"""
from .RemoteConnection.RemoteManager import RemoteManager
global __remote_manager, __session_manager
logger = logging.getLogger()
remote_ad... | Enables the user to login to the remote GMQL service.
If both username and password are None, the user will be connected as guest. | Below is the the instruction that describes the task:
### Input:
Enables the user to login to the remote GMQL service.
If both username and password are None, the user will be connected as guest.
### Response:
def login():
""" Enables the user to login to the remote GMQL service.
If both username and p... |
def _build_jss_object_list(self, response, obj_class):
"""Build a JSSListData object from response."""
response_objects = [item for item in response
if item is not None and
item.tag != "size"]
objects = [
JSSListData(obj_class, ... | Build a JSSListData object from response. | Below is the the instruction that describes the task:
### Input:
Build a JSSListData object from response.
### Response:
def _build_jss_object_list(self, response, obj_class):
"""Build a JSSListData object from response."""
response_objects = [item for item in response
i... |
def detach_events(self, *events):
"""Detach one or more events from the bot instance"""
reg = self.registry
delete = defaultdict(list)
# remove from self.events
all_events = reg.events
for e in events:
regexp = getattr(e.regexp, 're', e.regexp)
io... | Detach one or more events from the bot instance | Below is the the instruction that describes the task:
### Input:
Detach one or more events from the bot instance
### Response:
def detach_events(self, *events):
"""Detach one or more events from the bot instance"""
reg = self.registry
delete = defaultdict(list)
# remove from self.e... |
def _collect_potential_merges(dag, barriers):
"""
Returns a dict of DAGNode : Barrier objects, where the barrier needs to be
inserted where the corresponding DAGNode appears in the main DAG
"""
# if only got 1 or 0 barriers then can't merge
if len(barriers) < 2:
... | Returns a dict of DAGNode : Barrier objects, where the barrier needs to be
inserted where the corresponding DAGNode appears in the main DAG | Below is the the instruction that describes the task:
### Input:
Returns a dict of DAGNode : Barrier objects, where the barrier needs to be
inserted where the corresponding DAGNode appears in the main DAG
### Response:
def _collect_potential_merges(dag, barriers):
"""
Returns a dict of DAGN... |
def get_scoped_variable_m(self, data_port_id):
"""Returns the scoped variable model for the given data port id
:param data_port_id: The data port id to search for
:return: The model of the scoped variable with the given id
"""
for scoped_variable_m in self.scoped_variables:
... | Returns the scoped variable model for the given data port id
:param data_port_id: The data port id to search for
:return: The model of the scoped variable with the given id | Below is the the instruction that describes the task:
### Input:
Returns the scoped variable model for the given data port id
:param data_port_id: The data port id to search for
:return: The model of the scoped variable with the given id
### Response:
def get_scoped_variable_m(self, data_port_id):... |
def ndhess(f, delta=DELTA):
"""
Returns numerical hessian function of given input function
Input: f, scalar function of an numpy array object
delta(optional), finite difference step
Output: hessian function object
"""
def hess_f(*args, **kwargs):
x = args[0]
hess_val =... | Returns numerical hessian function of given input function
Input: f, scalar function of an numpy array object
delta(optional), finite difference step
Output: hessian function object | Below is the the instruction that describes the task:
### Input:
Returns numerical hessian function of given input function
Input: f, scalar function of an numpy array object
delta(optional), finite difference step
Output: hessian function object
### Response:
def ndhess(f, delta=DELTA):
"""... |
def parse_notifier_name(name):
"""Convert the name argument to a list of names.
Examples
--------
>>> parse_notifier_name('a')
['a']
>>> parse_notifier_name(['a','b'])
['a', 'b']
>>> parse_notifier_name(None)
['anytrait']
"""
if isinstance(name, str):
return [name]
... | Convert the name argument to a list of names.
Examples
--------
>>> parse_notifier_name('a')
['a']
>>> parse_notifier_name(['a','b'])
['a', 'b']
>>> parse_notifier_name(None)
['anytrait'] | Below is the the instruction that describes the task:
### Input:
Convert the name argument to a list of names.
Examples
--------
>>> parse_notifier_name('a')
['a']
>>> parse_notifier_name(['a','b'])
['a', 'b']
>>> parse_notifier_name(None)
['anytrait']
### Response:
def parse_noti... |
def calculate_heading_longpath(locator1, locator2):
"""calculates the heading from the first to the second locator (long path)
Args:
locator1 (string): Locator, either 4 or 6 characters
locator2 (string): Locator, either 4 or 6 characters
Returns:
float: Long pa... | calculates the heading from the first to the second locator (long path)
Args:
locator1 (string): Locator, either 4 or 6 characters
locator2 (string): Locator, either 4 or 6 characters
Returns:
float: Long path heading in deg
Raises:
ValueError: ... | Below is the the instruction that describes the task:
### Input:
calculates the heading from the first to the second locator (long path)
Args:
locator1 (string): Locator, either 4 or 6 characters
locator2 (string): Locator, either 4 or 6 characters
Returns:
floa... |
def value_attr(attr_name):
"""
Creates a getter that will retrieve value's attribute
with specified name.
@param attr_name: the name of an attribute belonging to the value.
@type attr_name: str
"""
def value_attr(value, context, **_params):
value = getattr(value, attr_name)
... | Creates a getter that will retrieve value's attribute
with specified name.
@param attr_name: the name of an attribute belonging to the value.
@type attr_name: str | Below is the the instruction that describes the task:
### Input:
Creates a getter that will retrieve value's attribute
with specified name.
@param attr_name: the name of an attribute belonging to the value.
@type attr_name: str
### Response:
def value_attr(attr_name):
"""
Creates a getter that ... |
def uniqualize(l,**kwargs):
'''
from elist.elist import *
l = [1, 2, 2]
new = uniqualize(l)
new
id(l)
id(new)
####
l = [1, 2, 2]
rslt = uniqualize(l,mode="original")
rslt
id(l)
id(rslt)
'''
if('mode' in kwargs):
... | from elist.elist import *
l = [1, 2, 2]
new = uniqualize(l)
new
id(l)
id(new)
####
l = [1, 2, 2]
rslt = uniqualize(l,mode="original")
rslt
id(l)
id(rslt) | Below is the the instruction that describes the task:
### Input:
from elist.elist import *
l = [1, 2, 2]
new = uniqualize(l)
new
id(l)
id(new)
####
l = [1, 2, 2]
rslt = uniqualize(l,mode="original")
rslt
id(l)
id(rslt)
### Respo... |
def list_build_records(page_size=200, page_index=0, sort="", q=""):
"""
List all BuildRecords
"""
data = list_build_records_raw(page_size, page_index, sort, q)
if data:
return utils.format_json_list(data) | List all BuildRecords | Below is the the instruction that describes the task:
### Input:
List all BuildRecords
### Response:
def list_build_records(page_size=200, page_index=0, sort="", q=""):
"""
List all BuildRecords
"""
data = list_build_records_raw(page_size, page_index, sort, q)
if data:
return utils.form... |
def setup(app):
""" Initializer for Sphinx extension API.
See http://www.sphinx-doc.org/en/stable/extdev/index.html#dev-extensions.
"""
lexer = MarkdownLexer()
for alias in lexer.aliases:
app.add_lexer(alias, lexer)
return dict(version=__version__) | Initializer for Sphinx extension API.
See http://www.sphinx-doc.org/en/stable/extdev/index.html#dev-extensions. | Below is the the instruction that describes the task:
### Input:
Initializer for Sphinx extension API.
See http://www.sphinx-doc.org/en/stable/extdev/index.html#dev-extensions.
### Response:
def setup(app):
""" Initializer for Sphinx extension API.
See http://www.sphinx-doc.org/en/stable/extd... |
def generate_k(order, secexp, hash_func, data):
'''
order - order of the DSA generator used in the signature
secexp - secure exponent (private key) in numeric form
hash_func - reference to the same hash function used for generating hash
data - hash in binary form of the signing data
... | order - order of the DSA generator used in the signature
secexp - secure exponent (private key) in numeric form
hash_func - reference to the same hash function used for generating hash
data - hash in binary form of the signing data | Below is the the instruction that describes the task:
### Input:
order - order of the DSA generator used in the signature
secexp - secure exponent (private key) in numeric form
hash_func - reference to the same hash function used for generating hash
data - hash in binary form of the signing ... |
def as_dict(self, join='.'):
"""
Returns the error as a path to message dictionary. Paths are joined
with the ``join`` string.
"""
if self.path:
path = [str(node) for node in self.path]
else:
path = ''
return { join.join(path): self.message... | Returns the error as a path to message dictionary. Paths are joined
with the ``join`` string. | Below is the the instruction that describes the task:
### Input:
Returns the error as a path to message dictionary. Paths are joined
with the ``join`` string.
### Response:
def as_dict(self, join='.'):
"""
Returns the error as a path to message dictionary. Paths are joined
with the ... |
def add_row(self, data: list=None):
"""
Add a row of data to the current widget, add a <Tab> \
binding to the last element of the last row, and set \
the focus at the beginning of the next row.
:param data: a row of data
:return: None
"""
# validation
... | Add a row of data to the current widget, add a <Tab> \
binding to the last element of the last row, and set \
the focus at the beginning of the next row.
:param data: a row of data
:return: None | Below is the the instruction that describes the task:
### Input:
Add a row of data to the current widget, add a <Tab> \
binding to the last element of the last row, and set \
the focus at the beginning of the next row.
:param data: a row of data
:return: None
### Response:
def add_... |
def visit_For(self, node):
"""
Create For representation for Cxx generation.
Examples
--------
>> for i in xrange(10):
>> ... work ...
Becomes
>> typename returnable<decltype(__builtin__.xrange(10))>::type __iterX
= __builtin__.xrange(10)... | Create For representation for Cxx generation.
Examples
--------
>> for i in xrange(10):
>> ... work ...
Becomes
>> typename returnable<decltype(__builtin__.xrange(10))>::type __iterX
= __builtin__.xrange(10);
>> ... possible container size reserv... | Below is the the instruction that describes the task:
### Input:
Create For representation for Cxx generation.
Examples
--------
>> for i in xrange(10):
>> ... work ...
Becomes
>> typename returnable<decltype(__builtin__.xrange(10))>::type __iterX
= ... |
def result(self):
"""Formats the result."""
self.__result.sort(cmp = self.__cmp, key = self.__key, reverse = self.__reverse)
return self.__result | Formats the result. | Below is the the instruction that describes the task:
### Input:
Formats the result.
### Response:
def result(self):
"""Formats the result."""
self.__result.sort(cmp = self.__cmp, key = self.__key, reverse = self.__reverse)
return self.__result |
def communicate(self, input=None, timeout=-1):
"""Communicate with the child and return its output.
If *input* is provided, it is sent to the client. Concurrent with
sending the input, the child's standard output and standard error are
read, until the child exits.
The return va... | Communicate with the child and return its output.
If *input* is provided, it is sent to the client. Concurrent with
sending the input, the child's standard output and standard error are
read, until the child exits.
The return value is a tuple ``(stdout_data, stderr_data)`` containing
... | Below is the the instruction that describes the task:
### Input:
Communicate with the child and return its output.
If *input* is provided, it is sent to the client. Concurrent with
sending the input, the child's standard output and standard error are
read, until the child exits.
Th... |
def evaluate_cartesian(self, s, t, _verify=True):
r"""Compute a point on the surface.
Evaluates :math:`B\left(1 - s - t, s, t\right)` by calling
:meth:`evaluate_barycentric`:
This method acts as a (partial) inverse to :meth:`locate`.
.. testsetup:: surface-cartesian
... | r"""Compute a point on the surface.
Evaluates :math:`B\left(1 - s - t, s, t\right)` by calling
:meth:`evaluate_barycentric`:
This method acts as a (partial) inverse to :meth:`locate`.
.. testsetup:: surface-cartesian
import numpy as np
import bezier
.. ... | Below is the the instruction that describes the task:
### Input:
r"""Compute a point on the surface.
Evaluates :math:`B\left(1 - s - t, s, t\right)` by calling
:meth:`evaluate_barycentric`:
This method acts as a (partial) inverse to :meth:`locate`.
.. testsetup:: surface-cartesian... |
def fetch(self):
"""
Fetch & return a new `SSHKey` object representing the SSH key's current
state
:rtype: SSHKey
:raises DOAPIError: if the API endpoint replies with an error (e.g., if
the SSH key no longer exists)
"""
api = self.doapi_manager
... | Fetch & return a new `SSHKey` object representing the SSH key's current
state
:rtype: SSHKey
:raises DOAPIError: if the API endpoint replies with an error (e.g., if
the SSH key no longer exists) | Below is the the instruction that describes the task:
### Input:
Fetch & return a new `SSHKey` object representing the SSH key's current
state
:rtype: SSHKey
:raises DOAPIError: if the API endpoint replies with an error (e.g., if
the SSH key no longer exists)
### Response:
def ... |
def jaccard(seq1, seq2):
"""Compute the Jaccard distance between the two sequences `seq1` and `seq2`.
They should contain hashable items.
The return value is a float between 0 and 1, where 0 means equal, and 1 totally different.
"""
set1, set2 = set(seq1), set(seq2)
return 1 - len(set1 & set2) / float(len(set1 ... | Compute the Jaccard distance between the two sequences `seq1` and `seq2`.
They should contain hashable items.
The return value is a float between 0 and 1, where 0 means equal, and 1 totally different. | Below is the the instruction that describes the task:
### Input:
Compute the Jaccard distance between the two sequences `seq1` and `seq2`.
They should contain hashable items.
The return value is a float between 0 and 1, where 0 means equal, and 1 totally different.
### Response:
def jaccard(seq1, seq2):
"""Co... |
def has_tsm(self):
"""True if this particular server have a TSM based service processor
"""
if (self.oemid['manufacturer_id'] == 19046 and
self.oemid['device_id'] == 32):
try:
self.ipmicmd.xraw_command(netfn=0x3a, command=0xf)
except pygexc... | True if this particular server have a TSM based service processor | Below is the the instruction that describes the task:
### Input:
True if this particular server have a TSM based service processor
### Response:
def has_tsm(self):
"""True if this particular server have a TSM based service processor
"""
if (self.oemid['manufacturer_id'] == 19046 and
... |
def summary(processors, metrics, context):
"""Print the summary"""
# display aggregated metric values on language level
def display_header(processors, before='', after=''):
"""Display the header for the summary results."""
print(before, end=' ')
for processor in processors:
... | Print the summary | Below is the the instruction that describes the task:
### Input:
Print the summary
### Response:
def summary(processors, metrics, context):
"""Print the summary"""
# display aggregated metric values on language level
def display_header(processors, before='', after=''):
"""Display the header for... |
def energies(self, samples_like, dtype=np.float):
"""Determine the energies of the given samples.
Args:
samples_like (samples_like):
A collection of raw samples. `samples_like` is an extension of NumPy's array_like
structure. See :func:`.as_samples`.
... | Determine the energies of the given samples.
Args:
samples_like (samples_like):
A collection of raw samples. `samples_like` is an extension of NumPy's array_like
structure. See :func:`.as_samples`.
dtype (:class:`numpy.dtype`):
The data t... | Below is the the instruction that describes the task:
### Input:
Determine the energies of the given samples.
Args:
samples_like (samples_like):
A collection of raw samples. `samples_like` is an extension of NumPy's array_like
structure. See :func:`.as_samples`.
... |
def get_pubmed_for_beleditor(pmid: str) -> Mapping[str, Any]:
"""Get fully annotated pubmed doc with Pubtator and full entity/annotation_types
Args:
pmid: Pubmed PMID
Returns:
Mapping[str, Any]: pubmed dictionary
"""
pubmed = get_pubmed(pmid)
pubtator = get_pubtator(pmid)
... | Get fully annotated pubmed doc with Pubtator and full entity/annotation_types
Args:
pmid: Pubmed PMID
Returns:
Mapping[str, Any]: pubmed dictionary | Below is the the instruction that describes the task:
### Input:
Get fully annotated pubmed doc with Pubtator and full entity/annotation_types
Args:
pmid: Pubmed PMID
Returns:
Mapping[str, Any]: pubmed dictionary
### Response:
def get_pubmed_for_beleditor(pmid: str) -> Mapping[str, Any]:
... |
def newLayer(self, effect=''):
"""
Creates a new :py:class:`Layer` and set that as the active.
:param effect: A string with the blend mode for that layer that will be used when during the rendering process. The accepted values are: :code:`'soft_light','lighten','screen','dodge','addition','darken','multiply','... | Creates a new :py:class:`Layer` and set that as the active.
:param effect: A string with the blend mode for that layer that will be used when during the rendering process. The accepted values are: :code:`'soft_light','lighten','screen','dodge','addition','darken','multiply','hard_light','difference','subtract','gr... | Below is the the instruction that describes the task:
### Input:
Creates a new :py:class:`Layer` and set that as the active.
:param effect: A string with the blend mode for that layer that will be used when during the rendering process. The accepted values are: :code:`'soft_light','lighten','screen','dodge','a... |
def open(self) -> bool:
"""
Ensures we have a connection to the email server. Returns whether or
not a new connection was required (True or False).
"""
if self.connection:
# Nothing to do if the connection is already open.
return False
connection_... | Ensures we have a connection to the email server. Returns whether or
not a new connection was required (True or False). | Below is the the instruction that describes the task:
### Input:
Ensures we have a connection to the email server. Returns whether or
not a new connection was required (True or False).
### Response:
def open(self) -> bool:
"""
Ensures we have a connection to the email server. Returns whethe... |
def Module(EPIC, campaign=None):
'''
Returns the module number for a given EPIC target.
'''
channel = Channel(EPIC, campaign=campaign)
nums = {2: 1, 3: 5, 4: 9, 6: 13, 7: 17, 8: 21, 9: 25,
10: 29, 11: 33, 12: 37, 13: 41, 14: 45, 15: 49,
16: 53, 17: 57, 18: 61, 19: 65, 20: 6... | Returns the module number for a given EPIC target. | Below is the the instruction that describes the task:
### Input:
Returns the module number for a given EPIC target.
### Response:
def Module(EPIC, campaign=None):
'''
Returns the module number for a given EPIC target.
'''
channel = Channel(EPIC, campaign=campaign)
nums = {2: 1, 3: 5, 4: 9, 6:... |
def determine_extended_chord5(chord, shorthand=False, no_inversions=False,
no_polychords=False):
"""Determine the names of an extended chord."""
if len(chord) != 5:
# warning raise exeption: not an extended chord
return False
def inversion_exhauster(chord, shorthand, tries, result, ... | Determine the names of an extended chord. | Below is the the instruction that describes the task:
### Input:
Determine the names of an extended chord.
### Response:
def determine_extended_chord5(chord, shorthand=False, no_inversions=False,
no_polychords=False):
"""Determine the names of an extended chord."""
if len(chord) != 5:
# war... |
def _get_args_contents(self):
"""
Mimic the argument formatting behaviour of
ActionBase._execute_module().
"""
return ' '.join(
'%s=%s' % (key, shlex_quote(str(self.args[key])))
for key in self.args
) + ' ' | Mimic the argument formatting behaviour of
ActionBase._execute_module(). | Below is the the instruction that describes the task:
### Input:
Mimic the argument formatting behaviour of
ActionBase._execute_module().
### Response:
def _get_args_contents(self):
"""
Mimic the argument formatting behaviour of
ActionBase._execute_module().
"""
retu... |
def _missing_(cls, value):
"""Lookup function used when value is not found."""
if not (isinstance(value, int) and 0x0000 <= value <= 0xFFFF):
raise ValueError('%r is not a valid %s' % (value, cls.__name__))
if 0x0001 <= value <= 0x0BB8:
extend_enum(cls, 'Registered by Xer... | Lookup function used when value is not found. | Below is the the instruction that describes the task:
### Input:
Lookup function used when value is not found.
### Response:
def _missing_(cls, value):
"""Lookup function used when value is not found."""
if not (isinstance(value, int) and 0x0000 <= value <= 0xFFFF):
raise ValueError('%r... |
def marks(value):
"""list or KeyedList of ``Mark`` : Mark definitions
Marks are the visual objects (such as lines, bars, etc.) that
represent the data in the visualization space. See the :class:`Mark`
class for details.
"""
for i, entry in enumerate(value):
_... | list or KeyedList of ``Mark`` : Mark definitions
Marks are the visual objects (such as lines, bars, etc.) that
represent the data in the visualization space. See the :class:`Mark`
class for details. | Below is the the instruction that describes the task:
### Input:
list or KeyedList of ``Mark`` : Mark definitions
Marks are the visual objects (such as lines, bars, etc.) that
represent the data in the visualization space. See the :class:`Mark`
class for details.
### Response:
def marks(va... |
def _Rforce(self,R,z,phi=0.,t=0.):
"""
NAME:
_Rforce
PURPOSE:
evaluate the radial force for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
... | NAME:
_Rforce
PURPOSE:
evaluate the radial force for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
the radial force
HISTORY:
2010-07-09... | Below is the the instruction that describes the task:
### Input:
NAME:
_Rforce
PURPOSE:
evaluate the radial force for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPU... |
def guest_reset(self, userid):
"""Reset z/VM instance."""
LOG.info("Begin to reset vm %s", userid)
self._smtclient.guest_reset(userid)
LOG.info("Complete reset vm %s", userid) | Reset z/VM instance. | Below is the the instruction that describes the task:
### Input:
Reset z/VM instance.
### Response:
def guest_reset(self, userid):
"""Reset z/VM instance."""
LOG.info("Begin to reset vm %s", userid)
self._smtclient.guest_reset(userid)
LOG.info("Complete reset vm %s", userid) |
def calcEndOfPrdvPP(self):
'''
Calculates end-of-period marginal marginal value using a pre-defined
array of next period market resources in self.mNrmNext.
Parameters
----------
none
Returns
-------
EndOfPrdvPP : np.array
End-of-perio... | Calculates end-of-period marginal marginal value using a pre-defined
array of next period market resources in self.mNrmNext.
Parameters
----------
none
Returns
-------
EndOfPrdvPP : np.array
End-of-period marginal marginal value of assets at each val... | Below is the the instruction that describes the task:
### Input:
Calculates end-of-period marginal marginal value using a pre-defined
array of next period market resources in self.mNrmNext.
Parameters
----------
none
Returns
-------
EndOfPrdvPP : np.array
... |
def getElements(self, zero_based=True, pared=False):
"""
Get the elements of the mesh as a list of point index list.
:param zero_based: use zero based index of points if true otherwise use 1-based index of points.
:param pared: use the pared down list of points
:return: A list of... | Get the elements of the mesh as a list of point index list.
:param zero_based: use zero based index of points if true otherwise use 1-based index of points.
:param pared: use the pared down list of points
:return: A list of point index lists | Below is the the instruction that describes the task:
### Input:
Get the elements of the mesh as a list of point index list.
:param zero_based: use zero based index of points if true otherwise use 1-based index of points.
:param pared: use the pared down list of points
:return: A list of poi... |
def render(self, template, **kwargs):
"""Renders the template
:param template: The template to render.
The template is actually a file, which is usually generated
by :class:`rtcclient.template.Templater.getTemplate`
and can also be modified by user accordingly.
... | Renders the template
:param template: The template to render.
The template is actually a file, which is usually generated
by :class:`rtcclient.template.Templater.getTemplate`
and can also be modified by user accordingly.
:param kwargs: The `kwargs` dict is used to fi... | Below is the the instruction that describes the task:
### Input:
Renders the template
:param template: The template to render.
The template is actually a file, which is usually generated
by :class:`rtcclient.template.Templater.getTemplate`
and can also be modified by use... |
def register(cls, name: str, plugin: Type[ConnectionPlugin]) -> None:
"""Registers a connection plugin with a specified name
Args:
name: name of the connection plugin to register
plugin: defined connection plugin class
Raises:
:obj:`nornir.core.exceptions.Co... | Registers a connection plugin with a specified name
Args:
name: name of the connection plugin to register
plugin: defined connection plugin class
Raises:
:obj:`nornir.core.exceptions.ConnectionPluginAlreadyRegistered` if
another plugin with the speci... | Below is the the instruction that describes the task:
### Input:
Registers a connection plugin with a specified name
Args:
name: name of the connection plugin to register
plugin: defined connection plugin class
Raises:
:obj:`nornir.core.exceptions.ConnectionPlug... |
def connections(self, wait):
"""
wait for connections to both rabbitmq and elasticsearch to be made
before binding a routing key to a channel and sending messages to
elasticsearch
"""
while wait:
try:
params = pika.ConnectionParameters(host=sel... | wait for connections to both rabbitmq and elasticsearch to be made
before binding a routing key to a channel and sending messages to
elasticsearch | Below is the the instruction that describes the task:
### Input:
wait for connections to both rabbitmq and elasticsearch to be made
before binding a routing key to a channel and sending messages to
elasticsearch
### Response:
def connections(self, wait):
"""
wait for connections to ... |
def sph_coords_to_pose(theta, psi):
""" Convert spherical coordinates to a pose.
Parameters
----------
theta : float
azimuth angle
psi : float
elevation angle
Returns
-------
:obj:`RigidTransformation`
rigid tr... | Convert spherical coordinates to a pose.
Parameters
----------
theta : float
azimuth angle
psi : float
elevation angle
Returns
-------
:obj:`RigidTransformation`
rigid transformation corresponding to rotation with no t... | Below is the the instruction that describes the task:
### Input:
Convert spherical coordinates to a pose.
Parameters
----------
theta : float
azimuth angle
psi : float
elevation angle
Returns
-------
:obj:`RigidTransformation`... |
def corners(bounds):
"""
Given a pair of axis aligned bounds, return all
8 corners of the bounding box.
Parameters
----------
bounds : (2,3) or (2,2) float
Axis aligned bounds
Returns
----------
corners : (8,3) float
Corner vertices of the cube
"""
bounds = np.... | Given a pair of axis aligned bounds, return all
8 corners of the bounding box.
Parameters
----------
bounds : (2,3) or (2,2) float
Axis aligned bounds
Returns
----------
corners : (8,3) float
Corner vertices of the cube | Below is the the instruction that describes the task:
### Input:
Given a pair of axis aligned bounds, return all
8 corners of the bounding box.
Parameters
----------
bounds : (2,3) or (2,2) float
Axis aligned bounds
Returns
----------
corners : (8,3) float
Corner vertices o... |
def _inject_into_mod(mod, name, value, force_lock=False):
'''
Inject a variable into a module. This is used to inject "globals" like
``__salt__``, ``__pillar``, or ``grains``.
Instead of injecting the value directly, a ``ThreadLocalProxy`` is created.
If such a proxy is already present under the sp... | Inject a variable into a module. This is used to inject "globals" like
``__salt__``, ``__pillar``, or ``grains``.
Instead of injecting the value directly, a ``ThreadLocalProxy`` is created.
If such a proxy is already present under the specified name, it is updated
with the new value. This update only a... | Below is the the instruction that describes the task:
### Input:
Inject a variable into a module. This is used to inject "globals" like
``__salt__``, ``__pillar``, or ``grains``.
Instead of injecting the value directly, a ``ThreadLocalProxy`` is created.
If such a proxy is already present under the spe... |
def _attribute_is_magic(node, attrs, parents):
"""Checks that node is an attribute used inside one of allowed parents"""
if node.attrname not in attrs:
return False
if not node.last_child():
return False
try:
for cls in node.last_child().inferred():
if isinstance(cls... | Checks that node is an attribute used inside one of allowed parents | Below is the the instruction that describes the task:
### Input:
Checks that node is an attribute used inside one of allowed parents
### Response:
def _attribute_is_magic(node, attrs, parents):
"""Checks that node is an attribute used inside one of allowed parents"""
if node.attrname not in attrs:
... |
def qteIsQtmacsWidget(widgetObj):
"""
Determine if a widget is part of Qtmacs widget hierarchy.
A widget belongs to the Qtmacs hierarchy if it, or one of its
parents, has a "_qteAdmin" attribute (added via ``qteAddWidget``).
Since every applet has this attribute is guaranteed that the
function ... | Determine if a widget is part of Qtmacs widget hierarchy.
A widget belongs to the Qtmacs hierarchy if it, or one of its
parents, has a "_qteAdmin" attribute (added via ``qteAddWidget``).
Since every applet has this attribute is guaranteed that the
function returns **True** if the widget is embedded ins... | Below is the the instruction that describes the task:
### Input:
Determine if a widget is part of Qtmacs widget hierarchy.
A widget belongs to the Qtmacs hierarchy if it, or one of its
parents, has a "_qteAdmin" attribute (added via ``qteAddWidget``).
Since every applet has this attribute is guaranteed... |
def retrieve(self, namespace, stream, start_time, end_time, start_id,
configuration, order=ResultOrder.ASCENDING, limit=sys.maxint):
"""
Retrieves all the events for `stream` from `start_time` (inclusive) till
`end_time` (inclusive). Alternatively to `start_time`, `start_id` can be
provid... | Retrieves all the events for `stream` from `start_time` (inclusive) till
`end_time` (inclusive). Alternatively to `start_time`, `start_id` can be
provided, and then all events from `start_id` (exclusive) till `end_time`
(inclusive) are returned. `start_id` should be used in cases when the client
got dis... | Below is the the instruction that describes the task:
### Input:
Retrieves all the events for `stream` from `start_time` (inclusive) till
`end_time` (inclusive). Alternatively to `start_time`, `start_id` can be
provided, and then all events from `start_id` (exclusive) till `end_time`
(inclusive) are ret... |
def conditional_jit(function=None, **kwargs): # noqa: D202
"""Use numba's jit decorator if numba is installed.
Notes
-----
If called without arguments then return wrapped function.
@conditional_jit
def my_func():
return
else called with arguments
@co... | Use numba's jit decorator if numba is installed.
Notes
-----
If called without arguments then return wrapped function.
@conditional_jit
def my_func():
return
else called with arguments
@conditional_jit(nopython=True)
def my_func():
ret... | Below is the the instruction that describes the task:
### Input:
Use numba's jit decorator if numba is installed.
Notes
-----
If called without arguments then return wrapped function.
@conditional_jit
def my_func():
return
else called with arguments
@... |
def check_and_mutate_row(
self,
table_name,
row_key,
app_profile_id=None,
predicate_filter=None,
true_mutations=None,
false_mutations=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
meta... | Mutates a row atomically based on the output of a predicate Reader filter.
Example:
>>> from google.cloud import bigtable_v2
>>>
>>> client = bigtable_v2.BigtableClient()
>>>
>>> table_name = client.table_path('[PROJECT]', '[INSTANCE]', '[TABLE]')
... | Below is the the instruction that describes the task:
### Input:
Mutates a row atomically based on the output of a predicate Reader filter.
Example:
>>> from google.cloud import bigtable_v2
>>>
>>> client = bigtable_v2.BigtableClient()
>>>
>>> tab... |
def tree_build(self):
"""Build a tree from the taxonomy data present in this `ClassificationsDataFrame` or
`SampleCollection`.
Returns
-------
`skbio.tree.TreeNode`, the root node of a tree that contains all the taxa in the current
analysis and their parents leading back... | Build a tree from the taxonomy data present in this `ClassificationsDataFrame` or
`SampleCollection`.
Returns
-------
`skbio.tree.TreeNode`, the root node of a tree that contains all the taxa in the current
analysis and their parents leading back to the root node. | Below is the the instruction that describes the task:
### Input:
Build a tree from the taxonomy data present in this `ClassificationsDataFrame` or
`SampleCollection`.
Returns
-------
`skbio.tree.TreeNode`, the root node of a tree that contains all the taxa in the current
ana... |
def ephem(self, *args, **kwargs):
"""Create an Ephem object which is a subset of this one
Take the same keyword arguments as :py:meth:`ephemeris`
Return:
Ephem:
"""
return self.__class__(self.ephemeris(*args, **kwargs)) | Create an Ephem object which is a subset of this one
Take the same keyword arguments as :py:meth:`ephemeris`
Return:
Ephem: | Below is the the instruction that describes the task:
### Input:
Create an Ephem object which is a subset of this one
Take the same keyword arguments as :py:meth:`ephemeris`
Return:
Ephem:
### Response:
def ephem(self, *args, **kwargs):
"""Create an Ephem object which is a sub... |
def Print(self, output_writer):
"""Prints a human readable version of the filter.
Args:
output_writer (CLIOutputWriter): output writer.
"""
if self._names:
output_writer.Write('\tnames: {0:s}\n'.format(
', '.join(self._names))) | Prints a human readable version of the filter.
Args:
output_writer (CLIOutputWriter): output writer. | Below is the the instruction that describes the task:
### Input:
Prints a human readable version of the filter.
Args:
output_writer (CLIOutputWriter): output writer.
### Response:
def Print(self, output_writer):
"""Prints a human readable version of the filter.
Args:
output_writer (CLIOut... |
def run_on_main_thread(self, func, args=None, kwargs=None):
"""
Runs the ``func`` callable on the main thread, by using the provided microservice
instance's IOLoop.
:param func: callable to run on the main thread
:param args: tuple or list with the positional arguments.
... | Runs the ``func`` callable on the main thread, by using the provided microservice
instance's IOLoop.
:param func: callable to run on the main thread
:param args: tuple or list with the positional arguments.
:param kwargs: dict with the keyword arguments.
:return: | Below is the the instruction that describes the task:
### Input:
Runs the ``func`` callable on the main thread, by using the provided microservice
instance's IOLoop.
:param func: callable to run on the main thread
:param args: tuple or list with the positional arguments.
:param kwar... |
def slice_slice(old_slice, applied_slice, size):
"""Given a slice and the size of the dimension to which it will be applied,
index it with another slice to return a new slice equivalent to applying
the slices sequentially
"""
step = (old_slice.step or 1) * (applied_slice.step or 1)
# For now, u... | Given a slice and the size of the dimension to which it will be applied,
index it with another slice to return a new slice equivalent to applying
the slices sequentially | Below is the the instruction that describes the task:
### Input:
Given a slice and the size of the dimension to which it will be applied,
index it with another slice to return a new slice equivalent to applying
the slices sequentially
### Response:
def slice_slice(old_slice, applied_slice, size):
"""Gi... |
def get_task_cost(self, task_name):
"""
Get task cost
:param task_name: name of the task
:return: task cost
:rtype: Instance.TaskCost
:Example:
>>> cost = instance.get_task_cost(instance.get_task_names()[0])
>>> cost.cpu_cost
200
>>> cos... | Get task cost
:param task_name: name of the task
:return: task cost
:rtype: Instance.TaskCost
:Example:
>>> cost = instance.get_task_cost(instance.get_task_names()[0])
>>> cost.cpu_cost
200
>>> cost.memory_cost
4096
>>> cost.input_size
... | Below is the the instruction that describes the task:
### Input:
Get task cost
:param task_name: name of the task
:return: task cost
:rtype: Instance.TaskCost
:Example:
>>> cost = instance.get_task_cost(instance.get_task_names()[0])
>>> cost.cpu_cost
200
... |
def rnd_datetime_array(size, start=datetime(1970, 1, 1), end=None):
"""
Array or Matrix of random datetime generator.
:returns: 1d or 2d array of datetime.date
"""
if end is None:
end = datetime.now()
start = parser.parse_datetime(start)
end = parser.parse_datetime(end)
_assert_... | Array or Matrix of random datetime generator.
:returns: 1d or 2d array of datetime.date | Below is the the instruction that describes the task:
### Input:
Array or Matrix of random datetime generator.
:returns: 1d or 2d array of datetime.date
### Response:
def rnd_datetime_array(size, start=datetime(1970, 1, 1), end=None):
"""
Array or Matrix of random datetime generator.
:returns: 1d... |
def groupby(self, io_select):
"""
SLICE THIS MATRIX INTO ONES WITH LESS DIMENSIONALITY
io_select - 1 IF GROUPING BY THIS DIMENSION, 0 IF FLATTENING
return -
"""
# offsets WILL SERVE TO MASK DIMS WE ARE NOT GROUPING BY, AND SERVE AS RELATIVE INDEX FOR EACH COORDINATE
... | SLICE THIS MATRIX INTO ONES WITH LESS DIMENSIONALITY
io_select - 1 IF GROUPING BY THIS DIMENSION, 0 IF FLATTENING
return - | Below is the the instruction that describes the task:
### Input:
SLICE THIS MATRIX INTO ONES WITH LESS DIMENSIONALITY
io_select - 1 IF GROUPING BY THIS DIMENSION, 0 IF FLATTENING
return -
### Response:
def groupby(self, io_select):
"""
SLICE THIS MATRIX INTO ONES WITH LESS DIMENSION... |
def named_tuple(
element_name, # type: Text
tuple_type, # type: Type[Tuple]
child_processors, # type: List[Processor]
required=True, # type: bool
alias=None, # type: Optional[Text]
hooks=None # type: Optional[Hooks]
):
# type: (...) -> RootProcessor
"""
... | Create a processor for namedtuple values.
:param tuple_type: The namedtuple type.
See also :func:`declxml.dictionary` | Below is the the instruction that describes the task:
### Input:
Create a processor for namedtuple values.
:param tuple_type: The namedtuple type.
See also :func:`declxml.dictionary`
### Response:
def named_tuple(
element_name, # type: Text
tuple_type, # type: Type[Tuple]
child_... |
def memcache(self, f):
"""Cache a function in memory using an internal dictionary."""
name = _fullname(f)
cache = self.load_memcache(name)
@wraps(f)
def memcached(*args):
"""Cache the function in memory."""
# The arguments need to be hashable. Much faster... | Cache a function in memory using an internal dictionary. | Below is the the instruction that describes the task:
### Input:
Cache a function in memory using an internal dictionary.
### Response:
def memcache(self, f):
"""Cache a function in memory using an internal dictionary."""
name = _fullname(f)
cache = self.load_memcache(name)
@wraps(... |
def cleanupContainers(self):
"""
Cleans up all containers to the right of the current one.
"""
for i in range(self.count() - 1, self.currentIndex(), -1):
widget = self.widget(i)
widget.close()
widget.setParent(None)
widget.deleteLat... | Cleans up all containers to the right of the current one. | Below is the the instruction that describes the task:
### Input:
Cleans up all containers to the right of the current one.
### Response:
def cleanupContainers(self):
"""
Cleans up all containers to the right of the current one.
"""
for i in range(self.count() - 1, self.currentIn... |
def get_last_args(tp):
"""Get last arguments of (multiply) subscripted type.
Parameters for Callable are flattened. Examples::
get_last_args(int) == ()
get_last_args(Union) == ()
get_last_args(ClassVar[int]) == (int,)
get_last_args(Union[T, int]) == (T, int)
get_last_... | Get last arguments of (multiply) subscripted type.
Parameters for Callable are flattened. Examples::
get_last_args(int) == ()
get_last_args(Union) == ()
get_last_args(ClassVar[int]) == (int,)
get_last_args(Union[T, int]) == (T, int)
get_last_args(Iterable[Tuple[T, S]][int... | Below is the the instruction that describes the task:
### Input:
Get last arguments of (multiply) subscripted type.
Parameters for Callable are flattened. Examples::
get_last_args(int) == ()
get_last_args(Union) == ()
get_last_args(ClassVar[int]) == (int,)
get_last_args(Union... |
def string(cls, name, description=None, unit='',
default=None, initial_status=None):
"""Instantiate a new string sensor object.
Parameters
----------
name : str
The name of the sensor.
description : str
A short description of the sensor.
... | Instantiate a new string sensor object.
Parameters
----------
name : str
The name of the sensor.
description : str
A short description of the sensor.
units : str
The units of the sensor value. May be the empty string
if there are n... | Below is the the instruction that describes the task:
### Input:
Instantiate a new string sensor object.
Parameters
----------
name : str
The name of the sensor.
description : str
A short description of the sensor.
units : str
The units of... |
def list_packages(request):
"""
Retrieve a list of the package names registered with the package index.
Returns a list of name strings.
"""
session = DBSession()
names = [p.name for p in Package.all(session, order_by=Package.name)]
return names | Retrieve a list of the package names registered with the package index.
Returns a list of name strings. | Below is the the instruction that describes the task:
### Input:
Retrieve a list of the package names registered with the package index.
Returns a list of name strings.
### Response:
def list_packages(request):
"""
Retrieve a list of the package names registered with the package index.
Returns a li... |
def autoLayoutSelected( self,
padX = None,
padY = None,
direction = Qt.Horizontal,
layout = 'Layered',
animate = 0,
centerOn = None,
... | Automatically lays out all the selected nodes in the scene using the \
autoLayoutNodes method.
:param padX | <int> || None | default is 2 * cell width
padY | <int> || None | default is 2 * cell height
direction | <Qt.Direction>
la... | Below is the the instruction that describes the task:
### Input:
Automatically lays out all the selected nodes in the scene using the \
autoLayoutNodes method.
:param padX | <int> || None | default is 2 * cell width
padY | <int> || None | default is 2 * cell height
... |
def to_netcdf(self, filename, compress=True):
"""Write InferenceData to file using netcdf4.
Parameters
----------
filename : str
Location to write to
compress : bool
Whether to compress result. Note this saves disk space, but may make
saving a... | Write InferenceData to file using netcdf4.
Parameters
----------
filename : str
Location to write to
compress : bool
Whether to compress result. Note this saves disk space, but may make
saving and loading somewhat slower (default: True).
Retu... | Below is the the instruction that describes the task:
### Input:
Write InferenceData to file using netcdf4.
Parameters
----------
filename : str
Location to write to
compress : bool
Whether to compress result. Note this saves disk space, but may make
... |
def get_equipment(self, **kwargs):
"""
Return list environments related with environment vip
"""
uri = 'api/v3/equipment/'
uri = self.prepare_url(uri, kwargs)
return super(ApiEquipment, self).get(uri) | Return list environments related with environment vip | Below is the the instruction that describes the task:
### Input:
Return list environments related with environment vip
### Response:
def get_equipment(self, **kwargs):
"""
Return list environments related with environment vip
"""
uri = 'api/v3/equipment/'
uri = self.prepare... |
def display_latex(*objs, **kwargs):
"""Display the LaTeX representation of an object.
Parameters
----------
objs : tuple of objects
The Python objects to display, or if raw=True raw latex data to
display.
raw : bool
Are the data objects raw data or Python objects that need t... | Display the LaTeX representation of an object.
Parameters
----------
objs : tuple of objects
The Python objects to display, or if raw=True raw latex data to
display.
raw : bool
Are the data objects raw data or Python objects that need to be
formatted before display? [def... | Below is the the instruction that describes the task:
### Input:
Display the LaTeX representation of an object.
Parameters
----------
objs : tuple of objects
The Python objects to display, or if raw=True raw latex data to
display.
raw : bool
Are the data objects raw data or ... |
def p_members(self, p):
"""members :
| members member VALUE_SEPARATOR
| members member"""
if len(p) == 1:
p[0] = list()
else:
p[1].append(p[2])
p[0] = p[1] | members :
| members member VALUE_SEPARATOR
| members member | Below is the the instruction that describes the task:
### Input:
members :
| members member VALUE_SEPARATOR
| members member
### Response:
def p_members(self, p):
"""members :
| members member VALUE_SEPARATOR
| members member"""
... |
def silence(cls, *modules, **kwargs):
"""
Args:
*modules: Modules, or names of modules to silence (by setting their log level to WARNING or above)
**kwargs: Pass as kwargs due to python 2.7, would be level=logging.WARNING otherwise
"""
level = kwargs.pop("level", ... | Args:
*modules: Modules, or names of modules to silence (by setting their log level to WARNING or above)
**kwargs: Pass as kwargs due to python 2.7, would be level=logging.WARNING otherwise | Below is the the instruction that describes the task:
### Input:
Args:
*modules: Modules, or names of modules to silence (by setting their log level to WARNING or above)
**kwargs: Pass as kwargs due to python 2.7, would be level=logging.WARNING otherwise
### Response:
def silence(cls, *modu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.