code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def database_caller_creator(self, name=None):
'''creates a sqlite3 db
returns the related connection object
which will be later used to spawn the cursor
'''
try:
if name:
database = name + '.db'
else:
database = 'sqlite_' +... | creates a sqlite3 db
returns the related connection object
which will be later used to spawn the cursor | Below is the the instruction that describes the task:
### Input:
creates a sqlite3 db
returns the related connection object
which will be later used to spawn the cursor
### Response:
def database_caller_creator(self, name=None):
'''creates a sqlite3 db
returns the related connection... |
def labels(self):
"""Return the 10-tuple of text labels from `header`.
The value is determined from the header entries ``'nlabl'`` and
``'label'``.
"""
label_array = self.header['label']['value']
labels = tuple(''.join(row.astype(str)) for row in label_array)
tr... | Return the 10-tuple of text labels from `header`.
The value is determined from the header entries ``'nlabl'`` and
``'label'``. | Below is the the instruction that describes the task:
### Input:
Return the 10-tuple of text labels from `header`.
The value is determined from the header entries ``'nlabl'`` and
``'label'``.
### Response:
def labels(self):
"""Return the 10-tuple of text labels from `header`.
The ... |
def batch_help():
"""Help message for Batch Dialog.
.. versionadded:: 3.2.1
:returns: A message object containing helpful information.
:rtype: messaging.message.Message
"""
message = m.Message()
message.add(m.Brand())
message.add(heading())
message.add(content())
return messag... | Help message for Batch Dialog.
.. versionadded:: 3.2.1
:returns: A message object containing helpful information.
:rtype: messaging.message.Message | Below is the the instruction that describes the task:
### Input:
Help message for Batch Dialog.
.. versionadded:: 3.2.1
:returns: A message object containing helpful information.
:rtype: messaging.message.Message
### Response:
def batch_help():
"""Help message for Batch Dialog.
.. versionadd... |
def muteThread(self, mute_time=-1, thread_id=None):
"""
Mutes thread
:param mute_time: Mute time in seconds, leave blank to mute forever
:param thread_id: User/Group ID to mute. See :ref:`intro_threads`
"""
thread_id, thread_type = self._getThread(thread_id, None)
... | Mutes thread
:param mute_time: Mute time in seconds, leave blank to mute forever
:param thread_id: User/Group ID to mute. See :ref:`intro_threads` | Below is the the instruction that describes the task:
### Input:
Mutes thread
:param mute_time: Mute time in seconds, leave blank to mute forever
:param thread_id: User/Group ID to mute. See :ref:`intro_threads`
### Response:
def muteThread(self, mute_time=-1, thread_id=None):
"""
... |
def arithmetic_crossover(random, mom, dad, args):
"""Return the offspring of arithmetic crossover on the candidates.
This function performs arithmetic crossover (AX), which is similar to a
generalized weighted averaging of the candidate elements. The allele
of each parent is weighted by the *ax_alpha*... | Return the offspring of arithmetic crossover on the candidates.
This function performs arithmetic crossover (AX), which is similar to a
generalized weighted averaging of the candidate elements. The allele
of each parent is weighted by the *ax_alpha* keyword argument, and
the allele of the complement p... | Below is the the instruction that describes the task:
### Input:
Return the offspring of arithmetic crossover on the candidates.
This function performs arithmetic crossover (AX), which is similar to a
generalized weighted averaging of the candidate elements. The allele
of each parent is weighted by th... |
def convert_ini(config_dict):
"""Convert _config_dict_ into a list of INI formatted strings.
Args:
config_dict (dict): Configuration dictionary to be flattened.
Returns:
(list) Lines to be written to a file in the format of KEY1_KEY2=value.
"""
config_lines = []
for env, confi... | Convert _config_dict_ into a list of INI formatted strings.
Args:
config_dict (dict): Configuration dictionary to be flattened.
Returns:
(list) Lines to be written to a file in the format of KEY1_KEY2=value. | Below is the the instruction that describes the task:
### Input:
Convert _config_dict_ into a list of INI formatted strings.
Args:
config_dict (dict): Configuration dictionary to be flattened.
Returns:
(list) Lines to be written to a file in the format of KEY1_KEY2=value.
### Response:
de... |
def start(self, interval=None):
"""
Emits the start requested signal for this timer, effectively starting
its internal timer.
:param interval | <int>
"""
# update the interval value
with QtCore.QReadLocker(self.__lock):
if interv... | Emits the start requested signal for this timer, effectively starting
its internal timer.
:param interval | <int> | Below is the the instruction that describes the task:
### Input:
Emits the start requested signal for this timer, effectively starting
its internal timer.
:param interval | <int>
### Response:
def start(self, interval=None):
"""
Emits the start requested signal fo... |
def filter_cells(
data: AnnData,
min_counts: Optional[int] = None,
min_genes: Optional[int] = None,
max_counts: Optional[int] = None,
max_genes: Optional[int] = None,
inplace: bool = True,
copy: bool = False,
) -> Optional[Tuple[np.ndarray, np.ndarray]]:
"""Filter cell outliers based o... | Filter cell outliers based on counts and numbers of genes expressed.
For instance, only keep cells with at least `min_counts` counts or
`min_genes` genes expressed. This is to filter measurement outliers,
i.e. “unreliable” observations.
Only provide one of the optional parameters ``min_counts``, ``min... | Below is the the instruction that describes the task:
### Input:
Filter cell outliers based on counts and numbers of genes expressed.
For instance, only keep cells with at least `min_counts` counts or
`min_genes` genes expressed. This is to filter measurement outliers,
i.e. “unreliable” observations.
... |
def _init_obo_version(self, line):
"""Save obo version and release."""
if line[0:14] == "format-version":
self.format_version = line[16:-1]
if line[0:12] == "data-version":
self.data_version = line[14:-1] | Save obo version and release. | Below is the the instruction that describes the task:
### Input:
Save obo version and release.
### Response:
def _init_obo_version(self, line):
"""Save obo version and release."""
if line[0:14] == "format-version":
self.format_version = line[16:-1]
if line[0:12] == "data-version... |
def get_declared_fields(bases, attrs, cls_filter,
with_base_fields=True,
extra_attr_name='base_fields'):
"""
Create a list of form field instances from the passed in 'attrs', plus any
similar fields on the base classes (in 'bases'). This is used by both the
Form and ModelForm metclasses.... | Create a list of form field instances from the passed in 'attrs', plus any
similar fields on the base classes (in 'bases'). This is used by both the
Form and ModelForm metclasses.
If 'with_base_fields' is True, all fields from the bases are used.
Otherwise, only fields in the 'declared_fields' attribut... | Below is the the instruction that describes the task:
### Input:
Create a list of form field instances from the passed in 'attrs', plus any
similar fields on the base classes (in 'bases'). This is used by both the
Form and ModelForm metclasses.
If 'with_base_fields' is True, all fields from the bases a... |
def _AddVariable(self, variable):
"""
Add a variable to the model. Should not be used by end-user
"""
if isinstance(variable, Signal):
if not variable in self.signals:
self.signals.append(variable)
elif isinstance(variable, Variable):
if no... | Add a variable to the model. Should not be used by end-user | Below is the the instruction that describes the task:
### Input:
Add a variable to the model. Should not be used by end-user
### Response:
def _AddVariable(self, variable):
"""
Add a variable to the model. Should not be used by end-user
"""
if isinstance(variable, Signal):
... |
def remove(self, identifier: Union[DataObjectReplica, int]):
"""
Removes a data object from this collection that has the given unique identifier. A `ValueError` will be raised
if a data object with the given identifier does not exist.
:param identifier: the identifier of the data object
... | Removes a data object from this collection that has the given unique identifier. A `ValueError` will be raised
if a data object with the given identifier does not exist.
:param identifier: the identifier of the data object | Below is the the instruction that describes the task:
### Input:
Removes a data object from this collection that has the given unique identifier. A `ValueError` will be raised
if a data object with the given identifier does not exist.
:param identifier: the identifier of the data object
### Response... |
def _initialize_counter(self):
"""Initialize our counter pointer.
If we're the top-level factory, instantiate a new counter
Otherwise, point to the top-level factory's counter.
"""
if self._counter is not None:
return
if self.counter_reference is self:
... | Initialize our counter pointer.
If we're the top-level factory, instantiate a new counter
Otherwise, point to the top-level factory's counter. | Below is the the instruction that describes the task:
### Input:
Initialize our counter pointer.
If we're the top-level factory, instantiate a new counter
Otherwise, point to the top-level factory's counter.
### Response:
def _initialize_counter(self):
"""Initialize our counter pointer.
... |
def generate_lines(input_file,
start=0,
stop=float('inf')):
"""Generate (yield) lines in a gzipped file (*.txt.gz) one line at a time"""
with gzip.GzipFile(input_file, 'rU') as f:
for i, line in enumerate(f):
if i < start:
continue
... | Generate (yield) lines in a gzipped file (*.txt.gz) one line at a time | Below is the the instruction that describes the task:
### Input:
Generate (yield) lines in a gzipped file (*.txt.gz) one line at a time
### Response:
def generate_lines(input_file,
start=0,
stop=float('inf')):
"""Generate (yield) lines in a gzipped file (*.txt.gz) one line... |
def register_upload_command(self, upload_func):
"""
Add the upload command to the parser and call upload_func(project_name, folders, follow_symlinks) when chosen.
:param upload_func: func Called when this option is chosen: upload_func(project_name, folders, follow_symlinks).
"""
... | Add the upload command to the parser and call upload_func(project_name, folders, follow_symlinks) when chosen.
:param upload_func: func Called when this option is chosen: upload_func(project_name, folders, follow_symlinks). | Below is the the instruction that describes the task:
### Input:
Add the upload command to the parser and call upload_func(project_name, folders, follow_symlinks) when chosen.
:param upload_func: func Called when this option is chosen: upload_func(project_name, folders, follow_symlinks).
### Response:
def ... |
def configure_sentry_errors(self):
"""
Configure sentry.errors to use the same loggers as the root handler
@rtype: None
"""
sentry_errors_logger = logging.getLogger('sentry.errors')
root_logger = logging.getLogger()
for handler in root_logger.handlers:
... | Configure sentry.errors to use the same loggers as the root handler
@rtype: None | Below is the the instruction that describes the task:
### Input:
Configure sentry.errors to use the same loggers as the root handler
@rtype: None
### Response:
def configure_sentry_errors(self):
"""
Configure sentry.errors to use the same loggers as the root handler
@rtype: None
... |
def to_satoshis(input_quantity, input_type):
''' convert to satoshis, no rounding '''
assert input_type in UNIT_CHOICES, input_type
# convert to satoshis
if input_type in ('btc', 'mbtc', 'bit'):
satoshis = float(input_quantity) * float(UNIT_MAPPINGS[input_type]['satoshis_per'])
elif input_t... | convert to satoshis, no rounding | Below is the the instruction that describes the task:
### Input:
convert to satoshis, no rounding
### Response:
def to_satoshis(input_quantity, input_type):
''' convert to satoshis, no rounding '''
assert input_type in UNIT_CHOICES, input_type
# convert to satoshis
if input_type in ('btc', 'mbtc',... |
def info(self):
"""Get connection info."""
backend_cls = self.backend_cls or "amqplib"
port = self.port or self.create_backend().default_port
return {"hostname": self.hostname,
"userid": self.userid,
"password": self.password,
"virtual_host... | Get connection info. | Below is the the instruction that describes the task:
### Input:
Get connection info.
### Response:
def info(self):
"""Get connection info."""
backend_cls = self.backend_cls or "amqplib"
port = self.port or self.create_backend().default_port
return {"hostname": self.hostname,
... |
def category(msg):
"""Aircraft category number
Args:
msg (string): 28 bytes hexadecimal message string
Returns:
int: category number
"""
if common.typecode(msg) < 1 or common.typecode(msg) > 4:
raise RuntimeError("%s: Not a identification message" % msg)
msgbin = comm... | Aircraft category number
Args:
msg (string): 28 bytes hexadecimal message string
Returns:
int: category number | Below is the the instruction that describes the task:
### Input:
Aircraft category number
Args:
msg (string): 28 bytes hexadecimal message string
Returns:
int: category number
### Response:
def category(msg):
"""Aircraft category number
Args:
msg (string): 28 bytes hexade... |
def parse(cls, data: bytes) -> 'MessageContent':
"""Parse the bytestring into message content.
Args:
data: The bytestring to parse.
"""
lines = cls._find_lines(data)
view = memoryview(data)
return cls._parse(data, view, lines) | Parse the bytestring into message content.
Args:
data: The bytestring to parse. | Below is the the instruction that describes the task:
### Input:
Parse the bytestring into message content.
Args:
data: The bytestring to parse.
### Response:
def parse(cls, data: bytes) -> 'MessageContent':
"""Parse the bytestring into message content.
Args:
data:... |
def get_servo_torque(self):
""" Gets the current torque of Herkulex
Gives the current load on the servo shaft.
It is actually the PWM value to the motors
Args:
none
Returns:
int: the torque on servo shaft. range from -1023 to 1023
Raises:
... | Gets the current torque of Herkulex
Gives the current load on the servo shaft.
It is actually the PWM value to the motors
Args:
none
Returns:
int: the torque on servo shaft. range from -1023 to 1023
Raises:
SerialException: Error occured wh... | Below is the the instruction that describes the task:
### Input:
Gets the current torque of Herkulex
Gives the current load on the servo shaft.
It is actually the PWM value to the motors
Args:
none
Returns:
int: the torque on servo shaft. range from -1023 t... |
def remove_functions(source, all_inline=False):
"""removes functions and returns new source, and 2 dicts.
first dict with removed hoisted(global) functions and second with replaced inline functions"""
global INLINE_COUNT
inline = {}
hoisted = {}
n = 0
limit = len(source) - 9 # 8 is leng... | removes functions and returns new source, and 2 dicts.
first dict with removed hoisted(global) functions and second with replaced inline functions | Below is the the instruction that describes the task:
### Input:
removes functions and returns new source, and 2 dicts.
first dict with removed hoisted(global) functions and second with replaced inline functions
### Response:
def remove_functions(source, all_inline=False):
"""removes functions and retu... |
def org_remove_member(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /org-xxxx/removeMember API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Organizations#API-method%3A-%2Forg-xxxx%2FremoveMember
"""
return DXHTTPRequest('/%s/removeMember... | Invokes the /org-xxxx/removeMember API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Organizations#API-method%3A-%2Forg-xxxx%2FremoveMember | Below is the the instruction that describes the task:
### Input:
Invokes the /org-xxxx/removeMember API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Organizations#API-method%3A-%2Forg-xxxx%2FremoveMember
### Response:
def org_remove_member(object_id, input_params={}, always_r... |
def do_levmarq_n_directions(s, directions, max_iter=2, run_length=2,
damping=1e-3, collect_stats=False, marquardt_damping=True, **kwargs):
"""
Optimization of a state along a specific set of directions in parameter
space.
Parameters
----------
s : :class:`peri.states.State`
... | Optimization of a state along a specific set of directions in parameter
space.
Parameters
----------
s : :class:`peri.states.State`
The state to optimize
directions : np.ndarray
[n,d] element numpy.ndarray of the n directions in the d-
dimensional space t... | Below is the the instruction that describes the task:
### Input:
Optimization of a state along a specific set of directions in parameter
space.
Parameters
----------
s : :class:`peri.states.State`
The state to optimize
directions : np.ndarray
[n,d] element numpy.... |
def group_subscribe(self, topics):
"""Add topics to the current group subscription.
This is used by the group leader to ensure that it receives metadata
updates for all topics that any member of the group is subscribed to.
Arguments:
topics (list of str): topics to add to t... | Add topics to the current group subscription.
This is used by the group leader to ensure that it receives metadata
updates for all topics that any member of the group is subscribed to.
Arguments:
topics (list of str): topics to add to the group subscription | Below is the the instruction that describes the task:
### Input:
Add topics to the current group subscription.
This is used by the group leader to ensure that it receives metadata
updates for all topics that any member of the group is subscribed to.
Arguments:
topics (list of s... |
def get_groups_of_user(self, user_id, **kwargs): # noqa: E501
"""Get groups of the user. # noqa: E501
An endpoint for retrieving groups of the user. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/users/{user-id}/groups -H 'Authorization: Bearer API_KEY'` # noqa: E501
This ... | Get groups of the user. # noqa: E501
An endpoint for retrieving groups of the user. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/users/{user-id}/groups -H 'Authorization: Bearer API_KEY'` # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asy... | Below is the the instruction that describes the task:
### Input:
Get groups of the user. # noqa: E501
An endpoint for retrieving groups of the user. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/users/{user-id}/groups -H 'Authorization: Bearer API_KEY'` # noqa: E501
This metho... |
def media_type_str(mediatype):
"""Convert internal API media type to string."""
if mediatype == const.MEDIA_TYPE_UNKNOWN:
return 'Unknown'
if mediatype == const.MEDIA_TYPE_VIDEO:
return 'Video'
if mediatype == const.MEDIA_TYPE_MUSIC:
return 'Music'
if mediatype == const.MEDIA... | Convert internal API media type to string. | Below is the the instruction that describes the task:
### Input:
Convert internal API media type to string.
### Response:
def media_type_str(mediatype):
"""Convert internal API media type to string."""
if mediatype == const.MEDIA_TYPE_UNKNOWN:
return 'Unknown'
if mediatype == const.MEDIA_TYPE_V... |
def qname(self, stmt):
"""Return (prefixed) node name of `stmt`.
The result is prefixed with the local prefix unless we are
inside a global grouping.
"""
if self.gg_level: return stmt.arg
return self.prefix_stack[-1] + ":" + stmt.arg | Return (prefixed) node name of `stmt`.
The result is prefixed with the local prefix unless we are
inside a global grouping. | Below is the the instruction that describes the task:
### Input:
Return (prefixed) node name of `stmt`.
The result is prefixed with the local prefix unless we are
inside a global grouping.
### Response:
def qname(self, stmt):
"""Return (prefixed) node name of `stmt`.
The result is... |
def ready(self, node_id, metadata_priority=True):
"""Check whether a node is connected and ok to send more requests.
Arguments:
node_id (int): the id of the node to check
metadata_priority (bool): Mark node as not-ready if a metadata
refresh is required. Default:... | Check whether a node is connected and ok to send more requests.
Arguments:
node_id (int): the id of the node to check
metadata_priority (bool): Mark node as not-ready if a metadata
refresh is required. Default: True
Returns:
bool: True if we are read... | Below is the the instruction that describes the task:
### Input:
Check whether a node is connected and ok to send more requests.
Arguments:
node_id (int): the id of the node to check
metadata_priority (bool): Mark node as not-ready if a metadata
refresh is required. ... |
def startPacketCapture(self, pcap_output_file, pcap_data_link_type="DLT_EN10MB"):
"""
:param pcap_output_file: PCAP destination file for the capture
:param pcap_data_link_type: PCAP data link type (DLT_*), default is DLT_EN10MB
"""
self._capturing = True
self._pcap_outpu... | :param pcap_output_file: PCAP destination file for the capture
:param pcap_data_link_type: PCAP data link type (DLT_*), default is DLT_EN10MB | Below is the the instruction that describes the task:
### Input:
:param pcap_output_file: PCAP destination file for the capture
:param pcap_data_link_type: PCAP data link type (DLT_*), default is DLT_EN10MB
### Response:
def startPacketCapture(self, pcap_output_file, pcap_data_link_type="DLT_EN10MB"):
... |
def get_pstats_print2list(fnames, filter_fnames=None, exclude_fnames=None,
sort=None, sort_reverse=None, limit=None):
"""Print stats with a filter or exclude filenames, sort index and limit.
:param list fnames: cProfile standard files to process.
:param list filter_fnames: Relative... | Print stats with a filter or exclude filenames, sort index and limit.
:param list fnames: cProfile standard files to process.
:param list filter_fnames: Relative paths to filter and show them.
:param list exclude_fnames: Relative paths to avoid show them.
:param str sort: Standard `pstats` key of value ... | Below is the the instruction that describes the task:
### Input:
Print stats with a filter or exclude filenames, sort index and limit.
:param list fnames: cProfile standard files to process.
:param list filter_fnames: Relative paths to filter and show them.
:param list exclude_fnames: Relative paths to ... |
def validate(self):
"""Validate the configuration against its contract.
:raises DbtProjectError: If the configuration fails validation.
"""
try:
Configuration(**self.serialize())
except ValidationException as e:
raise DbtProjectError(str(e))
if g... | Validate the configuration against its contract.
:raises DbtProjectError: If the configuration fails validation. | Below is the the instruction that describes the task:
### Input:
Validate the configuration against its contract.
:raises DbtProjectError: If the configuration fails validation.
### Response:
def validate(self):
"""Validate the configuration against its contract.
:raises DbtProjectError: ... |
def to_dict(self):
"""Convert to a nested dict. """
return {k: v.to_dict() if isinstance(v, AttrDict) else v
for k, v in self.__dict__.items() if not k.startswith('_')} | Convert to a nested dict. | Below is the the instruction that describes the task:
### Input:
Convert to a nested dict.
### Response:
def to_dict(self):
"""Convert to a nested dict. """
return {k: v.to_dict() if isinstance(v, AttrDict) else v
for k, v in self.__dict__.items() if not k.startswith('_')} |
def _load_library(library_names, library_file_extensions,
library_search_paths, version_check_callback):
"""
Finds, loads and returns the most recent version of the library.
"""
candidates = _find_library_candidates(library_names,
library_file_... | Finds, loads and returns the most recent version of the library. | Below is the the instruction that describes the task:
### Input:
Finds, loads and returns the most recent version of the library.
### Response:
def _load_library(library_names, library_file_extensions,
library_search_paths, version_check_callback):
"""
Finds, loads and returns the most re... |
def _determine_uses(self, included_files, forward_declarations):
"""Set up the use type of each symbol."""
file_uses = dict.fromkeys(included_files, UNUSED)
decl_uses = dict.fromkeys(forward_declarations, UNUSED)
symbol_table = self.symbol_table
for name, node in forward_declara... | Set up the use type of each symbol. | Below is the the instruction that describes the task:
### Input:
Set up the use type of each symbol.
### Response:
def _determine_uses(self, included_files, forward_declarations):
"""Set up the use type of each symbol."""
file_uses = dict.fromkeys(included_files, UNUSED)
decl_uses = dict.fr... |
def convertWCS(inwcs,drizwcs):
""" Copy WCSObject WCS into Drizzle compatible array."""
drizwcs[0] = inwcs.crpix[0]
drizwcs[1] = inwcs.crval[0]
drizwcs[2] = inwcs.crpix[1]
drizwcs[3] = inwcs.crval[1]
drizwcs[4] = inwcs.cd[0][0]
drizwcs[5] = inwcs.cd[1][0]
drizwcs[6] = inwcs.cd[0][1]
... | Copy WCSObject WCS into Drizzle compatible array. | Below is the the instruction that describes the task:
### Input:
Copy WCSObject WCS into Drizzle compatible array.
### Response:
def convertWCS(inwcs,drizwcs):
""" Copy WCSObject WCS into Drizzle compatible array."""
drizwcs[0] = inwcs.crpix[0]
drizwcs[1] = inwcs.crval[0]
drizwcs[2] = inwcs.crpix[1... |
def _process_stock_genotype(self, limit):
"""
The genotypes of the stocks.
:param limit:
:return:
"""
if self.test_mode:
graph = self.testgraph
else:
graph = self.graph
raw = '/'.join((self.rawdir, 'stock_genotype'))
LOG.... | The genotypes of the stocks.
:param limit:
:return: | Below is the the instruction that describes the task:
### Input:
The genotypes of the stocks.
:param limit:
:return:
### Response:
def _process_stock_genotype(self, limit):
"""
The genotypes of the stocks.
:param limit:
:return:
"""
if self.test_mo... |
def reset (self):
"""
Reset all variables to default values.
"""
# self.url is constructed by self.build_url() out of base_url
# and (base_ref or parent) as absolute and normed url.
# This the real url we use when checking so it also referred to
# as 'real url'
... | Reset all variables to default values. | Below is the the instruction that describes the task:
### Input:
Reset all variables to default values.
### Response:
def reset (self):
"""
Reset all variables to default values.
"""
# self.url is constructed by self.build_url() out of base_url
# and (base_ref or parent) as ... |
def ParseArguments(self):
"""Parses the command line arguments.
Returns:
bool: True if the arguments were successfully parsed.
"""
loggers.ConfigureLogging()
argument_parser = argparse.ArgumentParser(
description=self.DESCRIPTION, epilog=self.EPILOG, add_help=False,
formatter... | Parses the command line arguments.
Returns:
bool: True if the arguments were successfully parsed. | Below is the the instruction that describes the task:
### Input:
Parses the command line arguments.
Returns:
bool: True if the arguments were successfully parsed.
### Response:
def ParseArguments(self):
"""Parses the command line arguments.
Returns:
bool: True if the arguments were succes... |
def get_compiler(self, using=None, connection=None):
""" Overrides the Query method get_compiler in order to return
an instance of the above custom compiler.
"""
# Copy the body of this method from Django except the final
# return statement. We will ignore code coverage for t... | Overrides the Query method get_compiler in order to return
an instance of the above custom compiler. | Below is the the instruction that describes the task:
### Input:
Overrides the Query method get_compiler in order to return
an instance of the above custom compiler.
### Response:
def get_compiler(self, using=None, connection=None):
""" Overrides the Query method get_compiler in order to return... |
def update_load_balancer(access_token, subscription_id, resource_group, lb_name, body):
'''Updates a load balancer model, i.e. PUT an updated LB body.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure ... | Updates a load balancer model, i.e. PUT an updated LB body.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.
lb_name (str): Name of the new load balancer.
body (str): ... | Below is the the instruction that describes the task:
### Input:
Updates a load balancer model, i.e. PUT an updated LB body.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.
... |
def process_insert_get_id(self, query, sql, values, sequence=None):
"""
Process an "insert get ID" query.
:param query: A QueryBuilder instance
:type query: QueryBuilder
:param sql: The sql query to execute
:type sql: str
:param values: The value bindings
... | Process an "insert get ID" query.
:param query: A QueryBuilder instance
:type query: QueryBuilder
:param sql: The sql query to execute
:type sql: str
:param values: The value bindings
:type values: list
:param sequence: The ids sequence
:type sequence:... | Below is the the instruction that describes the task:
### Input:
Process an "insert get ID" query.
:param query: A QueryBuilder instance
:type query: QueryBuilder
:param sql: The sql query to execute
:type sql: str
:param values: The value bindings
:type values: li... |
def get_supported_permissions(self):
"""
Get permissions which this handler can treat.
Specified with :attr:`includes` and :attr:`excludes` of this instance.
Returns
-------
set
A set instance of `app_label.codename` formatted permission strings
"""
... | Get permissions which this handler can treat.
Specified with :attr:`includes` and :attr:`excludes` of this instance.
Returns
-------
set
A set instance of `app_label.codename` formatted permission strings | Below is the the instruction that describes the task:
### Input:
Get permissions which this handler can treat.
Specified with :attr:`includes` and :attr:`excludes` of this instance.
Returns
-------
set
A set instance of `app_label.codename` formatted permission strings
#... |
def _process_keystroke_commands(self, inp):
"""Process keystrokes that issue commands (side effects)."""
if inp in (u'1', u'2'):
# chose 1 or 2-character wide
if int(inp) != self.screen.wide:
self.screen.wide = int(inp)
self.on_resize(None, None)
... | Process keystrokes that issue commands (side effects). | Below is the the instruction that describes the task:
### Input:
Process keystrokes that issue commands (side effects).
### Response:
def _process_keystroke_commands(self, inp):
"""Process keystrokes that issue commands (side effects)."""
if inp in (u'1', u'2'):
# chose 1 or 2-character... |
def version_object_and_next(string, retries=0): # type: (str, int) -> VersionThing
"""
Try three parsing strategies, favoring semver, then pep440, then whatev.
:param string:
:return:
"""
if retries > 2:
raise JiggleVersionException(
"Can't parse, ran out of retries: " + uni... | Try three parsing strategies, favoring semver, then pep440, then whatev.
:param string:
:return: | Below is the the instruction that describes the task:
### Input:
Try three parsing strategies, favoring semver, then pep440, then whatev.
:param string:
:return:
### Response:
def version_object_and_next(string, retries=0): # type: (str, int) -> VersionThing
"""
Try three parsing strategies, favor... |
def find_following_working_day(self, day):
"""Looks for the following working day, if not already a working day.
**WARNING**: this function doesn't take into account the calendar
holidays, only the days of the week and the weekend days parameters.
"""
day = cleaned_date(day)
... | Looks for the following working day, if not already a working day.
**WARNING**: this function doesn't take into account the calendar
holidays, only the days of the week and the weekend days parameters. | Below is the the instruction that describes the task:
### Input:
Looks for the following working day, if not already a working day.
**WARNING**: this function doesn't take into account the calendar
holidays, only the days of the week and the weekend days parameters.
### Response:
def find_followin... |
def multiget_count(self, keys, column_parent, predicate, consistency_level):
"""
Perform a get_count in parallel on the given list<binary> keys. The return value maps keys to the count found.
Parameters:
- keys
- column_parent
- predicate
- consistency_level
"""
self._seqid += 1... | Perform a get_count in parallel on the given list<binary> keys. The return value maps keys to the count found.
Parameters:
- keys
- column_parent
- predicate
- consistency_level | Below is the the instruction that describes the task:
### Input:
Perform a get_count in parallel on the given list<binary> keys. The return value maps keys to the count found.
Parameters:
- keys
- column_parent
- predicate
- consistency_level
### Response:
def multiget_count(self, keys, co... |
def meta_retrieve(self, meta_lookahead = None):
"""
Get metadata from the query itself. This is guaranteed to only
return a Python dictionary.
Note that if the query failed, the metadata might not be in JSON
format, in which case there may be additional, non-JSON data
wh... | Get metadata from the query itself. This is guaranteed to only
return a Python dictionary.
Note that if the query failed, the metadata might not be in JSON
format, in which case there may be additional, non-JSON data
which can be retrieved using the following
::
ra... | Below is the the instruction that describes the task:
### Input:
Get metadata from the query itself. This is guaranteed to only
return a Python dictionary.
Note that if the query failed, the metadata might not be in JSON
format, in which case there may be additional, non-JSON data
w... |
def list_containers(self):
"""
List all available docker containers.
Container objects returned from this methods will contain a limited
amount of metadata in property `short_metadata`. These are just a subset
of `.inspect()`, but don't require an API call against dockerd.
... | List all available docker containers.
Container objects returned from this methods will contain a limited
amount of metadata in property `short_metadata`. These are just a subset
of `.inspect()`, but don't require an API call against dockerd.
:return: collection of instances of :class:... | Below is the the instruction that describes the task:
### Input:
List all available docker containers.
Container objects returned from this methods will contain a limited
amount of metadata in property `short_metadata`. These are just a subset
of `.inspect()`, but don't require an API call ... |
def get_dag(self, dag_id):
"""
:param dag_id: DAG ID
:type dag_id: unicode
:return: if the given DAG ID exists in the bag, return the BaseDag
corresponding to that ID. Otherwise, throw an Exception
:rtype: airflow.utils.dag_processing.SimpleDag
"""
if dag_... | :param dag_id: DAG ID
:type dag_id: unicode
:return: if the given DAG ID exists in the bag, return the BaseDag
corresponding to that ID. Otherwise, throw an Exception
:rtype: airflow.utils.dag_processing.SimpleDag | Below is the the instruction that describes the task:
### Input:
:param dag_id: DAG ID
:type dag_id: unicode
:return: if the given DAG ID exists in the bag, return the BaseDag
corresponding to that ID. Otherwise, throw an Exception
:rtype: airflow.utils.dag_processing.SimpleDag
### R... |
def _set_af_vrf_name(self, v, load=False):
"""
Setter method for af_vrf_name, mapped from YANG variable /routing_system/router/router_bgp/address_family/ipv4/ipv4_unicast/af_vrf/af_vrf_name (string)
If this variable is read-only (config: false) in the
source YANG file, then _set_af_vrf_name is considere... | Setter method for af_vrf_name, mapped from YANG variable /routing_system/router/router_bgp/address_family/ipv4/ipv4_unicast/af_vrf/af_vrf_name (string)
If this variable is read-only (config: false) in the
source YANG file, then _set_af_vrf_name is considered as a private
method. Backends looking to populate... | Below is the the instruction that describes the task:
### Input:
Setter method for af_vrf_name, mapped from YANG variable /routing_system/router/router_bgp/address_family/ipv4/ipv4_unicast/af_vrf/af_vrf_name (string)
If this variable is read-only (config: false) in the
source YANG file, then _set_af_vrf_nam... |
def lookup(self, path_info: str) -> MatchResult:
""" lookup url match for path_info
"""
for name, pattern in self.patterns.items():
match = pattern.match(path_info)
if match is None:
continue
match.name = name
return match
r... | lookup url match for path_info | Below is the the instruction that describes the task:
### Input:
lookup url match for path_info
### Response:
def lookup(self, path_info: str) -> MatchResult:
""" lookup url match for path_info
"""
for name, pattern in self.patterns.items():
match = pattern.match(path_info)
... |
def load(f):
"""Load audio metadata from filepath or file-like object.
Parameters:
f (str, os.PathLike, or file-like object):
A filepath, path-like object or file-like object of an audio file.
Returns:
Format: An audio format object.
Raises:
UnsupportedFormat: If file is not of a supported format.
Val... | Load audio metadata from filepath or file-like object.
Parameters:
f (str, os.PathLike, or file-like object):
A filepath, path-like object or file-like object of an audio file.
Returns:
Format: An audio format object.
Raises:
UnsupportedFormat: If file is not of a supported format.
ValueError: If filep... | Below is the the instruction that describes the task:
### Input:
Load audio metadata from filepath or file-like object.
Parameters:
f (str, os.PathLike, or file-like object):
A filepath, path-like object or file-like object of an audio file.
Returns:
Format: An audio format object.
Raises:
Unsupporte... |
def build(self, package_dir, output_style='nested'):
"""Builds the Sass/SCSS files in the specified :attr:`sass_path`.
It finds :attr:`sass_path` and locates :attr:`css_path`
as relative to the given ``package_dir``.
:param package_dir: the path of package directory
:type packag... | Builds the Sass/SCSS files in the specified :attr:`sass_path`.
It finds :attr:`sass_path` and locates :attr:`css_path`
as relative to the given ``package_dir``.
:param package_dir: the path of package directory
:type package_dir: :class:`str`, :class:`basestring`
:param output_s... | Below is the the instruction that describes the task:
### Input:
Builds the Sass/SCSS files in the specified :attr:`sass_path`.
It finds :attr:`sass_path` and locates :attr:`css_path`
as relative to the given ``package_dir``.
:param package_dir: the path of package directory
:type p... |
def request(self, hash_, quickkey, doc_type, page=None,
output=None, size_id=None, metadata=None,
request_conversion_only=None):
"""Query conversion server
hash_: 4 characters of file hash
quickkey: File quickkey
doc_type: "i" for image, "d" for documents... | Query conversion server
hash_: 4 characters of file hash
quickkey: File quickkey
doc_type: "i" for image, "d" for documents
page: The page to convert. If page is set to 'initial', the first
10 pages of the document will be provided. (document)
output: "pdf", "img",... | Below is the the instruction that describes the task:
### Input:
Query conversion server
hash_: 4 characters of file hash
quickkey: File quickkey
doc_type: "i" for image, "d" for documents
page: The page to convert. If page is set to 'initial', the first
10 pages of th... |
def on_event(self, event):
"""Pygame event processing callback method.
:param event: Event to process.
"""
if self.state > 0:
if event.type == MOUSEBUTTONDOWN:
key = self.layout.get_key_at(pygame.mouse.get_pos())
if key is not None:
... | Pygame event processing callback method.
:param event: Event to process. | Below is the the instruction that describes the task:
### Input:
Pygame event processing callback method.
:param event: Event to process.
### Response:
def on_event(self, event):
"""Pygame event processing callback method.
:param event: Event to process.
"""
if self.state ... |
def set_message_last_post(cr, uid, pool, models):
"""
Given a list of models, set their 'message_last_post' fields to an
estimated last post datetime.
To be called in post-migration scripts
:param cr: database cursor
:param uid: user id, assumed to be openerp.SUPERUSER_ID
:param pool: orm p... | Given a list of models, set their 'message_last_post' fields to an
estimated last post datetime.
To be called in post-migration scripts
:param cr: database cursor
:param uid: user id, assumed to be openerp.SUPERUSER_ID
:param pool: orm pool, assumed to be openerp.pooler.get_pool(cr.dbname)
:par... | Below is the the instruction that describes the task:
### Input:
Given a list of models, set their 'message_last_post' fields to an
estimated last post datetime.
To be called in post-migration scripts
:param cr: database cursor
:param uid: user id, assumed to be openerp.SUPERUSER_ID
:param pool... |
def load_yaml(filename):
"""
Loads a YAML-formatted file.
"""
with open(filename) as f:
ydoc = yaml.safe_load(f.read())
return (ydoc, serialize_tojson(ydoc)) | Loads a YAML-formatted file. | Below is the the instruction that describes the task:
### Input:
Loads a YAML-formatted file.
### Response:
def load_yaml(filename):
"""
Loads a YAML-formatted file.
"""
with open(filename) as f:
ydoc = yaml.safe_load(f.read())
return (ydoc, serialize_tojson(ydoc)) |
def gradient(self, wrt):
"""Gets the autodiff of current symbol.
This function can only be used if current symbol is a loss function.
.. note:: This function is currently not implemented.
Parameters
----------
wrt : Array of String
keyword arguments of the ... | Gets the autodiff of current symbol.
This function can only be used if current symbol is a loss function.
.. note:: This function is currently not implemented.
Parameters
----------
wrt : Array of String
keyword arguments of the symbol that the gradients are taken.... | Below is the the instruction that describes the task:
### Input:
Gets the autodiff of current symbol.
This function can only be used if current symbol is a loss function.
.. note:: This function is currently not implemented.
Parameters
----------
wrt : Array of String
... |
def bundle_visualization_url(self, bundle_id, channel=None):
'''Generate the path to the visualization for bundles.
@param charm_id The ID of the bundle.
@param channel Optional channel name.
@return The url to the visualization.
'''
url = '{}/{}/diagram.svg'.format(self... | Generate the path to the visualization for bundles.
@param charm_id The ID of the bundle.
@param channel Optional channel name.
@return The url to the visualization. | Below is the the instruction that describes the task:
### Input:
Generate the path to the visualization for bundles.
@param charm_id The ID of the bundle.
@param channel Optional channel name.
@return The url to the visualization.
### Response:
def bundle_visualization_url(self, bundle_id,... |
def _ProcessPathSpec(self, extraction_worker, parser_mediator, path_spec):
"""Processes a path specification.
Args:
extraction_worker (worker.ExtractionWorker): extraction worker.
parser_mediator (ParserMediator): parser mediator.
path_spec (dfvfs.PathSpec): path specification.
"""
se... | Processes a path specification.
Args:
extraction_worker (worker.ExtractionWorker): extraction worker.
parser_mediator (ParserMediator): parser mediator.
path_spec (dfvfs.PathSpec): path specification. | Below is the the instruction that describes the task:
### Input:
Processes a path specification.
Args:
extraction_worker (worker.ExtractionWorker): extraction worker.
parser_mediator (ParserMediator): parser mediator.
path_spec (dfvfs.PathSpec): path specification.
### Response:
def _Process... |
def set_input_score_end_range(self, score):
"""Sets the input score start range.
arg: score (decimal): the new start range
raise: InvalidArgument - ``score`` is invalid
raise: NoAccess - ``range`` cannot be modified
*compliance: mandatory -- This method must be implemented.... | Sets the input score start range.
arg: score (decimal): the new start range
raise: InvalidArgument - ``score`` is invalid
raise: NoAccess - ``range`` cannot be modified
*compliance: mandatory -- This method must be implemented.* | Below is the the instruction that describes the task:
### Input:
Sets the input score start range.
arg: score (decimal): the new start range
raise: InvalidArgument - ``score`` is invalid
raise: NoAccess - ``range`` cannot be modified
*compliance: mandatory -- This method must b... |
def verify_eth_transaction(signed_hextx, eth_data_field):
"""
Verify ethDataField field in transaction
:param signed_hextx:
:param eth_data_field:
:return:
"""
logging.info('verifying ethDataField value for transaction')
ethdata_hash = []
for s in signed_hextx.split('80a0'):
... | Verify ethDataField field in transaction
:param signed_hextx:
:param eth_data_field:
:return: | Below is the the instruction that describes the task:
### Input:
Verify ethDataField field in transaction
:param signed_hextx:
:param eth_data_field:
:return:
### Response:
def verify_eth_transaction(signed_hextx, eth_data_field):
"""
Verify ethDataField field in transaction
:param signed_h... |
async def info(self):
"""Return device info."""
"""
{'MasterCapability': 9, 'TransportPort': 3975}
"""
act = self.service.action("X_GetDeviceInfo")
res = await act.async_call()
return res | Return device info. | Below is the the instruction that describes the task:
### Input:
Return device info.
### Response:
async def info(self):
"""Return device info."""
"""
{'MasterCapability': 9, 'TransportPort': 3975}
"""
act = self.service.action("X_GetDeviceInfo")
res = await act.asyn... |
def p_stringValueList(p):
"""stringValueList : stringValue
| stringValueList stringValue
"""
if len(p) == 2:
p[0] = _fixStringValue(p[1], p)
else:
p[0] = p[1] + _fixStringValue(p[2], p) | stringValueList : stringValue
| stringValueList stringValue | Below is the the instruction that describes the task:
### Input:
stringValueList : stringValue
| stringValueList stringValue
### Response:
def p_stringValueList(p):
"""stringValueList : stringValue
| stringValueList stringValue
"""
if len... |
def write_svg(self):
"""
Returns PUML from the system as a SVG image. Requires plantuml library.
"""
import plantuml
puml = self.write_puml()
server = plantuml.PlantUML(url=self.url)
svg = server.processes(puml)
return svg | Returns PUML from the system as a SVG image. Requires plantuml library. | Below is the the instruction that describes the task:
### Input:
Returns PUML from the system as a SVG image. Requires plantuml library.
### Response:
def write_svg(self):
"""
Returns PUML from the system as a SVG image. Requires plantuml library.
"""
import plantuml
pum... |
def unget_service(self, service):
# type: (Any) -> bool
"""
Releases a service object for the associated service.
:param service: An instance of a service returned by ``get_service()``
:return: True if the bundle usage has been removed
"""
return self.__registry.... | Releases a service object for the associated service.
:param service: An instance of a service returned by ``get_service()``
:return: True if the bundle usage has been removed | Below is the the instruction that describes the task:
### Input:
Releases a service object for the associated service.
:param service: An instance of a service returned by ``get_service()``
:return: True if the bundle usage has been removed
### Response:
def unget_service(self, service):
#... |
def _write_mflist_ins(ins_filename,df,prefix):
""" write an instruction file for a MODFLOW list file
Parameters
----------
ins_filename : str
name of the instruction file to write
df : pandas.DataFrame
the dataframe of list file entries
prefix : str
the prefix to add to ... | write an instruction file for a MODFLOW list file
Parameters
----------
ins_filename : str
name of the instruction file to write
df : pandas.DataFrame
the dataframe of list file entries
prefix : str
the prefix to add to the column names to form
obseravtions names | Below is the the instruction that describes the task:
### Input:
write an instruction file for a MODFLOW list file
Parameters
----------
ins_filename : str
name of the instruction file to write
df : pandas.DataFrame
the dataframe of list file entries
prefix : str
the pre... |
def fix_config(self, options):
"""
Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict
"""
opt = "setup"
... | Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict
### Response:
def fi... |
def create_from_snapshot(self, *args, **kwargs):
"""
Creates a Block Storage volume
Note: Every argument and parameter given to this method will be
assigned to the object.
Args:
name: string - a name for the volume
snapshot_id: string - unique identifier... | Creates a Block Storage volume
Note: Every argument and parameter given to this method will be
assigned to the object.
Args:
name: string - a name for the volume
snapshot_id: string - unique identifier for the volume snapshot
size_gigabytes: int - size of th... | Below is the the instruction that describes the task:
### Input:
Creates a Block Storage volume
Note: Every argument and parameter given to this method will be
assigned to the object.
Args:
name: string - a name for the volume
snapshot_id: string - unique identifier... |
def fit_linear(xdata, ydata):
"""
Returns slope and intercept of line of best fit:
y = a*x + b
through the supplied data.
Parameters
----------
xdata, ydata:
Arrays of x data and y data (having matching lengths).
"""
x = _n.array(xdata)
y = _n.arra... | Returns slope and intercept of line of best fit:
y = a*x + b
through the supplied data.
Parameters
----------
xdata, ydata:
Arrays of x data and y data (having matching lengths). | Below is the the instruction that describes the task:
### Input:
Returns slope and intercept of line of best fit:
y = a*x + b
through the supplied data.
Parameters
----------
xdata, ydata:
Arrays of x data and y data (having matching lengths).
### Response:
def fi... |
def create_scaling_policy(self, scaling_policy):
"""
Creates a new Scaling Policy.
:type scaling_policy: :class:`boto.ec2.autoscale.policy.ScalingPolicy`
:param scaling_policy: ScalingPolicy object.
"""
params = {'AdjustmentType': scaling_policy.adjustment_type,
... | Creates a new Scaling Policy.
:type scaling_policy: :class:`boto.ec2.autoscale.policy.ScalingPolicy`
:param scaling_policy: ScalingPolicy object. | Below is the the instruction that describes the task:
### Input:
Creates a new Scaling Policy.
:type scaling_policy: :class:`boto.ec2.autoscale.policy.ScalingPolicy`
:param scaling_policy: ScalingPolicy object.
### Response:
def create_scaling_policy(self, scaling_policy):
"""
Crea... |
def draw_cross(self, position, color=(255, 0, 0), radius=4):
"""Draw a cross on the canvas.
:param position: (row, col) tuple
:param color: RGB tuple
:param radius: radius of the cross (int)
"""
y, x = position
for xmod in np.arange(-radius, radius+1, 1):
... | Draw a cross on the canvas.
:param position: (row, col) tuple
:param color: RGB tuple
:param radius: radius of the cross (int) | Below is the the instruction that describes the task:
### Input:
Draw a cross on the canvas.
:param position: (row, col) tuple
:param color: RGB tuple
:param radius: radius of the cross (int)
### Response:
def draw_cross(self, position, color=(255, 0, 0), radius=4):
"""Draw a cross... |
def image_read(filename, dimension=None, pixeltype='float', reorient=False):
"""
Read an ANTsImage from file
ANTsR function: `antsImageRead`
Arguments
---------
filename : string
Name of the file to read the image from.
dimension : int
Number of dimensions of the image rea... | Read an ANTsImage from file
ANTsR function: `antsImageRead`
Arguments
---------
filename : string
Name of the file to read the image from.
dimension : int
Number of dimensions of the image read. This need not be the same as
the dimensions of the image in the file. Allowed ... | Below is the the instruction that describes the task:
### Input:
Read an ANTsImage from file
ANTsR function: `antsImageRead`
Arguments
---------
filename : string
Name of the file to read the image from.
dimension : int
Number of dimensions of the image read. This need not be ... |
def get_peptable_headerfields(headertypes, lookup=False, poolnames=False):
"""Called by driver to generate headerfields object"""
field_defs = {'isoquant': get_isoquant_fields,
'precursorquant': get_precursorquant_fields,
'peptidefdr': get_peptidefdr_fields,
... | Called by driver to generate headerfields object | Below is the the instruction that describes the task:
### Input:
Called by driver to generate headerfields object
### Response:
def get_peptable_headerfields(headertypes, lookup=False, poolnames=False):
"""Called by driver to generate headerfields object"""
field_defs = {'isoquant': get_isoquant_fields,
... |
def _qualifiers_tomof(qualifiers, indent, maxline=MAX_MOF_LINE):
"""
Return a MOF string with the qualifier values, including the surrounding
square brackets. The qualifiers are ordered by their name.
Return empty string if no qualifiers.
Normally multiline output and may fold qualifiers into mult... | Return a MOF string with the qualifier values, including the surrounding
square brackets. The qualifiers are ordered by their name.
Return empty string if no qualifiers.
Normally multiline output and may fold qualifiers into multiple lines.
The order of qualifiers is preserved.
Parameters:
... | Below is the the instruction that describes the task:
### Input:
Return a MOF string with the qualifier values, including the surrounding
square brackets. The qualifiers are ordered by their name.
Return empty string if no qualifiers.
Normally multiline output and may fold qualifiers into multiple lin... |
def extract(self, item, list_article_candidate):
"""Compares the extracted publish dates.
:param item: The corresponding NewscrawlerItem
:param list_article_candidate: A list, the list of ArticleCandidate-Objects which have been extracted
:return: A string, the most likely publish date
... | Compares the extracted publish dates.
:param item: The corresponding NewscrawlerItem
:param list_article_candidate: A list, the list of ArticleCandidate-Objects which have been extracted
:return: A string, the most likely publish date | Below is the the instruction that describes the task:
### Input:
Compares the extracted publish dates.
:param item: The corresponding NewscrawlerItem
:param list_article_candidate: A list, the list of ArticleCandidate-Objects which have been extracted
:return: A string, the most likely publ... |
def sim(self, src, tar, threshold=0.25, max_mismatches=2):
"""Return the MLIPNS similarity of two strings.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
threshold : float
A number [... | Return the MLIPNS similarity of two strings.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
threshold : float
A number [0, 1] indicating the maximum similarity score, below
which... | Below is the the instruction that describes the task:
### Input:
Return the MLIPNS similarity of two strings.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
threshold : float
A number [0... |
def get_vertical_orientation_property(value, is_bytes=False):
"""Get `VO` property."""
obj = unidata.ascii_vertical_orientation if is_bytes else unidata.unicode_vertical_orientation
if value.startswith('^'):
negated = value[1:]
value = '^' + unidata.unicode_alias['verticalorientation'].get... | Get `VO` property. | Below is the the instruction that describes the task:
### Input:
Get `VO` property.
### Response:
def get_vertical_orientation_property(value, is_bytes=False):
"""Get `VO` property."""
obj = unidata.ascii_vertical_orientation if is_bytes else unidata.unicode_vertical_orientation
if value.startswith('... |
def list_gen(self, keyword=None, arg=None):
"""Generator for LIST command.
See list() for more information.
Yields:
An element in the list returned by list().
"""
if keyword:
keyword = keyword.upper()
if keyword is None or keyword == "ACTIVE":
... | Generator for LIST command.
See list() for more information.
Yields:
An element in the list returned by list(). | Below is the the instruction that describes the task:
### Input:
Generator for LIST command.
See list() for more information.
Yields:
An element in the list returned by list().
### Response:
def list_gen(self, keyword=None, arg=None):
"""Generator for LIST command.
Se... |
def to_coo(self, fp=None, vartype_header=False):
"""Serialize the binary quadratic model to a COOrdinate_ format encoding.
.. _COOrdinate: https://en.wikipedia.org/wiki/Sparse_matrix#Coordinate_list_(COO)
Args:
fp (file, optional):
`.write()`-supporting `file object... | Serialize the binary quadratic model to a COOrdinate_ format encoding.
.. _COOrdinate: https://en.wikipedia.org/wiki/Sparse_matrix#Coordinate_list_(COO)
Args:
fp (file, optional):
`.write()`-supporting `file object`_ to save the linear and quadratic biases
o... | Below is the the instruction that describes the task:
### Input:
Serialize the binary quadratic model to a COOrdinate_ format encoding.
.. _COOrdinate: https://en.wikipedia.org/wiki/Sparse_matrix#Coordinate_list_(COO)
Args:
fp (file, optional):
`.write()`-supporting `fi... |
def _read_stream_as_string(stream, encoding):
"""Read stream as string
Originally in azure-batch-samples.Python.Batch.common.helpers
:param stream: input stream generator
:param str encoding: The encoding of the file. The default is utf-8.
:return: The file content.
:rtype: str
"""
outp... | Read stream as string
Originally in azure-batch-samples.Python.Batch.common.helpers
:param stream: input stream generator
:param str encoding: The encoding of the file. The default is utf-8.
:return: The file content.
:rtype: str | Below is the the instruction that describes the task:
### Input:
Read stream as string
Originally in azure-batch-samples.Python.Batch.common.helpers
:param stream: input stream generator
:param str encoding: The encoding of the file. The default is utf-8.
:return: The file content.
:rtype: str
... |
def read(self, timeout=20.0):
"""
read data on the IN endpoint associated to the HID interface
"""
start = time()
while len(self.rcv_data) == 0:
sleep(0)
if time() - start > timeout:
# Read operations should typically take ~1-2ms.
... | read data on the IN endpoint associated to the HID interface | Below is the the instruction that describes the task:
### Input:
read data on the IN endpoint associated to the HID interface
### Response:
def read(self, timeout=20.0):
"""
read data on the IN endpoint associated to the HID interface
"""
start = time()
while len(self.rcv_da... |
def copy(self):
"""Copy text to clipboard"""
if not self.selectedIndexes():
return
(row_min, row_max,
col_min, col_max) = get_idx_rect(self.selectedIndexes())
index = header = False
df = self.model().df
obj = df.iloc[slice(row_min, row_max + 1... | Copy text to clipboard | Below is the the instruction that describes the task:
### Input:
Copy text to clipboard
### Response:
def copy(self):
"""Copy text to clipboard"""
if not self.selectedIndexes():
return
(row_min, row_max,
col_min, col_max) = get_idx_rect(self.selectedIndexes())
... |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: FunctionContext for this FunctionInstance
:rtype: twilio.rest.serverless.v1.service.function.Func... | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: FunctionContext for this FunctionInstance
:rtype: twilio.rest.serverless.v1.service.function.FunctionContext | Below is the the instruction that describes the task:
### Input:
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: FunctionContext for this FunctionInstance
:rtype: twilio.rest.serv... |
def add_case(self, case_obj):
"""Add a case obj with individuals to adapter
Args:
case_obj (puzzle.models.Case)
"""
for ind_obj in case_obj.individuals:
self._add_individual(ind_obj)
logger.debug("Adding case {0} to plugin... | Add a case obj with individuals to adapter
Args:
case_obj (puzzle.models.Case) | Below is the the instruction that describes the task:
### Input:
Add a case obj with individuals to adapter
Args:
case_obj (puzzle.models.Case)
### Response:
def add_case(self, case_obj):
"""Add a case obj with individuals to adapter
Args:
... |
def _setup_xauth(self):
'''
Set up the Xauthority file and the XAUTHORITY environment variable.
'''
handle, filename = tempfile.mkstemp(prefix='PyVirtualDisplay.',
suffix='.Xauthority')
self._xauth_filename = filename
os.close(h... | Set up the Xauthority file and the XAUTHORITY environment variable. | Below is the the instruction that describes the task:
### Input:
Set up the Xauthority file and the XAUTHORITY environment variable.
### Response:
def _setup_xauth(self):
'''
Set up the Xauthority file and the XAUTHORITY environment variable.
'''
handle, filename = tempfile.mkstemp(... |
def load(self, config):
"""load the configuration"""
self.config = config
if 'start' not in self.config:
raise ParseError('missing start entry')
if 'states' not in self.config:
raise ParseError('missing states entry')
if 'transitions' not in self.... | load the configuration | Below is the the instruction that describes the task:
### Input:
load the configuration
### Response:
def load(self, config):
"""load the configuration"""
self.config = config
if 'start' not in self.config:
raise ParseError('missing start entry')
if 'states' not... |
def cli(ctx, hpo_term, check_terms, output, p_value_limit, verbose, username,
password, to_json):
"Give hpo terms either on the form 'HP:0001623', or '0001623'"
loglevel = LEVELS.get(min(verbose, 3))
configure_stream(level=loglevel)
if not hpo_term:
logger.info("Please specify ... | Give hpo terms either on the form 'HP:0001623', or '0001623 | Below is the the instruction that describes the task:
### Input:
Give hpo terms either on the form 'HP:0001623', or '0001623
### Response:
def cli(ctx, hpo_term, check_terms, output, p_value_limit, verbose, username,
password, to_json):
"Give hpo terms either on the form 'HP:0001623', or '0001623'" ... |
def differential_pressure_meter_solver(D, rho, mu, k, D2=None, P1=None, P2=None,
m=None, meter_type=ISO_5167_ORIFICE,
taps=None):
r'''Calculates either the mass flow rate, the upstream pressure, the second
pressure value, or the ori... | r'''Calculates either the mass flow rate, the upstream pressure, the second
pressure value, or the orifice diameter for a differential
pressure flow meter based on the geometry of the meter, measured pressures
of the meter, and the density, viscosity, and isentropic exponent of the
fluid. This solves ... | Below is the the instruction that describes the task:
### Input:
r'''Calculates either the mass flow rate, the upstream pressure, the second
pressure value, or the orifice diameter for a differential
pressure flow meter based on the geometry of the meter, measured pressures
of the meter, and the densit... |
def make_str_node(rawtext, app, prefixed_name, obj, parent, modname, options):
"""Render a Python object to text using the repr() function.
:param rawtext: Text being replaced with link node.
:param app: Sphinx application context
:param prefixed_name: The dotted Python name for obj.
:param obj: Th... | Render a Python object to text using the repr() function.
:param rawtext: Text being replaced with link node.
:param app: Sphinx application context
:param prefixed_name: The dotted Python name for obj.
:param obj: The Python object to be rendered to text.
:param parent: The parent Python object of... | Below is the the instruction that describes the task:
### Input:
Render a Python object to text using the repr() function.
:param rawtext: Text being replaced with link node.
:param app: Sphinx application context
:param prefixed_name: The dotted Python name for obj.
:param obj: The Python object t... |
def ffill(self, dim, limit=None):
'''Fill NaN values by propogating values forward
*Requires bottleneck.*
Parameters
----------
dim : str
Specifies the dimension along which to propagate values when
filling.
limit : int, default None
... | Fill NaN values by propogating values forward
*Requires bottleneck.*
Parameters
----------
dim : str
Specifies the dimension along which to propagate values when
filling.
limit : int, default None
The maximum number of consecutive NaN values ... | Below is the the instruction that describes the task:
### Input:
Fill NaN values by propogating values forward
*Requires bottleneck.*
Parameters
----------
dim : str
Specifies the dimension along which to propagate values when
filling.
limit : int, d... |
def graphite(context, server, port, interval, prefix):
"""Display energy stats of all actors"""
fritz = context.obj
fritz.login()
sid_ttl = time.time() + 600
# Find actors and create carbon keys
click.echo(" * Requesting actors list")
simple_chars = re.compile('[^A-Za-z0-9]+')
actors = ... | Display energy stats of all actors | Below is the the instruction that describes the task:
### Input:
Display energy stats of all actors
### Response:
def graphite(context, server, port, interval, prefix):
"""Display energy stats of all actors"""
fritz = context.obj
fritz.login()
sid_ttl = time.time() + 600
# Find actors and crea... |
def line(name, content=None, match=None, mode=None, location=None,
before=None, after=None, show_changes=True, backup=False,
quiet=False, indent=True, create=False, user=None,
group=None, file_mode=None):
'''
Line-based editing of a file.
.. versionadded:: 2015.8.0
:param na... | Line-based editing of a file.
.. versionadded:: 2015.8.0
:param name:
Filesystem path to the file to be edited.
:param content:
Content of the line. Allowed to be empty if mode=delete.
:param match:
Match the target line for an action by
a fragment of a string or regu... | Below is the the instruction that describes the task:
### Input:
Line-based editing of a file.
.. versionadded:: 2015.8.0
:param name:
Filesystem path to the file to be edited.
:param content:
Content of the line. Allowed to be empty if mode=delete.
:param match:
Match th... |
def attach_kernel_driver(self, interface):
r"""Re-attach an interface's kernel driver, which was previously
detached using detach_kernel_driver().
The interface parameter is the device interface number to attach the
driver to.
"""
self._ctx.managed_open()
self._c... | r"""Re-attach an interface's kernel driver, which was previously
detached using detach_kernel_driver().
The interface parameter is the device interface number to attach the
driver to. | Below is the the instruction that describes the task:
### Input:
r"""Re-attach an interface's kernel driver, which was previously
detached using detach_kernel_driver().
The interface parameter is the device interface number to attach the
driver to.
### Response:
def attach_kernel_driver(se... |
def ed25519_private_key_to_string(key):
"""Convert an ed25519 private key to a base64-encoded string.
Args:
key (Ed25519PrivateKey): the key to write to the file.
Returns:
str: the key representation as a str
"""
return base64.b64encode(key.private_bytes(
encoding=serializ... | Convert an ed25519 private key to a base64-encoded string.
Args:
key (Ed25519PrivateKey): the key to write to the file.
Returns:
str: the key representation as a str | Below is the the instruction that describes the task:
### Input:
Convert an ed25519 private key to a base64-encoded string.
Args:
key (Ed25519PrivateKey): the key to write to the file.
Returns:
str: the key representation as a str
### Response:
def ed25519_private_key_to_string(key):
... |
def cidr_to_ipv4_netmask(cidr_bits):
'''
Returns an IPv4 netmask
'''
try:
cidr_bits = int(cidr_bits)
if not 1 <= cidr_bits <= 32:
return ''
except ValueError:
return ''
netmask = ''
for idx in range(4):
if idx:
netmask += '.'
i... | Returns an IPv4 netmask | Below is the the instruction that describes the task:
### Input:
Returns an IPv4 netmask
### Response:
def cidr_to_ipv4_netmask(cidr_bits):
'''
Returns an IPv4 netmask
'''
try:
cidr_bits = int(cidr_bits)
if not 1 <= cidr_bits <= 32:
return ''
except ValueError:
... |
def disconnect(self, node):
"""
Disconnect node
:param node:
:return:
"""
if super(OneOrMore, self).__len__() < 2:
raise AttemptedCardinalityViolation("One or more expected")
return super(OneOrMore, self).disconnect(node) | Disconnect node
:param node:
:return: | Below is the the instruction that describes the task:
### Input:
Disconnect node
:param node:
:return:
### Response:
def disconnect(self, node):
"""
Disconnect node
:param node:
:return:
"""
if super(OneOrMore, self).__len__() < 2:
raise A... |
def do_filesize(self, line):
"""filesize FILE
Prints the size of the file, in bytes. This function is primarily
for testing.
"""
if len(line) == 0:
print_err("Must provide a filename")
return
filename = resolve_path(line)
self.print(... | filesize FILE
Prints the size of the file, in bytes. This function is primarily
for testing. | Below is the the instruction that describes the task:
### Input:
filesize FILE
Prints the size of the file, in bytes. This function is primarily
for testing.
### Response:
def do_filesize(self, line):
"""filesize FILE
Prints the size of the file, in bytes. This function i... |
def export_icon(self, icon, size, color='black', scale='auto',
filename=None, export_dir='exported'):
"""
Exports given icon with provided parameters.
If the desired icon size is less than 150x150 pixels, we will first
create a 150x150 pixels image and then scale it ... | Exports given icon with provided parameters.
If the desired icon size is less than 150x150 pixels, we will first
create a 150x150 pixels image and then scale it down, so that
it's much less likely that the edges of the icon end up cropped.
:param icon: valid icon name
:param fi... | Below is the the instruction that describes the task:
### Input:
Exports given icon with provided parameters.
If the desired icon size is less than 150x150 pixels, we will first
create a 150x150 pixels image and then scale it down, so that
it's much less likely that the edges of the icon en... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.