code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def getMetricDetails(self, metricLabel):
"""
Gets detailed info about a given metric, in addition to its value. This
may including any statistics or auxilary data that are computed for a given
metric.
:param metricLabel: (string) label of the given metric (see
:class:`~nupic.frameworks... | Gets detailed info about a given metric, in addition to its value. This
may including any statistics or auxilary data that are computed for a given
metric.
:param metricLabel: (string) label of the given metric (see
:class:`~nupic.frameworks.opf.metrics.MetricSpec`)
:returns: (dict) of met... | Below is the the instruction that describes the task:
### Input:
Gets detailed info about a given metric, in addition to its value. This
may including any statistics or auxilary data that are computed for a given
metric.
:param metricLabel: (string) label of the given metric (see
:class:`~n... |
def delete_repository_tag(self, project_id, tag_name):
"""
Deletes a tag of a repository with given name.
:param project_id: The ID of a project
:param tag_name: The name of a tag
:return: Dictionary containing delete tag
:raise: HttpError: If invalid response returned
... | Deletes a tag of a repository with given name.
:param project_id: The ID of a project
:param tag_name: The name of a tag
:return: Dictionary containing delete tag
:raise: HttpError: If invalid response returned | Below is the the instruction that describes the task:
### Input:
Deletes a tag of a repository with given name.
:param project_id: The ID of a project
:param tag_name: The name of a tag
:return: Dictionary containing delete tag
:raise: HttpError: If invalid response returned
### Res... |
async def get_game_high_scores(self, user_id: base.Integer,
chat_id: typing.Union[base.Integer, None] = None,
message_id: typing.Union[base.Integer, None] = None,
inline_message_id: typing.Union[base.String,
... | Use this method to get data for high score tables.
This method will currently return scores for the target user, plus two of his closest neighbors on each side.
Will also return the top three users if the user and his neighbors are not among them.
Please note that this behavior is subject to ch... | Below is the the instruction that describes the task:
### Input:
Use this method to get data for high score tables.
This method will currently return scores for the target user, plus two of his closest neighbors on each side.
Will also return the top three users if the user and his neighbors are no... |
def defUtilityFuncs(self):
'''
Defines CRRA utility function for this period (and its derivatives,
and their inverses), saving them as attributes of self for other methods
to use. Extends version from ConsIndShock models by also defining inverse
marginal utility function over me... | Defines CRRA utility function for this period (and its derivatives,
and their inverses), saving them as attributes of self for other methods
to use. Extends version from ConsIndShock models by also defining inverse
marginal utility function over medical care.
Parameters
-------... | Below is the the instruction that describes the task:
### Input:
Defines CRRA utility function for this period (and its derivatives,
and their inverses), saving them as attributes of self for other methods
to use. Extends version from ConsIndShock models by also defining inverse
marginal ut... |
def login(self, username, password, disableautosave=True, print_response=True):
"""
:param username:
:param password:
:param disableautosave: boolean
:param print_response: print log if required
:return: status code, response data
"""
if type(username) != ... | :param username:
:param password:
:param disableautosave: boolean
:param print_response: print log if required
:return: status code, response data | Below is the the instruction that describes the task:
### Input:
:param username:
:param password:
:param disableautosave: boolean
:param print_response: print log if required
:return: status code, response data
### Response:
def login(self, username, password, disableautosave=True,... |
def gets(self, key, default=None, cas_default=None):
"""
The memcached "gets" command for one key, as a convenience.
Args:
key: str, see class docs for details.
default: value that will be returned if the key was not found.
cas_default: same behaviour as default ar... | The memcached "gets" command for one key, as a convenience.
Args:
key: str, see class docs for details.
default: value that will be returned if the key was not found.
cas_default: same behaviour as default argument.
Returns:
A tuple of (value, cas)
or ... | Below is the the instruction that describes the task:
### Input:
The memcached "gets" command for one key, as a convenience.
Args:
key: str, see class docs for details.
default: value that will be returned if the key was not found.
cas_default: same behaviour as default argume... |
def get_file_url(path, config):
""" Update this function to help build the link to your file
"""
file_url_regex = re.compile(config['file_url_regex'])
new_path = re.sub(file_url_regex, config['file_url_base'], path)
return new_path | Update this function to help build the link to your file | Below is the the instruction that describes the task:
### Input:
Update this function to help build the link to your file
### Response:
def get_file_url(path, config):
""" Update this function to help build the link to your file
"""
file_url_regex = re.compile(config['file_url_regex'])
new_path = r... |
def delete(self, *args, **kwargs):
"""
Deletes the actual file from storage after the object is deleted.
Calls super to actually delete the object.
"""
file_obj = self.file
super(AssetBase, self).delete(*args, **kwargs)
self.delete_real_file(file_obj) | Deletes the actual file from storage after the object is deleted.
Calls super to actually delete the object. | Below is the the instruction that describes the task:
### Input:
Deletes the actual file from storage after the object is deleted.
Calls super to actually delete the object.
### Response:
def delete(self, *args, **kwargs):
"""
Deletes the actual file from storage after the object is delete... |
def delete(self, roomId):
"""Delete a room.
Args:
roomId(basestring): The ID of the room to be deleted.
Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams cloud returns an error.
"""
check_type(roomId, base... | Delete a room.
Args:
roomId(basestring): The ID of the room to be deleted.
Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams cloud returns an error. | Below is the the instruction that describes the task:
### Input:
Delete a room.
Args:
roomId(basestring): The ID of the room to be deleted.
Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams cloud returns an error.
### Response... |
def delays(self, delays=[]):
"""
Gets / Sets the delays.
"""
if delays:
return self._session.put(
self.__v1() + "/delays", data=json.dumps(delays)).json()
else:
return self._session.get(self.__v1() + "/delays").json() | Gets / Sets the delays. | Below is the the instruction that describes the task:
### Input:
Gets / Sets the delays.
### Response:
def delays(self, delays=[]):
"""
Gets / Sets the delays.
"""
if delays:
return self._session.put(
self.__v1() + "/delays", data=json.dumps(delays)).jso... |
def execute(command, working_directory=config.BASE_DIR, stderr=sp.STDOUT):
"""
Executes shell command in a given working_directory.
Command is a string to pass to the shell.
Output is ignored.
"""
LOG.info("Executing in %s ...", working_directory)
LOG.info(command)
sp.check_call(command,... | Executes shell command in a given working_directory.
Command is a string to pass to the shell.
Output is ignored. | Below is the the instruction that describes the task:
### Input:
Executes shell command in a given working_directory.
Command is a string to pass to the shell.
Output is ignored.
### Response:
def execute(command, working_directory=config.BASE_DIR, stderr=sp.STDOUT):
"""
Executes shell command in a... |
def readComplexCode(self, hskip, alphabet):
"""Read complex code"""
stream = self.stream
#read the lengths for the length code
lengths = [1,2,3,4,0,5,17,6,16,7,8,9,10,11,12,13,14,15][hskip:]
codeLengths = {}
total = 0
lol = LengthOfLengthAlphabet('##'+alphabet.nam... | Read complex code | Below is the the instruction that describes the task:
### Input:
Read complex code
### Response:
def readComplexCode(self, hskip, alphabet):
"""Read complex code"""
stream = self.stream
#read the lengths for the length code
lengths = [1,2,3,4,0,5,17,6,16,7,8,9,10,11,12,13,14,15][hsk... |
def update_path_labels(self):
"""Update labels showing config paths
"""
self.view['core_label'].set_text("Core Config Path: " + str(self.core_config_model.config.config_file_path))
self.view['gui_label'].set_text("GUI Config Path: " + str(self.gui_config_model.config.config_file_path)) | Update labels showing config paths | Below is the the instruction that describes the task:
### Input:
Update labels showing config paths
### Response:
def update_path_labels(self):
"""Update labels showing config paths
"""
self.view['core_label'].set_text("Core Config Path: " + str(self.core_config_model.config.config_file_pat... |
def get_apphook_configs(obj):
"""
Get apphook configs for an object obj
:param obj: any model instance
:return: list of apphook configs for given obj
"""
keys = get_apphook_field_names(obj)
return [getattr(obj, key) for key in keys] if keys else [] | Get apphook configs for an object obj
:param obj: any model instance
:return: list of apphook configs for given obj | Below is the the instruction that describes the task:
### Input:
Get apphook configs for an object obj
:param obj: any model instance
:return: list of apphook configs for given obj
### Response:
def get_apphook_configs(obj):
"""
Get apphook configs for an object obj
:param obj: any model inst... |
def common_directory(paths):
"""Find the deepest common directory of a list of paths.
:return: if no paths are provided, None is returned;
if there is no common directory, '' is returned;
otherwise the common directory with a trailing / is returned.
"""
import posixpath
def get_dir_with... | Find the deepest common directory of a list of paths.
:return: if no paths are provided, None is returned;
if there is no common directory, '' is returned;
otherwise the common directory with a trailing / is returned. | Below is the the instruction that describes the task:
### Input:
Find the deepest common directory of a list of paths.
:return: if no paths are provided, None is returned;
if there is no common directory, '' is returned;
otherwise the common directory with a trailing / is returned.
### Response:
d... |
def summarizeReads(file_handle, file_type):
"""
open a fasta or fastq file, prints number of of reads,
average length of read, total number of bases, longest,
shortest and median read, total number and average of
individual base (A, T, G, C, N).
"""
base_counts = defaultdict(int)
read_nu... | open a fasta or fastq file, prints number of of reads,
average length of read, total number of bases, longest,
shortest and median read, total number and average of
individual base (A, T, G, C, N). | Below is the the instruction that describes the task:
### Input:
open a fasta or fastq file, prints number of of reads,
average length of read, total number of bases, longest,
shortest and median read, total number and average of
individual base (A, T, G, C, N).
### Response:
def summarizeReads(file_ha... |
def extend(self, base, key, value=None):
"""
Adds a new definition to this enumerated type, extending the given
base type. This will create a new key for the type and register
it as a new viable option from the system, however, it will also
register its base information so you c... | Adds a new definition to this enumerated type, extending the given
base type. This will create a new key for the type and register
it as a new viable option from the system, however, it will also
register its base information so you can use enum.base to retrieve
the root type.
... | Below is the the instruction that describes the task:
### Input:
Adds a new definition to this enumerated type, extending the given
base type. This will create a new key for the type and register
it as a new viable option from the system, however, it will also
register its base information ... |
def create_requests_session(
retries=None,
backoff_factor=None,
status_forcelist=None,
pools_size=4,
maxsize=4,
ssl_verify=None,
ssl_cert=None,
proxy=None,
session=None,
):
"""Create a requests session that retries some errors."""
# pylint: disable=too-many-branches
confi... | Create a requests session that retries some errors. | Below is the the instruction that describes the task:
### Input:
Create a requests session that retries some errors.
### Response:
def create_requests_session(
retries=None,
backoff_factor=None,
status_forcelist=None,
pools_size=4,
maxsize=4,
ssl_verify=None,
ssl_cert=None,
proxy=No... |
def parse(self, **kwargs):
"""Parse the contents of the output files retrieved in the `FolderData`."""
try:
output_folder = self.retrieved
except exceptions.NotExistent:
return self.exit_codes.ERROR_NO_RETRIEVED_FOLDER
filename_stdout = self.node.get_attribute('o... | Parse the contents of the output files retrieved in the `FolderData`. | Below is the the instruction that describes the task:
### Input:
Parse the contents of the output files retrieved in the `FolderData`.
### Response:
def parse(self, **kwargs):
"""Parse the contents of the output files retrieved in the `FolderData`."""
try:
output_folder = self.retrieved... |
def save_message_from_pat_portal(self, patient_id,
p_vendor_name,
p_message_id,
p_practice_id,
message,
sent_date,
... | invokes TouchWorksMagicConstants.ACTION_GET_ENCOUNTER_LIST_FOR_PATIENT action
:param
:param message
:param sent_date
:param transaction_type - type To register a patient with the portal,
this should be 'Register Patient Request.'
Valid types are stored in iH... | Below is the the instruction that describes the task:
### Input:
invokes TouchWorksMagicConstants.ACTION_GET_ENCOUNTER_LIST_FOR_PATIENT action
:param
:param message
:param sent_date
:param transaction_type - type To register a patient with the portal,
this should be 'Re... |
def get_valid_build_systems(working_dir, package=None):
"""Returns the build system classes that could build the source in given dir.
Args:
working_dir (str): Dir containing the package definition and potentially
build files.
package (`Package`): Package to be built. This may or may... | Returns the build system classes that could build the source in given dir.
Args:
working_dir (str): Dir containing the package definition and potentially
build files.
package (`Package`): Package to be built. This may or may not be needed
to determine the build system. For e... | Below is the the instruction that describes the task:
### Input:
Returns the build system classes that could build the source in given dir.
Args:
working_dir (str): Dir containing the package definition and potentially
build files.
package (`Package`): Package to be built. This may ... |
def __discover_node(self, node, depth):
'''
Given a node, recursively enumerate its adjacencies
until we reach the specified depth (>0).
Args:
node: natlas_node object to enumerate.
depth: The depth left that we can go further away from the root.
'''
... | Given a node, recursively enumerate its adjacencies
until we reach the specified depth (>0).
Args:
node: natlas_node object to enumerate.
depth: The depth left that we can go further away from the root. | Below is the the instruction that describes the task:
### Input:
Given a node, recursively enumerate its adjacencies
until we reach the specified depth (>0).
Args:
node: natlas_node object to enumerate.
depth: The depth left that we can go further away from the root.
### ... |
def resync(
ctx,
opts,
owner_repo_package,
skip_errors,
wait_interval,
no_wait_for_sync,
sync_attempts,
):
"""
Resynchronise a package in a repository.
This requires appropriate permissions for package.
- OWNER/REPO/PACKAGE: Specify the OWNER namespace (i.e. user or org), t... | Resynchronise a package in a repository.
This requires appropriate permissions for package.
- OWNER/REPO/PACKAGE: Specify the OWNER namespace (i.e. user or org), the
REPO name where the package is stored, and the PACKAGE name (slug) of the
package itself. All separated by a slash.
Example: 'you... | Below is the the instruction that describes the task:
### Input:
Resynchronise a package in a repository.
This requires appropriate permissions for package.
- OWNER/REPO/PACKAGE: Specify the OWNER namespace (i.e. user or org), the
REPO name where the package is stored, and the PACKAGE name (slug) of t... |
def add_batch_parser(subparsers, parent_parser):
"""Adds arguments parsers for the batch list, batch show and batch status
commands
Args:
subparsers: Add parsers to this subparser object
parent_parser: The parent argparse.ArgumentParser object
"""
parser = subparsers.add... | Adds arguments parsers for the batch list, batch show and batch status
commands
Args:
subparsers: Add parsers to this subparser object
parent_parser: The parent argparse.ArgumentParser object | Below is the the instruction that describes the task:
### Input:
Adds arguments parsers for the batch list, batch show and batch status
commands
Args:
subparsers: Add parsers to this subparser object
parent_parser: The parent argparse.ArgumentParser object
### Response:
def add... |
def encrypt(**kwargs):
"""Encrypts and serializes provided plaintext.
.. note::
When using this function, the entire ciphertext message is encrypted into memory before returning
any data. If streaming is desired, see :class:`aws_encryption_sdk.stream`.
.. code:: python
>>> import... | Encrypts and serializes provided plaintext.
.. note::
When using this function, the entire ciphertext message is encrypted into memory before returning
any data. If streaming is desired, see :class:`aws_encryption_sdk.stream`.
.. code:: python
>>> import aws_encryption_sdk
>>... | Below is the the instruction that describes the task:
### Input:
Encrypts and serializes provided plaintext.
.. note::
When using this function, the entire ciphertext message is encrypted into memory before returning
any data. If streaming is desired, see :class:`aws_encryption_sdk.stream`.
... |
def get_action_descriptions(self, action_name=None):
"""
Get the thing's actions as an array.
action_name -- Optional action name to get descriptions for
Returns the action descriptions.
"""
descriptions = []
if action_name is None:
for name in self... | Get the thing's actions as an array.
action_name -- Optional action name to get descriptions for
Returns the action descriptions. | Below is the the instruction that describes the task:
### Input:
Get the thing's actions as an array.
action_name -- Optional action name to get descriptions for
Returns the action descriptions.
### Response:
def get_action_descriptions(self, action_name=None):
"""
Get the thing's... |
def s3_cache_readonly(self):
"""
Whether the Amazon S3 bucket is considered read only.
If this is :data:`True` then the Amazon S3 bucket will only be used for
:class:`~pip_accel.caches.s3.S3CacheBackend.get()` operations (all
:class:`~pip_accel.caches.s3.S3CacheBackend.put()` op... | Whether the Amazon S3 bucket is considered read only.
If this is :data:`True` then the Amazon S3 bucket will only be used for
:class:`~pip_accel.caches.s3.S3CacheBackend.get()` operations (all
:class:`~pip_accel.caches.s3.S3CacheBackend.put()` operations will
be disabled).
- En... | Below is the the instruction that describes the task:
### Input:
Whether the Amazon S3 bucket is considered read only.
If this is :data:`True` then the Amazon S3 bucket will only be used for
:class:`~pip_accel.caches.s3.S3CacheBackend.get()` operations (all
:class:`~pip_accel.caches.s3.S3Ca... |
def open_unknown(self, fullurl, data=None):
"""Overridable interface to open unknown URL type."""
type, url = splittype(fullurl)
raise IOError('url error', 'unknown url type', type) | Overridable interface to open unknown URL type. | Below is the the instruction that describes the task:
### Input:
Overridable interface to open unknown URL type.
### Response:
def open_unknown(self, fullurl, data=None):
"""Overridable interface to open unknown URL type."""
type, url = splittype(fullurl)
raise IOError('url error', 'unknown... |
def update_course_runs(self, course_runs, enterprise_customer, enterprise_context):
"""
Update Marketing urls in course metadata and return updated course.
Arguments:
course_runs (list): List of course runs.
enterprise_customer (EnterpriseCustomer): enterprise customer i... | Update Marketing urls in course metadata and return updated course.
Arguments:
course_runs (list): List of course runs.
enterprise_customer (EnterpriseCustomer): enterprise customer instance.
enterprise_context (dict): The context to inject into URLs.
Returns:
... | Below is the the instruction that describes the task:
### Input:
Update Marketing urls in course metadata and return updated course.
Arguments:
course_runs (list): List of course runs.
enterprise_customer (EnterpriseCustomer): enterprise customer instance.
enterprise_con... |
def set_input(self, variable_name, period, value):
"""
Set a variable's value for a given period
:param variable: the variable to be set
:param value: the input value for the variable
:param period: the period for which the value is setted
Example:
... | Set a variable's value for a given period
:param variable: the variable to be set
:param value: the input value for the variable
:param period: the period for which the value is setted
Example:
>>> from openfisca_country_template import CountryTaxBenefitSyst... | Below is the the instruction that describes the task:
### Input:
Set a variable's value for a given period
:param variable: the variable to be set
:param value: the input value for the variable
:param period: the period for which the value is setted
Example:
... |
def recursive_dirname(f):
"""Given a relative path like 'a/b/c/d', yield all ascending path components like:
'a/b/c/d'
'a/b/c'
'a/b'
'a'
''
"""
prev = None
while f != prev:
yield f
prev = f
f = os.path.dirname(f)
yield '' | Given a relative path like 'a/b/c/d', yield all ascending path components like:
'a/b/c/d'
'a/b/c'
'a/b'
'a'
'' | Below is the the instruction that describes the task:
### Input:
Given a relative path like 'a/b/c/d', yield all ascending path components like:
'a/b/c/d'
'a/b/c'
'a/b'
'a'
''
### Response:
def recursive_dirname(f):
"""Given a relative path like 'a/b/c/d', yield all ascen... |
def run(create_application, settings=None, log_config=None):
"""
Run a Tornado create_application.
:param create_application: function to call to create a new
application instance
:param dict|None settings: optional configuration dictionary
that will be passed through to ``create_applic... | Run a Tornado create_application.
:param create_application: function to call to create a new
application instance
:param dict|None settings: optional configuration dictionary
that will be passed through to ``create_application``
as kwargs.
:param dict|None log_config: optional logg... | Below is the the instruction that describes the task:
### Input:
Run a Tornado create_application.
:param create_application: function to call to create a new
application instance
:param dict|None settings: optional configuration dictionary
that will be passed through to ``create_applicatio... |
def validate_email(value: str) -> Tuple[str, str]:
"""
Brutally simple email address validation. Note unlike most email address validation
* raw ip address (literal) domain parts are not allowed.
* "John Doe <local_part@domain.com>" style "pretty" email addresses are processed
* the local part check... | Brutally simple email address validation. Note unlike most email address validation
* raw ip address (literal) domain parts are not allowed.
* "John Doe <local_part@domain.com>" style "pretty" email addresses are processed
* the local part check is extremely basic. This raises the possibility of unicode spo... | Below is the the instruction that describes the task:
### Input:
Brutally simple email address validation. Note unlike most email address validation
* raw ip address (literal) domain parts are not allowed.
* "John Doe <local_part@domain.com>" style "pretty" email addresses are processed
* the local part... |
def one_point_crossover(parents):
"""Perform one point crossover on two parent chromosomes.
Select a random position in the chromosome.
Take genes to the left from one parent and the rest from the other parent.
Ex. p1 = xxxxx, p2 = yyyyy, position = 2 (starting at 0), child = xxyyy
"""
# The po... | Perform one point crossover on two parent chromosomes.
Select a random position in the chromosome.
Take genes to the left from one parent and the rest from the other parent.
Ex. p1 = xxxxx, p2 = yyyyy, position = 2 (starting at 0), child = xxyyy | Below is the the instruction that describes the task:
### Input:
Perform one point crossover on two parent chromosomes.
Select a random position in the chromosome.
Take genes to the left from one parent and the rest from the other parent.
Ex. p1 = xxxxx, p2 = yyyyy, position = 2 (starting at 0), child ... |
def check_smart_storage_config_ids(self):
"""Check SmartStorageConfig controllers is there in hardware.
:raises: IloError, on an error from iLO.
"""
if self.smart_storage_config_identities is None:
msg = ('The Redfish controller failed to get the '
'SmartS... | Check SmartStorageConfig controllers is there in hardware.
:raises: IloError, on an error from iLO. | Below is the the instruction that describes the task:
### Input:
Check SmartStorageConfig controllers is there in hardware.
:raises: IloError, on an error from iLO.
### Response:
def check_smart_storage_config_ids(self):
"""Check SmartStorageConfig controllers is there in hardware.
:raise... |
def discovery_mdns(self):
"""
Installs the mDNS discovery bundles and instantiates components
"""
# Remove Zeroconf debug output
logging.getLogger("zeroconf").setLevel(logging.WARNING)
# Install the bundle
self.context.install_bundle("pelix.remote.discovery.mdns"... | Installs the mDNS discovery bundles and instantiates components | Below is the the instruction that describes the task:
### Input:
Installs the mDNS discovery bundles and instantiates components
### Response:
def discovery_mdns(self):
"""
Installs the mDNS discovery bundles and instantiates components
"""
# Remove Zeroconf debug output
log... |
def slotsToJSON(obj, slots=None):
"""Converts the given Python object to one suitable for Javascript
Object Notation (JSON) serialization via :func:`json.dump` or
:func:`json.dumps`. This function delegates to :func:`toJSON`.
Specifically only attributes in the list of *slots* are converted.
If *s... | Converts the given Python object to one suitable for Javascript
Object Notation (JSON) serialization via :func:`json.dump` or
:func:`json.dumps`. This function delegates to :func:`toJSON`.
Specifically only attributes in the list of *slots* are converted.
If *slots* is not provided, it defaults to the... | Below is the the instruction that describes the task:
### Input:
Converts the given Python object to one suitable for Javascript
Object Notation (JSON) serialization via :func:`json.dump` or
:func:`json.dumps`. This function delegates to :func:`toJSON`.
Specifically only attributes in the list of *slo... |
def calculate_diagram_ranges(data):
"""
Given a numpy array calculate what the ranges of the H-R
diagram should be.
"""
data = round_arr_teff_luminosity(data)
temps = data['temp']
x_range = [1.05 * np.amax(temps), .95 * np.amin(temps)]
lums = data['lum']
y_range = [.50 * np.amin(lums... | Given a numpy array calculate what the ranges of the H-R
diagram should be. | Below is the the instruction that describes the task:
### Input:
Given a numpy array calculate what the ranges of the H-R
diagram should be.
### Response:
def calculate_diagram_ranges(data):
"""
Given a numpy array calculate what the ranges of the H-R
diagram should be.
"""
data = round_arr... |
def inset_sizes(cls, original_width, original_height, target_width, target_height):
"""
Calculate new image sizes for inset mode
:param original_width: int
:param original_height: int
:param target_width: int
:param target_height: int
:return: tuple(int, int)
... | Calculate new image sizes for inset mode
:param original_width: int
:param original_height: int
:param target_width: int
:param target_height: int
:return: tuple(int, int) | Below is the the instruction that describes the task:
### Input:
Calculate new image sizes for inset mode
:param original_width: int
:param original_height: int
:param target_width: int
:param target_height: int
:return: tuple(int, int)
### Response:
def inset_sizes(cls, ori... |
def temporary_attr(obj, name, value):
"""
Context manager that removes key from dictionary on closing
The dictionary will hold the key for the duration of
the context.
Parameters
----------
obj : object
Object onto which to add a temporary attribute.
name : str
Name of ... | Context manager that removes key from dictionary on closing
The dictionary will hold the key for the duration of
the context.
Parameters
----------
obj : object
Object onto which to add a temporary attribute.
name : str
Name of attribute to add to ``obj``.
value : object
... | Below is the the instruction that describes the task:
### Input:
Context manager that removes key from dictionary on closing
The dictionary will hold the key for the duration of
the context.
Parameters
----------
obj : object
Object onto which to add a temporary attribute.
name : s... |
def change_object_link_card(obj, perms):
"""
If the user has permission to change `obj`, show a link to its Admin page.
obj -- An object like Movie, Play, ClassicalWork, Publication, etc.
perms -- The `perms` object that it's the template.
"""
# eg: 'movie' or 'classicalwork':
name = obj.__c... | If the user has permission to change `obj`, show a link to its Admin page.
obj -- An object like Movie, Play, ClassicalWork, Publication, etc.
perms -- The `perms` object that it's the template. | Below is the the instruction that describes the task:
### Input:
If the user has permission to change `obj`, show a link to its Admin page.
obj -- An object like Movie, Play, ClassicalWork, Publication, etc.
perms -- The `perms` object that it's the template.
### Response:
def change_object_link_card(obj, ... |
def get_url(self, *paths, **params):
"""
Returns the URL for this request.
:param paths: Additional URL path parts to add to the request
:param params: Additional query parameters to add to the request
"""
path_stack = self._attribute_stack[:]
if paths:
... | Returns the URL for this request.
:param paths: Additional URL path parts to add to the request
:param params: Additional query parameters to add to the request | Below is the the instruction that describes the task:
### Input:
Returns the URL for this request.
:param paths: Additional URL path parts to add to the request
:param params: Additional query parameters to add to the request
### Response:
def get_url(self, *paths, **params):
"""
R... |
def addFreetextAnnot(self, rect, text, fontsize=12, fontname=None, color=None, rotate=0):
"""Add a 'FreeText' annotation in rectangle 'rect'."""
CheckParent(self)
val = _fitz.Page_addFreetextAnnot(self, rect, text, fontsize, fontname, color, rotate)
if not val: return
val.thiso... | Add a 'FreeText' annotation in rectangle 'rect'. | Below is the the instruction that describes the task:
### Input:
Add a 'FreeText' annotation in rectangle 'rect'.
### Response:
def addFreetextAnnot(self, rect, text, fontsize=12, fontname=None, color=None, rotate=0):
"""Add a 'FreeText' annotation in rectangle 'rect'."""
CheckParent(self)
... |
def root_chip(self):
"""The coordinates (x, y) of the chip used to boot the machine."""
# If not known, query the machine
if self._root_chip is None:
self._root_chip = self.get_software_version(255, 255, 0).position
return self._root_chip | The coordinates (x, y) of the chip used to boot the machine. | Below is the the instruction that describes the task:
### Input:
The coordinates (x, y) of the chip used to boot the machine.
### Response:
def root_chip(self):
"""The coordinates (x, y) of the chip used to boot the machine."""
# If not known, query the machine
if self._root_chip is None:
... |
def add_event(self, event):
"""Adds an event to the event file.
Args:
event: An `Event` protocol buffer.
"""
if not isinstance(event, event_pb2.Event):
raise TypeError("Expected an event_pb2.Event proto, "
" but got %s" % type(event))
... | Adds an event to the event file.
Args:
event: An `Event` protocol buffer. | Below is the the instruction that describes the task:
### Input:
Adds an event to the event file.
Args:
event: An `Event` protocol buffer.
### Response:
def add_event(self, event):
"""Adds an event to the event file.
Args:
event: An `Event` protocol buffer.
"""... |
def init_passbands(refresh=False):
"""
This function should be called only once, at import time. It
traverses the passbands directory and builds a lookup table of
passband names qualified as 'pbset:pbname' and corresponding files
and atmosphere content within.
"""
global _initialized
if... | This function should be called only once, at import time. It
traverses the passbands directory and builds a lookup table of
passband names qualified as 'pbset:pbname' and corresponding files
and atmosphere content within. | Below is the the instruction that describes the task:
### Input:
This function should be called only once, at import time. It
traverses the passbands directory and builds a lookup table of
passband names qualified as 'pbset:pbname' and corresponding files
and atmosphere content within.
### Response:
de... |
def define(cls, start, step, num, dtype=None):
"""Define a new `Index`.
The output is basically::
start + numpy.arange(num) * step
Parameters
----------
start : `Number`
The starting value of the index.
step : `Number`
The step size... | Define a new `Index`.
The output is basically::
start + numpy.arange(num) * step
Parameters
----------
start : `Number`
The starting value of the index.
step : `Number`
The step size of the index.
num : `int`
The size o... | Below is the the instruction that describes the task:
### Input:
Define a new `Index`.
The output is basically::
start + numpy.arange(num) * step
Parameters
----------
start : `Number`
The starting value of the index.
step : `Number`
Th... |
def context_path(cls, project, session, context):
"""Return a fully-qualified context string."""
return google.api_core.path_template.expand(
'projects/{project}/agent/sessions/{session}/contexts/{context}',
project=project,
session=session,
context=contex... | Return a fully-qualified context string. | Below is the the instruction that describes the task:
### Input:
Return a fully-qualified context string.
### Response:
def context_path(cls, project, session, context):
"""Return a fully-qualified context string."""
return google.api_core.path_template.expand(
'projects/{project}/agent... |
def qindex2index(index):
""" from a QIndex (row/column coordinate system), get the buffer index of the byte """
r = index.row()
c = index.column()
if c > 0x10:
return (0x10 * r) + c - 0x11
else:
return (0x10 * r) + c | from a QIndex (row/column coordinate system), get the buffer index of the byte | Below is the the instruction that describes the task:
### Input:
from a QIndex (row/column coordinate system), get the buffer index of the byte
### Response:
def qindex2index(index):
""" from a QIndex (row/column coordinate system), get the buffer index of the byte """
r = index.row()
c = i... |
def publish_alias(self, func_data, alias):
"""Create or update an alias for the given function.
"""
if not alias:
return func_data['FunctionArn']
func_name = func_data['FunctionName']
func_version = func_data['Version']
exists = resource_exists(
s... | Create or update an alias for the given function. | Below is the the instruction that describes the task:
### Input:
Create or update an alias for the given function.
### Response:
def publish_alias(self, func_data, alias):
"""Create or update an alias for the given function.
"""
if not alias:
return func_data['FunctionArn']
... |
def get_real_related(self, id_equip):
"""
Find reals related with equipment
:param id_equip: Identifier of equipment
:return: Following dictionary:
::
{'vips': [{'port_real': < port_real >,
'server_pool_member_id': < server_pool_member_id >,
... | Find reals related with equipment
:param id_equip: Identifier of equipment
:return: Following dictionary:
::
{'vips': [{'port_real': < port_real >,
'server_pool_member_id': < server_pool_member_id >,
'ip': < ip >,
'port_vip': < port_vip >,
... | Below is the the instruction that describes the task:
### Input:
Find reals related with equipment
:param id_equip: Identifier of equipment
:return: Following dictionary:
::
{'vips': [{'port_real': < port_real >,
'server_pool_member_id': < server_pool_member_id >,... |
def process_credentials_elements(cred_tree):
""" Receive an XML object with the credentials to run
a scan against a given target.
@param:
<credentials>
<credential type="up" service="ssh" port="22">
<username>scanuser</username>
<password>mypass</passwo... | Receive an XML object with the credentials to run
a scan against a given target.
@param:
<credentials>
<credential type="up" service="ssh" port="22">
<username>scanuser</username>
<password>mypass</password>
</credential>
<credential type="u... | Below is the the instruction that describes the task:
### Input:
Receive an XML object with the credentials to run
a scan against a given target.
@param:
<credentials>
<credential type="up" service="ssh" port="22">
<username>scanuser</username>
<password>my... |
def generate(basename, xml):
'''generate complete MAVLink CSharp implemenation'''
structsfilename = basename + '.generated.cs'
msgs = []
enums = []
filelist = []
for x in xml:
msgs.extend(x.message)
enums.extend(x.enum)
filelist.append(os.path.basename(x.filename))
... | generate complete MAVLink CSharp implemenation | Below is the the instruction that describes the task:
### Input:
generate complete MAVLink CSharp implemenation
### Response:
def generate(basename, xml):
'''generate complete MAVLink CSharp implemenation'''
structsfilename = basename + '.generated.cs'
msgs = []
enums = []
filelist = []
... |
def select_ignore_interrupts(iwtd, owtd, ewtd, timeout=None):
'''This is a wrapper around select.select() that ignores signals. If
select.select raises a select.error exception and errno is an EINTR
error then it is ignored. Mainly this is used to ignore sigwinch
(terminal resize). '''
# if select... | This is a wrapper around select.select() that ignores signals. If
select.select raises a select.error exception and errno is an EINTR
error then it is ignored. Mainly this is used to ignore sigwinch
(terminal resize). | Below is the the instruction that describes the task:
### Input:
This is a wrapper around select.select() that ignores signals. If
select.select raises a select.error exception and errno is an EINTR
error then it is ignored. Mainly this is used to ignore sigwinch
(terminal resize).
### Response:
def se... |
def get_atoms(self, ligands=True, inc_alt_states=False):
"""Flat list of all the Atoms in the Polymer.
Parameters
----------
inc_alt_states : bool
If true atoms from alternate conformations are included rather
than only the "active" states.
Returns
... | Flat list of all the Atoms in the Polymer.
Parameters
----------
inc_alt_states : bool
If true atoms from alternate conformations are included rather
than only the "active" states.
Returns
-------
atoms : itertools.chain
Returns an it... | Below is the the instruction that describes the task:
### Input:
Flat list of all the Atoms in the Polymer.
Parameters
----------
inc_alt_states : bool
If true atoms from alternate conformations are included rather
than only the "active" states.
Returns
... |
def swaggerize_response(response, op):
"""
Delegate handling the Swagger concerns of the response to bravado-core.
:type response: :class:`pyramid.response.Response`
:type op: :class:`bravado_core.operation.Operation`
"""
response_spec = get_response_spec(response.status_int, op)
bravado_co... | Delegate handling the Swagger concerns of the response to bravado-core.
:type response: :class:`pyramid.response.Response`
:type op: :class:`bravado_core.operation.Operation` | Below is the the instruction that describes the task:
### Input:
Delegate handling the Swagger concerns of the response to bravado-core.
:type response: :class:`pyramid.response.Response`
:type op: :class:`bravado_core.operation.Operation`
### Response:
def swaggerize_response(response, op):
"""
D... |
def fmt(self, fills):
"""Format block (CSS)
args:
fills (dict): Fill elements
returns:
str (CSS)
"""
f = "%(identifier)s%(ws)s{%(nl)s%(proplist)s}%(eb)s"
out = []
name = self.name.fmt(fills)
if self.parsed and any(
p... | Format block (CSS)
args:
fills (dict): Fill elements
returns:
str (CSS) | Below is the the instruction that describes the task:
### Input:
Format block (CSS)
args:
fills (dict): Fill elements
returns:
str (CSS)
### Response:
def fmt(self, fills):
"""Format block (CSS)
args:
fills (dict): Fill elements
returns:
... |
def parse_copy_object(bucket_name, object_name, data):
"""
Parser for copy object response.
:param data: Response data for copy object.
:return: :class:`CopyObjectResult <CopyObjectResult>`
"""
root = S3Element.fromstring('CopyObjectResult', data)
return CopyObjectResult(
bucket_na... | Parser for copy object response.
:param data: Response data for copy object.
:return: :class:`CopyObjectResult <CopyObjectResult>` | Below is the the instruction that describes the task:
### Input:
Parser for copy object response.
:param data: Response data for copy object.
:return: :class:`CopyObjectResult <CopyObjectResult>`
### Response:
def parse_copy_object(bucket_name, object_name, data):
"""
Parser for copy object respon... |
def _load_assembly_mapping_data(filename):
""" Load assembly mapping data.
Parameters
----------
filename : str
path to compressed archive with assembly mapping data
Returns
-------
assembly_mapping_data : dict
dict of assembly maps if lo... | Load assembly mapping data.
Parameters
----------
filename : str
path to compressed archive with assembly mapping data
Returns
-------
assembly_mapping_data : dict
dict of assembly maps if loading was successful, else None
Notes
... | Below is the the instruction that describes the task:
### Input:
Load assembly mapping data.
Parameters
----------
filename : str
path to compressed archive with assembly mapping data
Returns
-------
assembly_mapping_data : dict
dict of assem... |
def p_chars(self, p):
"""chars :
| chars char"""
if len(p) == 1:
p[0] = unicode()
else:
p[0] = p[1] + p[2] | chars :
| chars char | Below is the the instruction that describes the task:
### Input:
chars :
| chars char
### Response:
def p_chars(self, p):
"""chars :
| chars char"""
if len(p) == 1:
p[0] = unicode()
else:
p[0] = p[1] + p[2] |
def vmeasure(reference_intervals, reference_labels, estimated_intervals,
estimated_labels, frame_size=0.1, beta=1.0):
"""Frame-clustering segmentation: v-measure
Computes cross-entropy of cluster assignment, normalized by the
marginal-entropy.
This is equivalent to `nce(..., marginal=True... | Frame-clustering segmentation: v-measure
Computes cross-entropy of cluster assignment, normalized by the
marginal-entropy.
This is equivalent to `nce(..., marginal=True)`.
Examples
--------
>>> (ref_intervals,
... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab')
>>> (est_i... | Below is the the instruction that describes the task:
### Input:
Frame-clustering segmentation: v-measure
Computes cross-entropy of cluster assignment, normalized by the
marginal-entropy.
This is equivalent to `nce(..., marginal=True)`.
Examples
--------
>>> (ref_intervals,
... ref_l... |
def zlim(name, min, max):
"""
This function will set the z axis range displayed for a specific tplot variable.
This is only used for spec plots, where the z axis represents the magnitude of the values
in each bin.
Parameters:
name : str
The name of the tplot variable that ... | This function will set the z axis range displayed for a specific tplot variable.
This is only used for spec plots, where the z axis represents the magnitude of the values
in each bin.
Parameters:
name : str
The name of the tplot variable that you wish to set z limits for.
... | Below is the the instruction that describes the task:
### Input:
This function will set the z axis range displayed for a specific tplot variable.
This is only used for spec plots, where the z axis represents the magnitude of the values
in each bin.
Parameters:
name : str
The n... |
def pack_new_sequence(self, sequence):
"""Packs a new sequence onto the polymer using Scwrl4.
Parameters
----------
sequence : str
String containing the amino acid sequence. This must
be the same length as the Polymer
Raises
------
ValueE... | Packs a new sequence onto the polymer using Scwrl4.
Parameters
----------
sequence : str
String containing the amino acid sequence. This must
be the same length as the Polymer
Raises
------
ValueError
Raised if the sequence length doe... | Below is the the instruction that describes the task:
### Input:
Packs a new sequence onto the polymer using Scwrl4.
Parameters
----------
sequence : str
String containing the amino acid sequence. This must
be the same length as the Polymer
Raises
--... |
def predict_proba(self, X):
"""Returns the predicted probabilities for ``X``.
Arguments:
X (array-like or sparse matrix of shape (n_samples, n_features)): The input samples.
Sparse matrices are accepted only if they are supported by the weak model.
Returns:
... | Returns the predicted probabilities for ``X``.
Arguments:
X (array-like or sparse matrix of shape (n_samples, n_features)): The input samples.
Sparse matrices are accepted only if they are supported by the weak model.
Returns:
array of shape (n_samples, n_classe... | Below is the the instruction that describes the task:
### Input:
Returns the predicted probabilities for ``X``.
Arguments:
X (array-like or sparse matrix of shape (n_samples, n_features)): The input samples.
Sparse matrices are accepted only if they are supported by the weak mod... |
def pivot(self, md5, tag=''):
"""Pivot on an md5 (md5 can be a single sample or a sample_set)
Args:
md5: The md5 can be a single sample or a sample_set
tags (optional): a tag for the sample (for the prompt)
Returns:
Nothing but it's sets th... | Pivot on an md5 (md5 can be a single sample or a sample_set)
Args:
md5: The md5 can be a single sample or a sample_set
tags (optional): a tag for the sample (for the prompt)
Returns:
Nothing but it's sets the active sample/sample_set | Below is the the instruction that describes the task:
### Input:
Pivot on an md5 (md5 can be a single sample or a sample_set)
Args:
md5: The md5 can be a single sample or a sample_set
tags (optional): a tag for the sample (for the prompt)
Returns:
... |
def disabledBrush( self ):
"""
Return the main brush for this node.
:return <QBrush>
"""
# create the background brush
grad = QLinearGradient()
rect = self.rect()
grad.setStart(QPointF(0, rect.y()))
grad.setFinalStop(QPointF(0... | Return the main brush for this node.
:return <QBrush> | Below is the the instruction that describes the task:
### Input:
Return the main brush for this node.
:return <QBrush>
### Response:
def disabledBrush( self ):
"""
Return the main brush for this node.
:return <QBrush>
"""
# create the backgr... |
def list_nodes(conn=None, call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
if not conn:
conn = get_conn() # pylint: disable=E0... | Return a list of the VMs that are on the provider | Below is the the instruction that describes the task:
### Input:
Return a list of the VMs that are on the provider
### Response:
def list_nodes(conn=None, call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The l... |
def _filter_markdown(source, filters):
"""Only keep some Markdown headers from a Markdown string."""
lines = source.splitlines()
# Filters is a list of 'hN' strings where 1 <= N <= 6.
headers = [_replace_header_filter(filter) for filter in filters]
lines = [line for line in lines if line.startswith(... | Only keep some Markdown headers from a Markdown string. | Below is the the instruction that describes the task:
### Input:
Only keep some Markdown headers from a Markdown string.
### Response:
def _filter_markdown(source, filters):
"""Only keep some Markdown headers from a Markdown string."""
lines = source.splitlines()
# Filters is a list of 'hN' strings whe... |
def evict(self, urls):
"""Remove items from cache matching URLs.
Return the number of items removed.
"""
if isinstance(urls, six.text_type):
urls = [urls]
urls = set(normalize_url(url) for url in urls)
retval = 0
for key in list(self.cache):
... | Remove items from cache matching URLs.
Return the number of items removed. | Below is the the instruction that describes the task:
### Input:
Remove items from cache matching URLs.
Return the number of items removed.
### Response:
def evict(self, urls):
"""Remove items from cache matching URLs.
Return the number of items removed.
"""
if isinstance(... |
def _inv_key(list_keys, valid_keys):
"""
-----
Brief
-----
A sub-function of _filter_keywords function.
-----------
Description
-----------
Function used for identification when a list of keywords contains invalid keywords not present
in the valid list.
----------
Param... | -----
Brief
-----
A sub-function of _filter_keywords function.
-----------
Description
-----------
Function used for identification when a list of keywords contains invalid keywords not present
in the valid list.
----------
Parameters
----------
list_keys : list
... | Below is the the instruction that describes the task:
### Input:
-----
Brief
-----
A sub-function of _filter_keywords function.
-----------
Description
-----------
Function used for identification when a list of keywords contains invalid keywords not present
in the valid list.
... |
def scheme_host_port_prefix(self, scheme='http', host='host',
port=None, prefix=None):
"""Return URI composed of scheme, server, port, and prefix."""
uri = scheme + '://' + host
if (port and not ((scheme == 'http' and port == 80) or
(sche... | Return URI composed of scheme, server, port, and prefix. | Below is the the instruction that describes the task:
### Input:
Return URI composed of scheme, server, port, and prefix.
### Response:
def scheme_host_port_prefix(self, scheme='http', host='host',
port=None, prefix=None):
"""Return URI composed of scheme, server, port, and ... |
def nacm_rule_list_rule_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
nacm = ET.SubElement(config, "nacm", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-acm")
rule_list = ET.SubElement(nacm, "rule-list")
name_key = ET.SubElement(rule_lis... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def nacm_rule_list_rule_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
nacm = ET.SubElement(config, "nacm", xmlns="urn:ietf:params:xml:ns:yang:ietf-netc... |
def reset_params(self):
"""Reset all parameters to their default values."""
self.__params = dict([p, None] for p in self.param_names)
self.set_params(self.param_defaults) | Reset all parameters to their default values. | Below is the the instruction that describes the task:
### Input:
Reset all parameters to their default values.
### Response:
def reset_params(self):
"""Reset all parameters to their default values."""
self.__params = dict([p, None] for p in self.param_names)
self.set_params(self.param_defau... |
def set_shellwidget(self, shellwidget):
"""Bind the shellwidget instance to the figure browser"""
self.shellwidget = shellwidget
shellwidget.set_figurebrowser(self)
shellwidget.sig_new_inline_figure.connect(self._handle_new_figure) | Bind the shellwidget instance to the figure browser | Below is the the instruction that describes the task:
### Input:
Bind the shellwidget instance to the figure browser
### Response:
def set_shellwidget(self, shellwidget):
"""Bind the shellwidget instance to the figure browser"""
self.shellwidget = shellwidget
shellwidget.set_figurebrowser(s... |
def apply_mesh_programs(self, mesh_programs=None):
"""Applies mesh programs to meshes"""
if not mesh_programs:
mesh_programs = [ColorProgram(), TextureProgram(), FallbackProgram()]
for mesh in self.meshes:
for mp in mesh_programs:
instance = mp.apply(mesh... | Applies mesh programs to meshes | Below is the the instruction that describes the task:
### Input:
Applies mesh programs to meshes
### Response:
def apply_mesh_programs(self, mesh_programs=None):
"""Applies mesh programs to meshes"""
if not mesh_programs:
mesh_programs = [ColorProgram(), TextureProgram(), FallbackProgra... |
def create_new_state_from_state_with_type(source_state, target_state_class):
"""The function duplicates/transforms a state to a new state type. If the source state type and the new state
type both are ContainerStates the new state will have not transitions to force the user to explicitly re-order
the logica... | The function duplicates/transforms a state to a new state type. If the source state type and the new state
type both are ContainerStates the new state will have not transitions to force the user to explicitly re-order
the logical flow according the paradigm of the new state type.
:param source_state: previ... | Below is the the instruction that describes the task:
### Input:
The function duplicates/transforms a state to a new state type. If the source state type and the new state
type both are ContainerStates the new state will have not transitions to force the user to explicitly re-order
the logical flow accordin... |
def from_array(array):
"""
Deserialize a new PassportData from a given dictionary.
:return: new PassportData instance.
:rtype: PassportData
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_nam... | Deserialize a new PassportData from a given dictionary.
:return: new PassportData instance.
:rtype: PassportData | Below is the the instruction that describes the task:
### Input:
Deserialize a new PassportData from a given dictionary.
:return: new PassportData instance.
:rtype: PassportData
### Response:
def from_array(array):
"""
Deserialize a new PassportData from a given dictionary.
... |
def add_meta(self, name, value):
"""
Add a pair of meta data to the definition
:param name: name of the meta
:type name: str
:param value: value of the meta
:type value: str
"""
for mt in self.metas:
if mt.name == name:
mt.valu... | Add a pair of meta data to the definition
:param name: name of the meta
:type name: str
:param value: value of the meta
:type value: str | Below is the the instruction that describes the task:
### Input:
Add a pair of meta data to the definition
:param name: name of the meta
:type name: str
:param value: value of the meta
:type value: str
### Response:
def add_meta(self, name, value):
"""
Add a pair of... |
def genesis_signing_lockset(genesis, privkey):
"""
in order to avoid a complicated bootstrapping, we define
the genesis_signing_lockset as a lockset with one vote by any validator.
"""
v = VoteBlock(0, 0, genesis.hash)
v.sign(privkey)
ls = LockSet(num_eligible_votes=1)
ls.add(v)
asse... | in order to avoid a complicated bootstrapping, we define
the genesis_signing_lockset as a lockset with one vote by any validator. | Below is the the instruction that describes the task:
### Input:
in order to avoid a complicated bootstrapping, we define
the genesis_signing_lockset as a lockset with one vote by any validator.
### Response:
def genesis_signing_lockset(genesis, privkey):
"""
in order to avoid a complicated bootstrappi... |
def _execute_sbatch(self):
"""Schedule the sbatch file using the sbatch command
:returns the slurm job id
"""
commands = self.campaign.process.get('commands', {})
sbatch = find_executable(commands.get('sbatch', 'sbatch'))
sbatch_command = [sbatch, '--parsable', self.sbatc... | Schedule the sbatch file using the sbatch command
:returns the slurm job id | Below is the the instruction that describes the task:
### Input:
Schedule the sbatch file using the sbatch command
:returns the slurm job id
### Response:
def _execute_sbatch(self):
"""Schedule the sbatch file using the sbatch command
:returns the slurm job id
"""
commands =... |
def to_struct_file(self, f):
""" write the Vario2d to a PEST-style structure file
Parameters
----------
f : (str or file handle)
item to write to
"""
if isinstance(f, str):
f = open(f,'w')
f.write("VARIOGRAM {0}\n".format(self.name))
... | write the Vario2d to a PEST-style structure file
Parameters
----------
f : (str or file handle)
item to write to | Below is the the instruction that describes the task:
### Input:
write the Vario2d to a PEST-style structure file
Parameters
----------
f : (str or file handle)
item to write to
### Response:
def to_struct_file(self, f):
""" write the Vario2d to a PEST-style structure f... |
def num_choice(choices, default='1', valid_keys='', depth=1, icons='', sn_info=None,
indent=4, fg_color='green', separator='',
with_img=6, img_list=None, img_cache_dir='/tmp', use_cache=False,
extra_hints='', clear_previous=False, quit_app=True,
):
"""
... | 传入数组, 生成待选择列表, 如果启用图片支持, 需要额外传入与数组排序一致的图片列表,
- 图片在 iterms 中显示速度较慢, 不推荐使用
.. note: 图片在 iterms 中显示速度较慢, 如果数组长度大于10, 不推荐使用
.. code:: python
sn_info = {
'align': '-', # 左右对齐
'length': 2, # 显示长度
}
:param use_cache:
:type use_cache:
... | Below is the the instruction that describes the task:
### Input:
传入数组, 生成待选择列表, 如果启用图片支持, 需要额外传入与数组排序一致的图片列表,
- 图片在 iterms 中显示速度较慢, 不推荐使用
.. note: 图片在 iterms 中显示速度较慢, 如果数组长度大于10, 不推荐使用
.. code:: python
sn_info = {
'align': '-', # 左右对齐
'length': ... |
def designPrimers(seq_args, global_args=None, misprime_lib=None,
mishyb_lib=None, debug=False):
''' Run the Primer3 design process.
If the global args have been previously set (either by a pervious
`designPrimers` call or by a `setGlobals` call), `designPrimers` may be
called with seq... | Run the Primer3 design process.
If the global args have been previously set (either by a pervious
`designPrimers` call or by a `setGlobals` call), `designPrimers` may be
called with seqArgs alone (as a means of optimization).
Args:
seq_args (dict) : Primer3 sequence/design args a... | Below is the the instruction that describes the task:
### Input:
Run the Primer3 design process.
If the global args have been previously set (either by a pervious
`designPrimers` call or by a `setGlobals` call), `designPrimers` may be
called with seqArgs alone (as a means of optimization).
Args:
... |
def enbase64(byte_str):
"""
Encode bytes/strings to base64.
Args:
- ``byte_str``: The string or bytes to base64 encode.
Returns:
- byte_str encoded as base64.
"""
# Python 3: base64.b64encode() expects type byte
if isinstance(byte_str, str) and not PYTHON2:
byte_s... | Encode bytes/strings to base64.
Args:
- ``byte_str``: The string or bytes to base64 encode.
Returns:
- byte_str encoded as base64. | Below is the the instruction that describes the task:
### Input:
Encode bytes/strings to base64.
Args:
- ``byte_str``: The string or bytes to base64 encode.
Returns:
- byte_str encoded as base64.
### Response:
def enbase64(byte_str):
"""
Encode bytes/strings to base64.
Args:... |
def backward_word(self, e): # (M-b)
u"""Move back to the start of the current or previous word. Words are
composed of letters and digits."""
self.l_buffer.backward_word(self.argument_reset)
self.finalize() | u"""Move back to the start of the current or previous word. Words are
composed of letters and digits. | Below is the the instruction that describes the task:
### Input:
u"""Move back to the start of the current or previous word. Words are
composed of letters and digits.
### Response:
def backward_word(self, e): # (M-b)
u"""Move back to the start of the current or previous word. Words are
c... |
def messages(self, channel='sse'):
"""
A generator of :class:`~flask_sse.Message` objects from the given channel.
"""
pubsub = self.redis.pubsub()
pubsub.subscribe(channel)
for pubsub_message in pubsub.listen():
if pubsub_message['type'] == 'message':
... | A generator of :class:`~flask_sse.Message` objects from the given channel. | Below is the the instruction that describes the task:
### Input:
A generator of :class:`~flask_sse.Message` objects from the given channel.
### Response:
def messages(self, channel='sse'):
"""
A generator of :class:`~flask_sse.Message` objects from the given channel.
"""
pubsub = se... |
def parse(html):
"""
Parses the given HTML message and returns its stripped representation
plus a list of the MessageEntity's that were found.
:param message: the message with HTML to be parsed.
:return: a tuple consisting of (clean message, [message entities]).
"""
if not html:
ret... | Parses the given HTML message and returns its stripped representation
plus a list of the MessageEntity's that were found.
:param message: the message with HTML to be parsed.
:return: a tuple consisting of (clean message, [message entities]). | Below is the the instruction that describes the task:
### Input:
Parses the given HTML message and returns its stripped representation
plus a list of the MessageEntity's that were found.
:param message: the message with HTML to be parsed.
:return: a tuple consisting of (clean message, [message entities... |
def mask(self, image, nan_to_num=True, layers=None, in_global_mask=False):
""" Vectorize an image and mask out all invalid voxels.
Args:
images: The image to vectorize and mask. Input can be any object
handled by get_image().
layers: Which mask layers to use (spe... | Vectorize an image and mask out all invalid voxels.
Args:
images: The image to vectorize and mask. Input can be any object
handled by get_image().
layers: Which mask layers to use (specified as int, string, or
list of ints and strings). When None, applies... | Below is the the instruction that describes the task:
### Input:
Vectorize an image and mask out all invalid voxels.
Args:
images: The image to vectorize and mask. Input can be any object
handled by get_image().
layers: Which mask layers to use (specified as int, str... |
def wiggleFileHandleToProtocol(self, fileHandle):
"""
Return a continuous protocol object satsifiying the given query
parameters from the given wiggle file handle.
"""
for line in fileHandle:
self.readWiggleLine(line)
return self._data | Return a continuous protocol object satsifiying the given query
parameters from the given wiggle file handle. | Below is the the instruction that describes the task:
### Input:
Return a continuous protocol object satsifiying the given query
parameters from the given wiggle file handle.
### Response:
def wiggleFileHandleToProtocol(self, fileHandle):
"""
Return a continuous protocol object satsifiying ... |
def removePixmap(self, pixmap):
"""
Removes the pixmap from this widgets list of pixmaps.
:param pixmap | <QPixmap>
"""
scene = self.scene()
for item in self.items():
if item.basePixmap() == pixmap:
scene.removeItem(item)... | Removes the pixmap from this widgets list of pixmaps.
:param pixmap | <QPixmap> | Below is the the instruction that describes the task:
### Input:
Removes the pixmap from this widgets list of pixmaps.
:param pixmap | <QPixmap>
### Response:
def removePixmap(self, pixmap):
"""
Removes the pixmap from this widgets list of pixmaps.
:para... |
def predict_on_stream(config: Union[str, Path, dict], batch_size: int = 1, file_path: Optional[str] = None) -> None:
"""Make a prediction with the component described in corresponding configuration file."""
if file_path is None or file_path == '-':
if sys.stdin.isatty():
raise RuntimeError('... | Make a prediction with the component described in corresponding configuration file. | Below is the the instruction that describes the task:
### Input:
Make a prediction with the component described in corresponding configuration file.
### Response:
def predict_on_stream(config: Union[str, Path, dict], batch_size: int = 1, file_path: Optional[str] = None) -> None:
"""Make a prediction with the c... |
def lines(self, encoding=None, errors='strict', retain=True):
r""" Open this file, read all lines, return them in a list.
Optional arguments:
`encoding` - The Unicode encoding (or character set) of
the file. The default is ``None``, meaning the content
of th... | r""" Open this file, read all lines, return them in a list.
Optional arguments:
`encoding` - The Unicode encoding (or character set) of
the file. The default is ``None``, meaning the content
of the file is read as 8-bit characters and returned
as a l... | Below is the the instruction that describes the task:
### Input:
r""" Open this file, read all lines, return them in a list.
Optional arguments:
`encoding` - The Unicode encoding (or character set) of
the file. The default is ``None``, meaning the content
of the... |
def _setup(self):
"""
Load the settings module pointed to by the environment variable. This
is used the first time we need any settings at all, if the user has not
previously configured the settings manually.
"""
settings_module = os.environ.get(ENVIRONMENT_SETTINGS_VARIA... | Load the settings module pointed to by the environment variable. This
is used the first time we need any settings at all, if the user has not
previously configured the settings manually. | Below is the the instruction that describes the task:
### Input:
Load the settings module pointed to by the environment variable. This
is used the first time we need any settings at all, if the user has not
previously configured the settings manually.
### Response:
def _setup(self):
"""
... |
def _merge_metadata_dictionaries(cls, dictionaries):
"""
Helper function for combining variant collections: given multiple
dictionaries mapping:
source name -> (variant -> (attribute -> value))
Returns dictionary with union of all variants and sources.
"""
#... | Helper function for combining variant collections: given multiple
dictionaries mapping:
source name -> (variant -> (attribute -> value))
Returns dictionary with union of all variants and sources. | Below is the the instruction that describes the task:
### Input:
Helper function for combining variant collections: given multiple
dictionaries mapping:
source name -> (variant -> (attribute -> value))
Returns dictionary with union of all variants and sources.
### Response:
def _merge... |
def _output_validators(self):
"""Output common validator types based on usage."""
if self._walk_for_type('Boolean'):
print("from .validators import boolean")
if self._walk_for_type('Integer'):
print("from .validators import integer")
vlist = self.override.get_vali... | Output common validator types based on usage. | Below is the the instruction that describes the task:
### Input:
Output common validator types based on usage.
### Response:
def _output_validators(self):
"""Output common validator types based on usage."""
if self._walk_for_type('Boolean'):
print("from .validators import boolean")
... |
def _get_node_parent(self, age, pos):
"""Get the parent node of node, whch is located in tree's node list.
Returns:
object: The parent node.
"""
return self.nodes[age][int(pos / self.comp)] | Get the parent node of node, whch is located in tree's node list.
Returns:
object: The parent node. | Below is the the instruction that describes the task:
### Input:
Get the parent node of node, whch is located in tree's node list.
Returns:
object: The parent node.
### Response:
def _get_node_parent(self, age, pos):
"""Get the parent node of node, whch is located in tree's node list.
... |
def build_null_stop_time_series(
feed: "Feed",
date_label: str = "20010101",
freq: str = "5Min",
*,
split_directions: bool = False,
) -> DataFrame:
"""
Return a stop time series with the same index and hierarchical columns
as output by :func:`compute_stop_time_series_base`,
but fill ... | Return a stop time series with the same index and hierarchical columns
as output by :func:`compute_stop_time_series_base`,
but fill it full of null values. | Below is the the instruction that describes the task:
### Input:
Return a stop time series with the same index and hierarchical columns
as output by :func:`compute_stop_time_series_base`,
but fill it full of null values.
### Response:
def build_null_stop_time_series(
feed: "Feed",
date_label: str =... |
def parse_period(period: str):
""" parses period from date range picker. The received values are full ISO date """
period = period.split(" - ")
date_from = Datum()
if len(period[0]) == 10:
date_from.from_iso_date_string(period[0])
else:
date_from.from_iso_long_date(period[0])
da... | parses period from date range picker. The received values are full ISO date | Below is the the instruction that describes the task:
### Input:
parses period from date range picker. The received values are full ISO date
### Response:
def parse_period(period: str):
""" parses period from date range picker. The received values are full ISO date """
period = period.split(" - ")
dat... |
def train(config_path: str, cl_arguments: Iterable[str], output_root: str) -> None:
"""
Load config and start the training.
:param config_path: path to configuration file
:param cl_arguments: additional command line arguments which will update the configuration
:param output_root: output root in wh... | Load config and start the training.
:param config_path: path to configuration file
:param cl_arguments: additional command line arguments which will update the configuration
:param output_root: output root in which the training directory will be created | Below is the the instruction that describes the task:
### Input:
Load config and start the training.
:param config_path: path to configuration file
:param cl_arguments: additional command line arguments which will update the configuration
:param output_root: output root in which the training directory ... |
def command_create_tables(self, meta_name=None, verbose=False):
'''
Create tables according sqlalchemy data model.
Is not a complex migration tool like alembic, just creates tables that
does not exist::
./manage.py sqla:create_tables [--verbose] [meta_name]
'''
... | Create tables according sqlalchemy data model.
Is not a complex migration tool like alembic, just creates tables that
does not exist::
./manage.py sqla:create_tables [--verbose] [meta_name] | Below is the the instruction that describes the task:
### Input:
Create tables according sqlalchemy data model.
Is not a complex migration tool like alembic, just creates tables that
does not exist::
./manage.py sqla:create_tables [--verbose] [meta_name]
### Response:
def command_crea... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.