code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def smart_unicode_decode(encoded_string):
"""
Given an encoded string of unknown format, detect the format with
chardet and return the unicode version.
Example input from bug #11:
('\xfe\xff\x00I\x00n\x00s\x00p\x00e\x00c\x00t\x00i\x00o\x00n\x00'
'\x00R\x00e\x00p\x00o... | Given an encoded string of unknown format, detect the format with
chardet and return the unicode version.
Example input from bug #11:
('\xfe\xff\x00I\x00n\x00s\x00p\x00e\x00c\x00t\x00i\x00o\x00n\x00'
'\x00R\x00e\x00p\x00o\x00r\x00t\x00 \x00v\x002\x00.\x002') | Below is the the instruction that describes the task:
### Input:
Given an encoded string of unknown format, detect the format with
chardet and return the unicode version.
Example input from bug #11:
('\xfe\xff\x00I\x00n\x00s\x00p\x00e\x00c\x00t\x00i\x00o\x00n\x00'
'\x00R\x00e\... |
def _process_query(self, query, prepared=False):
""" Process query recursively, if the text is too long,
it is split and processed bit a bit.
Args:
query (sdict): Text to be processed.
prepared (bool): True when the query is ready to be submitted via
POST req... | Process query recursively, if the text is too long,
it is split and processed bit a bit.
Args:
query (sdict): Text to be processed.
prepared (bool): True when the query is ready to be submitted via
POST request.
Returns:
str: Body ready to be subm... | Below is the the instruction that describes the task:
### Input:
Process query recursively, if the text is too long,
it is split and processed bit a bit.
Args:
query (sdict): Text to be processed.
prepared (bool): True when the query is ready to be submitted via
... |
def is_invalid_marker(cls, text):
"""
Validate text as a PEP 426 environment marker; return an exception
if invalid or False otherwise.
"""
try:
cls.evaluate_marker(text)
except SyntaxError:
return cls.normalize_exception(sys.exc_info()[1])
... | Validate text as a PEP 426 environment marker; return an exception
if invalid or False otherwise. | Below is the the instruction that describes the task:
### Input:
Validate text as a PEP 426 environment marker; return an exception
if invalid or False otherwise.
### Response:
def is_invalid_marker(cls, text):
"""
Validate text as a PEP 426 environment marker; return an exception
i... |
def apply_defaults(self, commands):
""" apply default settings to commands
not static, shadow "self" in eval
"""
for command in commands:
if 'action' in command and "()" in command['action']:
command['action'] = eval("self.{}".format(command['action']))
... | apply default settings to commands
not static, shadow "self" in eval | Below is the the instruction that describes the task:
### Input:
apply default settings to commands
not static, shadow "self" in eval
### Response:
def apply_defaults(self, commands):
""" apply default settings to commands
not static, shadow "self" in eval
"""
for co... |
def write(self, file_path):
"""
Write the audio data to file.
Return ``True`` on success, or ``False`` otherwise.
:param string file_path: the path of the output file to be written
:raises: :class:`~aeneas.audiofile.AudioFileNotInitializedError`: if the audio file is not initial... | Write the audio data to file.
Return ``True`` on success, or ``False`` otherwise.
:param string file_path: the path of the output file to be written
:raises: :class:`~aeneas.audiofile.AudioFileNotInitializedError`: if the audio file is not initialized yet
.. versionadded:: 1.2.0 | Below is the the instruction that describes the task:
### Input:
Write the audio data to file.
Return ``True`` on success, or ``False`` otherwise.
:param string file_path: the path of the output file to be written
:raises: :class:`~aeneas.audiofile.AudioFileNotInitializedError`: if the audi... |
def _reindex(self):
"""
Index every sentence into a cluster
"""
self._len2split_idx = {}
last_split = -1
for split_idx, split in enumerate(self._splits):
self._len2split_idx.update(
dict(list(zip(list(range(last_split + 1, split)), [split_idx] ... | Index every sentence into a cluster | Below is the the instruction that describes the task:
### Input:
Index every sentence into a cluster
### Response:
def _reindex(self):
"""
Index every sentence into a cluster
"""
self._len2split_idx = {}
last_split = -1
for split_idx, split in enumerate(self._splits)... |
def add_f95_to_env(env):
"""Add Builders and construction variables for f95 to an Environment."""
try:
F95Suffixes = env['F95FILESUFFIXES']
except KeyError:
F95Suffixes = ['.f95']
#print("Adding %s to f95 suffixes" % F95Suffixes)
try:
F95PPSuffixes = env['F95PPFILESUFFIXES']... | Add Builders and construction variables for f95 to an Environment. | Below is the the instruction that describes the task:
### Input:
Add Builders and construction variables for f95 to an Environment.
### Response:
def add_f95_to_env(env):
"""Add Builders and construction variables for f95 to an Environment."""
try:
F95Suffixes = env['F95FILESUFFIXES']
except Ke... |
def _ScanEncryptedVolumeNode(self, scan_context, scan_node):
"""Scans an encrypted volume node for supported formats.
Args:
scan_context (SourceScannerContext): source scanner context.
scan_node (SourceScanNode): source scan node.
Raises:
BackEndError: if the scan node cannot be unlocked... | Scans an encrypted volume node for supported formats.
Args:
scan_context (SourceScannerContext): source scanner context.
scan_node (SourceScanNode): source scan node.
Raises:
BackEndError: if the scan node cannot be unlocked.
ValueError: if the scan context or scan node is invalid. | Below is the the instruction that describes the task:
### Input:
Scans an encrypted volume node for supported formats.
Args:
scan_context (SourceScannerContext): source scanner context.
scan_node (SourceScanNode): source scan node.
Raises:
BackEndError: if the scan node cannot be unlocke... |
def batch_size(self):
"""int: The number of results to fetch per batch. Clamped to
limit if limit is set and is smaller than the given batch
size.
"""
batch_size = self.get("batch_size", DEFAULT_BATCH_SIZE)
if self.limit is not None:
return min(self.limit, ba... | int: The number of results to fetch per batch. Clamped to
limit if limit is set and is smaller than the given batch
size. | Below is the the instruction that describes the task:
### Input:
int: The number of results to fetch per batch. Clamped to
limit if limit is set and is smaller than the given batch
size.
### Response:
def batch_size(self):
"""int: The number of results to fetch per batch. Clamped to
... |
def check_crc(f, inf, desc):
"""Compare result crc to expected value.
"""
exp = inf._md_expect
if exp is None:
return
ucrc = f._md_context.digest()
if ucrc != exp:
print('crc error - %s - exp=%r got=%r' % (desc, exp, ucrc)) | Compare result crc to expected value. | Below is the the instruction that describes the task:
### Input:
Compare result crc to expected value.
### Response:
def check_crc(f, inf, desc):
"""Compare result crc to expected value.
"""
exp = inf._md_expect
if exp is None:
return
ucrc = f._md_context.digest()
if ucrc != exp:
... |
def write(connection, skip, directory, force):
"""Write all as BEL."""
os.makedirs(directory, exist_ok=True)
from .manager.bel_manager import BELManagerMixin
import pybel
for idx, name, manager in _iterate_managers(connection, skip):
if not isinstance(manager, BELManagerMixin):
c... | Write all as BEL. | Below is the the instruction that describes the task:
### Input:
Write all as BEL.
### Response:
def write(connection, skip, directory, force):
"""Write all as BEL."""
os.makedirs(directory, exist_ok=True)
from .manager.bel_manager import BELManagerMixin
import pybel
for idx, name, manager in _... |
def overlaps(self, box, th=0.0001):
"""
Check whether this box and given box overlaps at least by given threshold.
:param box: Box to compare with
:param th: Threshold above which overlapping should be considered
:returns: True if overlaps
"""
int_box = Box.inter... | Check whether this box and given box overlaps at least by given threshold.
:param box: Box to compare with
:param th: Threshold above which overlapping should be considered
:returns: True if overlaps | Below is the the instruction that describes the task:
### Input:
Check whether this box and given box overlaps at least by given threshold.
:param box: Box to compare with
:param th: Threshold above which overlapping should be considered
:returns: True if overlaps
### Response:
def overlap... |
def time(self) -> Time:
"""Generate a random time object.
:return: ``datetime.time`` object.
"""
random_time = time(
self.random.randint(0, 23),
self.random.randint(0, 59),
self.random.randint(0, 59),
self.random.randint(0, 999999),
... | Generate a random time object.
:return: ``datetime.time`` object. | Below is the the instruction that describes the task:
### Input:
Generate a random time object.
:return: ``datetime.time`` object.
### Response:
def time(self) -> Time:
"""Generate a random time object.
:return: ``datetime.time`` object.
"""
random_time = time(
... |
def condition_details_has_owner(condition_details, owner):
"""Check if the public_key of owner is in the condition details
as an Ed25519Fulfillment.public_key
Args:
condition_details (dict): dict with condition details
owner (str): base58 public key of owner
Returns:
bool: True... | Check if the public_key of owner is in the condition details
as an Ed25519Fulfillment.public_key
Args:
condition_details (dict): dict with condition details
owner (str): base58 public key of owner
Returns:
bool: True if the public key is found in the condition details, False otherw... | Below is the the instruction that describes the task:
### Input:
Check if the public_key of owner is in the condition details
as an Ed25519Fulfillment.public_key
Args:
condition_details (dict): dict with condition details
owner (str): base58 public key of owner
Returns:
bool: T... |
def virtual_networks_list_all(**kwargs):
'''
.. versionadded:: 2019.2.0
List all virtual networks within a subscription.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.virtual_networks_list_all
'''
result = {}
netconn = __utils__['azurearm.get_client']('network... | .. versionadded:: 2019.2.0
List all virtual networks within a subscription.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.virtual_networks_list_all | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 2019.2.0
List all virtual networks within a subscription.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.virtual_networks_list_all
### Response:
def virtual_networks_list_all(**kwargs):
'''
... |
def get_param(par, args, m1, m2, s1z, s2z):
"""
Helper function
Parameters
----------
par : string
Name of parameter to calculate
args : Namespace object returned from ArgumentParser instance
Calling code command line options, used for f_lower value
m1 : float or array of fl... | Helper function
Parameters
----------
par : string
Name of parameter to calculate
args : Namespace object returned from ArgumentParser instance
Calling code command line options, used for f_lower value
m1 : float or array of floats
First binary component mass (etc.)
Ret... | Below is the the instruction that describes the task:
### Input:
Helper function
Parameters
----------
par : string
Name of parameter to calculate
args : Namespace object returned from ArgumentParser instance
Calling code command line options, used for f_lower value
m1 : float o... |
def _run_cmd(cmd):
"""Run command specified by :cmd: and return stdout, stderr and code."""
if not os.path.exists(cmd[0]):
cmd[0] = shutil.which(cmd[0])
assert cmd[0] is not None
shebang_parts = parseshebang.parse(cmd[0])
proc = subprocess.Popen(shebang_parts + cmd,
... | Run command specified by :cmd: and return stdout, stderr and code. | Below is the the instruction that describes the task:
### Input:
Run command specified by :cmd: and return stdout, stderr and code.
### Response:
def _run_cmd(cmd):
"""Run command specified by :cmd: and return stdout, stderr and code."""
if not os.path.exists(cmd[0]):
cmd[0] = shutil.which(cmd[0])
... |
def on_put(self, request, response, txn_id=None):
"""Responds to PUT request containing events."""
response.body = "{}"
# Check whether repeat txn_id
if not self._is_new(txn_id):
response.status = falcon.HTTP_200
return
request.context["body"] = request.... | Responds to PUT request containing events. | Below is the the instruction that describes the task:
### Input:
Responds to PUT request containing events.
### Response:
def on_put(self, request, response, txn_id=None):
"""Responds to PUT request containing events."""
response.body = "{}"
# Check whether repeat txn_id
if not sel... |
def readline(self, size=None):
"""Read a single line from rfile buffer and return it.
Args:
size (int): minimum amount of data to read
Returns:
bytes: One line from rfile.
"""
data = EMPTY
if size == 0:
return data
while Tr... | Read a single line from rfile buffer and return it.
Args:
size (int): minimum amount of data to read
Returns:
bytes: One line from rfile. | Below is the the instruction that describes the task:
### Input:
Read a single line from rfile buffer and return it.
Args:
size (int): minimum amount of data to read
Returns:
bytes: One line from rfile.
### Response:
def readline(self, size=None):
"""Read a single ... |
def createReference(self, fromnode, tonode, edge_data=None):
"""
Create a reference from fromnode to tonode
"""
if fromnode is None:
fromnode = self
fromident, toident = self.getIdent(fromnode), self.getIdent(tonode)
if fromident is None or toident is None:
... | Create a reference from fromnode to tonode | Below is the the instruction that describes the task:
### Input:
Create a reference from fromnode to tonode
### Response:
def createReference(self, fromnode, tonode, edge_data=None):
"""
Create a reference from fromnode to tonode
"""
if fromnode is None:
fromnode = self
... |
def searchTriples(filenames,plant=False):
"""Given a list of exposure numbers, find all the KBOs in that set of exposures"""
print filenames
if opt.none :
return
import MOPfits,os
import MOPdbaccess
import string
import os.path
import pyfits
if len(filenames)!=3:
... | Given a list of exposure numbers, find all the KBOs in that set of exposures | Below is the the instruction that describes the task:
### Input:
Given a list of exposure numbers, find all the KBOs in that set of exposures
### Response:
def searchTriples(filenames,plant=False):
"""Given a list of exposure numbers, find all the KBOs in that set of exposures"""
print filenames
if op... |
def _remove_media(self,directory,files=None):
"""Removes specified files from flickr"""
# Connect if we aren't already
if not self._connectToFlickr():
logger.error("%s - Couldn't connect to flickr")
return False
db=self._loadDB(directory)
# If no files gi... | Removes specified files from flickr | Below is the the instruction that describes the task:
### Input:
Removes specified files from flickr
### Response:
def _remove_media(self,directory,files=None):
"""Removes specified files from flickr"""
# Connect if we aren't already
if not self._connectToFlickr():
logger.error(... |
def _append(self, menu):
'''append this menu item to a menu'''
from wx_loader import wx
menu.AppendMenu(-1, self.name, self.wx_menu()) | append this menu item to a menu | Below is the the instruction that describes the task:
### Input:
append this menu item to a menu
### Response:
def _append(self, menu):
'''append this menu item to a menu'''
from wx_loader import wx
menu.AppendMenu(-1, self.name, self.wx_menu()) |
def to_uint(self):
"""Convert vector to an unsigned integer, if possible.
This is only useful for arrays filled with zero/one entries.
"""
num = 0
for i, f in enumerate(self._items):
if f.is_zero():
pass
elif f.is_one():
nu... | Convert vector to an unsigned integer, if possible.
This is only useful for arrays filled with zero/one entries. | Below is the the instruction that describes the task:
### Input:
Convert vector to an unsigned integer, if possible.
This is only useful for arrays filled with zero/one entries.
### Response:
def to_uint(self):
"""Convert vector to an unsigned integer, if possible.
This is only useful for... |
def smooth(self, smoothing_factor):
"""
return a new time series which is a exponential smoothed version of the original data series.
soomth forward once, backward once, and then take the average.
:param float smoothing_factor: smoothing factor
:return: :class:`TimeSeries` objec... | return a new time series which is a exponential smoothed version of the original data series.
soomth forward once, backward once, and then take the average.
:param float smoothing_factor: smoothing factor
:return: :class:`TimeSeries` object. | Below is the the instruction that describes the task:
### Input:
return a new time series which is a exponential smoothed version of the original data series.
soomth forward once, backward once, and then take the average.
:param float smoothing_factor: smoothing factor
:return: :class:`Time... |
def _run_pants(self, sock, arguments, environment):
"""Execute a given run with a pants runner."""
self.server.runner_factory(sock, arguments, environment).run() | Execute a given run with a pants runner. | Below is the the instruction that describes the task:
### Input:
Execute a given run with a pants runner.
### Response:
def _run_pants(self, sock, arguments, environment):
"""Execute a given run with a pants runner."""
self.server.runner_factory(sock, arguments, environment).run() |
def get_object_url(self):
"""
Returns the url to link to the object
The get_view_url will be called on the current bundle using
'edit` as the view name.
"""
return self.bundle.get_view_url('edit',
self.request.user, {}, self.kwargs) | Returns the url to link to the object
The get_view_url will be called on the current bundle using
'edit` as the view name. | Below is the the instruction that describes the task:
### Input:
Returns the url to link to the object
The get_view_url will be called on the current bundle using
'edit` as the view name.
### Response:
def get_object_url(self):
"""
Returns the url to link to the object
The g... |
def _get_secret_from_vault(
key, environment=None, stage=None, namespace=None,
wait_exponential_multiplier=50, wait_exponential_max=5000,
stop_max_delay=10000):
"""Retrieves a secret from the secrets vault."""
# Get the encrypted secret from DynamoDB
table_name = _secrets_table_name(... | Retrieves a secret from the secrets vault. | Below is the the instruction that describes the task:
### Input:
Retrieves a secret from the secrets vault.
### Response:
def _get_secret_from_vault(
key, environment=None, stage=None, namespace=None,
wait_exponential_multiplier=50, wait_exponential_max=5000,
stop_max_delay=10000):
"""R... |
def populateFromFile(self, dataUrls, indexFiles):
"""
Populates this variant set using the specified lists of data
files and indexes. These must be in the same order, such that
the jth index file corresponds to the jth data file.
"""
assert len(dataUrls) == len(indexFiles... | Populates this variant set using the specified lists of data
files and indexes. These must be in the same order, such that
the jth index file corresponds to the jth data file. | Below is the the instruction that describes the task:
### Input:
Populates this variant set using the specified lists of data
files and indexes. These must be in the same order, such that
the jth index file corresponds to the jth data file.
### Response:
def populateFromFile(self, dataUrls, indexFi... |
def getattr_path(obj, path):
"""
Get an attribute path, as defined by a string separated by '__'.
getattr_path(foo, 'a__b__c') is roughly equivalent to foo.a.b.c but
will short circuit to return None if something on the path is None.
"""
path = path.split('__')
for name in path:
obj ... | Get an attribute path, as defined by a string separated by '__'.
getattr_path(foo, 'a__b__c') is roughly equivalent to foo.a.b.c but
will short circuit to return None if something on the path is None. | Below is the the instruction that describes the task:
### Input:
Get an attribute path, as defined by a string separated by '__'.
getattr_path(foo, 'a__b__c') is roughly equivalent to foo.a.b.c but
will short circuit to return None if something on the path is None.
### Response:
def getattr_path(obj, path)... |
def get_role_policy(role_name, policy_name, region=None, key=None,
keyid=None, profile=None):
'''
Get a role policy.
CLI Example:
.. code-block:: bash
salt myminion boto_iam.get_role_policy myirole mypolicy
'''
conn = _get_conn(region=region, key=key, keyid=keyid, ... | Get a role policy.
CLI Example:
.. code-block:: bash
salt myminion boto_iam.get_role_policy myirole mypolicy | Below is the the instruction that describes the task:
### Input:
Get a role policy.
CLI Example:
.. code-block:: bash
salt myminion boto_iam.get_role_policy myirole mypolicy
### Response:
def get_role_policy(role_name, policy_name, region=None, key=None,
keyid=None, profile=N... |
def partition_horizontal_twice(thelist, numbers):
"""
numbers is split on a comma to n and n2.
Break a list into peices each peice alternating between n and n2 items long
``partition_horizontal_twice(range(14), "3,4")`` gives::
[[0, 1, 2],
[3, 4, 5, 6],
[7, 8, 9],
... | numbers is split on a comma to n and n2.
Break a list into peices each peice alternating between n and n2 items long
``partition_horizontal_twice(range(14), "3,4")`` gives::
[[0, 1, 2],
[3, 4, 5, 6],
[7, 8, 9],
[10, 11, 12, 13]]
Clear as mud? | Below is the the instruction that describes the task:
### Input:
numbers is split on a comma to n and n2.
Break a list into peices each peice alternating between n and n2 items long
``partition_horizontal_twice(range(14), "3,4")`` gives::
[[0, 1, 2],
[3, 4, 5, 6],
[7, 8, 9],... |
def abstract(class_):
"""Mark the class as _abstract_ base class, forbidding its instantiation.
.. note::
Unlike other modifiers, ``@abstract`` can be applied
to all Python classes, not just subclasses of :class:`Object`.
.. versionadded:: 0.0.3
"""
if not inspect.isclass(class_):... | Mark the class as _abstract_ base class, forbidding its instantiation.
.. note::
Unlike other modifiers, ``@abstract`` can be applied
to all Python classes, not just subclasses of :class:`Object`.
.. versionadded:: 0.0.3 | Below is the the instruction that describes the task:
### Input:
Mark the class as _abstract_ base class, forbidding its instantiation.
.. note::
Unlike other modifiers, ``@abstract`` can be applied
to all Python classes, not just subclasses of :class:`Object`.
.. versionadded:: 0.0.3
###... |
def libvlc_video_get_size(p_mi, num):
'''Get the pixel dimensions of a video.
@param p_mi: media player.
@param num: number of the video (starting from, and most commonly 0).
@return: px pixel width, py pixel height.
'''
f = _Cfunctions.get('libvlc_video_get_size', None) or \
_Cfunction(... | Get the pixel dimensions of a video.
@param p_mi: media player.
@param num: number of the video (starting from, and most commonly 0).
@return: px pixel width, py pixel height. | Below is the the instruction that describes the task:
### Input:
Get the pixel dimensions of a video.
@param p_mi: media player.
@param num: number of the video (starting from, and most commonly 0).
@return: px pixel width, py pixel height.
### Response:
def libvlc_video_get_size(p_mi, num):
'''Get... |
def clear_stale_pids(pids, pid_dir='/tmp', prefix='', multi=False):
'check for and remove any pids which have no corresponding process'
if isinstance(pids, (int, float, long)):
pids = [pids]
pids = str2list(pids, map_=unicode)
procs = map(unicode, os.listdir('/proc'))
running = [pid for pid ... | check for and remove any pids which have no corresponding process | Below is the the instruction that describes the task:
### Input:
check for and remove any pids which have no corresponding process
### Response:
def clear_stale_pids(pids, pid_dir='/tmp', prefix='', multi=False):
'check for and remove any pids which have no corresponding process'
if isinstance(pids, (int, ... |
def mean(a, rep=0.75, **kwargs):
"""Compute the average along a 1D array like ma.mean,
but with a representativity coefficient : if ma.count(a)/ma.size(a)>=rep,
then the result is a masked value
"""
return rfunc(a, ma.mean, rep, **kwargs) | Compute the average along a 1D array like ma.mean,
but with a representativity coefficient : if ma.count(a)/ma.size(a)>=rep,
then the result is a masked value | Below is the the instruction that describes the task:
### Input:
Compute the average along a 1D array like ma.mean,
but with a representativity coefficient : if ma.count(a)/ma.size(a)>=rep,
then the result is a masked value
### Response:
def mean(a, rep=0.75, **kwargs):
"""Compute the average along a 1... |
def verifyG1(x, tTilde, y, pi, errorOnFail=True):
"""
Verifies a zero-knowledge proof where p \in G1.
@errorOnFail: Raise an exception if the proof does not hold.
"""
# Unpack the proof
p,c,u = pi
# Verify types
assertType(x, G1Element)
assertType(tTilde, G2Element)
assertType(y... | Verifies a zero-knowledge proof where p \in G1.
@errorOnFail: Raise an exception if the proof does not hold. | Below is the the instruction that describes the task:
### Input:
Verifies a zero-knowledge proof where p \in G1.
@errorOnFail: Raise an exception if the proof does not hold.
### Response:
def verifyG1(x, tTilde, y, pi, errorOnFail=True):
"""
Verifies a zero-knowledge proof where p \in G1.
@errorOnF... |
def fisher_mean(data):
"""
Calculates the Fisher mean and associated parameter from a di_block
Parameters
----------
di_block : a nested list of [dec,inc] or [dec,inc,intensity]
Returns
-------
fpars : dictionary containing the Fisher mean and statistics
dec : mean declination
... | Calculates the Fisher mean and associated parameter from a di_block
Parameters
----------
di_block : a nested list of [dec,inc] or [dec,inc,intensity]
Returns
-------
fpars : dictionary containing the Fisher mean and statistics
dec : mean declination
inc : mean inclination
... | Below is the the instruction that describes the task:
### Input:
Calculates the Fisher mean and associated parameter from a di_block
Parameters
----------
di_block : a nested list of [dec,inc] or [dec,inc,intensity]
Returns
-------
fpars : dictionary containing the Fisher mean and statisti... |
def bulk_insert_rows(self, table, rows, target_fields=None, commit_every=5000):
"""
A performant bulk insert for cx_Oracle
that uses prepared statements via `executemany()`.
For best performance, pass in `rows` as an iterator.
:param table: target Oracle table, use dot notation ... | A performant bulk insert for cx_Oracle
that uses prepared statements via `executemany()`.
For best performance, pass in `rows` as an iterator.
:param table: target Oracle table, use dot notation to target a
specific database
:type table: str
:param rows: the rows to ... | Below is the the instruction that describes the task:
### Input:
A performant bulk insert for cx_Oracle
that uses prepared statements via `executemany()`.
For best performance, pass in `rows` as an iterator.
:param table: target Oracle table, use dot notation to target a
specifi... |
def chipqc(bam_file, sample, out_dir):
"""Attempt code to run ChIPQC bioconductor packate in one sample"""
sample_name = dd.get_sample_name(sample)
logger.warning("ChIPQC is unstable right now, if it breaks, turn off the tool.")
if utils.file_exists(out_dir):
return _get_output(out_dir)
with... | Attempt code to run ChIPQC bioconductor packate in one sample | Below is the the instruction that describes the task:
### Input:
Attempt code to run ChIPQC bioconductor packate in one sample
### Response:
def chipqc(bam_file, sample, out_dir):
"""Attempt code to run ChIPQC bioconductor packate in one sample"""
sample_name = dd.get_sample_name(sample)
logger.warning... |
def _NSPrefix(self, ns):
""" Get xml ns prefix. self.nsMap must be set """
if ns == self.defaultNS:
return ''
prefix = self.nsMap[ns]
return prefix and prefix + ':' or '' | Get xml ns prefix. self.nsMap must be set | Below is the the instruction that describes the task:
### Input:
Get xml ns prefix. self.nsMap must be set
### Response:
def _NSPrefix(self, ns):
""" Get xml ns prefix. self.nsMap must be set """
if ns == self.defaultNS:
return ''
prefix = self.nsMap[ns]
return prefix and prefix + ... |
def update_queue(self):
"""Update queue"""
started = 0
for parent_id, threadlist in list(self.started_threads.items()):
still_running = []
for thread in threadlist:
if thread.isFinished():
end_callback = self.end_callbacks.pop(id... | Update queue | Below is the the instruction that describes the task:
### Input:
Update queue
### Response:
def update_queue(self):
"""Update queue"""
started = 0
for parent_id, threadlist in list(self.started_threads.items()):
still_running = []
for thread in threadlist:
... |
def get_subdomain_entry(self, fqn, accepted=True, cur=None):
"""
Given a fully-qualified subdomain, get its (latest) subdomain record.
Raises SubdomainNotFound if there is no such subdomain
"""
get_cmd = "SELECT * FROM {} WHERE fully_qualified_subdomain=? {} ORDER BY sequence DES... | Given a fully-qualified subdomain, get its (latest) subdomain record.
Raises SubdomainNotFound if there is no such subdomain | Below is the the instruction that describes the task:
### Input:
Given a fully-qualified subdomain, get its (latest) subdomain record.
Raises SubdomainNotFound if there is no such subdomain
### Response:
def get_subdomain_entry(self, fqn, accepted=True, cur=None):
"""
Given a fully-qualifie... |
def advance_recurring_todo(p_todo, p_offset=None, p_strict=False):
"""
Given a Todo item, return a new instance of a Todo item with the dates
shifted according to the recurrence rule.
Strict means that the real due date is taken as a offset, not today or a
future date to determine the offset.
... | Given a Todo item, return a new instance of a Todo item with the dates
shifted according to the recurrence rule.
Strict means that the real due date is taken as a offset, not today or a
future date to determine the offset.
When the todo item has no due date, then the date is used passed by the
cal... | Below is the the instruction that describes the task:
### Input:
Given a Todo item, return a new instance of a Todo item with the dates
shifted according to the recurrence rule.
Strict means that the real due date is taken as a offset, not today or a
future date to determine the offset.
When the t... |
def add_key_value(self, key, value):
"""Add custom field to Group object.
.. note:: The key must be the exact name required by the batch schema.
Example::
document = tcex.batch.group('Document', 'My Document')
document.add_key_value('fileName', 'something.pdf')
... | Add custom field to Group object.
.. note:: The key must be the exact name required by the batch schema.
Example::
document = tcex.batch.group('Document', 'My Document')
document.add_key_value('fileName', 'something.pdf')
Args:
key (str): The field key to ... | Below is the the instruction that describes the task:
### Input:
Add custom field to Group object.
.. note:: The key must be the exact name required by the batch schema.
Example::
document = tcex.batch.group('Document', 'My Document')
document.add_key_value('fileName', 'so... |
def run_da(self, rs, overwrite=True, skip_existing=False, path=None,
chunksize=None):
"""Compute timestamps for current populations."""
if path is None:
path = str(self.S.store.filepath.parent)
kwargs = dict(rs=rs, overwrite=overwrite, path=path,
... | Compute timestamps for current populations. | Below is the the instruction that describes the task:
### Input:
Compute timestamps for current populations.
### Response:
def run_da(self, rs, overwrite=True, skip_existing=False, path=None,
chunksize=None):
"""Compute timestamps for current populations."""
if path is None:
... |
def consume(self, length):
"""
>>> OutBuffer().add(b"spam").consume(2).getvalue() == b"am"
True
@type length: int
@returns: self
"""
self.buff = io.BytesIO(self.getvalue()[length:])
return self | >>> OutBuffer().add(b"spam").consume(2).getvalue() == b"am"
True
@type length: int
@returns: self | Below is the the instruction that describes the task:
### Input:
>>> OutBuffer().add(b"spam").consume(2).getvalue() == b"am"
True
@type length: int
@returns: self
### Response:
def consume(self, length):
"""
>>> OutBuffer().add(b"spam").consume(2).getvalue() == b"am"
True
@type length: int
@retur... |
def walk(dispatcher, node, definition=None):
"""
The default, standalone walk function following the standard
argument ordering for the unparsing walkers.
Arguments:
dispatcher
a Dispatcher instance, defined earlier in this module. This
instance will dispatch out the correct calla... | The default, standalone walk function following the standard
argument ordering for the unparsing walkers.
Arguments:
dispatcher
a Dispatcher instance, defined earlier in this module. This
instance will dispatch out the correct callable for the various
object types encountered thro... | Below is the the instruction that describes the task:
### Input:
The default, standalone walk function following the standard
argument ordering for the unparsing walkers.
Arguments:
dispatcher
a Dispatcher instance, defined earlier in this module. This
instance will dispatch out the c... |
def diff(self, path_a, path_b):
""" Performs a deep comparison of path_a/ and path_b/
For each child, it yields (rv, child) where rv:
-1 if doesn't exist in path_b (destination)
0 if they are different
1 if it doesn't exist in path_a (source)
"""
... | Performs a deep comparison of path_a/ and path_b/
For each child, it yields (rv, child) where rv:
-1 if doesn't exist in path_b (destination)
0 if they are different
1 if it doesn't exist in path_a (source) | Below is the the instruction that describes the task:
### Input:
Performs a deep comparison of path_a/ and path_b/
For each child, it yields (rv, child) where rv:
-1 if doesn't exist in path_b (destination)
0 if they are different
1 if it doesn't exist in path_a... |
def resource_create_ticket(self, token, id, scopes, **kwargs):
"""
Create a ticket form permission to resource.
https://www.keycloak.org/docs/latest/authorization_services/index.html#_service_protection_permission_api_papi
:param str token: user access token
:param str id: reso... | Create a ticket form permission to resource.
https://www.keycloak.org/docs/latest/authorization_services/index.html#_service_protection_permission_api_papi
:param str token: user access token
:param str id: resource id
:param list scopes: scopes access is wanted
:param dict cla... | Below is the the instruction that describes the task:
### Input:
Create a ticket form permission to resource.
https://www.keycloak.org/docs/latest/authorization_services/index.html#_service_protection_permission_api_papi
:param str token: user access token
:param str id: resource id
... |
def get_last_nonce(app, key, nonce):
"""
Get the last_nonce used by the given key from the SQLAlchemy database.
Update the last_nonce to nonce at the same time.
:param str key: the public key the nonce belongs to
:param int nonce: the last nonce used by this key
"""
uk = ses.query(um.UserKe... | Get the last_nonce used by the given key from the SQLAlchemy database.
Update the last_nonce to nonce at the same time.
:param str key: the public key the nonce belongs to
:param int nonce: the last nonce used by this key | Below is the the instruction that describes the task:
### Input:
Get the last_nonce used by the given key from the SQLAlchemy database.
Update the last_nonce to nonce at the same time.
:param str key: the public key the nonce belongs to
:param int nonce: the last nonce used by this key
### Response:
d... |
def clusters(self):
"""Instance depends on the API version:
* 2018-01-01-preview: :class:`ClustersOperations<azure.mgmt.eventhub.v2018_01_01_preview.operations.ClustersOperations>`
"""
api_version = self._get_api_version('clusters')
if api_version == '2018-01-01-preview':
... | Instance depends on the API version:
* 2018-01-01-preview: :class:`ClustersOperations<azure.mgmt.eventhub.v2018_01_01_preview.operations.ClustersOperations>` | Below is the the instruction that describes the task:
### Input:
Instance depends on the API version:
* 2018-01-01-preview: :class:`ClustersOperations<azure.mgmt.eventhub.v2018_01_01_preview.operations.ClustersOperations>`
### Response:
def clusters(self):
"""Instance depends on the API version... |
def ext_pillar(minion_id, # pylint: disable=W0613
pillar, # pylint: disable=W0613
conf,
nesting_key=None):
'''
Get pillar data from Vault for the configuration ``conf``.
'''
comps = conf.split()
paths = [comp for comp in comps if comp.startswith('path=... | Get pillar data from Vault for the configuration ``conf``. | Below is the the instruction that describes the task:
### Input:
Get pillar data from Vault for the configuration ``conf``.
### Response:
def ext_pillar(minion_id, # pylint: disable=W0613
pillar, # pylint: disable=W0613
conf,
nesting_key=None):
'''
Get pillar ... |
def nodeSatisfiesValues(cntxt: Context, n: Node, nc: ShExJ.NodeConstraint, _c: DebugContext) -> bool:
""" `5.4.5 Values Constraint <http://shex.io/shex-semantics/#values>`_
For a node n and constraint value v, nodeSatisfies(n, v) if n matches some valueSetValue vsv in v.
"""
if nc.values is None:
... | `5.4.5 Values Constraint <http://shex.io/shex-semantics/#values>`_
For a node n and constraint value v, nodeSatisfies(n, v) if n matches some valueSetValue vsv in v. | Below is the the instruction that describes the task:
### Input:
`5.4.5 Values Constraint <http://shex.io/shex-semantics/#values>`_
For a node n and constraint value v, nodeSatisfies(n, v) if n matches some valueSetValue vsv in v.
### Response:
def nodeSatisfiesValues(cntxt: Context, n: Node, nc: ShExJ.NodeC... |
def set_image(self, image):
"""
Update the current comparison (real) image
"""
if isinstance(image, np.ndarray):
image = util.Image(image)
if isinstance(image, util.NullImage):
self.model_as_data = True
else:
self.model_as_data = False... | Update the current comparison (real) image | Below is the the instruction that describes the task:
### Input:
Update the current comparison (real) image
### Response:
def set_image(self, image):
"""
Update the current comparison (real) image
"""
if isinstance(image, np.ndarray):
image = util.Image(image)
i... |
def directories(self):
""" Return the names of directories to be created. """
directories_description = [
self.project_name,
self.project_name + '/conf',
self.project_name + '/static',
]
return directories_description | Return the names of directories to be created. | Below is the the instruction that describes the task:
### Input:
Return the names of directories to be created.
### Response:
def directories(self):
""" Return the names of directories to be created. """
directories_description = [
self.project_name,
self.project_name + '/co... |
def _get_collection_restrictions(collection):
"""Get all restrictions for a given collection, users and fireroles."""
try:
from invenio.dbquery import run_sql
from invenio.access_control_firerole import compile_role_definition
except ImportError:
from invenio.modules.access.firerole ... | Get all restrictions for a given collection, users and fireroles. | Below is the the instruction that describes the task:
### Input:
Get all restrictions for a given collection, users and fireroles.
### Response:
def _get_collection_restrictions(collection):
"""Get all restrictions for a given collection, users and fireroles."""
try:
from invenio.dbquery import run... |
def is_in_interval(n, l, r, border = 'included'):
"""
Checks whether a number is inside the interval l, r.
"""
if 'included' == border:
return (n >= l) and (n <= r)
elif 'excluded' == border:
return (n > l) and (n < r)
else:
raise Value... | Checks whether a number is inside the interval l, r. | Below is the the instruction that describes the task:
### Input:
Checks whether a number is inside the interval l, r.
### Response:
def is_in_interval(n, l, r, border = 'included'):
"""
Checks whether a number is inside the interval l, r.
"""
if 'included' == border:
ret... |
def save_file(data_file, data, dry_run=None):
"""Writes JSON data to data file."""
if dry_run:
return
with open(data_file, 'w', encoding='utf-8') as f:
if sys.version_info > (3, 0):
f.write(json.dumps(data))
else:
f.write(json.dumps(data).decode('utf-8')) | Writes JSON data to data file. | Below is the the instruction that describes the task:
### Input:
Writes JSON data to data file.
### Response:
def save_file(data_file, data, dry_run=None):
"""Writes JSON data to data file."""
if dry_run:
return
with open(data_file, 'w', encoding='utf-8') as f:
if sys.version_info > (3... |
def export(self):
"""
Returns a representation of the Mechanism Name which is suitable for direct string
comparison against other exported Mechanism Names. Its form is defined in the GSSAPI
specification (RFC 2743). It can also be re-imported by constructing a :class:`Name` with
... | Returns a representation of the Mechanism Name which is suitable for direct string
comparison against other exported Mechanism Names. Its form is defined in the GSSAPI
specification (RFC 2743). It can also be re-imported by constructing a :class:`Name` with
the `name_type` param set to :const:`g... | Below is the the instruction that describes the task:
### Input:
Returns a representation of the Mechanism Name which is suitable for direct string
comparison against other exported Mechanism Names. Its form is defined in the GSSAPI
specification (RFC 2743). It can also be re-imported by constructin... |
def toggle(self, key):
""" Toggles a boolean key """
val = self[key]
assert isinstance(val, bool), 'key[%r] = %r is not a bool' % (key, val)
self.pref_update(key, not val) | Toggles a boolean key | Below is the the instruction that describes the task:
### Input:
Toggles a boolean key
### Response:
def toggle(self, key):
""" Toggles a boolean key """
val = self[key]
assert isinstance(val, bool), 'key[%r] = %r is not a bool' % (key, val)
self.pref_update(key, not val) |
def access_to_sympy(self, var_name, access):
"""
Transform a (multidimensional) variable access to a flattend sympy expression.
Also works with flat array accesses.
"""
base_sizes = self.variables[var_name][1]
expr = sympy.Number(0)
for dimension, a in enumerat... | Transform a (multidimensional) variable access to a flattend sympy expression.
Also works with flat array accesses. | Below is the the instruction that describes the task:
### Input:
Transform a (multidimensional) variable access to a flattend sympy expression.
Also works with flat array accesses.
### Response:
def access_to_sympy(self, var_name, access):
"""
Transform a (multidimensional) variable access... |
def interp_like(self, other, method='linear', assume_sorted=False,
kwargs={}):
"""Interpolate this object onto the coordinates of another object,
filling the out of range values with NaN.
Parameters
----------
other : Dataset or DataArray
Object w... | Interpolate this object onto the coordinates of another object,
filling the out of range values with NaN.
Parameters
----------
other : Dataset or DataArray
Object with an 'indexes' attribute giving a mapping from dimension
names to an 1d array-like, which provid... | Below is the the instruction that describes the task:
### Input:
Interpolate this object onto the coordinates of another object,
filling the out of range values with NaN.
Parameters
----------
other : Dataset or DataArray
Object with an 'indexes' attribute giving a mappi... |
def search_bm25(cls, term, weights=None, with_score=False,
score_alias='score', explicit_ordering=False):
"""Full-text search using selected `term`."""
if not weights:
rank = SQL('rank')
elif isinstance(weights, dict):
weight_args = []
for ... | Full-text search using selected `term`. | Below is the the instruction that describes the task:
### Input:
Full-text search using selected `term`.
### Response:
def search_bm25(cls, term, weights=None, with_score=False,
score_alias='score', explicit_ordering=False):
"""Full-text search using selected `term`."""
if not w... |
def present(name,
source,
aliases=None,
public=None,
auto_update=None,
remote_addr=None,
cert=None,
key=None,
verify_cert=True):
'''
Ensure an image exists, copy it else from source
name :
An alias of th... | Ensure an image exists, copy it else from source
name :
An alias of the image, this is used to check if the image exists and
it will be added as alias to the image on copy/create.
source :
Source dict.
For an LXD to LXD copy:
.. code-block: yaml
source:
... | Below is the the instruction that describes the task:
### Input:
Ensure an image exists, copy it else from source
name :
An alias of the image, this is used to check if the image exists and
it will be added as alias to the image on copy/create.
source :
Source dict.
For an... |
def add_protein_to_organisms(self, orgprot_list):
'''
Protein factory method.
Iterates through a list of SearchIO hit objects, matches
the accession against SeqRecord features for each organism.
If there is a match, the new Protein object is created and
stored in the pr... | Protein factory method.
Iterates through a list of SearchIO hit objects, matches
the accession against SeqRecord features for each organism.
If there is a match, the new Protein object is created and
stored in the protein list of that Organism.
Args
orgprot_list: a ... | Below is the the instruction that describes the task:
### Input:
Protein factory method.
Iterates through a list of SearchIO hit objects, matches
the accession against SeqRecord features for each organism.
If there is a match, the new Protein object is created and
stored in the prot... |
def callback_handler_install(self, prompt, callback):
u'''bool readline_callback_handler_install ( string prompt, callback callback)
Initializes the readline callback interface and terminal, prints the prompt and returns immediately
'''
self.callback = callback
self.readline_setu... | u'''bool readline_callback_handler_install ( string prompt, callback callback)
Initializes the readline callback interface and terminal, prints the prompt and returns immediately | Below is the the instruction that describes the task:
### Input:
u'''bool readline_callback_handler_install ( string prompt, callback callback)
Initializes the readline callback interface and terminal, prints the prompt and returns immediately
### Response:
def callback_handler_install(self, prompt, callba... |
def _inject():
""" Copy functions from OpenGL.GL into _pyopengl namespace.
"""
NS = _pyopengl2.__dict__
for glname, ourname in _pyopengl2._functions_to_import:
func = _get_function_from_pyopengl(glname)
NS[ourname] = func | Copy functions from OpenGL.GL into _pyopengl namespace. | Below is the the instruction that describes the task:
### Input:
Copy functions from OpenGL.GL into _pyopengl namespace.
### Response:
def _inject():
""" Copy functions from OpenGL.GL into _pyopengl namespace.
"""
NS = _pyopengl2.__dict__
for glname, ourname in _pyopengl2._functions_to_import:
... |
def show_system_monitor_output_switch_status_switch_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_system_monitor = ET.Element("show_system_monitor")
config = show_system_monitor
output = ET.SubElement(show_system_monitor, "output")
... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def show_system_monitor_output_switch_status_switch_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_system_monitor = ET.Element("show_system_monito... |
def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
... | Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be... | Below is the the instruction that describes the task:
### Input:
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
... |
def parse_extra_model_fields(extra_model_fields):
"""
Parses the value of EXTRA_MODEL_FIELDS, grouping the entries by model
and instantiating the extra fields. Returns a sequence of tuples of
the form (model_key, fields) where model_key is a pair of app_label,
model_name and fields is a list of (fie... | Parses the value of EXTRA_MODEL_FIELDS, grouping the entries by model
and instantiating the extra fields. Returns a sequence of tuples of
the form (model_key, fields) where model_key is a pair of app_label,
model_name and fields is a list of (field_name, field_instance) pairs. | Below is the the instruction that describes the task:
### Input:
Parses the value of EXTRA_MODEL_FIELDS, grouping the entries by model
and instantiating the extra fields. Returns a sequence of tuples of
the form (model_key, fields) where model_key is a pair of app_label,
model_name and fields is a list ... |
def offset(self, location, dy=0):
""" Returns a new ``Region`` offset from this one by ``location``
Width and height remain the same
"""
if not isinstance(location, Location):
# Assume variables passed were dx,dy
location = Location(location, dy)
r = Regi... | Returns a new ``Region`` offset from this one by ``location``
Width and height remain the same | Below is the the instruction that describes the task:
### Input:
Returns a new ``Region`` offset from this one by ``location``
Width and height remain the same
### Response:
def offset(self, location, dy=0):
""" Returns a new ``Region`` offset from this one by ``location``
Width and heigh... |
def post_check_request(self, check, subscribers):
"""
Issues a check execution request.
"""
data = {
'check': check,
'subscribers': [subscribers]
}
self._request('POST', '/request', data=json.dumps(data))
return True | Issues a check execution request. | Below is the the instruction that describes the task:
### Input:
Issues a check execution request.
### Response:
def post_check_request(self, check, subscribers):
"""
Issues a check execution request.
"""
data = {
'check': check,
'subscribers': [subscribers]
... |
def _add_hash(source):
"""Add a leading hash '#' at the beginning of every line in the source."""
source = '\n'.join('# ' + line.rstrip()
for line in source.splitlines())
return source | Add a leading hash '#' at the beginning of every line in the source. | Below is the the instruction that describes the task:
### Input:
Add a leading hash '#' at the beginning of every line in the source.
### Response:
def _add_hash(source):
"""Add a leading hash '#' at the beginning of every line in the source."""
source = '\n'.join('# ' + line.rstrip()
... |
def text(self, cls = 'current', retaintokenisation=False, previousdelimiter="",strict=False, correctionhandling=CorrectionHandling.CURRENT, normalize_spaces=False):
"""See :meth:`AbstractElement.text`"""
if cls == 'original': correctionhandling = CorrectionHandling.ORIGINAL #backward compatibility
... | See :meth:`AbstractElement.text` | Below is the the instruction that describes the task:
### Input:
See :meth:`AbstractElement.text`
### Response:
def text(self, cls = 'current', retaintokenisation=False, previousdelimiter="",strict=False, correctionhandling=CorrectionHandling.CURRENT, normalize_spaces=False):
"""See :meth:`AbstractElement.... |
def _rule_compare(rule1, rule2):
'''
Compare the common keys between security group rules against eachother
'''
commonkeys = set(rule1.keys()).intersection(rule2.keys())
for key in commonkeys:
if rule1[key] != rule2[key]:
return False
return True | Compare the common keys between security group rules against eachother | Below is the the instruction that describes the task:
### Input:
Compare the common keys between security group rules against eachother
### Response:
def _rule_compare(rule1, rule2):
'''
Compare the common keys between security group rules against eachother
'''
commonkeys = set(rule1.keys()).inter... |
def get_tasks(self):
"""Returns an ordered dictionary {task_name: task} of all tasks within this workflow.
:return: Ordered dictionary with key being task_name (str) and an instance of a corresponding task from this
workflow
:rtype: OrderedDict
"""
tasks = collect... | Returns an ordered dictionary {task_name: task} of all tasks within this workflow.
:return: Ordered dictionary with key being task_name (str) and an instance of a corresponding task from this
workflow
:rtype: OrderedDict | Below is the the instruction that describes the task:
### Input:
Returns an ordered dictionary {task_name: task} of all tasks within this workflow.
:return: Ordered dictionary with key being task_name (str) and an instance of a corresponding task from this
workflow
:rtype: OrderedDict
#... |
def loudness(self, gain_db=-10.0, reference_level=65.0):
'''Loudness control. Similar to the gain effect, but provides
equalisation for the human auditory system.
The gain is adjusted by gain_db and the signal is equalised according
to ISO 226 w.r.t. reference_level.
Parameters... | Loudness control. Similar to the gain effect, but provides
equalisation for the human auditory system.
The gain is adjusted by gain_db and the signal is equalised according
to ISO 226 w.r.t. reference_level.
Parameters
----------
gain_db : float, default=-10.0
... | Below is the the instruction that describes the task:
### Input:
Loudness control. Similar to the gain effect, but provides
equalisation for the human auditory system.
The gain is adjusted by gain_db and the signal is equalised according
to ISO 226 w.r.t. reference_level.
Parameter... |
def set_amount(self, amount):
"""
Set transaction amount
"""
if amount:
try:
self.IsoMessage.FieldData(4, int(amount))
except ValueError:
self.IsoMessage.FieldData(4, 0)
self.rebuild() | Set transaction amount | Below is the the instruction that describes the task:
### Input:
Set transaction amount
### Response:
def set_amount(self, amount):
"""
Set transaction amount
"""
if amount:
try:
self.IsoMessage.FieldData(4, int(amount))
except ValueError:
... |
def hash_pair(first: Keccak256, second: Optional[Keccak256]) -> Keccak256:
""" Computes the keccak hash of the elements ordered topologically.
Since a merkle proof will not include all the elements, but only the path
starting from the leaves up to the root, the order of the elements is not
known by the... | Computes the keccak hash of the elements ordered topologically.
Since a merkle proof will not include all the elements, but only the path
starting from the leaves up to the root, the order of the elements is not
known by the proof checker. The topological order is used as a
deterministic way of orderin... | Below is the the instruction that describes the task:
### Input:
Computes the keccak hash of the elements ordered topologically.
Since a merkle proof will not include all the elements, but only the path
starting from the leaves up to the root, the order of the elements is not
known by the proof checker... |
def convert_gru(builder, layer, input_names, output_names, keras_layer):
"""Convert a GRU layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
hidden_size = keras_layer... | Convert a GRU layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object. | Below is the the instruction that describes the task:
### Input:
Convert a GRU layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
### Response:
def convert_gru(builder, layer, in... |
def bifurcation_partition(bif_point):
'''Calculate the partition at a bifurcation point
We first ensure that the input point has only two children.
The number of nodes in each child tree is counted. The partition is
defined as the ratio of the largest number to the smallest number.'''
assert len(b... | Calculate the partition at a bifurcation point
We first ensure that the input point has only two children.
The number of nodes in each child tree is counted. The partition is
defined as the ratio of the largest number to the smallest number. | Below is the the instruction that describes the task:
### Input:
Calculate the partition at a bifurcation point
We first ensure that the input point has only two children.
The number of nodes in each child tree is counted. The partition is
defined as the ratio of the largest number to the smallest num... |
def print_tally(self):
"""
Prints the final tally to stdout.
"""
self.update_count = self.upload_count - self.create_count
if self.test_run:
print("Test run complete with the following results:")
print("Skipped {0}. Created {1}. Updated {2}. Deleted {3}.".form... | Prints the final tally to stdout. | Below is the the instruction that describes the task:
### Input:
Prints the final tally to stdout.
### Response:
def print_tally(self):
"""
Prints the final tally to stdout.
"""
self.update_count = self.upload_count - self.create_count
if self.test_run:
print("Te... |
def contains_value(self, value):
"""
Determines whether this map contains one or more keys for the specified value.
:param value: (object), the specified value.
:return: (bool), ``true`` if this map contains an entry for the specified value.
"""
check_not_none(value, "va... | Determines whether this map contains one or more keys for the specified value.
:param value: (object), the specified value.
:return: (bool), ``true`` if this map contains an entry for the specified value. | Below is the the instruction that describes the task:
### Input:
Determines whether this map contains one or more keys for the specified value.
:param value: (object), the specified value.
:return: (bool), ``true`` if this map contains an entry for the specified value.
### Response:
def contains_v... |
def _h_function(self,h):
""" private method for the spherical variogram "h" function
Parameters
----------
h : (float or numpy.ndarray)
distance(s)
Returns
-------
h_function : float or numpy.ndarray
the value of the "h" function implied ... | private method for the spherical variogram "h" function
Parameters
----------
h : (float or numpy.ndarray)
distance(s)
Returns
-------
h_function : float or numpy.ndarray
the value of the "h" function implied by the SphVario | Below is the the instruction that describes the task:
### Input:
private method for the spherical variogram "h" function
Parameters
----------
h : (float or numpy.ndarray)
distance(s)
Returns
-------
h_function : float or numpy.ndarray
the va... |
def validate(self):
"""Validate that the BinaryComposition is correctly representable."""
_validate_operator_name(self.operator, BinaryComposition.SUPPORTED_OPERATORS)
if not isinstance(self.left, Expression):
raise TypeError(u'Expected Expression left, got: {} {} {}'.format(
... | Validate that the BinaryComposition is correctly representable. | Below is the the instruction that describes the task:
### Input:
Validate that the BinaryComposition is correctly representable.
### Response:
def validate(self):
"""Validate that the BinaryComposition is correctly representable."""
_validate_operator_name(self.operator, BinaryComposition.SUPPORTED... |
def makeCoreValuesSubqueryCondition(engine, column, values: List[Union[int, str]]):
""" Make Core Values Subquery
:param engine: The database engine, used to determine the dialect
:param column: The column, eg TableItem.__table__.c.colName
:param values: A list of string or int values
"""
if i... | Make Core Values Subquery
:param engine: The database engine, used to determine the dialect
:param column: The column, eg TableItem.__table__.c.colName
:param values: A list of string or int values | Below is the the instruction that describes the task:
### Input:
Make Core Values Subquery
:param engine: The database engine, used to determine the dialect
:param column: The column, eg TableItem.__table__.c.colName
:param values: A list of string or int values
### Response:
def makeCoreValuesSubquer... |
def model_field_attr(model, model_field, attr):
"""
Returns the specified attribute for the specified field on the model class.
"""
fields = dict([(field.name, field) for field in model._meta.fields])
return getattr(fields[model_field], attr) | Returns the specified attribute for the specified field on the model class. | Below is the the instruction that describes the task:
### Input:
Returns the specified attribute for the specified field on the model class.
### Response:
def model_field_attr(model, model_field, attr):
"""
Returns the specified attribute for the specified field on the model class.
"""
fields = dic... |
def rdn_to_dn(changes: Changeset, name: str, base_dn: str) -> Changeset:
""" Convert the rdn to a fully qualified DN for the specified LDAP
connection.
:param changes: The changes object to lookup.
:param name: rdn to convert.
:param base_dn: The base_dn to lookup.
:return: fully qualified DN.
... | Convert the rdn to a fully qualified DN for the specified LDAP
connection.
:param changes: The changes object to lookup.
:param name: rdn to convert.
:param base_dn: The base_dn to lookup.
:return: fully qualified DN. | Below is the the instruction that describes the task:
### Input:
Convert the rdn to a fully qualified DN for the specified LDAP
connection.
:param changes: The changes object to lookup.
:param name: rdn to convert.
:param base_dn: The base_dn to lookup.
:return: fully qualified DN.
### Response... |
def remove_eoc_marker(self, text, next_text):
"""Remove end of cell marker when next cell has an explicit start marker"""
if self.cell_marker_start:
return text
if self.is_code() and text[-1] == self.comment + ' -':
# remove end of cell marker when redundant with next ex... | Remove end of cell marker when next cell has an explicit start marker | Below is the the instruction that describes the task:
### Input:
Remove end of cell marker when next cell has an explicit start marker
### Response:
def remove_eoc_marker(self, text, next_text):
"""Remove end of cell marker when next cell has an explicit start marker"""
if self.cell_marker_start:
... |
def _LogInvalidRunLevels(states, valid):
"""Log any invalid run states found."""
invalid = set()
for state in states:
if state not in valid:
invalid.add(state)
if invalid:
logging.warning("Invalid init runlevel(s) encountered: %s",
", ".join(invalid)) | Log any invalid run states found. | Below is the the instruction that describes the task:
### Input:
Log any invalid run states found.
### Response:
def _LogInvalidRunLevels(states, valid):
"""Log any invalid run states found."""
invalid = set()
for state in states:
if state not in valid:
invalid.add(state)
if invalid:
logging.... |
def main():
"""Parse arguments and print generated documentation to stdout."""
parser = argparse.ArgumentParser()
parser.add_argument('protofilepath')
args = parser.parse_args()
out_file = compile_protofile(args.protofilepath)
with open(out_file, 'rb') as proto_file:
# pylint: disable=n... | Parse arguments and print generated documentation to stdout. | Below is the the instruction that describes the task:
### Input:
Parse arguments and print generated documentation to stdout.
### Response:
def main():
"""Parse arguments and print generated documentation to stdout."""
parser = argparse.ArgumentParser()
parser.add_argument('protofilepath')
args = p... |
def create_bmi_model(self, engine, bmi_class=None, wrapper_kwargs=None):
"""initialize a bmi mode using an optional class"""
if wrapper_kwargs is None:
wrapper_kwargs = {}
if bmi_class is None:
wrapper_class = bmi.wrapper.BMIWrapper
else:
wrapper_class... | initialize a bmi mode using an optional class | Below is the the instruction that describes the task:
### Input:
initialize a bmi mode using an optional class
### Response:
def create_bmi_model(self, engine, bmi_class=None, wrapper_kwargs=None):
"""initialize a bmi mode using an optional class"""
if wrapper_kwargs is None:
wrapper_kw... |
def create(
meta_schema,
validators=(),
version=None,
default_types=None,
type_checker=None,
id_of=_id_of,
):
"""
Create a new validator class.
Arguments:
meta_schema (collections.Mapping):
the meta schema for the new validator class
validators (collec... | Create a new validator class.
Arguments:
meta_schema (collections.Mapping):
the meta schema for the new validator class
validators (collections.Mapping):
a mapping from names to callables, where each callable will
validate the schema property with the given n... | Below is the the instruction that describes the task:
### Input:
Create a new validator class.
Arguments:
meta_schema (collections.Mapping):
the meta schema for the new validator class
validators (collections.Mapping):
a mapping from names to callables, where each ca... |
def print_all_commands(self, *, no_pager=False):
"""Print help for all commands.
Commands are sorted in alphabetical order and wrapping is done
based on the width of the terminal.
"""
formatter = self.parent_parser._get_formatter()
command_names = sorted(self.parent_pars... | Print help for all commands.
Commands are sorted in alphabetical order and wrapping is done
based on the width of the terminal. | Below is the the instruction that describes the task:
### Input:
Print help for all commands.
Commands are sorted in alphabetical order and wrapping is done
based on the width of the terminal.
### Response:
def print_all_commands(self, *, no_pager=False):
"""Print help for all commands.
... |
async def issuer_create_credential(wallet_handle: int,
cred_offer_json: str,
cred_req_json: str,
cred_values_json: str,
rev_reg_id: Optional[str],
... | Check Cred Request for the given Cred Offer and issue Credential for the given Cred Request.
Cred Request must match Cred Offer. The credential definition and revocation registry definition
referenced in Cred Offer and Cred Request must be already created and stored into the wallet.
Information for this c... | Below is the the instruction that describes the task:
### Input:
Check Cred Request for the given Cred Offer and issue Credential for the given Cred Request.
Cred Request must match Cred Offer. The credential definition and revocation registry definition
referenced in Cred Offer and Cred Request must be al... |
def chunks(seq, chunk_size):
# type: (Sequence[T], int) -> Iterable[Sequence[T]]
""" Split seq into chunk_size-sized chunks.
:param seq: A sequence to chunk.
:param chunk_size: The size of chunk.
"""
return (seq[i:i + chunk_size] for i in range(0, len(seq), chunk_size)) | Split seq into chunk_size-sized chunks.
:param seq: A sequence to chunk.
:param chunk_size: The size of chunk. | Below is the the instruction that describes the task:
### Input:
Split seq into chunk_size-sized chunks.
:param seq: A sequence to chunk.
:param chunk_size: The size of chunk.
### Response:
def chunks(seq, chunk_size):
# type: (Sequence[T], int) -> Iterable[Sequence[T]]
""" Split seq into ... |
def offset(self, value):
"""
Allows for skipping a specified number of results in query. Useful
for pagination.
"""
self._query = self._query.skip(value)
return self | Allows for skipping a specified number of results in query. Useful
for pagination. | Below is the the instruction that describes the task:
### Input:
Allows for skipping a specified number of results in query. Useful
for pagination.
### Response:
def offset(self, value):
"""
Allows for skipping a specified number of results in query. Useful
for pagination.
"... |
def _begin_write(session: UpdateSession,
loop: asyncio.AbstractEventLoop,
rootfs_file_path: str):
""" Start the write process. """
session.set_progress(0)
session.set_stage(Stages.WRITING)
write_future = asyncio.ensure_future(loop.run_in_executor(
None, file_act... | Start the write process. | Below is the the instruction that describes the task:
### Input:
Start the write process.
### Response:
def _begin_write(session: UpdateSession,
loop: asyncio.AbstractEventLoop,
rootfs_file_path: str):
""" Start the write process. """
session.set_progress(0)
session.se... |
def load_into(self, obj, data, inplace=True, *args, **kwargs):
"""Load data and update existing object.
:param obj: Object to update with deserialized data.
:param data: Raw data to get value to deserialize from.
:param bool inplace: If True update data inplace;
otherwise - ... | Load data and update existing object.
:param obj: Object to update with deserialized data.
:param data: Raw data to get value to deserialize from.
:param bool inplace: If True update data inplace;
otherwise - create new data.
:param kwargs: Same keyword arguments as for :met... | Below is the the instruction that describes the task:
### Input:
Load data and update existing object.
:param obj: Object to update with deserialized data.
:param data: Raw data to get value to deserialize from.
:param bool inplace: If True update data inplace;
otherwise - creat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.