code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _search(self, trie, strings, limit=None):
"""Search in cache
:param strings: list of strings to get from the cache
:type strings: str list
:param limit: limit search results
:type limit: int
:rtype: [Resource | Collection]
"""
results = [trie.has_key... | Search in cache
:param strings: list of strings to get from the cache
:type strings: str list
:param limit: limit search results
:type limit: int
:rtype: [Resource | Collection] | Below is the the instruction that describes the task:
### Input:
Search in cache
:param strings: list of strings to get from the cache
:type strings: str list
:param limit: limit search results
:type limit: int
:rtype: [Resource | Collection]
### Response:
def _search(self... |
def patch_traces(
self,
project_id,
traces,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Sends new traces to Stackdriver Trace or updates existing traces. If the ID
of a t... | Sends new traces to Stackdriver Trace or updates existing traces. If the ID
of a trace that you send matches that of an existing trace, any fields
in the existing trace and its spans are overwritten by the provided values,
and any new fields provided are merged with the existing trace data. If t... | Below is the the instruction that describes the task:
### Input:
Sends new traces to Stackdriver Trace or updates existing traces. If the ID
of a trace that you send matches that of an existing trace, any fields
in the existing trace and its spans are overwritten by the provided values,
and ... |
def mode(self, set_bytes):
"""Set the operating protocol of the USB-ISS with additional
parameters for the protocol
"""
self._mode = set_bytes
data = [self.ISS_CMD, self.ISS_SET_MODE] + set_bytes
self.write_data(data)
response = self.read_data(2)
if respo... | Set the operating protocol of the USB-ISS with additional
parameters for the protocol | Below is the the instruction that describes the task:
### Input:
Set the operating protocol of the USB-ISS with additional
parameters for the protocol
### Response:
def mode(self, set_bytes):
"""Set the operating protocol of the USB-ISS with additional
parameters for the protocol
... |
def with_args(self, **kwargs):
"""Send these keyword-arguments to the phase when called."""
# Make a copy so we can have multiple of the same phase with different args
# in the same test.
new_info = mutablerecords.CopyRecord(self)
new_info.options = new_info.options.format_strings(**kwargs)
new_... | Send these keyword-arguments to the phase when called. | Below is the the instruction that describes the task:
### Input:
Send these keyword-arguments to the phase when called.
### Response:
def with_args(self, **kwargs):
"""Send these keyword-arguments to the phase when called."""
# Make a copy so we can have multiple of the same phase with different args
#... |
def plot_comp(df_var, fig=None, ax=None, **kwargs):
"""Short summary.
Parameters
----------
df_var : pd.DataFrame
DataFrame containing variables to plot with datetime as index
Returns
-------
MPL.figure
figure showing 1:1 line plot
"""
if fig is None and ax is None... | Short summary.
Parameters
----------
df_var : pd.DataFrame
DataFrame containing variables to plot with datetime as index
Returns
-------
MPL.figure
figure showing 1:1 line plot | Below is the the instruction that describes the task:
### Input:
Short summary.
Parameters
----------
df_var : pd.DataFrame
DataFrame containing variables to plot with datetime as index
Returns
-------
MPL.figure
figure showing 1:1 line plot
### Response:
def plot_comp(df_... |
def marvcli_query(ctx, list_tags, collections, discarded, outdated, path, tags, null):
"""Query datasets.
Use --collection=* to list all datasets across all collections.
"""
if not any([collections, discarded, list_tags, outdated, path, tags]):
click.echo(ctx.get_help())
ctx.exit(1)
... | Query datasets.
Use --collection=* to list all datasets across all collections. | Below is the the instruction that describes the task:
### Input:
Query datasets.
Use --collection=* to list all datasets across all collections.
### Response:
def marvcli_query(ctx, list_tags, collections, discarded, outdated, path, tags, null):
"""Query datasets.
Use --collection=* to list all datas... |
def get_ticker(self):
'''Return a ticker object. Generated from quote and trade.'''
lastQuote = self.data['quote'][-1]
lastTrade = self.data['trade'][-1]
ticker = {
"last": lastTrade['price'],
"buy": lastQuote['bidPrice'],
"sell": lastQuote['askPrice']... | Return a ticker object. Generated from quote and trade. | Below is the the instruction that describes the task:
### Input:
Return a ticker object. Generated from quote and trade.
### Response:
def get_ticker(self):
'''Return a ticker object. Generated from quote and trade.'''
lastQuote = self.data['quote'][-1]
lastTrade = self.data['trade'][-1]
... |
def get_port_profile_for_intf_output_interface_port_profile_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_port_profile_for_intf = ET.Element("get_port_profile_for_intf")
config = get_port_profile_for_intf
output = ET.SubElement(get_por... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def get_port_profile_for_intf_output_interface_port_profile_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_port_profile_for_intf = ET.Element("get_p... |
def get_rowspanned_columns(self):
"""Return a dictionary mapping column indices to the number of columns
spanned."""
spanned_columns = {}
current_row_index = self._index
current_row_cols = sum(cell.colspan for cell in self)
prev_rows = iter(reversed(self.section[:current_... | Return a dictionary mapping column indices to the number of columns
spanned. | Below is the the instruction that describes the task:
### Input:
Return a dictionary mapping column indices to the number of columns
spanned.
### Response:
def get_rowspanned_columns(self):
"""Return a dictionary mapping column indices to the number of columns
spanned."""
spanned_co... |
def _repr_values(self):
"""Return values that are to be shown in repr string."""
def getattr_better(obj, field):
try:
return getattr(obj, field)
except AttributeError as e:
try:
return getattr(obj, '_' + field)
e... | Return values that are to be shown in repr string. | Below is the the instruction that describes the task:
### Input:
Return values that are to be shown in repr string.
### Response:
def _repr_values(self):
"""Return values that are to be shown in repr string."""
def getattr_better(obj, field):
try:
return getattr(obj, fie... |
def ensure_text(str_or_bytes, encoding='utf-8'):
"""Ensures an input is a string, decoding if it is bytes.
"""
if not isinstance(str_or_bytes, six.text_type):
return str_or_bytes.decode(encoding)
return str_or_bytes | Ensures an input is a string, decoding if it is bytes. | Below is the the instruction that describes the task:
### Input:
Ensures an input is a string, decoding if it is bytes.
### Response:
def ensure_text(str_or_bytes, encoding='utf-8'):
"""Ensures an input is a string, decoding if it is bytes.
"""
if not isinstance(str_or_bytes, six.text_type):
re... |
def _all_add_or_modify_row(self, item_name, insert_dict, table, index=None, condition=None,
condvars=None,
flags=(ADD_ROW, MODIFY_ROW,)):
"""Adds or changes a row in a pytable.
:param item_name: Name of item, the row is about, only important... | Adds or changes a row in a pytable.
:param item_name: Name of item, the row is about, only important for throwing errors.
:param insert_dict:
Dictionary of data that is about to be inserted into the pytables row.
:param table:
The table to insert or modify a row in
... | Below is the the instruction that describes the task:
### Input:
Adds or changes a row in a pytable.
:param item_name: Name of item, the row is about, only important for throwing errors.
:param insert_dict:
Dictionary of data that is about to be inserted into the pytables row.
... |
def to_list(i, use_keys=False):
'''
Converts items to a list.
:param i: Item to convert
* If `i` is ``None``, the result is an empty list
* If `i` is 'string', the result won't be \
``['s', 't', 'r',...]`` rather more like ``['string']``
* If `i` is a nested dictionary, t... | Converts items to a list.
:param i: Item to convert
* If `i` is ``None``, the result is an empty list
* If `i` is 'string', the result won't be \
``['s', 't', 'r',...]`` rather more like ``['string']``
* If `i` is a nested dictionary, the result will be a flattened list.
:pa... | Below is the the instruction that describes the task:
### Input:
Converts items to a list.
:param i: Item to convert
* If `i` is ``None``, the result is an empty list
* If `i` is 'string', the result won't be \
``['s', 't', 'r',...]`` rather more like ``['string']``
* If `i` ... |
def check_sso_login(self, operator_email, request_id):
"""
Login to the CloudGenix API, and see if SAML SSO has occurred.
This function is used to check and see if SAML SSO has succeeded while waiting.
**Parameters:**
- **operator_email:** String with the username to log in w... | Login to the CloudGenix API, and see if SAML SSO has occurred.
This function is used to check and see if SAML SSO has succeeded while waiting.
**Parameters:**
- **operator_email:** String with the username to log in with
- **request_id:** String containing the SAML 2.0 Request ID f... | Below is the the instruction that describes the task:
### Input:
Login to the CloudGenix API, and see if SAML SSO has occurred.
This function is used to check and see if SAML SSO has succeeded while waiting.
**Parameters:**
- **operator_email:** String with the username to log in with
... |
def prep_message(msg):
"""
Add the size header
"""
if six.PY3:
msg_out = msg.as_string().encode("utf-8")
else:
msg_out = msg.as_string()
our_len = len(msg_out) + 4
size = struct.pack('>L', our_len)
# why the hell is this "bytes" on python3?
return size + msg_out | Add the size header | Below is the the instruction that describes the task:
### Input:
Add the size header
### Response:
def prep_message(msg):
"""
Add the size header
"""
if six.PY3:
msg_out = msg.as_string().encode("utf-8")
else:
msg_out = msg.as_string()
our_len = len(msg_out) + 4
size = ... |
def receive_message_batch(self, max_batch_size=None, on_message_received=None, timeout=0):
"""Receive a batch of messages. Messages returned in the batch have already been
accepted - if you wish to add logic to accept or reject messages based on custom
criteria, pass in a callback. This method w... | Receive a batch of messages. Messages returned in the batch have already been
accepted - if you wish to add logic to accept or reject messages based on custom
criteria, pass in a callback. This method will return as soon as some messages are
available rather than waiting to achieve a specific ba... | Below is the the instruction that describes the task:
### Input:
Receive a batch of messages. Messages returned in the batch have already been
accepted - if you wish to add logic to accept or reject messages based on custom
criteria, pass in a callback. This method will return as soon as some messag... |
def lambda_function(f):
"""
Decorator for making error handling on AWS Lambda easier
"""
@functools.wraps(f)
def wrapper(event, context):
global _CURRENT_LAMBDA_CONTEXT
_CURRENT_LAMBDA_CONTEXT = context
try:
result = f(event, context)
return wait(lambd... | Decorator for making error handling on AWS Lambda easier | Below is the the instruction that describes the task:
### Input:
Decorator for making error handling on AWS Lambda easier
### Response:
def lambda_function(f):
"""
Decorator for making error handling on AWS Lambda easier
"""
@functools.wraps(f)
def wrapper(event, context):
global _CURRE... |
def decode(self, bytes):
"""Decodes the given bytes according to this AIT Argument
Definition.
"""
value = self.type.decode(bytes)
if self._enum is not None:
for name, val in self._enum.items():
if value == val:
value = name
... | Decodes the given bytes according to this AIT Argument
Definition. | Below is the the instruction that describes the task:
### Input:
Decodes the given bytes according to this AIT Argument
Definition.
### Response:
def decode(self, bytes):
"""Decodes the given bytes according to this AIT Argument
Definition.
"""
value = self.type.decode(bytes... |
def personality(self, category: str = 'mbti') -> Union[str, int]:
"""Generate a type of personality.
:param category: Category.
:return: Personality type.
:rtype: str or int
:Example:
ISFJ.
"""
mbtis = ('ISFJ', 'ISTJ', 'INFJ', 'INTJ',
... | Generate a type of personality.
:param category: Category.
:return: Personality type.
:rtype: str or int
:Example:
ISFJ. | Below is the the instruction that describes the task:
### Input:
Generate a type of personality.
:param category: Category.
:return: Personality type.
:rtype: str or int
:Example:
ISFJ.
### Response:
def personality(self, category: str = 'mbti') -> Union[str, int]:
... |
def configure_alias(graph, ns, mappings):
"""
Register Alias endpoints for a resource object.
"""
convention = AliasConvention(graph)
convention.configure(ns, mappings) | Register Alias endpoints for a resource object. | Below is the the instruction that describes the task:
### Input:
Register Alias endpoints for a resource object.
### Response:
def configure_alias(graph, ns, mappings):
"""
Register Alias endpoints for a resource object.
"""
convention = AliasConvention(graph)
convention.configure(ns, mappings... |
def filter_service_by_host_bp_rule_label(label):
"""Filter for service
Filter on label
:param label: label to filter
:type label: str
:return: Filter
:rtype: bool
"""
def inner_filter(items):
"""Inner filter for service. Accept if label in service.host.labels"""
service... | Filter for service
Filter on label
:param label: label to filter
:type label: str
:return: Filter
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Filter for service
Filter on label
:param label: label to filter
:type label: str
:return: Filter
:rtype: bool
### Response:
def filter_service_by_host_bp_rule_label(label):
"""Filter for service
Filter on label
:par... |
def calculateLocalElasticity(self, bp, frames=None, helical=False, unit='kT'):
r"""Calculate local elastic matrix or stiffness matrix for local DNA segment
.. note:: Here local DNA segment referred to less than 5 base-pair long.
In case of :ref:`base-step-image`: Shift (:math:`Dx`), Slide (:ma... | r"""Calculate local elastic matrix or stiffness matrix for local DNA segment
.. note:: Here local DNA segment referred to less than 5 base-pair long.
In case of :ref:`base-step-image`: Shift (:math:`Dx`), Slide (:math:`Dy`), Rise (:math:`Dz`),
Tilt (:math:`\tau`), Roll (:math:`\rho`) and Twist... | Below is the the instruction that describes the task:
### Input:
r"""Calculate local elastic matrix or stiffness matrix for local DNA segment
.. note:: Here local DNA segment referred to less than 5 base-pair long.
In case of :ref:`base-step-image`: Shift (:math:`Dx`), Slide (:math:`Dy`), Rise (:m... |
def queue_manager_stats(self, queue_manager, tags):
"""
Get stats from the queue manager
"""
for mname, pymqi_value in iteritems(metrics.queue_manager_metrics()):
try:
m = queue_manager.inquire(pymqi_value)
mname = '{}.queue_manager.{}'.format... | Get stats from the queue manager | Below is the the instruction that describes the task:
### Input:
Get stats from the queue manager
### Response:
def queue_manager_stats(self, queue_manager, tags):
"""
Get stats from the queue manager
"""
for mname, pymqi_value in iteritems(metrics.queue_manager_metrics()):
... |
def get_alignment_df(a_aln_seq, b_aln_seq, a_seq_id=None, b_seq_id=None):
"""Summarize two alignment strings in a dataframe.
Args:
a_aln_seq (str): Aligned sequence string
b_aln_seq (str): Aligned sequence string
a_seq_id (str): Optional ID of a_seq
b_seq_id (str): Optional ID o... | Summarize two alignment strings in a dataframe.
Args:
a_aln_seq (str): Aligned sequence string
b_aln_seq (str): Aligned sequence string
a_seq_id (str): Optional ID of a_seq
b_seq_id (str): Optional ID of b_aln_seq
Returns:
DataFrame: a per-residue level annotation of th... | Below is the the instruction that describes the task:
### Input:
Summarize two alignment strings in a dataframe.
Args:
a_aln_seq (str): Aligned sequence string
b_aln_seq (str): Aligned sequence string
a_seq_id (str): Optional ID of a_seq
b_seq_id (str): Optional ID of b_aln_seq
... |
def parse_args(spectypes):
"""
Return arguments object formed by parsing the command line used to launch
the program.
"""
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument(
"-c", "--constants",
help="emit constants instead of spec dict",
action="store_true"
... | Return arguments object formed by parsing the command line used to launch
the program. | Below is the the instruction that describes the task:
### Input:
Return arguments object formed by parsing the command line used to launch
the program.
### Response:
def parse_args(spectypes):
"""
Return arguments object formed by parsing the command line used to launch
the program.
"""
arg... |
def vis_keypoints(img, kps, kp_thresh=2, alpha=0.7):
"""Visualizes keypoints (adapted from vis_one_image).
kps has shape (4, #keypoints) where 4 rows are (x, y, logit, prob).
"""
dataset_keypoints = PersonKeypoints.NAMES
kp_lines = PersonKeypoints.CONNECTIONS
# Convert from plt 0-1 RGBA colors ... | Visualizes keypoints (adapted from vis_one_image).
kps has shape (4, #keypoints) where 4 rows are (x, y, logit, prob). | Below is the the instruction that describes the task:
### Input:
Visualizes keypoints (adapted from vis_one_image).
kps has shape (4, #keypoints) where 4 rows are (x, y, logit, prob).
### Response:
def vis_keypoints(img, kps, kp_thresh=2, alpha=0.7):
"""Visualizes keypoints (adapted from vis_one_image).
... |
def throw_invalid_quad_params(quad, QUADS, nparams):
""" Exception raised when an invalid number of params in the
quad code has been emmitted.
"""
raise InvalidICError(str(quad),
"Invalid quad code params for '%s' (expected %i, but got %i)" %
(quad, ... | Exception raised when an invalid number of params in the
quad code has been emmitted. | Below is the the instruction that describes the task:
### Input:
Exception raised when an invalid number of params in the
quad code has been emmitted.
### Response:
def throw_invalid_quad_params(quad, QUADS, nparams):
""" Exception raised when an invalid number of params in the
quad code has be... |
def create_index(idx_url, clean=False):
"""Configure the index to work with"""
try:
r = requests.get(idx_url)
except requests.exceptions.ConnectionError:
cause = "Error connecting to Elastic Search (index: %s)" % idx_url
raise ElasticSearchError(cause=cause)
... | Configure the index to work with | Below is the the instruction that describes the task:
### Input:
Configure the index to work with
### Response:
def create_index(idx_url, clean=False):
"""Configure the index to work with"""
try:
r = requests.get(idx_url)
except requests.exceptions.ConnectionError:
... |
def sample_rwalk(args):
"""
Return a new live point proposed by random walking away from an
existing live point.
Parameters
----------
u : `~numpy.ndarray` with shape (npdim,)
Position of the initial sample. **This is a copy of an existing live
point.**
loglstar : float
... | Return a new live point proposed by random walking away from an
existing live point.
Parameters
----------
u : `~numpy.ndarray` with shape (npdim,)
Position of the initial sample. **This is a copy of an existing live
point.**
loglstar : float
Ln(likelihood) bound.
axes... | Below is the the instruction that describes the task:
### Input:
Return a new live point proposed by random walking away from an
existing live point.
Parameters
----------
u : `~numpy.ndarray` with shape (npdim,)
Position of the initial sample. **This is a copy of an existing live
p... |
def SmartStubAdapter(host='localhost', port=443, path='/sdk',
url=None, sock=None, poolSize=5,
certFile=None, certKeyFile=None,
httpProxyHost=None, httpProxyPort=80, sslProxyPath=None,
thumbprint=None, cacertsFile=None, preferredApiVers... | Determine the most preferred API version supported by the specified server,
then create a soap stub adapter using that version
The parameters are the same as for pyVmomi.SoapStubAdapter except for
version which is renamed to prefferedApiVersions
@param preferredApiVersions: Acceptable API version(s) (e.g.... | Below is the the instruction that describes the task:
### Input:
Determine the most preferred API version supported by the specified server,
then create a soap stub adapter using that version
The parameters are the same as for pyVmomi.SoapStubAdapter except for
version which is renamed to prefferedApiVers... |
def request(self, name, content={}, namespace=None):
""" Do a SOAP request and returns the result.
Simple wrapper arround pythonzimbra functions
:param name: ex: 'Auth' for performing an 'AuthRequest'
:param content: a dict formatted pythonzimbra-style for request
:param namespa... | Do a SOAP request and returns the result.
Simple wrapper arround pythonzimbra functions
:param name: ex: 'Auth' for performing an 'AuthRequest'
:param content: a dict formatted pythonzimbra-style for request
:param namespace: (optional), the namespace, if different from the
... | Below is the the instruction that describes the task:
### Input:
Do a SOAP request and returns the result.
Simple wrapper arround pythonzimbra functions
:param name: ex: 'Auth' for performing an 'AuthRequest'
:param content: a dict formatted pythonzimbra-style for request
:param nam... |
def GetCountStopTimes(self):
"""Return the number of stops made by this trip."""
cursor = self._schedule._connection.cursor()
cursor.execute(
'SELECT count(*) FROM stop_times WHERE trip_id=?', (self.trip_id,))
return cursor.fetchone()[0] | Return the number of stops made by this trip. | Below is the the instruction that describes the task:
### Input:
Return the number of stops made by this trip.
### Response:
def GetCountStopTimes(self):
"""Return the number of stops made by this trip."""
cursor = self._schedule._connection.cursor()
cursor.execute(
'SELECT count(*) FROM stop_t... |
def load_friends(self):
"""Fetches the MAL user friends page and sets the current user's friends attributes.
:rtype: :class:`.User`
:return: Current user object.
"""
user_friends = self.session.session.get(u'http://myanimelist.net/profile/' + utilities.urlencode(self.username) + u'/friends').text
... | Fetches the MAL user friends page and sets the current user's friends attributes.
:rtype: :class:`.User`
:return: Current user object. | Below is the the instruction that describes the task:
### Input:
Fetches the MAL user friends page and sets the current user's friends attributes.
:rtype: :class:`.User`
:return: Current user object.
### Response:
def load_friends(self):
"""Fetches the MAL user friends page and sets the current user's... |
def do_import(self):
"""Handle import files or streams passed with '-i'."""
tmp_import = None
try:
if self.args[0].startswith('@') and self.args[0] != '@-':
import_file = os.path.expanduser(self.args[0][1:])
if not os.path.isfile(import_file):
... | Handle import files or streams passed with '-i'. | Below is the the instruction that describes the task:
### Input:
Handle import files or streams passed with '-i'.
### Response:
def do_import(self):
"""Handle import files or streams passed with '-i'."""
tmp_import = None
try:
if self.args[0].startswith('@') and self.args[0] != ... |
def _get_private_key(cls, private_key_path, private_key_passphrase):
"""Get Snowflake private key by path or None."""
if private_key_path is None or private_key_passphrase is None:
return None
with open(private_key_path, 'rb') as key:
p_key = serialization.load_pem_priva... | Get Snowflake private key by path or None. | Below is the the instruction that describes the task:
### Input:
Get Snowflake private key by path or None.
### Response:
def _get_private_key(cls, private_key_path, private_key_passphrase):
"""Get Snowflake private key by path or None."""
if private_key_path is None or private_key_passphrase is No... |
def generate_code(meta, prefix=None, node=False, min=False):
"""
Generate res.js
Args:
meta: tuple(url_prefix, auth_header, resources) or metadata of API
Returns:
res.js source code
"""
if isinstance(meta, dict):
url_prefix, auth_header, resources = parse_meta(meta)
... | Generate res.js
Args:
meta: tuple(url_prefix, auth_header, resources) or metadata of API
Returns:
res.js source code | Below is the the instruction that describes the task:
### Input:
Generate res.js
Args:
meta: tuple(url_prefix, auth_header, resources) or metadata of API
Returns:
res.js source code
### Response:
def generate_code(meta, prefix=None, node=False, min=False):
"""
Generate res.js
... |
def run(self, **kwargs):
"""
Runs an instance of a scheduled task
"""
log = self.get_logger(**kwargs)
failures = ScheduleFailure.objects
log.info("Attempting to requeue <%s> failed schedules" % failures.count())
for failure in failures.iterator():
sche... | Runs an instance of a scheduled task | Below is the the instruction that describes the task:
### Input:
Runs an instance of a scheduled task
### Response:
def run(self, **kwargs):
"""
Runs an instance of a scheduled task
"""
log = self.get_logger(**kwargs)
failures = ScheduleFailure.objects
log.info("Atte... |
def dl_pb_file(inputs):
"""
Download a file from physiobank.
The input args are to be unpacked for the use of multiprocessing
map, because python2 doesn't have starmap...
"""
basefile, subdir, db, dl_dir, keep_subdirs, overwrite = inputs
# Full url of file
url = posixpath.join(config... | Download a file from physiobank.
The input args are to be unpacked for the use of multiprocessing
map, because python2 doesn't have starmap... | Below is the the instruction that describes the task:
### Input:
Download a file from physiobank.
The input args are to be unpacked for the use of multiprocessing
map, because python2 doesn't have starmap...
### Response:
def dl_pb_file(inputs):
"""
Download a file from physiobank.
The input ... |
def create(self, **kwargs):
"""Create a new Application.
Args:
**kwargs: Arbitrary keyword arguments, including:
name (str): A name for the new Application.
Returns:
A round.Application object if successful.
"""
resource = self.resource.create(kwa... | Create a new Application.
Args:
**kwargs: Arbitrary keyword arguments, including:
name (str): A name for the new Application.
Returns:
A round.Application object if successful. | Below is the the instruction that describes the task:
### Input:
Create a new Application.
Args:
**kwargs: Arbitrary keyword arguments, including:
name (str): A name for the new Application.
Returns:
A round.Application object if successful.
### Response:
def create... |
def save_storage(self, instance, schema):
"""Save basic:json values to a Storage collection."""
for field_schema, fields in iterate_fields(instance, schema):
name = field_schema['name']
value = fields[name]
if field_schema.get('type', '').startswith('basic:json:'):
... | Save basic:json values to a Storage collection. | Below is the the instruction that describes the task:
### Input:
Save basic:json values to a Storage collection.
### Response:
def save_storage(self, instance, schema):
"""Save basic:json values to a Storage collection."""
for field_schema, fields in iterate_fields(instance, schema):
na... |
def parse_scalar(scalar_data, version):
"""
Parse a Project Haystack scalar in ZINC format.
"""
try:
return hs_scalar[version].parseString(scalar_data, parseAll=True)[0]
except pp.ParseException as pe:
# Raise a new exception with the appropriate line number.
raise ZincParseE... | Parse a Project Haystack scalar in ZINC format. | Below is the the instruction that describes the task:
### Input:
Parse a Project Haystack scalar in ZINC format.
### Response:
def parse_scalar(scalar_data, version):
"""
Parse a Project Haystack scalar in ZINC format.
"""
try:
return hs_scalar[version].parseString(scalar_data, parseAll=Tru... |
def add_option(self, K=None, price=None, St=None, kind="call", pos="long"):
"""Add an option to the object's `options` container."""
kinds = {
"call": Call,
"Call": Call,
"c": Call,
"C": Call,
"put": Put,
"Put": Put,
... | Add an option to the object's `options` container. | Below is the the instruction that describes the task:
### Input:
Add an option to the object's `options` container.
### Response:
def add_option(self, K=None, price=None, St=None, kind="call", pos="long"):
"""Add an option to the object's `options` container."""
kinds = {
"call": Cal... |
def create_rackservers(self):
"""Get an instance of rackservers services facade."""
return RackServers(
self.networkapi_url,
self.user,
self.password,
self.user_ldap) | Get an instance of rackservers services facade. | Below is the the instruction that describes the task:
### Input:
Get an instance of rackservers services facade.
### Response:
def create_rackservers(self):
"""Get an instance of rackservers services facade."""
return RackServers(
self.networkapi_url,
self.user,
... |
def generate_tags_multiple_files(input_files, tag, ignore_tags, ns=None):
"""
Calls xmltag generator for multiple files.
"""
return itertools.chain.from_iterable([generate_xmltags(
fn, tag, ignore_tags, ns) for fn in input_files]) | Calls xmltag generator for multiple files. | Below is the the instruction that describes the task:
### Input:
Calls xmltag generator for multiple files.
### Response:
def generate_tags_multiple_files(input_files, tag, ignore_tags, ns=None):
"""
Calls xmltag generator for multiple files.
"""
return itertools.chain.from_iterable([generate_xmlta... |
def _copy_docstring(original_fn, new_fn):
"""Wraps new_fn with the doc of original_fn."""
original_spec = tf_inspect.getfullargspec(original_fn)
new_spec = tf_inspect.getfullargspec(new_fn)
if original_spec != new_spec:
raise ValueError(
'Arg specs do not match: original={}, new={}, fn={}'.format(
... | Wraps new_fn with the doc of original_fn. | Below is the the instruction that describes the task:
### Input:
Wraps new_fn with the doc of original_fn.
### Response:
def _copy_docstring(original_fn, new_fn):
"""Wraps new_fn with the doc of original_fn."""
original_spec = tf_inspect.getfullargspec(original_fn)
new_spec = tf_inspect.getfullargspec(new_fn... |
def _get_names(self):
"""Get the names of the objects to include in the table.
:returns: The names of the objects to include.
:rtype: generator(str)
"""
for line in self.content:
line = line.strip()
if line and re.search("^[a-zA-Z0-9]", line):
... | Get the names of the objects to include in the table.
:returns: The names of the objects to include.
:rtype: generator(str) | Below is the the instruction that describes the task:
### Input:
Get the names of the objects to include in the table.
:returns: The names of the objects to include.
:rtype: generator(str)
### Response:
def _get_names(self):
"""Get the names of the objects to include in the table.
... |
def _load_cache(self):
"""Load existing cache and merge for updating if required."""
if not self._disable_cache and os.path.exists(self._cache_path):
_LOGGER.debug("Cache found at: %s", self._cache_path)
loaded_cache = UTILS.load_cache(self._cache_path)
UTILS.update(... | Load existing cache and merge for updating if required. | Below is the the instruction that describes the task:
### Input:
Load existing cache and merge for updating if required.
### Response:
def _load_cache(self):
"""Load existing cache and merge for updating if required."""
if not self._disable_cache and os.path.exists(self._cache_path):
_L... |
def write(self):
"""If data exists for the entity, writes it to disk as a .JSON file with
the url-encoded URI as the filename and returns True. Else, returns
False."""
if (self.data):
dataPath = self.client.local_dir / (urllib.parse.quote_plus(self.uri)+'.json')
... | If data exists for the entity, writes it to disk as a .JSON file with
the url-encoded URI as the filename and returns True. Else, returns
False. | Below is the the instruction that describes the task:
### Input:
If data exists for the entity, writes it to disk as a .JSON file with
the url-encoded URI as the filename and returns True. Else, returns
False.
### Response:
def write(self):
"""If data exists for the entity, writes... |
def schema_delete_field(cls, key):
"""Deletes a field."""
root = '/'.join([API_ROOT, 'schemas', cls.__name__])
payload = {
'className': cls.__name__,
'fields': {
key: {
'__op': 'Delete'
}
}
}
... | Deletes a field. | Below is the the instruction that describes the task:
### Input:
Deletes a field.
### Response:
def schema_delete_field(cls, key):
"""Deletes a field."""
root = '/'.join([API_ROOT, 'schemas', cls.__name__])
payload = {
'className': cls.__name__,
'fields': {
... |
def wr_dat_files(self, expanded=False, write_dir=''):
"""
Write each of the specified dat files
"""
# Get the set of dat files to be written, and
# the channels to be written to each file.
file_names, dat_channels = describe_list_indices(self.file_name)
# Get th... | Write each of the specified dat files | Below is the the instruction that describes the task:
### Input:
Write each of the specified dat files
### Response:
def wr_dat_files(self, expanded=False, write_dir=''):
"""
Write each of the specified dat files
"""
# Get the set of dat files to be written, and
# the chann... |
def master_main(painter, router, select, delay):
"""
Loop until CTRL+C is pressed, waiting for the next result delivered by the
Select. Use parse_output() to turn that result ('ps' command output) into
rich data, and finally repaint the screen if the repaint delay has passed.
"""
next_paint = 0
... | Loop until CTRL+C is pressed, waiting for the next result delivered by the
Select. Use parse_output() to turn that result ('ps' command output) into
rich data, and finally repaint the screen if the repaint delay has passed. | Below is the the instruction that describes the task:
### Input:
Loop until CTRL+C is pressed, waiting for the next result delivered by the
Select. Use parse_output() to turn that result ('ps' command output) into
rich data, and finally repaint the screen if the repaint delay has passed.
### Response:
def ... |
def updateflags(self, flags):
"""
Thin wrapper around build_update(flags=X). This only handles simple
status changes, anything like needinfo requestee needs to call
build_update + update_bugs directly
:param flags: Dictionary of the form {"flagname": "status"}, example
... | Thin wrapper around build_update(flags=X). This only handles simple
status changes, anything like needinfo requestee needs to call
build_update + update_bugs directly
:param flags: Dictionary of the form {"flagname": "status"}, example
{"needinfo": "?", "devel_ack": "+"} | Below is the the instruction that describes the task:
### Input:
Thin wrapper around build_update(flags=X). This only handles simple
status changes, anything like needinfo requestee needs to call
build_update + update_bugs directly
:param flags: Dictionary of the form {"flagname": "status"}... |
def make_connection(self, node):
"""
Create a new connection
"""
if self.count_all_num_connections(node) >= self.max_connections:
if self.max_connections_per_node:
raise RedisClusterException("Too many connection ({0}) for node: {1}"
... | Create a new connection | Below is the the instruction that describes the task:
### Input:
Create a new connection
### Response:
def make_connection(self, node):
"""
Create a new connection
"""
if self.count_all_num_connections(node) >= self.max_connections:
if self.max_connections_per_node:
... |
def _FormatPackedIPv6Address(self, packed_ip_address):
"""Formats a packed IPv6 address as a human readable string.
Args:
packed_ip_address (list[int]): packed IPv6 address.
Returns:
str: human readable IPv6 address.
"""
# Note that socket.inet_ntop() is not supported on Windows.
o... | Formats a packed IPv6 address as a human readable string.
Args:
packed_ip_address (list[int]): packed IPv6 address.
Returns:
str: human readable IPv6 address. | Below is the the instruction that describes the task:
### Input:
Formats a packed IPv6 address as a human readable string.
Args:
packed_ip_address (list[int]): packed IPv6 address.
Returns:
str: human readable IPv6 address.
### Response:
def _FormatPackedIPv6Address(self, packed_ip_address):
... |
def command_template(self):
"""Build and return a string that can be used as a template invoking
this chain from the command line.
The actual command can be obtainted by using
`self.command_template().format(**self.args)`
"""
com_out = self.appname
arg_string = "... | Build and return a string that can be used as a template invoking
this chain from the command line.
The actual command can be obtainted by using
`self.command_template().format(**self.args)` | Below is the the instruction that describes the task:
### Input:
Build and return a string that can be used as a template invoking
this chain from the command line.
The actual command can be obtainted by using
`self.command_template().format(**self.args)`
### Response:
def command_template... |
def load(settings=None, namespace=None, prefix=None):
"""
Call this guy to init pyaas stuffs
:param settings: Alternative name of ini file to load
:param namespace: Namespace is used to derive paths, pass '' for an empty namespace
:param prefix: The root path of the app
:return: None
"""
... | Call this guy to init pyaas stuffs
:param settings: Alternative name of ini file to load
:param namespace: Namespace is used to derive paths, pass '' for an empty namespace
:param prefix: The root path of the app
:return: None | Below is the the instruction that describes the task:
### Input:
Call this guy to init pyaas stuffs
:param settings: Alternative name of ini file to load
:param namespace: Namespace is used to derive paths, pass '' for an empty namespace
:param prefix: The root path of the app
:return: None
### Resp... |
def dict_to_querystring(dictionary):
"""Converts a dict to a querystring suitable to be appended to a URL."""
s = u""
for d in dictionary.keys():
s = unicode.format(u"{0}{1}={2}&", s, d, dictionary[d])
return s[:-1] | Converts a dict to a querystring suitable to be appended to a URL. | Below is the the instruction that describes the task:
### Input:
Converts a dict to a querystring suitable to be appended to a URL.
### Response:
def dict_to_querystring(dictionary):
"""Converts a dict to a querystring suitable to be appended to a URL."""
s = u""
for d in dictionary.keys():
s =... |
def _merge_simple_selectors(a, b):
"""Merge two simple selectors, for the purposes of the LCS algorithm below.
In practice this returns the more specific selector if one is a subset of
the other, else it returns None.
"""
# TODO what about combinators
if a.is_superset_of(b):
return b
... | Merge two simple selectors, for the purposes of the LCS algorithm below.
In practice this returns the more specific selector if one is a subset of
the other, else it returns None. | Below is the the instruction that describes the task:
### Input:
Merge two simple selectors, for the purposes of the LCS algorithm below.
In practice this returns the more specific selector if one is a subset of
the other, else it returns None.
### Response:
def _merge_simple_selectors(a, b):
"""Merge... |
def html_clean(html_code):
"""获取网页源代码并进行预处理
Keyword arguments:
html_code -- 网页源代码,字符串类型
Return:
清洗后的网页源代码(只包含文本和换行符\n)
"""
temp = re.sub('<script([\s\S]*?)</script>', '', html_code)
temp = re.sub('<style([\s\S]*?)</style>', '', temp)
html_cleaned = re.sub('(?is)<.*?>',... | 获取网页源代码并进行预处理
Keyword arguments:
html_code -- 网页源代码,字符串类型
Return:
清洗后的网页源代码(只包含文本和换行符\n) | Below is the the instruction that describes the task:
### Input:
获取网页源代码并进行预处理
Keyword arguments:
html_code -- 网页源代码,字符串类型
Return:
清洗后的网页源代码(只包含文本和换行符\n)
### Response:
def html_clean(html_code):
"""获取网页源代码并进行预处理
Keyword arguments:
html_code -- 网页源代码,字符串类型
R... |
def mass_integral(self, x, axis_ratio):
"""Routine to integrate an elliptical light profiles - set axis ratio to 1 to compute the luminosity within a \
circle"""
r = x * axis_ratio
return 2 * np.pi * r * self.convergence_func(x) | Routine to integrate an elliptical light profiles - set axis ratio to 1 to compute the luminosity within a \
circle | Below is the the instruction that describes the task:
### Input:
Routine to integrate an elliptical light profiles - set axis ratio to 1 to compute the luminosity within a \
circle
### Response:
def mass_integral(self, x, axis_ratio):
"""Routine to integrate an elliptical light profiles - set axis ... |
def _get_norm_opts(self, obj):
"""
Gets the normalization options for a LabelledData object by
traversing the object to find elements and their ids.
The id is then used to select the appropriate OptionsTree,
accumulating the normalization options into a dictionary.
Return... | Gets the normalization options for a LabelledData object by
traversing the object to find elements and their ids.
The id is then used to select the appropriate OptionsTree,
accumulating the normalization options into a dictionary.
Returns a dictionary of normalization options for each
... | Below is the the instruction that describes the task:
### Input:
Gets the normalization options for a LabelledData object by
traversing the object to find elements and their ids.
The id is then used to select the appropriate OptionsTree,
accumulating the normalization options into a dictiona... |
def watch_profile(self):
"""Analyzes queries from a given log file"""
profile_parser = ProfileParser()
databases = self._get_requested_databases()
connection = pymongo.MongoClient(self._db_uri,
document_class=OrderedDict,
... | Analyzes queries from a given log file | Below is the the instruction that describes the task:
### Input:
Analyzes queries from a given log file
### Response:
def watch_profile(self):
"""Analyzes queries from a given log file"""
profile_parser = ProfileParser()
databases = self._get_requested_databases()
connection = pymon... |
def present(name,
user=None,
password=None,
auth='password',
encoding='UTF8',
locale=None,
runas=None,
waldir=None,
checksums=False):
'''
Initialize the PostgreSQL data directory
name
The name of the directory to initialize
user
... | Initialize the PostgreSQL data directory
name
The name of the directory to initialize
user
The database superuser name
password
The password to set for the postgres user
auth
The default authentication method for local connections
encoding
The default enc... | Below is the the instruction that describes the task:
### Input:
Initialize the PostgreSQL data directory
name
The name of the directory to initialize
user
The database superuser name
password
The password to set for the postgres user
auth
The default authenticati... |
def resolve_type_spec(self, name, lineno):
"""Finds and links the TypeSpec with the given name."""
if name in self.type_specs:
return self.type_specs[name].link(self)
if '.' in name:
include_name, component = name.split('.', 1)
if include_name in self.includ... | Finds and links the TypeSpec with the given name. | Below is the the instruction that describes the task:
### Input:
Finds and links the TypeSpec with the given name.
### Response:
def resolve_type_spec(self, name, lineno):
"""Finds and links the TypeSpec with the given name."""
if name in self.type_specs:
return self.type_specs[name].l... |
def wait(self, pattern, timeout=10.0, safe=False, **match_kwargs):
"""Wait till pattern is found or time is out (default: 10s)."""
t = time.time() + timeout
while time.time() < t:
ret = self.exists(pattern, **match_kwargs)
if ret:
return ret
ti... | Wait till pattern is found or time is out (default: 10s). | Below is the the instruction that describes the task:
### Input:
Wait till pattern is found or time is out (default: 10s).
### Response:
def wait(self, pattern, timeout=10.0, safe=False, **match_kwargs):
"""Wait till pattern is found or time is out (default: 10s)."""
t = time.time() + timeout
... |
def arr_to_vector(arr):
"""Reshape a multidimensional array to a vector.
"""
dim = array_dim(arr)
tmp_arr = []
for n in range(len(dim) - 1):
for inner in arr:
for i in inner:
tmp_arr.append(i)
arr = tmp_arr
tmp_arr = []
return arr | Reshape a multidimensional array to a vector. | Below is the the instruction that describes the task:
### Input:
Reshape a multidimensional array to a vector.
### Response:
def arr_to_vector(arr):
"""Reshape a multidimensional array to a vector.
"""
dim = array_dim(arr)
tmp_arr = []
for n in range(len(dim) - 1):
for inner in arr:
... |
def process_wait(process, timeout=0):
"""
Pauses script execution until a given process exists.
:param process:
:param timeout:
:return:
"""
ret = AUTO_IT.AU3_ProcessWait(LPCWSTR(process), INT(timeout))
return ret | Pauses script execution until a given process exists.
:param process:
:param timeout:
:return: | Below is the the instruction that describes the task:
### Input:
Pauses script execution until a given process exists.
:param process:
:param timeout:
:return:
### Response:
def process_wait(process, timeout=0):
"""
Pauses script execution until a given process exists.
:param process:
:... |
def create_rc(self, manifest_filename, namespace="default"):
"""
Creates an RC based on a manifest.
:Parameters:
- `manifest_filename`: The manifest file containing the ReplicationController definition, for example: `manifest/nginx-webserver-rc.yaml`
- `namespace`: In whic... | Creates an RC based on a manifest.
:Parameters:
- `manifest_filename`: The manifest file containing the ReplicationController definition, for example: `manifest/nginx-webserver-rc.yaml`
- `namespace`: In which namespace the RC should be created, defaults to, well, `default` | Below is the the instruction that describes the task:
### Input:
Creates an RC based on a manifest.
:Parameters:
- `manifest_filename`: The manifest file containing the ReplicationController definition, for example: `manifest/nginx-webserver-rc.yaml`
- `namespace`: In which namespace ... |
def curlrequests(curl_string, **kwargs):
"""Use tPool to request for curl string.
If kwargs contains the req which hasattr request method, like req=requests.
:param curl_string: standard curl string.
:type curl_string: str
:param kwargs: valid kwargs for tPool.
:type curl_string: dict
Basi... | Use tPool to request for curl string.
If kwargs contains the req which hasattr request method, like req=requests.
:param curl_string: standard curl string.
:type curl_string: str
:param kwargs: valid kwargs for tPool.
:type curl_string: dict
Basic Usage::
from torequests.utils import ... | Below is the the instruction that describes the task:
### Input:
Use tPool to request for curl string.
If kwargs contains the req which hasattr request method, like req=requests.
:param curl_string: standard curl string.
:type curl_string: str
:param kwargs: valid kwargs for tPool.
:type curl_s... |
def list_files(tag=None, sat_id=None, data_path=None, format_str=None):
"""Return a Pandas Series of every file for chosen satellite data
Parameters
-----------
tag : (string or NoneType)
Denotes type of file to load. Accepted types are '1min' and '5min'.
(default=None)
sat_id : (s... | Return a Pandas Series of every file for chosen satellite data
Parameters
-----------
tag : (string or NoneType)
Denotes type of file to load. Accepted types are '1min' and '5min'.
(default=None)
sat_id : (string or NoneType)
Specifies the satellite ID for a constellation. Not... | Below is the the instruction that describes the task:
### Input:
Return a Pandas Series of every file for chosen satellite data
Parameters
-----------
tag : (string or NoneType)
Denotes type of file to load. Accepted types are '1min' and '5min'.
(default=None)
sat_id : (string or N... |
def padded_sequence_accuracy(logits, labels):
"""Percentage of times that predictions matches labels everywhere (non-0)."""
with tf.variable_scope("padded_sequence_accuracy", values=[logits, labels]):
logits, labels = _pad_tensors_to_same_length(logits, labels)
weights = tf.to_float(tf.not_equal(labels, 0))... | Percentage of times that predictions matches labels everywhere (non-0). | Below is the the instruction that describes the task:
### Input:
Percentage of times that predictions matches labels everywhere (non-0).
### Response:
def padded_sequence_accuracy(logits, labels):
"""Percentage of times that predictions matches labels everywhere (non-0)."""
with tf.variable_scope("padded_seque... |
def submit_ham(self, params):
"""For submitting a ham comment to Akismet."""
# Check required params for submit-ham
for required in ['blog', 'user_ip', 'user_agent']:
if required not in params:
raise MissingParams(required)
response = self._request(... | For submitting a ham comment to Akismet. | Below is the the instruction that describes the task:
### Input:
For submitting a ham comment to Akismet.
### Response:
def submit_ham(self, params):
"""For submitting a ham comment to Akismet."""
# Check required params for submit-ham
for required in ['blog', 'user_ip', 'user_agent']:... |
def _get_child_validator(self, document_crumb=None, schema_crumb=None, **kwargs):
""" Creates a new instance of Validator-(sub-)class. All initial
parameters of the parent are passed to the initialization, unless
a parameter is given as an explicit *keyword*-parameter.
:param do... | Creates a new instance of Validator-(sub-)class. All initial
parameters of the parent are passed to the initialization, unless
a parameter is given as an explicit *keyword*-parameter.
:param document_crumb: Extends the
:attr:`~cerberus.Validator.document_p... | Below is the the instruction that describes the task:
### Input:
Creates a new instance of Validator-(sub-)class. All initial
parameters of the parent are passed to the initialization, unless
a parameter is given as an explicit *keyword*-parameter.
:param document_crumb: Extends the... |
def SetPyclassMetaclass(option, opt, value, parser, *args, **kwargs):
"""set up pyclass metaclass for complexTypes"""
from pyremotevbox.ZSI.generate.containers import ServiceHeaderContainer,\
TypecodeContainerBase, TypesHeaderContainer
TypecodeContainerBase.metaclass = kwargs['metaclass']
... | set up pyclass metaclass for complexTypes | Below is the the instruction that describes the task:
### Input:
set up pyclass metaclass for complexTypes
### Response:
def SetPyclassMetaclass(option, opt, value, parser, *args, **kwargs):
"""set up pyclass metaclass for complexTypes"""
from pyremotevbox.ZSI.generate.containers import ServiceHeaderContai... |
def null(self):
"""Zero crossing value."""
if not self.option.axis:
return -1
else:
return self.screen.height - (
-self.minimum * 4.0 / self.extents * self.size.y
) | Zero crossing value. | Below is the the instruction that describes the task:
### Input:
Zero crossing value.
### Response:
def null(self):
"""Zero crossing value."""
if not self.option.axis:
return -1
else:
return self.screen.height - (
-self.minimum * 4.0 / self.extents * ... |
def _get_bmdl_ratio(self, models):
"""Return BMDL ratio in list of models."""
bmdls = [model.output["BMDL"] for model in models if model.output["BMDL"] > 0]
return max(bmdls) / min(bmdls) if len(bmdls) > 0 else 0 | Return BMDL ratio in list of models. | Below is the the instruction that describes the task:
### Input:
Return BMDL ratio in list of models.
### Response:
def _get_bmdl_ratio(self, models):
"""Return BMDL ratio in list of models."""
bmdls = [model.output["BMDL"] for model in models if model.output["BMDL"] > 0]
return max(bmdls)... |
def mumps(self):
"""Call MUMPS, checking for errors in the return code.
The desired job should have already been set using `ctx.set_job(...)`.
As a convenience, you may wish to call `ctx.run(job=...)` which sets
the job and calls MUMPS.
"""
self._mumps_c(self.id)
... | Call MUMPS, checking for errors in the return code.
The desired job should have already been set using `ctx.set_job(...)`.
As a convenience, you may wish to call `ctx.run(job=...)` which sets
the job and calls MUMPS. | Below is the the instruction that describes the task:
### Input:
Call MUMPS, checking for errors in the return code.
The desired job should have already been set using `ctx.set_job(...)`.
As a convenience, you may wish to call `ctx.run(job=...)` which sets
the job and calls MUMPS.
### Respo... |
def ContainsIgnoreCase(self, value):
"""Sets the type of the WHERE clause as "contains ignore case".
Args:
value: The value to be used in the WHERE condition.
Returns:
The query builder that this WHERE builder links to.
"""
self._awql = self._CreateSingleValueCondition(value, 'CONTAINS... | Sets the type of the WHERE clause as "contains ignore case".
Args:
value: The value to be used in the WHERE condition.
Returns:
The query builder that this WHERE builder links to. | Below is the the instruction that describes the task:
### Input:
Sets the type of the WHERE clause as "contains ignore case".
Args:
value: The value to be used in the WHERE condition.
Returns:
The query builder that this WHERE builder links to.
### Response:
def ContainsIgnoreCase(self, value... |
def write_static_networks(gtfs, output_dir, fmt=None):
"""
Parameters
----------
gtfs: gtfspy.GTFS
output_dir: (str, unicode)
a path where to write
fmt: None, optional
defaulting to "edg" and writing results as ".edg" files
If "csv" csv files are produced instead
"""... | Parameters
----------
gtfs: gtfspy.GTFS
output_dir: (str, unicode)
a path where to write
fmt: None, optional
defaulting to "edg" and writing results as ".edg" files
If "csv" csv files are produced instead | Below is the the instruction that describes the task:
### Input:
Parameters
----------
gtfs: gtfspy.GTFS
output_dir: (str, unicode)
a path where to write
fmt: None, optional
defaulting to "edg" and writing results as ".edg" files
If "csv" csv files are produced instead
### R... |
def reinitialize_command(self, command, reinit_subcommands):
"""
Monkeypatch distutils.Distribution.reinitialize_command() to match behavior
of Distribution.get_command_obj()
This fixes a problem where 'pip install -e' does not reinitialise options
using the setup(options={...}) variable for the bui... | Monkeypatch distutils.Distribution.reinitialize_command() to match behavior
of Distribution.get_command_obj()
This fixes a problem where 'pip install -e' does not reinitialise options
using the setup(options={...}) variable for the build_ext command.
This also effects other option sourcs such as setup.c... | Below is the the instruction that describes the task:
### Input:
Monkeypatch distutils.Distribution.reinitialize_command() to match behavior
of Distribution.get_command_obj()
This fixes a problem where 'pip install -e' does not reinitialise options
using the setup(options={...}) variable for the build_e... |
def _words_by_distinctiveness_score(vocab, topic_word_distrib, doc_topic_distrib, doc_lengths, n=None,
least_to_most=False):
"""Return words in `vocab` ordered by distinctiveness score."""
p_t = get_marginal_topic_distrib(doc_topic_distrib, doc_lengths)
distinct = get_wor... | Return words in `vocab` ordered by distinctiveness score. | Below is the the instruction that describes the task:
### Input:
Return words in `vocab` ordered by distinctiveness score.
### Response:
def _words_by_distinctiveness_score(vocab, topic_word_distrib, doc_topic_distrib, doc_lengths, n=None,
least_to_most=False):
"""Return wor... |
def get_encrypted_pin(self, clear_pin, card_number):
"""
Get PIN block in ISO 0 format, encrypted with the terminal key
"""
if not self.terminal_key:
print('Terminal key is not set')
return ''
if self.pinblock_format == '01':
try:
... | Get PIN block in ISO 0 format, encrypted with the terminal key | Below is the the instruction that describes the task:
### Input:
Get PIN block in ISO 0 format, encrypted with the terminal key
### Response:
def get_encrypted_pin(self, clear_pin, card_number):
"""
Get PIN block in ISO 0 format, encrypted with the terminal key
"""
if not self.termi... |
async def connect(self, channel_id: int):
""" Connects to a voice channel. """
ws = self._lavalink.bot._connection._get_websocket(int(self.guild_id))
await ws.voice_state(self.guild_id, str(channel_id)) | Connects to a voice channel. | Below is the the instruction that describes the task:
### Input:
Connects to a voice channel.
### Response:
async def connect(self, channel_id: int):
""" Connects to a voice channel. """
ws = self._lavalink.bot._connection._get_websocket(int(self.guild_id))
await ws.voice_state(self.guil... |
def find_stop(self, query, direction=""):
"""
Search the list of stops, optionally in a direction (inbound or outbound),
for the term passed to the function. Case insensitive, searches both the
stop name and ID. Yields a generator.
Defaults to both directions.
""... | Search the list of stops, optionally in a direction (inbound or outbound),
for the term passed to the function. Case insensitive, searches both the
stop name and ID. Yields a generator.
Defaults to both directions. | Below is the the instruction that describes the task:
### Input:
Search the list of stops, optionally in a direction (inbound or outbound),
for the term passed to the function. Case insensitive, searches both the
stop name and ID. Yields a generator.
Defaults to both directions.
###... |
def creation_date(path_to_file, return_datetime=True):
"""
Retrieve a file's creation date.
Try to get the date that a file was created, falling back to when it was
last modified if that isn't possible.
See http://stackoverflow.com/a/39501288/1709587 for explanation.
:param path_to_file: File... | Retrieve a file's creation date.
Try to get the date that a file was created, falling back to when it was
last modified if that isn't possible.
See http://stackoverflow.com/a/39501288/1709587 for explanation.
:param path_to_file: File path
:param return_datetime: Bool, returns value in Datetime f... | Below is the the instruction that describes the task:
### Input:
Retrieve a file's creation date.
Try to get the date that a file was created, falling back to when it was
last modified if that isn't possible.
See http://stackoverflow.com/a/39501288/1709587 for explanation.
:param path_to_file: Fi... |
def run(self, path_or_tests, dot_env_path=None, mapping=None):
""" main interface.
Args:
path_or_tests:
str: testcase/testsuite file/foler path
dict: valid testcase/testsuite data
"""
if validator.is_testcase_path(path_or_tests):
... | main interface.
Args:
path_or_tests:
str: testcase/testsuite file/foler path
dict: valid testcase/testsuite data | Below is the the instruction that describes the task:
### Input:
main interface.
Args:
path_or_tests:
str: testcase/testsuite file/foler path
dict: valid testcase/testsuite data
### Response:
def run(self, path_or_tests, dot_env_path=None, mapping=None):
... |
def _get_modpkg_path(dotted_name, pathlist=None):
"""Get the filesystem path for a module or a package.
Return the file system path to a file for a module, and to a directory for
a package. Return None if the name is not found, or is a builtin or
extension module.
"""
# split off top-most name
... | Get the filesystem path for a module or a package.
Return the file system path to a file for a module, and to a directory for
a package. Return None if the name is not found, or is a builtin or
extension module. | Below is the the instruction that describes the task:
### Input:
Get the filesystem path for a module or a package.
Return the file system path to a file for a module, and to a directory for
a package. Return None if the name is not found, or is a builtin or
extension module.
### Response:
def _get_mo... |
def printMe(self, selfKey, selfValue):
'''Parse the single and its value and return the parsed str.
Args:
selfTag (str): The tag. Normally just ``self.tag``
selfValue (list): a list of value elements(single, subclasses, str, int). Normally just ``self.value``
Returns:
... | Parse the single and its value and return the parsed str.
Args:
selfTag (str): The tag. Normally just ``self.tag``
selfValue (list): a list of value elements(single, subclasses, str, int). Normally just ``self.value``
Returns:
str: A parsed text | Below is the the instruction that describes the task:
### Input:
Parse the single and its value and return the parsed str.
Args:
selfTag (str): The tag. Normally just ``self.tag``
selfValue (list): a list of value elements(single, subclasses, str, int). Normally just ``self.value``
... |
def _is_end(event, node, tagName): # pylint: disable=invalid-name
"""Return true if (event, node) is an end event for tagname."""
return event == pulldom.END_ELEMENT and node.tagName == tagName | Return true if (event, node) is an end event for tagname. | Below is the the instruction that describes the task:
### Input:
Return true if (event, node) is an end event for tagname.
### Response:
def _is_end(event, node, tagName): # pylint: disable=invalid-name
"""Return true if (event, node) is an end event for tagname."""
return event == pulldom.END_ELEMENT and... |
def get_snapshot(self, snapshot_id_or_uri, volume_id_or_uri=None):
"""
Gets a snapshot of a volume.
Args:
volume_id_or_uri:
Can be either the volume ID or the volume URI. It is optional if it is passed a snapshot URI,
but required if it passed a snaps... | Gets a snapshot of a volume.
Args:
volume_id_or_uri:
Can be either the volume ID or the volume URI. It is optional if it is passed a snapshot URI,
but required if it passed a snapshot ID.
snapshot_id_or_uri:
Can be either the snapshot ID o... | Below is the the instruction that describes the task:
### Input:
Gets a snapshot of a volume.
Args:
volume_id_or_uri:
Can be either the volume ID or the volume URI. It is optional if it is passed a snapshot URI,
but required if it passed a snapshot ID.
... |
def _sparse_tensor_dense_matmul(sp_a, b, **kwargs):
"""Returns (batched) matmul of a SparseTensor with a Tensor.
Args:
sp_a: `SparseTensor` representing a (batch of) matrices.
b: `Tensor` representing a (batch of) matrices, with the same batch shape of
`sp_a`. The shape must be compatible with the sh... | Returns (batched) matmul of a SparseTensor with a Tensor.
Args:
sp_a: `SparseTensor` representing a (batch of) matrices.
b: `Tensor` representing a (batch of) matrices, with the same batch shape of
`sp_a`. The shape must be compatible with the shape of `sp_a` and kwargs.
**kwargs: Keyword arguments... | Below is the the instruction that describes the task:
### Input:
Returns (batched) matmul of a SparseTensor with a Tensor.
Args:
sp_a: `SparseTensor` representing a (batch of) matrices.
b: `Tensor` representing a (batch of) matrices, with the same batch shape of
`sp_a`. The shape must be compatible... |
def Convert(self, metadata, checkresult, token=None):
"""Converts a single CheckResult.
Args:
metadata: ExportedMetadata to be used for conversion.
checkresult: CheckResult to be converted.
token: Security token.
Yields:
Resulting ExportedCheckResult. Empty list is a valid result a... | Converts a single CheckResult.
Args:
metadata: ExportedMetadata to be used for conversion.
checkresult: CheckResult to be converted.
token: Security token.
Yields:
Resulting ExportedCheckResult. Empty list is a valid result and means that
conversion wasn't possible. | Below is the the instruction that describes the task:
### Input:
Converts a single CheckResult.
Args:
metadata: ExportedMetadata to be used for conversion.
checkresult: CheckResult to be converted.
token: Security token.
Yields:
Resulting ExportedCheckResult. Empty list is a valid ... |
def get_query(self):
"""
Default filters for model
"""
return (
super().get_query()
.filter(or_(models.DagModel.is_active,
models.DagModel.is_paused))
.filter(~models.DagModel.is_subdag)
) | Default filters for model | Below is the the instruction that describes the task:
### Input:
Default filters for model
### Response:
def get_query(self):
"""
Default filters for model
"""
return (
super().get_query()
.filter(or_(models.DagModel.is_active,
models.... |
def _set_request_auth_type_metric(self, request):
"""
Add metric 'request_auth_type' for the authentication type used.
NOTE: This is a best guess at this point. Possible values include:
no-user
unauthenticated
jwt/bearer/other-token-type
session-... | Add metric 'request_auth_type' for the authentication type used.
NOTE: This is a best guess at this point. Possible values include:
no-user
unauthenticated
jwt/bearer/other-token-type
session-or-unknown (catch all) | Below is the the instruction that describes the task:
### Input:
Add metric 'request_auth_type' for the authentication type used.
NOTE: This is a best guess at this point. Possible values include:
no-user
unauthenticated
jwt/bearer/other-token-type
session-o... |
def read_value(self, offset=0):
"""
Reads the value of this descriptor.
When successful, the value will be returned, otherwise `descriptor_read_value_failed()` of the related
device is invoked.
"""
try:
val = self._object.ReadValue(
{'offset':... | Reads the value of this descriptor.
When successful, the value will be returned, otherwise `descriptor_read_value_failed()` of the related
device is invoked. | Below is the the instruction that describes the task:
### Input:
Reads the value of this descriptor.
When successful, the value will be returned, otherwise `descriptor_read_value_failed()` of the related
device is invoked.
### Response:
def read_value(self, offset=0):
"""
Reads the... |
def recipient(self):
"""
:returns: A :class:`~okcupyd.profile.Profile` instance belonging
to the recipient of this message.
"""
return (self._message_thread.correspondent_profile
if 'from_me' in self._message_element.attrib['class']
else ... | :returns: A :class:`~okcupyd.profile.Profile` instance belonging
to the recipient of this message. | Below is the the instruction that describes the task:
### Input:
:returns: A :class:`~okcupyd.profile.Profile` instance belonging
to the recipient of this message.
### Response:
def recipient(self):
"""
:returns: A :class:`~okcupyd.profile.Profile` instance belonging
... |
def p_notificationTypeClause(self, p):
"""notificationTypeClause : fuzzy_lowercase_identifier NOTIFICATION_TYPE NotificationObjectsPart STATUS Status DESCRIPTION Text ReferPart COLON_COLON_EQUAL '{' NotificationName '}'""" # some MIBs have uppercase and/or lowercase id
p[0] = ('notificationTypeClause',... | notificationTypeClause : fuzzy_lowercase_identifier NOTIFICATION_TYPE NotificationObjectsPart STATUS Status DESCRIPTION Text ReferPart COLON_COLON_EQUAL '{' NotificationName '} | Below is the the instruction that describes the task:
### Input:
notificationTypeClause : fuzzy_lowercase_identifier NOTIFICATION_TYPE NotificationObjectsPart STATUS Status DESCRIPTION Text ReferPart COLON_COLON_EQUAL '{' NotificationName '}
### Response:
def p_notificationTypeClause(self, p):
"""notificat... |
def poweroff_server(self, server=None, server_id=None):
"""
Poweroff a VM. If possible to pass the VM object or simply the ID
of the VM that we want to turn on.
Args:
server: VM Object that represent the VM to power off,
server_id: Int or Str representing the ID o... | Poweroff a VM. If possible to pass the VM object or simply the ID
of the VM that we want to turn on.
Args:
server: VM Object that represent the VM to power off,
server_id: Int or Str representing the ID of the VM to power off.
Returns:
return True if json_obj[... | Below is the the instruction that describes the task:
### Input:
Poweroff a VM. If possible to pass the VM object or simply the ID
of the VM that we want to turn on.
Args:
server: VM Object that represent the VM to power off,
server_id: Int or Str representing the ID of the V... |
def create_binary_descriptor(descriptor):
"""Convert a string node descriptor into a 20-byte binary descriptor.
This is the inverse operation of parse_binary_descriptor and composing
the two operations is a noop.
Args:
descriptor (str): A string node descriptor
Returns:
bytes: A 2... | Convert a string node descriptor into a 20-byte binary descriptor.
This is the inverse operation of parse_binary_descriptor and composing
the two operations is a noop.
Args:
descriptor (str): A string node descriptor
Returns:
bytes: A 20-byte binary node descriptor. | Below is the the instruction that describes the task:
### Input:
Convert a string node descriptor into a 20-byte binary descriptor.
This is the inverse operation of parse_binary_descriptor and composing
the two operations is a noop.
Args:
descriptor (str): A string node descriptor
Returns... |
def get_tournament(self, tag: crtag, timeout=0):
"""Get a tournament information
Parameters
----------
tag: str
A valid tournament tag. Minimum length: 3
Valid characters: 0289PYLQGRJCUV
\*\*timeout: Optional[int] = None
Custom timeout that ov... | Get a tournament information
Parameters
----------
tag: str
A valid tournament tag. Minimum length: 3
Valid characters: 0289PYLQGRJCUV
\*\*timeout: Optional[int] = None
Custom timeout that overwrites Client.timeout | Below is the the instruction that describes the task:
### Input:
Get a tournament information
Parameters
----------
tag: str
A valid tournament tag. Minimum length: 3
Valid characters: 0289PYLQGRJCUV
\*\*timeout: Optional[int] = None
Custom timeou... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.