code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def tci_path(self):
"""Return the path to the granules TrueColorImage."""
tci_paths = [
path for path in self.dataset._product_metadata.xpath(
".//Granule[@granuleIdentifier='%s']/IMAGE_FILE/text()"
% self.granule_identifier
) if path.endswith('TCI... | Return the path to the granules TrueColorImage. | Below is the the instruction that describes the task:
### Input:
Return the path to the granules TrueColorImage.
### Response:
def tci_path(self):
"""Return the path to the granules TrueColorImage."""
tci_paths = [
path for path in self.dataset._product_metadata.xpath(
"... |
def contacts_getPublicList(user_id):
"""Gets the contacts (Users) for the user_id"""
method = 'flickr.contacts.getPublicList'
data = _doget(method, auth=False, user_id=user_id)
if isinstance(data.rsp.contacts.contact, list):
return [User(user.nsid, username=user.username) \
for u... | Gets the contacts (Users) for the user_id | Below is the the instruction that describes the task:
### Input:
Gets the contacts (Users) for the user_id
### Response:
def contacts_getPublicList(user_id):
"""Gets the contacts (Users) for the user_id"""
method = 'flickr.contacts.getPublicList'
data = _doget(method, auth=False, user_id=user_id)
i... |
def get_script_module(script_information, package='pylabcontrol', verbose=False):
"""
wrapper to get the module for a script
Args:
script_information: information of the script. This can be
- a dictionary
- a Script instance
- name of ... | wrapper to get the module for a script
Args:
script_information: information of the script. This can be
- a dictionary
- a Script instance
- name of Script class
package (optional): name of the package to which the script belongs, i.e. pyl... | Below is the the instruction that describes the task:
### Input:
wrapper to get the module for a script
Args:
script_information: information of the script. This can be
- a dictionary
- a Script instance
- name of Script class
package ... |
def _open_channels(self) -> bool:
""" Open channels until there are `self.initial_channel_target`
channels open. Do nothing if there are enough channels open already.
Note:
- This method must be called with the lock held.
Return:
- False if no channels could be o... | Open channels until there are `self.initial_channel_target`
channels open. Do nothing if there are enough channels open already.
Note:
- This method must be called with the lock held.
Return:
- False if no channels could be opened | Below is the the instruction that describes the task:
### Input:
Open channels until there are `self.initial_channel_target`
channels open. Do nothing if there are enough channels open already.
Note:
- This method must be called with the lock held.
Return:
- False if... |
def _BuildToken(self, request, execution_time):
"""Build an ACLToken from the request."""
token = access_control.ACLToken(
username=request.user,
reason=request.args.get("reason", ""),
process="GRRAdminUI",
expiry=rdfvalue.RDFDatetime.Now() + execution_time)
for field in ["R... | Build an ACLToken from the request. | Below is the the instruction that describes the task:
### Input:
Build an ACLToken from the request.
### Response:
def _BuildToken(self, request, execution_time):
"""Build an ACLToken from the request."""
token = access_control.ACLToken(
username=request.user,
reason=request.args.get("reaso... |
def init_common(app):
"""Post initialization."""
if app.config['USERPROFILES_EXTEND_SECURITY_FORMS']:
security_ext = app.extensions['security']
security_ext.confirm_register_form = confirm_register_form_factory(
security_ext.confirm_register_form)
security_ext.register_form =... | Post initialization. | Below is the the instruction that describes the task:
### Input:
Post initialization.
### Response:
def init_common(app):
"""Post initialization."""
if app.config['USERPROFILES_EXTEND_SECURITY_FORMS']:
security_ext = app.extensions['security']
security_ext.confirm_register_form = confirm_re... |
def wait_until_first_element_is_found(self, elements, timeout=None):
"""Search list of elements and wait until one of them is found
:param elements: list of PageElements or element locators as a tuple (locator_type, locator_value) to be found
sequentially
:param timeout... | Search list of elements and wait until one of them is found
:param elements: list of PageElements or element locators as a tuple (locator_type, locator_value) to be found
sequentially
:param timeout: max time to wait
:returns: first element found
:rtype: toolium... | Below is the the instruction that describes the task:
### Input:
Search list of elements and wait until one of them is found
:param elements: list of PageElements or element locators as a tuple (locator_type, locator_value) to be found
sequentially
:param timeout: max time ... |
def push(self, repository, tag=None, stream=False, auth_config=None,
decode=False):
"""
Push an image or a repository to the registry. Similar to the ``docker
push`` command.
Args:
repository (str): The repository to push to
tag (str): An optional ta... | Push an image or a repository to the registry. Similar to the ``docker
push`` command.
Args:
repository (str): The repository to push to
tag (str): An optional tag to push
stream (bool): Stream the output as a blocking generator
auth_config (dict): Overri... | Below is the the instruction that describes the task:
### Input:
Push an image or a repository to the registry. Similar to the ``docker
push`` command.
Args:
repository (str): The repository to push to
tag (str): An optional tag to push
stream (bool): Stream the ... |
def add_replace(self, selector, replacement, upsert=False,
collation=None):
"""Create a replace document and add it to the list of ops.
"""
validate_ok_for_replace(replacement)
cmd = SON([('q', selector), ('u', replacement),
('multi', False), ('upse... | Create a replace document and add it to the list of ops. | Below is the the instruction that describes the task:
### Input:
Create a replace document and add it to the list of ops.
### Response:
def add_replace(self, selector, replacement, upsert=False,
collation=None):
"""Create a replace document and add it to the list of ops.
"""
... |
def basis_functions(degree, knot_vector, spans, knots):
""" Computes the non-vanishing basis functions for a list of parameters.
:param degree: degree, :math:`p`
:type degree: int
:param knot_vector: knot vector, :math:`U`
:type knot_vector: list, tuple
:param spans: list of knot spans
:typ... | Computes the non-vanishing basis functions for a list of parameters.
:param degree: degree, :math:`p`
:type degree: int
:param knot_vector: knot vector, :math:`U`
:type knot_vector: list, tuple
:param spans: list of knot spans
:type spans: list, tuple
:param knots: list of knots or paramet... | Below is the the instruction that describes the task:
### Input:
Computes the non-vanishing basis functions for a list of parameters.
:param degree: degree, :math:`p`
:type degree: int
:param knot_vector: knot vector, :math:`U`
:type knot_vector: list, tuple
:param spans: list of knot spans
... |
def depuncture(self,soft_bits,puncture_pattern = ('110','101'),
erase_value = 3.5):
"""
Apply de-puncturing to the soft bits coming from the channel. Erasure bits
are inserted to return the soft bit values back to a form that can be
Viterbi decoded.
:pa... | Apply de-puncturing to the soft bits coming from the channel. Erasure bits
are inserted to return the soft bit values back to a form that can be
Viterbi decoded.
:param soft_bits:
:param puncture_pattern:
:param erase_value:
:return:
Examples
-... | Below is the the instruction that describes the task:
### Input:
Apply de-puncturing to the soft bits coming from the channel. Erasure bits
are inserted to return the soft bit values back to a form that can be
Viterbi decoded.
:param soft_bits:
:param puncture_pattern:
... |
def tintWith(self, red, green, blue):
"""tintWith(self, red, green, blue)"""
if not self.colorspace or self.colorspace.n > 3:
print("warning: colorspace invalid for function")
return
return _fitz.Pixmap_tintWith(self, red, green, blue) | tintWith(self, red, green, blue) | Below is the the instruction that describes the task:
### Input:
tintWith(self, red, green, blue)
### Response:
def tintWith(self, red, green, blue):
"""tintWith(self, red, green, blue)"""
if not self.colorspace or self.colorspace.n > 3:
print("warning: colorspace invalid for function"... |
def user_organization_memberships(self, user_id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/organization_memberships#list-memberships"
api_path = "/api/v2/users/{user_id}/organization_memberships.json"
api_path = api_path.format(user_id=user_id)
return self.call(api_pat... | https://developer.zendesk.com/rest_api/docs/core/organization_memberships#list-memberships | Below is the the instruction that describes the task:
### Input:
https://developer.zendesk.com/rest_api/docs/core/organization_memberships#list-memberships
### Response:
def user_organization_memberships(self, user_id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/organization_memberships#li... |
def op_cmd(self, command, req_format='text', xpath_expr=""):
""" Execute an operational mode command.
Purpose: Used to send an operational mode command to the connected
| device. This requires and uses a paramiko.SSHClient() as
| the handler so that we can easily pass and ... | Execute an operational mode command.
Purpose: Used to send an operational mode command to the connected
| device. This requires and uses a paramiko.SSHClient() as
| the handler so that we can easily pass and allow all pipe
| commands to be used.
|
... | Below is the the instruction that describes the task:
### Input:
Execute an operational mode command.
Purpose: Used to send an operational mode command to the connected
| device. This requires and uses a paramiko.SSHClient() as
| the handler so that we can easily pass and allo... |
def status_update(self, crits_id, crits_type, status):
"""
Update the status of the TLO. By default, the options are:
- New
- In Progress
- Analyzed
- Deprecated
Args:
crits_id: The object id of the TLO
crits_type: The type of TLO. This mu... | Update the status of the TLO. By default, the options are:
- New
- In Progress
- Analyzed
- Deprecated
Args:
crits_id: The object id of the TLO
crits_type: The type of TLO. This must be 'Indicator', ''
status: The status to change.
Ret... | Below is the the instruction that describes the task:
### Input:
Update the status of the TLO. By default, the options are:
- New
- In Progress
- Analyzed
- Deprecated
Args:
crits_id: The object id of the TLO
crits_type: The type of TLO. This must be ... |
def get_form(self, request, obj=None, **kwargs):
"""
Pass the current language to the form.
"""
form_class = super(TranslatableAdmin, self).get_form(request, obj, **kwargs)
if self._has_translatable_model():
form_class.language_code = self.get_form_language(request, o... | Pass the current language to the form. | Below is the the instruction that describes the task:
### Input:
Pass the current language to the form.
### Response:
def get_form(self, request, obj=None, **kwargs):
"""
Pass the current language to the form.
"""
form_class = super(TranslatableAdmin, self).get_form(request, obj, **... |
def get_integration_module(integration_path):
"""Add custom paths to sys and import integration module.
:param integration_path: Path to integration folder
"""
# add custom paths so imports would work
paths = [
os.path.join(__file__, "..", ".."), # to import integrationmanager
os.p... | Add custom paths to sys and import integration module.
:param integration_path: Path to integration folder | Below is the the instruction that describes the task:
### Input:
Add custom paths to sys and import integration module.
:param integration_path: Path to integration folder
### Response:
def get_integration_module(integration_path):
"""Add custom paths to sys and import integration module.
:param inte... |
def _get_const_info(const_index, const_list):
"""Helper to get optional details about const references
Returns the dereferenced constant and its repr if the constant
list is defined.
Otherwise returns the constant index and its repr().
"""
argval = const_index
if const_list is not ... | Helper to get optional details about const references
Returns the dereferenced constant and its repr if the constant
list is defined.
Otherwise returns the constant index and its repr(). | Below is the the instruction that describes the task:
### Input:
Helper to get optional details about const references
Returns the dereferenced constant and its repr if the constant
list is defined.
Otherwise returns the constant index and its repr().
### Response:
def _get_const_info(const_i... |
def get(
self,
name=None,
group=None,
index=None,
raster=None,
samples_only=False,
data=None,
raw=False,
ignore_invalidation_bits=False,
source=None,
record_offset=0,
record_count=None,
copy_master=True,
):
... | Gets channel samples.
Channel can be specified in two ways:
* using the first positional argument *name*
* if *source* is given this will be first used to validate the
channel selection
* if there are multiple occurances for this channel then the
*gr... | Below is the the instruction that describes the task:
### Input:
Gets channel samples.
Channel can be specified in two ways:
* using the first positional argument *name*
* if *source* is given this will be first used to validate the
channel selection
* if ther... |
def inverted_level_order(self) -> Iterator["BSP"]:
"""Iterate over this BSP's hierarchy in inverse level order.
.. versionadded:: 8.3
"""
levels = [] # type: List[List['BSP']]
next = [self] # type: List['BSP']
while next:
levels.append(next)
lev... | Iterate over this BSP's hierarchy in inverse level order.
.. versionadded:: 8.3 | Below is the the instruction that describes the task:
### Input:
Iterate over this BSP's hierarchy in inverse level order.
.. versionadded:: 8.3
### Response:
def inverted_level_order(self) -> Iterator["BSP"]:
"""Iterate over this BSP's hierarchy in inverse level order.
.. versionadded:: ... |
def pstdev(data, mu=None):
"""Return the square root of the population variance.
See ``pvariance`` for arguments and other details.
"""
var = pvariance(data, mu)
try:
return var.sqrt()
except AttributeError:
return math.sqrt(var) | Return the square root of the population variance.
See ``pvariance`` for arguments and other details. | Below is the the instruction that describes the task:
### Input:
Return the square root of the population variance.
See ``pvariance`` for arguments and other details.
### Response:
def pstdev(data, mu=None):
"""Return the square root of the population variance.
See ``pvariance`` for arguments and oth... |
def fill_pool(self):
"""
Add connections as necessary to meet the target pool size. If there
are no nodes to connect to (because we maxed out connections-per-node
on all active connections and any unconnected nodes have pending
reconnect timers), call the on_insufficient_nodes ca... | Add connections as necessary to meet the target pool size. If there
are no nodes to connect to (because we maxed out connections-per-node
on all active connections and any unconnected nodes have pending
reconnect timers), call the on_insufficient_nodes callback. | Below is the the instruction that describes the task:
### Input:
Add connections as necessary to meet the target pool size. If there
are no nodes to connect to (because we maxed out connections-per-node
on all active connections and any unconnected nodes have pending
reconnect timers), call ... |
def execute_policy(self, policy):
"""
Executes the specified policy for this scaling group.
"""
return self.manager.execute_policy(scaling_group=self, policy=policy) | Executes the specified policy for this scaling group. | Below is the the instruction that describes the task:
### Input:
Executes the specified policy for this scaling group.
### Response:
def execute_policy(self, policy):
"""
Executes the specified policy for this scaling group.
"""
return self.manager.execute_policy(scaling_group=self,... |
def is_empty(self):
"""
Test interval emptiness.
:return: True if interval is empty, False otherwise.
"""
return (
self._lower > self._upper or
(self._lower == self._upper and (self._left == OPEN or self._right == OPEN))
) | Test interval emptiness.
:return: True if interval is empty, False otherwise. | Below is the the instruction that describes the task:
### Input:
Test interval emptiness.
:return: True if interval is empty, False otherwise.
### Response:
def is_empty(self):
"""
Test interval emptiness.
:return: True if interval is empty, False otherwise.
"""
re... |
def format_exc(limit=None):
"""Like print_exc() but return a string. Backport for Python 2.3."""
try:
etype, value, tb = sys.exc_info()
return ''.join(traceback.format_exception(etype, value, tb, limit))
finally:
etype = value = tb = None | Like print_exc() but return a string. Backport for Python 2.3. | Below is the the instruction that describes the task:
### Input:
Like print_exc() but return a string. Backport for Python 2.3.
### Response:
def format_exc(limit=None):
"""Like print_exc() but return a string. Backport for Python 2.3."""
try:
etype, value, tb = sys.exc_info()
return ''.joi... |
def squish(incs, f):
"""
returns 'flattened' inclination, assuming factor, f and King (1955) formula:
tan (I_o) = f tan (I_f)
Parameters
__________
incs : array of inclination (I_f) data to flatten
f : flattening factor
Returns
_______
I_o : inclinations after flattening
... | returns 'flattened' inclination, assuming factor, f and King (1955) formula:
tan (I_o) = f tan (I_f)
Parameters
__________
incs : array of inclination (I_f) data to flatten
f : flattening factor
Returns
_______
I_o : inclinations after flattening | Below is the the instruction that describes the task:
### Input:
returns 'flattened' inclination, assuming factor, f and King (1955) formula:
tan (I_o) = f tan (I_f)
Parameters
__________
incs : array of inclination (I_f) data to flatten
f : flattening factor
Returns
_______
I_o :... |
def _checkMousePositionForFocus(self):
"""Check the mouse position to know if move focus on a option"""
i = 0
cur_pos = pygame.mouse.get_pos()
ml, mt = self.position
for o in self.options:
rect = o.get('label_rect')
if rect:
if rect.collide... | Check the mouse position to know if move focus on a option | Below is the the instruction that describes the task:
### Input:
Check the mouse position to know if move focus on a option
### Response:
def _checkMousePositionForFocus(self):
"""Check the mouse position to know if move focus on a option"""
i = 0
cur_pos = pygame.mouse.get_pos()
ml... |
def _mc_error(x, batches=5, circular=False):
"""Calculate the simulation standard error, accounting for non-independent samples.
The trace is divided into batches, and the standard deviation of the batch
means is calculated.
Parameters
----------
x : Numpy array
An array containing MCM... | Calculate the simulation standard error, accounting for non-independent samples.
The trace is divided into batches, and the standard deviation of the batch
means is calculated.
Parameters
----------
x : Numpy array
An array containing MCMC samples
batches : integer
Number of ba... | Below is the the instruction that describes the task:
### Input:
Calculate the simulation standard error, accounting for non-independent samples.
The trace is divided into batches, and the standard deviation of the batch
means is calculated.
Parameters
----------
x : Numpy array
An arr... |
def set_attributes(self, doc, fields, # pylint: disable=arguments-differ
parent_type=None, catch_all_field=None):
"""
:param UnionField catch_all_field: The field designated as the
catch-all. This field should be a member of the list of fields.
See :meth:`Composite.set_... | :param UnionField catch_all_field: The field designated as the
catch-all. This field should be a member of the list of fields.
See :meth:`Composite.set_attributes` for parameter definitions. | Below is the the instruction that describes the task:
### Input:
:param UnionField catch_all_field: The field designated as the
catch-all. This field should be a member of the list of fields.
See :meth:`Composite.set_attributes` for parameter definitions.
### Response:
def set_attributes(self,... |
def set_kw_typeahead_input(cls):
"""
Map the typeahead input to remote dataset.
"""
# get reference to parent element
parent_id = cls.intput_el.parent.id
if "typeahead" not in parent_id.lower():
parent_id = cls.intput_el.parent.parent.id
window.make_k... | Map the typeahead input to remote dataset. | Below is the the instruction that describes the task:
### Input:
Map the typeahead input to remote dataset.
### Response:
def set_kw_typeahead_input(cls):
"""
Map the typeahead input to remote dataset.
"""
# get reference to parent element
parent_id = cls.intput_el.parent.id... |
def run_somaticsniper_with_merge(job, tumor_bam, normal_bam, univ_options, somaticsniper_options):
"""
A wrapper for the the entire SomaticSniper sub-graph.
:param dict tumor_bam: Dict of bam and bai for tumor DNA-Seq
:param dict normal_bam: Dict of bam and bai for normal DNA-Seq
:param dict univ_o... | A wrapper for the the entire SomaticSniper sub-graph.
:param dict tumor_bam: Dict of bam and bai for tumor DNA-Seq
:param dict normal_bam: Dict of bam and bai for normal DNA-Seq
:param dict univ_options: Dict of universal options used by almost all tools
:param dict somaticsniper_options: Options speci... | Below is the the instruction that describes the task:
### Input:
A wrapper for the the entire SomaticSniper sub-graph.
:param dict tumor_bam: Dict of bam and bai for tumor DNA-Seq
:param dict normal_bam: Dict of bam and bai for normal DNA-Seq
:param dict univ_options: Dict of universal options used by ... |
def view_tickets(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/views#list-tickets-from-a-view"
api_path = "/api/v2/views/{id}/tickets.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/views#list-tickets-from-a-view | Below is the the instruction that describes the task:
### Input:
https://developer.zendesk.com/rest_api/docs/core/views#list-tickets-from-a-view
### Response:
def view_tickets(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/views#list-tickets-from-a-view"
api_path = "/api/v2/... |
def run_remote_command(host, command, timeout_sec=5.0):
"""Retrieves the value of an environment variable of a
remote host over SSH
:param host: (str) host to query
:param command: (str) command
:param timeout_sec (float) seconds to wait before killing the command.
:return: (str) command output... | Retrieves the value of an environment variable of a
remote host over SSH
:param host: (str) host to query
:param command: (str) command
:param timeout_sec (float) seconds to wait before killing the command.
:return: (str) command output
:raises: TypeError, CommandError | Below is the the instruction that describes the task:
### Input:
Retrieves the value of an environment variable of a
remote host over SSH
:param host: (str) host to query
:param command: (str) command
:param timeout_sec (float) seconds to wait before killing the command.
:return: (str) command ... |
def runPlink(options):
"""Run Plink with the ``mind`` option.
:param options: the options.
:type options: argparse.Namespace
"""
# The plink command
plinkCommand = [
"plink",
"--noweb",
"--bfile" if options.is_bfile else "--tfile",
options.ifile,
"--min... | Run Plink with the ``mind`` option.
:param options: the options.
:type options: argparse.Namespace | Below is the the instruction that describes the task:
### Input:
Run Plink with the ``mind`` option.
:param options: the options.
:type options: argparse.Namespace
### Response:
def runPlink(options):
"""Run Plink with the ``mind`` option.
:param options: the options.
:type options: argpars... |
def add_vlan_int(self, vlan_id):
"""
Add VLAN Interface. VLAN interfaces are required for VLANs even when
not wanting to use the interface for any L3 features.
Args:
vlan_id: ID for the VLAN interface being created. Value of 2-4096.
Returns:
True if comm... | Add VLAN Interface. VLAN interfaces are required for VLANs even when
not wanting to use the interface for any L3 features.
Args:
vlan_id: ID for the VLAN interface being created. Value of 2-4096.
Returns:
True if command completes successfully or False if not.
... | Below is the the instruction that describes the task:
### Input:
Add VLAN Interface. VLAN interfaces are required for VLANs even when
not wanting to use the interface for any L3 features.
Args:
vlan_id: ID for the VLAN interface being created. Value of 2-4096.
Returns:
... |
def compute_auth_key(userid, password):
"""
Compute the authentication key for freedns.afraid.org.
This is the SHA1 hash of the string b'userid|password'.
:param userid: ascii username
:param password: ascii password
:return: ascii authentication key (SHA1 at this point)
"""
import sys... | Compute the authentication key for freedns.afraid.org.
This is the SHA1 hash of the string b'userid|password'.
:param userid: ascii username
:param password: ascii password
:return: ascii authentication key (SHA1 at this point) | Below is the the instruction that describes the task:
### Input:
Compute the authentication key for freedns.afraid.org.
This is the SHA1 hash of the string b'userid|password'.
:param userid: ascii username
:param password: ascii password
:return: ascii authentication key (SHA1 at this point)
### R... |
def docker(gandi, vm, args):
"""
Manage docker instance
"""
if not [basedir for basedir in os.getenv('PATH', '.:/usr/bin').split(':')
if os.path.exists('%s/docker' % basedir)]:
gandi.echo("""'docker' not found in $PATH, required for this command \
to work
See https://docs.docker.com/... | Manage docker instance | Below is the the instruction that describes the task:
### Input:
Manage docker instance
### Response:
def docker(gandi, vm, args):
"""
Manage docker instance
"""
if not [basedir for basedir in os.getenv('PATH', '.:/usr/bin').split(':')
if os.path.exists('%s/docker' % basedir)]:
... |
def render(self, container, descender, state, space_below=0,
first_line_only=False):
"""Typeset the paragraph
The paragraph is typeset in the given container starting below the
current cursor position of the container. When the end of the container
is reached, the renderi... | Typeset the paragraph
The paragraph is typeset in the given container starting below the
current cursor position of the container. When the end of the container
is reached, the rendering state is preserved to continue setting the
rest of the paragraph when this method is called with a n... | Below is the the instruction that describes the task:
### Input:
Typeset the paragraph
The paragraph is typeset in the given container starting below the
current cursor position of the container. When the end of the container
is reached, the rendering state is preserved to continue setting ... |
def get(method, hmc, uri, uri_parms, logon_required):
"""Operation: List Password Rules."""
query_str = uri_parms[0]
try:
console = hmc.consoles.lookup_by_oid(None)
except KeyError:
raise InvalidResourceError(method, uri)
result_password_rules = []
... | Operation: List Password Rules. | Below is the the instruction that describes the task:
### Input:
Operation: List Password Rules.
### Response:
def get(method, hmc, uri, uri_parms, logon_required):
"""Operation: List Password Rules."""
query_str = uri_parms[0]
try:
console = hmc.consoles.lookup_by_oid(None)
... |
def retrieve_client_credentials(self):
"""Return the client credentials.
:returns: tuple(client_id, client_secret)
"""
client_id = self.params.get('client_id')
client_secret = self.params.get('client_secret')
return (client_id, client_secret) | Return the client credentials.
:returns: tuple(client_id, client_secret) | Below is the the instruction that describes the task:
### Input:
Return the client credentials.
:returns: tuple(client_id, client_secret)
### Response:
def retrieve_client_credentials(self):
"""Return the client credentials.
:returns: tuple(client_id, client_secret)
"""
cl... |
def write_fcs(filename, chn_names, data,
endianness="big",
compat_chn_names=True,
compat_copy=True,
compat_negative=True,
compat_percent=True,
compat_max_int16=10000):
"""Write numpy data to an .fcs file (FCS3.0 file format)
P... | Write numpy data to an .fcs file (FCS3.0 file format)
Parameters
----------
filename: str or pathlib.Path
Path to the output .fcs file
ch_names: list of str, length C
Names of the output channels
data: 2d ndarray of shape (N,C)
The numpy array data to store as .fcs file for... | Below is the the instruction that describes the task:
### Input:
Write numpy data to an .fcs file (FCS3.0 file format)
Parameters
----------
filename: str or pathlib.Path
Path to the output .fcs file
ch_names: list of str, length C
Names of the output channels
data: 2d ndarray ... |
def disconnect_sync(self, conn_id):
"""Synchronously disconnect from a connected device
Args:
conn_id (int): A unique identifier that will refer to this connection
Returns:
dict: A dictionary with two elements
'success': a bool with the result of the con... | Synchronously disconnect from a connected device
Args:
conn_id (int): A unique identifier that will refer to this connection
Returns:
dict: A dictionary with two elements
'success': a bool with the result of the connection attempt
'failure_reason... | Below is the the instruction that describes the task:
### Input:
Synchronously disconnect from a connected device
Args:
conn_id (int): A unique identifier that will refer to this connection
Returns:
dict: A dictionary with two elements
'success': a bool with... |
def get_rendered_transform_path_relative(self, relative_transform_ref):
"""
Generates a rendered transform path relative to
parent.
:param relative_transform_ref:
:return:
"""
path = self.transform_path
parent = self.parent
while parent is not Non... | Generates a rendered transform path relative to
parent.
:param relative_transform_ref:
:return: | Below is the the instruction that describes the task:
### Input:
Generates a rendered transform path relative to
parent.
:param relative_transform_ref:
:return:
### Response:
def get_rendered_transform_path_relative(self, relative_transform_ref):
"""
Generates a rendered tra... |
def __create_distance_calculator(self):
"""!
@brief Creates distance calculator in line with algorithms parameters.
@return (callable) Distance calculator.
"""
if self.__data_type == 'points':
return lambda index1, index2: self.__metric(self.__pointer_data[i... | !
@brief Creates distance calculator in line with algorithms parameters.
@return (callable) Distance calculator. | Below is the the instruction that describes the task:
### Input:
!
@brief Creates distance calculator in line with algorithms parameters.
@return (callable) Distance calculator.
### Response:
def __create_distance_calculator(self):
"""!
@brief Creates distance calculator in li... |
def clipboard_get(self):
""" Get text from the clipboard.
"""
from IPython.lib.clipboard import (
osx_clipboard_get, tkinter_clipboard_get,
win32_clipboard_get
)
if sys.platform == 'win32':
chain = [win32_clipboard_get, tkinter_clipboard_get]
elif sys.platform == 'darwin'... | Get text from the clipboard. | Below is the the instruction that describes the task:
### Input:
Get text from the clipboard.
### Response:
def clipboard_get(self):
""" Get text from the clipboard.
"""
from IPython.lib.clipboard import (
osx_clipboard_get, tkinter_clipboard_get,
win32_clipboard_get
)
if sys.pl... |
def get_subsequence(self, resnums, new_id=None, copy_letter_annotations=True):
"""Get a subsequence as a new SeqProp object given a list of residue numbers"""
# XTODO: documentation
biop_compound_list = []
for resnum in resnums:
# XTODO can be sped up by separating into range... | Get a subsequence as a new SeqProp object given a list of residue numbers | Below is the the instruction that describes the task:
### Input:
Get a subsequence as a new SeqProp object given a list of residue numbers
### Response:
def get_subsequence(self, resnums, new_id=None, copy_letter_annotations=True):
"""Get a subsequence as a new SeqProp object given a list of residue number... |
def data(self, data):
""" Sets the font data of this item.
Does type conversion to ensure data is always of the correct type.
Also updates the children (which is the reason for this property to be overloaded.
"""
self._data = self._enforceDataType(data) # Enforce self._d... | Sets the font data of this item.
Does type conversion to ensure data is always of the correct type.
Also updates the children (which is the reason for this property to be overloaded. | Below is the the instruction that describes the task:
### Input:
Sets the font data of this item.
Does type conversion to ensure data is always of the correct type.
Also updates the children (which is the reason for this property to be overloaded.
### Response:
def data(self, data):
... |
def selections(self):
"""Build list of extra selections for rectangular selection"""
selections = []
cursors = self.cursors()
if cursors:
background = self._qpart.palette().color(QPalette.Highlight)
foreground = self._qpart.palette().color(QPalette.HighlightedText... | Build list of extra selections for rectangular selection | Below is the the instruction that describes the task:
### Input:
Build list of extra selections for rectangular selection
### Response:
def selections(self):
"""Build list of extra selections for rectangular selection"""
selections = []
cursors = self.cursors()
if cursors:
... |
def check_sha1(filename, sha1_hash):
"""Check whether the sha1 hash of the file content matches the expected hash.
Parameters
----------
filename : str
Path to the file.
sha1_hash : str
Expected sha1 hash in hexadecimal digits.
Returns
-------
bool
Whether the f... | Check whether the sha1 hash of the file content matches the expected hash.
Parameters
----------
filename : str
Path to the file.
sha1_hash : str
Expected sha1 hash in hexadecimal digits.
Returns
-------
bool
Whether the file content matches the expected hash. | Below is the the instruction that describes the task:
### Input:
Check whether the sha1 hash of the file content matches the expected hash.
Parameters
----------
filename : str
Path to the file.
sha1_hash : str
Expected sha1 hash in hexadecimal digits.
Returns
-------
b... |
def is_smooth_from(self, previous, warning_on=True):
"""[Warning: The name of this method is somewhat misleading (yet kept
for compatibility with scripts created using svg.path 2.0). This
method is meant only for d string creation and should not be used to
check for kinks. To check a s... | [Warning: The name of this method is somewhat misleading (yet kept
for compatibility with scripts created using svg.path 2.0). This
method is meant only for d string creation and should not be used to
check for kinks. To check a segment for differentiability, use the
joins_smoothly_wit... | Below is the the instruction that describes the task:
### Input:
[Warning: The name of this method is somewhat misleading (yet kept
for compatibility with scripts created using svg.path 2.0). This
method is meant only for d string creation and should not be used to
check for kinks. To chec... |
def _get_workflow_by_uuid(workflow_uuid):
"""Get Workflow with UUIDv4.
:param workflow_uuid: UUIDv4 of a Workflow.
:type workflow_uuid: String representing a valid UUIDv4.
:rtype: reana-db.models.Workflow
"""
from reana_db.models import Workflow
workflow = Workflow.query.filter(Workflow.id... | Get Workflow with UUIDv4.
:param workflow_uuid: UUIDv4 of a Workflow.
:type workflow_uuid: String representing a valid UUIDv4.
:rtype: reana-db.models.Workflow | Below is the the instruction that describes the task:
### Input:
Get Workflow with UUIDv4.
:param workflow_uuid: UUIDv4 of a Workflow.
:type workflow_uuid: String representing a valid UUIDv4.
:rtype: reana-db.models.Workflow
### Response:
def _get_workflow_by_uuid(workflow_uuid):
"""Get Workflow ... |
def ntp_server_key(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ntp = ET.SubElement(config, "ntp", xmlns="urn:brocade.com:mgmt:brocade-ntp")
server = ET.SubElement(ntp, "server")
ip_key = ET.SubElement(server, "ip")
ip_key.text = kwarg... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def ntp_server_key(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ntp = ET.SubElement(config, "ntp", xmlns="urn:brocade.com:mgmt:brocade-ntp")
server... |
def __onPickEvent(self, event=None):
"""pick events"""
legline = event.artist
trace = self.conf.legend_map.get(legline, None)
visible = True
if trace is not None and self.conf.hidewith_legend:
line, legline, legtext = trace
visible = not line.get_visible()... | pick events | Below is the the instruction that describes the task:
### Input:
pick events
### Response:
def __onPickEvent(self, event=None):
"""pick events"""
legline = event.artist
trace = self.conf.legend_map.get(legline, None)
visible = True
if trace is not None and self.conf.hidewith... |
def list(self, filter_function=None, list_root='', max_results=1, reverse_order=False, previous_file=''):
''' a method to list files on localhost from walk of directories
:param filter_function: (keyword arguments) function used to filter results
:param list_root: string with localhost pa... | a method to list files on localhost from walk of directories
:param filter_function: (keyword arguments) function used to filter results
:param list_root: string with localhost path from which to root list of files
:param max_results: integer with maximum number of results to return
... | Below is the the instruction that describes the task:
### Input:
a method to list files on localhost from walk of directories
:param filter_function: (keyword arguments) function used to filter results
:param list_root: string with localhost path from which to root list of files
:param ... |
def obfuscate_builtins(module, tokens, name_generator, table=None):
"""
Inserts an assignment, '<obfuscated identifier> = <builtin function>' at
the beginning of *tokens* (after the shebang and encoding if present) for
every Python built-in function that is used inside *tokens*. Also, replaces
all... | Inserts an assignment, '<obfuscated identifier> = <builtin function>' at
the beginning of *tokens* (after the shebang and encoding if present) for
every Python built-in function that is used inside *tokens*. Also, replaces
all of said builti-in functions in *tokens* with each respective obfuscated
ide... | Below is the the instruction that describes the task:
### Input:
Inserts an assignment, '<obfuscated identifier> = <builtin function>' at
the beginning of *tokens* (after the shebang and encoding if present) for
every Python built-in function that is used inside *tokens*. Also, replaces
all of said bu... |
def msetnx(self, *args, **kwargs):
"""
Sets key/values based on a mapping if none of the keys are already set.
Mapping can be supplied as a single dictionary argument or as kwargs.
Returns a boolean indicating if the operation was successful.
"""
if args:
if l... | Sets key/values based on a mapping if none of the keys are already set.
Mapping can be supplied as a single dictionary argument or as kwargs.
Returns a boolean indicating if the operation was successful. | Below is the the instruction that describes the task:
### Input:
Sets key/values based on a mapping if none of the keys are already set.
Mapping can be supplied as a single dictionary argument or as kwargs.
Returns a boolean indicating if the operation was successful.
### Response:
def msetnx(self,... |
def _get_file_from_s3(creds, metadata, saltenv, bucket, path,
cached_file_path):
'''
Checks the local cache for the file, if it's old or missing go grab the
file from S3 and update the cache
'''
# check the local cache...
if os.path.isfile(cached_file_path):
file_m... | Checks the local cache for the file, if it's old or missing go grab the
file from S3 and update the cache | Below is the the instruction that describes the task:
### Input:
Checks the local cache for the file, if it's old or missing go grab the
file from S3 and update the cache
### Response:
def _get_file_from_s3(creds, metadata, saltenv, bucket, path,
cached_file_path):
'''
Checks the ... |
def create(vm_):
'''
Create a single VM from a data dict
'''
if 'driver' not in vm_:
vm_['driver'] = vm_['provider']
private_networking = config.get_cloud_config_value(
'enable_private_network', vm_, __opts__, search_global=False, default=False,
)
startup_script = config.ge... | Create a single VM from a data dict | Below is the the instruction that describes the task:
### Input:
Create a single VM from a data dict
### Response:
def create(vm_):
'''
Create a single VM from a data dict
'''
if 'driver' not in vm_:
vm_['driver'] = vm_['provider']
private_networking = config.get_cloud_config_value(
... |
def _write_value_failed(self, dbus_error):
"""
Called when the write request has failed.
"""
error = _error_from_dbus_error(dbus_error)
self.service.device.characteristic_write_value_failed(characteristic=self, error=error) | Called when the write request has failed. | Below is the the instruction that describes the task:
### Input:
Called when the write request has failed.
### Response:
def _write_value_failed(self, dbus_error):
"""
Called when the write request has failed.
"""
error = _error_from_dbus_error(dbus_error)
self.service.devic... |
def round_robin(members, items):
"""
Default allocator with a round robin approach.
In this algorithm, each member of the group is cycled over and given an
item until there are no items left. This assumes roughly equal capacity
for each member and aims for even distribution of item counts.
"""... | Default allocator with a round robin approach.
In this algorithm, each member of the group is cycled over and given an
item until there are no items left. This assumes roughly equal capacity
for each member and aims for even distribution of item counts. | Below is the the instruction that describes the task:
### Input:
Default allocator with a round robin approach.
In this algorithm, each member of the group is cycled over and given an
item until there are no items left. This assumes roughly equal capacity
for each member and aims for even distribution... |
def makeairplantloop(data, commdct):
"""make the edges for the airloop and the plantloop"""
anode = "epnode"
endnode = "EndNode"
# in plantloop get:
# demand inlet, outlet, branchlist
# supply inlet, outlet, branchlist
plantloops = loops.plantloopfields(data, commdct)
# splitter... | make the edges for the airloop and the plantloop | Below is the the instruction that describes the task:
### Input:
make the edges for the airloop and the plantloop
### Response:
def makeairplantloop(data, commdct):
"""make the edges for the airloop and the plantloop"""
anode = "epnode"
endnode = "EndNode"
# in plantloop get:
# demand inle... |
def _convert_to_array(x, size, name):
"""Check length of array or convert scalar to array.
Check to see is `x` has the given length `size`. If this is true
then return Numpy array equivalent of `x`. If not then raise
ValueError, using `name` as an idnetification. If len(x) returns
TypeError, then a... | Check length of array or convert scalar to array.
Check to see is `x` has the given length `size`. If this is true
then return Numpy array equivalent of `x`. If not then raise
ValueError, using `name` as an idnetification. If len(x) returns
TypeError, then assume it is a scalar and create a Numpy array... | Below is the the instruction that describes the task:
### Input:
Check length of array or convert scalar to array.
Check to see is `x` has the given length `size`. If this is true
then return Numpy array equivalent of `x`. If not then raise
ValueError, using `name` as an idnetification. If len(x) retur... |
def sumApprox(self, timeout, confidence=0.95):
"""
.. note:: Experimental
Approximate operation to return the sum within a timeout
or meet the confidence.
>>> rdd = sc.parallelize(range(1000), 10)
>>> r = sum(range(1000))
>>> abs(rdd.sumApprox(1000) - r) / r < 0... | .. note:: Experimental
Approximate operation to return the sum within a timeout
or meet the confidence.
>>> rdd = sc.parallelize(range(1000), 10)
>>> r = sum(range(1000))
>>> abs(rdd.sumApprox(1000) - r) / r < 0.05
True | Below is the the instruction that describes the task:
### Input:
.. note:: Experimental
Approximate operation to return the sum within a timeout
or meet the confidence.
>>> rdd = sc.parallelize(range(1000), 10)
>>> r = sum(range(1000))
>>> abs(rdd.sumApprox(1000) - r) / r <... |
def _iter_descendants_preorder(self, is_leaf_fn=None):
""" Iterator over all descendant nodes. """
to_visit = deque()
node = self
while node is not None:
yield node
if not is_leaf_fn or not is_leaf_fn(node):
to_visit.extendleft(reversed(node.childr... | Iterator over all descendant nodes. | Below is the the instruction that describes the task:
### Input:
Iterator over all descendant nodes.
### Response:
def _iter_descendants_preorder(self, is_leaf_fn=None):
""" Iterator over all descendant nodes. """
to_visit = deque()
node = self
while node is not None:
yi... |
def print_signals_and_slots(self):
"""
List all active Slots and Signal.
Credits to: http://visitusers.org/index.php?title=PySide_Recipes#Debugging
"""
for i in xrange(self.metaObject().methodCount()):
m = self.metaObject().method(i)
if m.methodType() =... | List all active Slots and Signal.
Credits to: http://visitusers.org/index.php?title=PySide_Recipes#Debugging | Below is the the instruction that describes the task:
### Input:
List all active Slots and Signal.
Credits to: http://visitusers.org/index.php?title=PySide_Recipes#Debugging
### Response:
def print_signals_and_slots(self):
"""
List all active Slots and Signal.
Credits to: http://v... |
def find_doi(self, curr_dict):
"""
Recursively search the file for the DOI id. More taxing, but more flexible when dictionary structuring isn't absolute
:param dict curr_dict: Current dictionary being searched
:return dict bool: Recursive - Current dictionary, False flag that DOI was not... | Recursively search the file for the DOI id. More taxing, but more flexible when dictionary structuring isn't absolute
:param dict curr_dict: Current dictionary being searched
:return dict bool: Recursive - Current dictionary, False flag that DOI was not found
:return str bool: Final - DOI id, Tr... | Below is the the instruction that describes the task:
### Input:
Recursively search the file for the DOI id. More taxing, but more flexible when dictionary structuring isn't absolute
:param dict curr_dict: Current dictionary being searched
:return dict bool: Recursive - Current dictionary, False fla... |
def write(self, descrs):
"""
Convert descriptions into names
"""
# example: '(poe-[\d\.]+):float32' -> 'poe-[\d\.]+'
names = []
for descr in descrs:
mo = re.match(self.long_regex, descr)
if mo:
names.append(mo.group(mo.lastindex) + ... | Convert descriptions into names | Below is the the instruction that describes the task:
### Input:
Convert descriptions into names
### Response:
def write(self, descrs):
"""
Convert descriptions into names
"""
# example: '(poe-[\d\.]+):float32' -> 'poe-[\d\.]+'
names = []
for descr in descrs:
... |
def ip_hide_ext_community_list_holder_extcommunity_list_ext_community_expr(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip = ET.SubElement(config, "ip", xmlns="urn:brocade.com:mgmt:brocade-common-def")
hide_ext_community_list_holder = ET.SubElement(ip... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def ip_hide_ext_community_list_holder_extcommunity_list_ext_community_expr(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip = ET.SubElement(config, "ip", xm... |
def writeCommit(self, varBind, **context):
"""Commit new value of the Managed Object Instance.
Implements the second of the multi-step workflow of the SNMP SET
command processing (:RFC:`1905#section-4.2.5`).
The goal of the second phase is to actually modify the requested Managed
... | Commit new value of the Managed Object Instance.
Implements the second of the multi-step workflow of the SNMP SET
command processing (:RFC:`1905#section-4.2.5`).
The goal of the second phase is to actually modify the requested Managed
Object Instance. When multiple Managed Objects Inst... | Below is the the instruction that describes the task:
### Input:
Commit new value of the Managed Object Instance.
Implements the second of the multi-step workflow of the SNMP SET
command processing (:RFC:`1905#section-4.2.5`).
The goal of the second phase is to actually modify the requeste... |
def handleError(self, test, err, capt=None):
"""
If the database plugin is not present, we have to handle capturing
"errors" that shouldn't be reported as such in base.
"""
if not hasattr(test.test, "testcase_guid"):
if err[0] == errors.BlockedTest:
ra... | If the database plugin is not present, we have to handle capturing
"errors" that shouldn't be reported as such in base. | Below is the the instruction that describes the task:
### Input:
If the database plugin is not present, we have to handle capturing
"errors" that shouldn't be reported as such in base.
### Response:
def handleError(self, test, err, capt=None):
"""
If the database plugin is not present, we h... |
def request(self, method, url, **kwargs):
"""Override request method disabling verify on token renewal if disabled on session."""
if not url.startswith('https'):
url = '{}{}'.format(self.args.tc_api_path, url)
return super(TcExSession, self).request(method, url, **kwargs) | Override request method disabling verify on token renewal if disabled on session. | Below is the the instruction that describes the task:
### Input:
Override request method disabling verify on token renewal if disabled on session.
### Response:
def request(self, method, url, **kwargs):
"""Override request method disabling verify on token renewal if disabled on session."""
if not u... |
def build_clusters(data, sample, maxindels):
"""
Combines information from .utemp and .htemp files to create .clust files,
which contain un-aligned clusters. Hits to seeds are only kept in the
cluster if the number of internal indels is less than 'maxindels'.
By default, we set maxindels=6 for this ... | Combines information from .utemp and .htemp files to create .clust files,
which contain un-aligned clusters. Hits to seeds are only kept in the
cluster if the number of internal indels is less than 'maxindels'.
By default, we set maxindels=6 for this step (within-sample clustering). | Below is the the instruction that describes the task:
### Input:
Combines information from .utemp and .htemp files to create .clust files,
which contain un-aligned clusters. Hits to seeds are only kept in the
cluster if the number of internal indels is less than 'maxindels'.
By default, we set maxindels... |
def getargspecs(func):
"""Bridges inspect.getargspec and inspect.getfullargspec.
Automatically selects the proper one depending of current Python version.
Automatically bypasses wrappers from typechecked- and override-decorators.
"""
if func is None:
raise TypeError('None is not a Python fun... | Bridges inspect.getargspec and inspect.getfullargspec.
Automatically selects the proper one depending of current Python version.
Automatically bypasses wrappers from typechecked- and override-decorators. | Below is the the instruction that describes the task:
### Input:
Bridges inspect.getargspec and inspect.getfullargspec.
Automatically selects the proper one depending of current Python version.
Automatically bypasses wrappers from typechecked- and override-decorators.
### Response:
def getargspecs(func):
... |
def wait(self, limit=None):
"""Go into consume mode.
Mostly for testing purposes and simple programs, you probably
want :meth:`iterconsume` or :meth:`iterqueue` instead.
This runs an infinite loop, processing all incoming messages
using :meth:`receive` to apply the message to a... | Go into consume mode.
Mostly for testing purposes and simple programs, you probably
want :meth:`iterconsume` or :meth:`iterqueue` instead.
This runs an infinite loop, processing all incoming messages
using :meth:`receive` to apply the message to all registered
callbacks. | Below is the the instruction that describes the task:
### Input:
Go into consume mode.
Mostly for testing purposes and simple programs, you probably
want :meth:`iterconsume` or :meth:`iterqueue` instead.
This runs an infinite loop, processing all incoming messages
using :meth:`rece... |
def is_http_running_on(port):
""" Check if an http server runs on a given port.
Args:
The port to check.
Returns:
True if it is used by an http server. False otherwise.
"""
try:
conn = httplib.HTTPConnection('127.0.0.1:' + str(port))
conn.connect()
conn.close()
return True
except Ex... | Check if an http server runs on a given port.
Args:
The port to check.
Returns:
True if it is used by an http server. False otherwise. | Below is the the instruction that describes the task:
### Input:
Check if an http server runs on a given port.
Args:
The port to check.
Returns:
True if it is used by an http server. False otherwise.
### Response:
def is_http_running_on(port):
""" Check if an http server runs on a given port.
Arg... |
def acquire(self, replace_stale=False, force=False):
"""
Acquire the lock.
A lock can be claimed if any of these conditions are true:
1. The lock is unheld by anyone.
2. The lock is held but the 'force' argument is set.
3. The lock is held by the current proc... | Acquire the lock.
A lock can be claimed if any of these conditions are true:
1. The lock is unheld by anyone.
2. The lock is held but the 'force' argument is set.
3. The lock is held by the current process.
Arguments:
replace_stale (bool, optional) If tr... | Below is the the instruction that describes the task:
### Input:
Acquire the lock.
A lock can be claimed if any of these conditions are true:
1. The lock is unheld by anyone.
2. The lock is held but the 'force' argument is set.
3. The lock is held by the current process.... |
def on_finish(self):
"""Invoked once the request has been finished. Increments a counter
created in the format:
.. code::
<PREFIX>.counters.<host>.package[.module].Class.METHOD.STATUS
sprockets.counters.localhost.tornado.web.RequestHandler.GET.200
Adds a value ... | Invoked once the request has been finished. Increments a counter
created in the format:
.. code::
<PREFIX>.counters.<host>.package[.module].Class.METHOD.STATUS
sprockets.counters.localhost.tornado.web.RequestHandler.GET.200
Adds a value to a timer in the following form... | Below is the the instruction that describes the task:
### Input:
Invoked once the request has been finished. Increments a counter
created in the format:
.. code::
<PREFIX>.counters.<host>.package[.module].Class.METHOD.STATUS
sprockets.counters.localhost.tornado.web.RequestH... |
def is_on(self):
"""
Get sensor state.
Assume offline or open (worst case).
"""
return self.status not in (CONST.STATUS_OFF, CONST.STATUS_OFFLINE,
CONST.STATUS_CLOSED, CONST.STATUS_OPEN) | Get sensor state.
Assume offline or open (worst case). | Below is the the instruction that describes the task:
### Input:
Get sensor state.
Assume offline or open (worst case).
### Response:
def is_on(self):
"""
Get sensor state.
Assume offline or open (worst case).
"""
return self.status not in (CONST.STATUS_OFF, CONST.... |
def _getOLRootNumber(self):
"""_getOLRootNumber(self) -> PyObject *"""
if self.isClosed or self.isEncrypted:
raise ValueError("operation illegal for closed / encrypted doc")
return _fitz.Document__getOLRootNumber(self) | _getOLRootNumber(self) -> PyObject * | Below is the the instruction that describes the task:
### Input:
_getOLRootNumber(self) -> PyObject *
### Response:
def _getOLRootNumber(self):
"""_getOLRootNumber(self) -> PyObject *"""
if self.isClosed or self.isEncrypted:
raise ValueError("operation illegal for closed / encrypted doc... |
def install_site_py(self):
"""Make sure there's a site.py in the target dir, if needed"""
if self.sitepy_installed:
return # already did it, or don't need to
sitepy = os.path.join(self.install_dir, "site.py")
source = resource_string("setuptools", "site-patch.py")
... | Make sure there's a site.py in the target dir, if needed | Below is the the instruction that describes the task:
### Input:
Make sure there's a site.py in the target dir, if needed
### Response:
def install_site_py(self):
"""Make sure there's a site.py in the target dir, if needed"""
if self.sitepy_installed:
return # already did it, or don't... |
def items(self, section, raw=False, vars=None):
"""Return a list of tuples with (name, value) for each option
in the section.
All % interpolations are expanded in the return values, based on the
defaults passed into the constructor, unless the optional argument
`raw' is true. A... | Return a list of tuples with (name, value) for each option
in the section.
All % interpolations are expanded in the return values, based on the
defaults passed into the constructor, unless the optional argument
`raw' is true. Additional substitutions may be provided using the
`... | Below is the the instruction that describes the task:
### Input:
Return a list of tuples with (name, value) for each option
in the section.
All % interpolations are expanded in the return values, based on the
defaults passed into the constructor, unless the optional argument
`raw' i... |
def save_images(images, size, image_path='_temp.png'):
"""Save multiple images into one single image.
Parameters
-----------
images : numpy array
(batch, w, h, c)
size : list of 2 ints
row and column number.
number of images should be equal or less than size[0] * size[1]
... | Save multiple images into one single image.
Parameters
-----------
images : numpy array
(batch, w, h, c)
size : list of 2 ints
row and column number.
number of images should be equal or less than size[0] * size[1]
image_path : str
save path
Examples
--------... | Below is the the instruction that describes the task:
### Input:
Save multiple images into one single image.
Parameters
-----------
images : numpy array
(batch, w, h, c)
size : list of 2 ints
row and column number.
number of images should be equal or less than size[0] * size... |
def create_flat_start_model(feature_filename,
state_stay_probabilities,
symbol_list,
output_model_directory,
output_prototype_filename,
htk_trace):
"""
Creates a flat start... | Creates a flat start model by using HCompV to compute the global mean and variance.
Then uses these global mean and variance to create an N-state model for each symbol in the given list.
:param feature_filename: The filename containing the audio and feature file pairs
:param output_model_directory: The dir... | Below is the the instruction that describes the task:
### Input:
Creates a flat start model by using HCompV to compute the global mean and variance.
Then uses these global mean and variance to create an N-state model for each symbol in the given list.
:param feature_filename: The filename containing the au... |
def get(self):
"""
This method computes and returns a hitting set. The hitting set is
obtained using the underlying oracle operating the MaxSAT problem
formulation. The computed solution is mapped back to objects of the
problem domain.
:rtype: list(ob... | This method computes and returns a hitting set. The hitting set is
obtained using the underlying oracle operating the MaxSAT problem
formulation. The computed solution is mapped back to objects of the
problem domain.
:rtype: list(obj) | Below is the the instruction that describes the task:
### Input:
This method computes and returns a hitting set. The hitting set is
obtained using the underlying oracle operating the MaxSAT problem
formulation. The computed solution is mapped back to objects of the
problem domain... |
def drop(self, repo, args=[]):
"""
Cleanup the repo
"""
# Clean up the rootdir
rootdir = repo.rootdir
if os.path.exists(rootdir):
print("Cleaning repo directory: {}".format(rootdir))
shutil.rmtree(rootdir)
# Cleanup the local version of t... | Cleanup the repo | Below is the the instruction that describes the task:
### Input:
Cleanup the repo
### Response:
def drop(self, repo, args=[]):
"""
Cleanup the repo
"""
# Clean up the rootdir
rootdir = repo.rootdir
if os.path.exists(rootdir):
print("Cleaning repo directo... |
def q_diffuser(sed_inputs=sed_dict):
"""Return the flow through each diffuser.
Parameters
----------
sed_inputs : dict
A dictionary of all of the constant inputs needed for sedimentation tank
calculations can be found in sed.yaml
Returns
-------
float
Flow through eac... | Return the flow through each diffuser.
Parameters
----------
sed_inputs : dict
A dictionary of all of the constant inputs needed for sedimentation tank
calculations can be found in sed.yaml
Returns
-------
float
Flow through each diffuser in the sedimentation tank
Exa... | Below is the the instruction that describes the task:
### Input:
Return the flow through each diffuser.
Parameters
----------
sed_inputs : dict
A dictionary of all of the constant inputs needed for sedimentation tank
calculations can be found in sed.yaml
Returns
-------
float... |
def print_node(self, name): # noqa: D302
r"""
Print node information (parent, children and data).
:param name: Node name
:type name: :ref:`NodeName`
:raises:
* RuntimeError (Argument \`name\` is not valid)
* RuntimeError (Node *[name]* not in tree)
... | r"""
Print node information (parent, children and data).
:param name: Node name
:type name: :ref:`NodeName`
:raises:
* RuntimeError (Argument \`name\` is not valid)
* RuntimeError (Node *[name]* not in tree)
Using the same example tree created in
:p... | Below is the the instruction that describes the task:
### Input:
r"""
Print node information (parent, children and data).
:param name: Node name
:type name: :ref:`NodeName`
:raises:
* RuntimeError (Argument \`name\` is not valid)
* RuntimeError (Node *[name]* no... |
def _set_symlink_ownership(path, user, group, win_owner):
'''
Set the ownership of a symlink and return a boolean indicating
success/failure
'''
if salt.utils.platform.is_windows():
try:
salt.utils.win_dacl.set_owner(path, win_owner)
except CommandExecutionError:
... | Set the ownership of a symlink and return a boolean indicating
success/failure | Below is the the instruction that describes the task:
### Input:
Set the ownership of a symlink and return a boolean indicating
success/failure
### Response:
def _set_symlink_ownership(path, user, group, win_owner):
'''
Set the ownership of a symlink and return a boolean indicating
success/failure
... |
def getSizes(self):
"""
Get all the available sizes of the current image, and all available
data about them.
Returns: A list of dicts with the size data.
"""
method = 'flickr.photos.getSizes'
data = _doget(method, photo_id=self.id)
ret = []
# The g... | Get all the available sizes of the current image, and all available
data about them.
Returns: A list of dicts with the size data. | Below is the the instruction that describes the task:
### Input:
Get all the available sizes of the current image, and all available
data about them.
Returns: A list of dicts with the size data.
### Response:
def getSizes(self):
"""
Get all the available sizes of the current image, ... |
def lowstrip(term):
"""Convert to lowercase and strip spaces"""
term = re.sub('\s+', ' ', term)
term = term.lower()
return term | Convert to lowercase and strip spaces | Below is the the instruction that describes the task:
### Input:
Convert to lowercase and strip spaces
### Response:
def lowstrip(term):
"""Convert to lowercase and strip spaces"""
term = re.sub('\s+', ' ', term)
term = term.lower()
return term |
def kpath_from_seekpath(cls, seekpath, point_coords):
r"""Convert seekpath-formatted kpoints path to sumo-preferred format.
If 'GAMMA' is used as a label this will be replaced by '\Gamma'.
Args:
seekpath (list): A :obj:`list` of 2-tuples containing the labels at
eac... | r"""Convert seekpath-formatted kpoints path to sumo-preferred format.
If 'GAMMA' is used as a label this will be replaced by '\Gamma'.
Args:
seekpath (list): A :obj:`list` of 2-tuples containing the labels at
each side of each segment of the k-point path::
... | Below is the the instruction that describes the task:
### Input:
r"""Convert seekpath-formatted kpoints path to sumo-preferred format.
If 'GAMMA' is used as a label this will be replaced by '\Gamma'.
Args:
seekpath (list): A :obj:`list` of 2-tuples containing the labels at
... |
def bgmagenta(cls, string, auto=False):
"""Color-code entire string.
:param str string: String to colorize.
:param bool auto: Enable auto-color (dark/light terminal).
:return: Class instance for colorized string.
:rtype: Color
"""
return cls.colorize('bgmagenta'... | Color-code entire string.
:param str string: String to colorize.
:param bool auto: Enable auto-color (dark/light terminal).
:return: Class instance for colorized string.
:rtype: Color | Below is the the instruction that describes the task:
### Input:
Color-code entire string.
:param str string: String to colorize.
:param bool auto: Enable auto-color (dark/light terminal).
:return: Class instance for colorized string.
:rtype: Color
### Response:
def bgmagenta(cls,... |
def validate_params(request):
"""Validate request params."""
if 'params' in request:
correct_params = isinstance(request['params'], (list, dict))
error = 'Incorrect parameter values'
assert correct_params, error | Validate request params. | Below is the the instruction that describes the task:
### Input:
Validate request params.
### Response:
def validate_params(request):
"""Validate request params."""
if 'params' in request:
correct_params = isinstance(request['params'], (list, dict))
error = 'Incorrect parameter values'
... |
def create_bootstrap_dataframe(orig_df,
obs_id_col,
resampled_obs_ids_1d,
groupby_dict,
boot_id_col="bootstrap_id"):
"""
Will create the altered dataframe of data needed to estimate a choi... | Will create the altered dataframe of data needed to estimate a choice model
with the particular observations that belong to the current bootstrap
sample.
Parameters
----------
orig_df : pandas DataFrame.
Should be long-format dataframe containing the data used to estimate
the desire... | Below is the the instruction that describes the task:
### Input:
Will create the altered dataframe of data needed to estimate a choice model
with the particular observations that belong to the current bootstrap
sample.
Parameters
----------
orig_df : pandas DataFrame.
Should be long-for... |
def _createSlink(self, slinks):
"""
Create GSSHAPY SuperLink, Pipe, and SuperNode Objects Method
"""
for slink in slinks:
# Create GSSHAPY SuperLink object
superLink = SuperLink(slinkNumber=slink['slinkNumber'],
numPipes=slink['n... | Create GSSHAPY SuperLink, Pipe, and SuperNode Objects Method | Below is the the instruction that describes the task:
### Input:
Create GSSHAPY SuperLink, Pipe, and SuperNode Objects Method
### Response:
def _createSlink(self, slinks):
"""
Create GSSHAPY SuperLink, Pipe, and SuperNode Objects Method
"""
for slink in slinks:
# Create... |
def perform(self):
"""
Performs a straightforward TCP request and response.
Sends the TCP `query` to the proper host and port, and loops over the
socket, gathering response chunks until a full line is acquired.
If the response line matches the expected value, the check passes. ... | Performs a straightforward TCP request and response.
Sends the TCP `query` to the proper host and port, and loops over the
socket, gathering response chunks until a full line is acquired.
If the response line matches the expected value, the check passes. If
not, the check fails. The c... | Below is the the instruction that describes the task:
### Input:
Performs a straightforward TCP request and response.
Sends the TCP `query` to the proper host and port, and loops over the
socket, gathering response chunks until a full line is acquired.
If the response line matches the expe... |
def unregister(self, device, callback):
"""Remove a registered a callback.
device: device that has the subscription
callback: callback used in original registration
"""
if not device:
logger.error("Received an invalid device: %r", device)
return
... | Remove a registered a callback.
device: device that has the subscription
callback: callback used in original registration | Below is the the instruction that describes the task:
### Input:
Remove a registered a callback.
device: device that has the subscription
callback: callback used in original registration
### Response:
def unregister(self, device, callback):
"""Remove a registered a callback.
devic... |
def setup_logfile_logger(log_path, log_level='error', log_format=None,
date_format=None, max_bytes=0, backup_count=0):
'''
Setup the logfile logger
Since version 0.10.6 we support logging to syslog, some examples:
tcp://localhost:514/LOG_USER
tcp://localhost/LOG_DA... | Setup the logfile logger
Since version 0.10.6 we support logging to syslog, some examples:
tcp://localhost:514/LOG_USER
tcp://localhost/LOG_DAEMON
udp://localhost:5145/LOG_KERN
udp://localhost
file:///dev/log
file:///dev/log/LOG_SYSLOG
file:///dev/log/LOG_DA... | Below is the the instruction that describes the task:
### Input:
Setup the logfile logger
Since version 0.10.6 we support logging to syslog, some examples:
tcp://localhost:514/LOG_USER
tcp://localhost/LOG_DAEMON
udp://localhost:5145/LOG_KERN
udp://localhost
file:///dev/... |
def col(self):
"""Gives direct access to the columns only (useful for tab completion).
Convenient when working with ipython in combination with small DataFrames, since this gives tab-completion.
Columns can be accesed by there names, which are attributes. The attribues are currently expression... | Gives direct access to the columns only (useful for tab completion).
Convenient when working with ipython in combination with small DataFrames, since this gives tab-completion.
Columns can be accesed by there names, which are attributes. The attribues are currently expressions, so you can
do c... | Below is the the instruction that describes the task:
### Input:
Gives direct access to the columns only (useful for tab completion).
Convenient when working with ipython in combination with small DataFrames, since this gives tab-completion.
Columns can be accesed by there names, which are attribu... |
def zero(duration: int, name: str = None) -> SamplePulse:
"""Generates zero-sampled `SamplePulse`.
Args:
duration: Duration of pulse. Must be greater than zero.
name: Name of pulse.
"""
return _sampled_zero_pulse(duration, name=name) | Generates zero-sampled `SamplePulse`.
Args:
duration: Duration of pulse. Must be greater than zero.
name: Name of pulse. | Below is the the instruction that describes the task:
### Input:
Generates zero-sampled `SamplePulse`.
Args:
duration: Duration of pulse. Must be greater than zero.
name: Name of pulse.
### Response:
def zero(duration: int, name: str = None) -> SamplePulse:
"""Generates zero-sampled `Sampl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.