code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def nack(self, id, transaction=None, receipt=None):
"""
Let the server know that a message was not consumed.
:param str id: the unique id of the message to nack
:param str transaction: include this nack in a named transaction
"""
assert id is not None, "'id' is required"... | Let the server know that a message was not consumed.
:param str id: the unique id of the message to nack
:param str transaction: include this nack in a named transaction | Below is the the instruction that describes the task:
### Input:
Let the server know that a message was not consumed.
:param str id: the unique id of the message to nack
:param str transaction: include this nack in a named transaction
### Response:
def nack(self, id, transaction=None, receipt=None... |
def insertDict(self, tblname, d, fields = None):
'''Simple function for inserting a dictionary whose keys match the fieldnames of tblname.'''
if fields == None:
fields = sorted(d.keys())
values = None
try:
SQL = 'INSERT INTO %s (%s) VALUES (%s)' % (tblname, join(fields, ", "), join(['%s' for x in range... | Simple function for inserting a dictionary whose keys match the fieldnames of tblname. | Below is the the instruction that describes the task:
### Input:
Simple function for inserting a dictionary whose keys match the fieldnames of tblname.
### Response:
def insertDict(self, tblname, d, fields = None):
'''Simple function for inserting a dictionary whose keys match the fieldnames of tblname.'''
... |
def _argumentForLoader(loaderClass):
"""
Create an AMP argument for (de-)serializing instances of C{loaderClass}.
@param loaderClass: A type object with a L{load} class method that takes
some bytes and returns an instance of itself, and a L{dump} instance
method that returns some bytes.
... | Create an AMP argument for (de-)serializing instances of C{loaderClass}.
@param loaderClass: A type object with a L{load} class method that takes
some bytes and returns an instance of itself, and a L{dump} instance
method that returns some bytes.
@return: a class decorator which decorates an A... | Below is the the instruction that describes the task:
### Input:
Create an AMP argument for (de-)serializing instances of C{loaderClass}.
@param loaderClass: A type object with a L{load} class method that takes
some bytes and returns an instance of itself, and a L{dump} instance
method that ret... |
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
return '{}{} {} = {}'.format(' ' * indent, self.result, self.name,
pret... | Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation. | Below is the the instruction that describes the task:
### Input:
Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
### Response:
def pretty_str(self, indent=0):
"""Return a human-readable string representatio... |
def blip_rId(self):
"""Value of `p:blipFill/a:blip/@r:embed`.
Returns |None| if not present.
"""
blip = self.blipFill.blip
if blip is not None and blip.rEmbed is not None:
return blip.rEmbed
return None | Value of `p:blipFill/a:blip/@r:embed`.
Returns |None| if not present. | Below is the the instruction that describes the task:
### Input:
Value of `p:blipFill/a:blip/@r:embed`.
Returns |None| if not present.
### Response:
def blip_rId(self):
"""Value of `p:blipFill/a:blip/@r:embed`.
Returns |None| if not present.
"""
blip = self.blipFill.blip
... |
def get_extensions(self):
"""
Get X.509 extensions in the certificate signing request.
:return: The X.509 extensions in this request.
:rtype: :py:class:`list` of :py:class:`X509Extension` objects.
.. versionadded:: 0.15
"""
exts = []
native_exts_obj = _l... | Get X.509 extensions in the certificate signing request.
:return: The X.509 extensions in this request.
:rtype: :py:class:`list` of :py:class:`X509Extension` objects.
.. versionadded:: 0.15 | Below is the the instruction that describes the task:
### Input:
Get X.509 extensions in the certificate signing request.
:return: The X.509 extensions in this request.
:rtype: :py:class:`list` of :py:class:`X509Extension` objects.
.. versionadded:: 0.15
### Response:
def get_extensions(s... |
def post_info(self, name, message):
"""Asynchronously post a user facing info message about a service.
Args:
name (string): The name of the service
message (string): The user facing info message that will be stored
for the service and can be queried later.
... | Asynchronously post a user facing info message about a service.
Args:
name (string): The name of the service
message (string): The user facing info message that will be stored
for the service and can be queried later. | Below is the the instruction that describes the task:
### Input:
Asynchronously post a user facing info message about a service.
Args:
name (string): The name of the service
message (string): The user facing info message that will be stored
for the service and can be... |
def get_assets(self):
'''
Return a flat list of absolute paths to all assets required by this
viewer
'''
return sum([
[self.prefix_asset(viewer, relpath) for relpath in viewer.assets]
for viewer in self.viewers
], []) | Return a flat list of absolute paths to all assets required by this
viewer | Below is the the instruction that describes the task:
### Input:
Return a flat list of absolute paths to all assets required by this
viewer
### Response:
def get_assets(self):
'''
Return a flat list of absolute paths to all assets required by this
viewer
'''
return s... |
def _notify_single_step(self, event):
"""
Notify breakpoints of a single step exception event.
@type event: L{ExceptionEvent}
@param event: Single step exception event.
@rtype: bool
@return: C{True} to call the user-defined handle, C{False} otherwise.
"""
... | Notify breakpoints of a single step exception event.
@type event: L{ExceptionEvent}
@param event: Single step exception event.
@rtype: bool
@return: C{True} to call the user-defined handle, C{False} otherwise. | Below is the the instruction that describes the task:
### Input:
Notify breakpoints of a single step exception event.
@type event: L{ExceptionEvent}
@param event: Single step exception event.
@rtype: bool
@return: C{True} to call the user-defined handle, C{False} otherwise.
### R... |
def run(self):
"""
Run pycodestyle checker and record warnings.
"""
# Set a stream to replace stdout, and get results in it
stdoutBak = sys.stdout
streamResult = StringIO()
sys.stdout = streamResult
try:
pycodestyle.Checker.check_all(self)
... | Run pycodestyle checker and record warnings. | Below is the the instruction that describes the task:
### Input:
Run pycodestyle checker and record warnings.
### Response:
def run(self):
"""
Run pycodestyle checker and record warnings.
"""
# Set a stream to replace stdout, and get results in it
stdoutBak = sys.stdout
... |
def auth_ec2(self, pkcs7, nonce=None, role=None, use_token=True, mount_point='aws-ec2'):
"""POST /auth/<mount point>/login
:param pkcs7: PKCS#7 version of an AWS Instance Identity Document from the EC2 Metadata Service.
:type pkcs7: str.
:param nonce: Optional nonce returned as part of ... | POST /auth/<mount point>/login
:param pkcs7: PKCS#7 version of an AWS Instance Identity Document from the EC2 Metadata Service.
:type pkcs7: str.
:param nonce: Optional nonce returned as part of the original authentication request. Not required if the backend
has "allow_instance_mig... | Below is the the instruction that describes the task:
### Input:
POST /auth/<mount point>/login
:param pkcs7: PKCS#7 version of an AWS Instance Identity Document from the EC2 Metadata Service.
:type pkcs7: str.
:param nonce: Optional nonce returned as part of the original authentication req... |
def extract(self, path, outdir, concurrency_safe=False, **kwargs):
"""Extracts an archive's contents to the specified outdir with an optional filter.
Keyword arguments are forwarded to the instance's self._extract() method.
:API: public
:param string path: path to the zipfile to extract from
:par... | Extracts an archive's contents to the specified outdir with an optional filter.
Keyword arguments are forwarded to the instance's self._extract() method.
:API: public
:param string path: path to the zipfile to extract from
:param string outdir: directory to extract files into
:param bool concurre... | Below is the the instruction that describes the task:
### Input:
Extracts an archive's contents to the specified outdir with an optional filter.
Keyword arguments are forwarded to the instance's self._extract() method.
:API: public
:param string path: path to the zipfile to extract from
:param st... |
def load_table(self, table, rows, colnames=None, limit=None):
"""Load 'rows' into table 'table'. If 'colnames' is not provided, the
first element of 'rows' must provide column names.
"""
conn = self.engine.raw_connection()
cur = conn.cursor()
colnames = colnames or nex... | Load 'rows' into table 'table'. If 'colnames' is not provided, the
first element of 'rows' must provide column names. | Below is the the instruction that describes the task:
### Input:
Load 'rows' into table 'table'. If 'colnames' is not provided, the
first element of 'rows' must provide column names.
### Response:
def load_table(self, table, rows, colnames=None, limit=None):
"""Load 'rows' into table 'table'. If 'c... |
def read_template_source(filename):
"""Read the source of a Django template, returning the Unicode text."""
# Import this late to be sure we don't trigger settings machinery too
# early.
from django.conf import settings
if not settings.configured:
settings.configure()
with open(filenam... | Read the source of a Django template, returning the Unicode text. | Below is the the instruction that describes the task:
### Input:
Read the source of a Django template, returning the Unicode text.
### Response:
def read_template_source(filename):
"""Read the source of a Django template, returning the Unicode text."""
# Import this late to be sure we don't trigger setting... |
def calc_paired_insert_stats_save(in_bam, stat_file, nsample=1000000):
"""Calculate paired stats, saving to a file for re-runs.
"""
if utils.file_exists(stat_file):
with open(stat_file) as in_handle:
return yaml.safe_load(in_handle)
else:
stats = calc_paired_insert_stats(in_b... | Calculate paired stats, saving to a file for re-runs. | Below is the the instruction that describes the task:
### Input:
Calculate paired stats, saving to a file for re-runs.
### Response:
def calc_paired_insert_stats_save(in_bam, stat_file, nsample=1000000):
"""Calculate paired stats, saving to a file for re-runs.
"""
if utils.file_exists(stat_file):
... |
def get_node(self):
"""return etree Element representing this slide"""
# already added title, text frames
# add animation chunks
if self.animations:
anim_par = el("anim:par", attrib={"presentation:node-type": "timing-root"})
self._page.append(anim_par)
... | return etree Element representing this slide | Below is the the instruction that describes the task:
### Input:
return etree Element representing this slide
### Response:
def get_node(self):
"""return etree Element representing this slide"""
# already added title, text frames
# add animation chunks
if self.animations:
... |
def _loadDB(self):
"""Connect to the database to load myself"""
if not self._validID():
raise NotFound, self._getID()
(sql, fields) = self._prepareSQL("SELECT")
curs = self.cursor()
curs.execute(sql, self._getID())
result = curs.fetchone()
if not resul... | Connect to the database to load myself | Below is the the instruction that describes the task:
### Input:
Connect to the database to load myself
### Response:
def _loadDB(self):
"""Connect to the database to load myself"""
if not self._validID():
raise NotFound, self._getID()
(sql, fields) = self._prepareSQL("SELECT")
... |
def run(self):
"""Sends data to the callback functions."""
while True:
result = json.loads(self.ws.recv())
if result["cmd"] == "chat" and not result["nick"] == self.nick:
for handler in list(self.on_message):
handler(self, result["text"], resul... | Sends data to the callback functions. | Below is the the instruction that describes the task:
### Input:
Sends data to the callback functions.
### Response:
def run(self):
"""Sends data to the callback functions."""
while True:
result = json.loads(self.ws.recv())
if result["cmd"] == "chat" and not result["nick"] =... |
def one_rule_present(self, pol_id):
"""Returns if atleast one rule is present in the policy. """
pol_dict = self.policies[pol_id]
for rule in pol_dict['rule_dict']:
if self.is_rule_present(rule):
return True
return False | Returns if atleast one rule is present in the policy. | Below is the the instruction that describes the task:
### Input:
Returns if atleast one rule is present in the policy.
### Response:
def one_rule_present(self, pol_id):
"""Returns if atleast one rule is present in the policy. """
pol_dict = self.policies[pol_id]
for rule in pol_dict['rule_d... |
def verify_token(token, public_key_or_address, signing_algorithm="ES256K"):
""" A function for validating an individual token.
"""
decoded_token = decode_token(token)
decoded_token_payload = decoded_token["payload"]
if "subject" not in decoded_token_payload:
raise ValueError("Token doesn't ... | A function for validating an individual token. | Below is the the instruction that describes the task:
### Input:
A function for validating an individual token.
### Response:
def verify_token(token, public_key_or_address, signing_algorithm="ES256K"):
""" A function for validating an individual token.
"""
decoded_token = decode_token(token)
decode... |
def build_task(self, name):
""" Builds a task by name, resolving any dependencies on the way """
try:
self._gettask(name).value = (
self._gettask(name).task.resolve_and_build())
except TaskExecutionException as e:
perror(e.header, indent="+0")
... | Builds a task by name, resolving any dependencies on the way | Below is the the instruction that describes the task:
### Input:
Builds a task by name, resolving any dependencies on the way
### Response:
def build_task(self, name):
""" Builds a task by name, resolving any dependencies on the way """
try:
self._gettask(name).value = (
... |
def write_long(self, n):
"""
Write an integer as an unsigned2 32-bit value.
"""
if (n < 0) or (n >= (2**32)):
raise ValueError('Octet out of range 0..2**31-1')
self._flushbits()
self.out.write(pack('>I', n)) | Write an integer as an unsigned2 32-bit value. | Below is the the instruction that describes the task:
### Input:
Write an integer as an unsigned2 32-bit value.
### Response:
def write_long(self, n):
"""
Write an integer as an unsigned2 32-bit value.
"""
if (n < 0) or (n >= (2**32)):
raise ValueError('Octet out of ran... |
def _do_get(self, url, **kwargs):
"""
Convenient method for GET requests
Returns http request status value from a POST request
"""
#TODO:
# Add error handling. Check for HTTP status here would be much more conveinent than in each calling method
scaleioapi_post_hea... | Convenient method for GET requests
Returns http request status value from a POST request | Below is the the instruction that describes the task:
### Input:
Convenient method for GET requests
Returns http request status value from a POST request
### Response:
def _do_get(self, url, **kwargs):
"""
Convenient method for GET requests
Returns http request status value from a P... |
def two_pointers(self):
"""
Returns an ``int`` of the total number of two point field goals the
player made.
"""
if self.field_goals and self.three_pointers:
return int(self.field_goals - self.three_pointers)
# Occurs when the player didn't make any three poin... | Returns an ``int`` of the total number of two point field goals the
player made. | Below is the the instruction that describes the task:
### Input:
Returns an ``int`` of the total number of two point field goals the
player made.
### Response:
def two_pointers(self):
"""
Returns an ``int`` of the total number of two point field goals the
player made.
"""
... |
def add_chain_ids(self, chains):
"""Add chains by ID into the chains attribute
Args:
chains (str, list): Chain ID or list of IDs
"""
chains = ssbio.utils.force_list(chains)
for c in chains:
if self.chains.has_id(c):
log.debug('{}: chain ... | Add chains by ID into the chains attribute
Args:
chains (str, list): Chain ID or list of IDs | Below is the the instruction that describes the task:
### Input:
Add chains by ID into the chains attribute
Args:
chains (str, list): Chain ID or list of IDs
### Response:
def add_chain_ids(self, chains):
"""Add chains by ID into the chains attribute
Args:
chains (... |
def run(version, quiet, no_fetch, push, **kwargs): # pragma: no cover
"""
A nicer `git pull`.
"""
if version:
if NO_DISTRIBUTE:
print(colored('Please install \'git-up\' via pip in order to '
'get version information.', 'yellow'))
else:
... | A nicer `git pull`. | Below is the the instruction that describes the task:
### Input:
A nicer `git pull`.
### Response:
def run(version, quiet, no_fetch, push, **kwargs): # pragma: no cover
"""
A nicer `git pull`.
"""
if version:
if NO_DISTRIBUTE:
print(colored('Please install \'git-up\' via ... |
def range_difference(data, ground_truth, mask=None, normalized=False,
force_lower_is_better=True):
r"""Return dynamic range difference between ``data`` and ``ground_truth``.
Evaluates difference in range between input (``data``) and reference
data (``ground_truth``). Allows for normali... | r"""Return dynamic range difference between ``data`` and ``ground_truth``.
Evaluates difference in range between input (``data``) and reference
data (``ground_truth``). Allows for normalization (``normalized``) and a
masking of the two spaces (``mask``).
Parameters
----------
data : `array-lik... | Below is the the instruction that describes the task:
### Input:
r"""Return dynamic range difference between ``data`` and ``ground_truth``.
Evaluates difference in range between input (``data``) and reference
data (``ground_truth``). Allows for normalization (``normalized``) and a
masking of the two sp... |
def newbie(cls, *args, **kwargs):
""" Create a newbie class, with all the skills needed """
parser = cls(*args, **kwargs)
subparser = parser.add_subparsers(dest='command')
parents = [parser.pparser, parser.output_parser]
sparser = subparser.add_parser('search', help='Perform new... | Create a newbie class, with all the skills needed | Below is the the instruction that describes the task:
### Input:
Create a newbie class, with all the skills needed
### Response:
def newbie(cls, *args, **kwargs):
""" Create a newbie class, with all the skills needed """
parser = cls(*args, **kwargs)
subparser = parser.add_subparsers(dest='... |
def _get_gce_credentials(request=None):
"""Gets credentials and project ID from the GCE Metadata Service."""
# Ping requires a transport, but we want application default credentials
# to require no arguments. So, we'll use the _http_client transport which
# uses http.client. This is only acceptable beca... | Gets credentials and project ID from the GCE Metadata Service. | Below is the the instruction that describes the task:
### Input:
Gets credentials and project ID from the GCE Metadata Service.
### Response:
def _get_gce_credentials(request=None):
"""Gets credentials and project ID from the GCE Metadata Service."""
# Ping requires a transport, but we want application def... |
def get_with_range(self, name, start, end):
r"""Get a color table from the registry with a corresponding norm.
Builds a `matplotlib.colors.BoundaryNorm` using `start`, `end`, and
the number of colors, based on the color table obtained from `name`.
Parameters
----------
... | r"""Get a color table from the registry with a corresponding norm.
Builds a `matplotlib.colors.BoundaryNorm` using `start`, `end`, and
the number of colors, based on the color table obtained from `name`.
Parameters
----------
name : str
The name under which the colo... | Below is the the instruction that describes the task:
### Input:
r"""Get a color table from the registry with a corresponding norm.
Builds a `matplotlib.colors.BoundaryNorm` using `start`, `end`, and
the number of colors, based on the color table obtained from `name`.
Parameters
--... |
def run_refresh(args):
"""
Handle the refresh subcommand
:param args: Parsed command line arguments
:return: None, output is written to console
"""
image = args.image
branch = args.branch
try:
initial_version = get_latest_version(image, branch)
except DockerTagNamingExceptio... | Handle the refresh subcommand
:param args: Parsed command line arguments
:return: None, output is written to console | Below is the the instruction that describes the task:
### Input:
Handle the refresh subcommand
:param args: Parsed command line arguments
:return: None, output is written to console
### Response:
def run_refresh(args):
"""
Handle the refresh subcommand
:param args: Parsed command line arguments... |
def _check_spades_log_file(logfile):
'''SPAdes can fail with a strange error. Stop everything if this happens'''
f = pyfastaq.utils.open_file_read(logfile)
for line in f:
if line.startswith('== Error == system call for:') and line.rstrip().endswith('finished abnormally, err code: -... | SPAdes can fail with a strange error. Stop everything if this happens | Below is the the instruction that describes the task:
### Input:
SPAdes can fail with a strange error. Stop everything if this happens
### Response:
def _check_spades_log_file(logfile):
'''SPAdes can fail with a strange error. Stop everything if this happens'''
f = pyfastaq.utils.open_file_read(log... |
def cli(obj, scopes):
"""List permissions."""
client = obj['client']
query = [('scopes', s) for s in scopes]
if obj['output'] == 'json':
r = client.http.get('/perms', query)
click.echo(json.dumps(r['permissions'], sort_keys=True, indent=4, ensure_ascii=False))
else:
headers ... | List permissions. | Below is the the instruction that describes the task:
### Input:
List permissions.
### Response:
def cli(obj, scopes):
"""List permissions."""
client = obj['client']
query = [('scopes', s) for s in scopes]
if obj['output'] == 'json':
r = client.http.get('/perms', query)
click.echo(... |
def set_exposure_scale(self, name, scale=None):
"""Set the exposure correction of a source.
Parameters
----------
name : str
Source name.
scale : factor
Exposure scale factor (1.0 = nominal exposure).
"""
name = self.roi.get_source_by_na... | Set the exposure correction of a source.
Parameters
----------
name : str
Source name.
scale : factor
Exposure scale factor (1.0 = nominal exposure). | Below is the the instruction that describes the task:
### Input:
Set the exposure correction of a source.
Parameters
----------
name : str
Source name.
scale : factor
Exposure scale factor (1.0 = nominal exposure).
### Response:
def set_exposure_scale(self,... |
def del_feature(self, pr_name):
""" Permanently deletes a node's feature."""
if hasattr(self, pr_name):
delattr(self, pr_name)
self.features.remove(pr_name) | Permanently deletes a node's feature. | Below is the the instruction that describes the task:
### Input:
Permanently deletes a node's feature.
### Response:
def del_feature(self, pr_name):
""" Permanently deletes a node's feature."""
if hasattr(self, pr_name):
delattr(self, pr_name)
self.features.remove(pr_name) |
def __visit_target(self, node):
"""
Call this method to visit assignment targets and to add local variables
to the current stack frame. Used in #visit_Assign() and
#__visit_comprehension().
"""
if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):
self.__add_variable(node.id)... | Call this method to visit assignment targets and to add local variables
to the current stack frame. Used in #visit_Assign() and
#__visit_comprehension(). | Below is the the instruction that describes the task:
### Input:
Call this method to visit assignment targets and to add local variables
to the current stack frame. Used in #visit_Assign() and
#__visit_comprehension().
### Response:
def __visit_target(self, node):
"""
Call this method to visit assi... |
def kill(self) -> None:
"""Kill ffmpeg job."""
self._proc.kill()
self._loop.run_in_executor(None, self._proc.communicate) | Kill ffmpeg job. | Below is the the instruction that describes the task:
### Input:
Kill ffmpeg job.
### Response:
def kill(self) -> None:
"""Kill ffmpeg job."""
self._proc.kill()
self._loop.run_in_executor(None, self._proc.communicate) |
def get_genome_ref(genome_build, aligner, galaxy_base):
"""Retrieve the reference genome file location from galaxy configuration.
"""
ref_files = dict(
bowtie = "bowtie_indices.loc",
bwa = "bwa_index.loc",
samtools = "sam_fa_indices.loc",
maq = "bowtie_indices... | Retrieve the reference genome file location from galaxy configuration. | Below is the the instruction that describes the task:
### Input:
Retrieve the reference genome file location from galaxy configuration.
### Response:
def get_genome_ref(genome_build, aligner, galaxy_base):
"""Retrieve the reference genome file location from galaxy configuration.
"""
ref_files = dict(
... |
def process_event(self, event_id):
"""Process event in Celery."""
with db.session.begin_nested():
event = Event.query.get(event_id)
event._celery_task = self # internal binding to a Celery task
event.receiver.run(event) # call run directly to avoid circular calls
flag_modified(... | Process event in Celery. | Below is the the instruction that describes the task:
### Input:
Process event in Celery.
### Response:
def process_event(self, event_id):
"""Process event in Celery."""
with db.session.begin_nested():
event = Event.query.get(event_id)
event._celery_task = self # internal binding to a Cele... |
def _get_bolt(self):
"""Returns Bolt protobuf message"""
bolt = topology_pb2.Bolt()
bolt.comp.CopyFrom(self._get_base_component())
# Add streams
self._add_in_streams(bolt)
self._add_out_streams(bolt)
return bolt | Returns Bolt protobuf message | Below is the the instruction that describes the task:
### Input:
Returns Bolt protobuf message
### Response:
def _get_bolt(self):
"""Returns Bolt protobuf message"""
bolt = topology_pb2.Bolt()
bolt.comp.CopyFrom(self._get_base_component())
# Add streams
self._add_in_streams(bolt)
self._add... |
def igrf_value(lat, lon, alt=0., year=2005.):
"""
:return
D is declination (+ve east)
I is inclination (+ve down)
H is horizontal intensity
X is north component
Y is east component
Z is vertical component (+ve down)
F is total intensity
"""
... | :return
D is declination (+ve east)
I is inclination (+ve down)
H is horizontal intensity
X is north component
Y is east component
Z is vertical component (+ve down)
F is total intensity | Below is the the instruction that describes the task:
### Input:
:return
D is declination (+ve east)
I is inclination (+ve down)
H is horizontal intensity
X is north component
Y is east component
Z is vertical component (+ve down)
F is total intensity
#... |
def to_bytes(self, dochecksum=True):
'''
Return packed byte representation of the UDP header.
'''
csum = 0
if dochecksum:
csum = self.checksum()
return b''.join((struct.pack(ICMP._PACKFMT, self._type.value, self._code.value, csum), self._icmpdata.to_bytes())) | Return packed byte representation of the UDP header. | Below is the the instruction that describes the task:
### Input:
Return packed byte representation of the UDP header.
### Response:
def to_bytes(self, dochecksum=True):
'''
Return packed byte representation of the UDP header.
'''
csum = 0
if dochecksum:
csum = se... |
def find_peak(data, cutoff=.9):
'''
This will look for the point where cumulative cutoff is reached. For
example:
>>> find_peak({0: 27, 1: 71, 2: 1})
1
'''
total_length = sum(data.values())
count_cutoff = cutoff * total_length
cum_sum = 0
for i, count in sorted(data.items()):
... | This will look for the point where cumulative cutoff is reached. For
example:
>>> find_peak({0: 27, 1: 71, 2: 1})
1 | Below is the the instruction that describes the task:
### Input:
This will look for the point where cumulative cutoff is reached. For
example:
>>> find_peak({0: 27, 1: 71, 2: 1})
1
### Response:
def find_peak(data, cutoff=.9):
'''
This will look for the point where cumulative cutoff is reached... |
def add_token_to_database(encoded_token, identity_claim):
"""
Adds a new token to the database. It is not revoked when it is added.
:param identity_claim:
"""
decoded_token = decode_token(encoded_token)
jti = decoded_token['jti']
token_type = decoded_token['type']
user_identity = decoded... | Adds a new token to the database. It is not revoked when it is added.
:param identity_claim: | Below is the the instruction that describes the task:
### Input:
Adds a new token to the database. It is not revoked when it is added.
:param identity_claim:
### Response:
def add_token_to_database(encoded_token, identity_claim):
"""
Adds a new token to the database. It is not revoked when it is added.... |
def request(self, requests):
"""Requests resources from Mesos.
(see mesos.proto for a description of Request and how, for example, to
request resources from specific slaves.)
Any resources available are offered to the framework via
Scheduler.resourceOffers callback, asynchronou... | Requests resources from Mesos.
(see mesos.proto for a description of Request and how, for example, to
request resources from specific slaves.)
Any resources available are offered to the framework via
Scheduler.resourceOffers callback, asynchronously. | Below is the the instruction that describes the task:
### Input:
Requests resources from Mesos.
(see mesos.proto for a description of Request and how, for example, to
request resources from specific slaves.)
Any resources available are offered to the framework via
Scheduler.resourc... |
def set_file_copyright(self, doc, text):
"""Raises OrderError if no package or file defined.
Raises CardinalityError if more than one.
"""
if self.has_package(doc) and self.has_file(doc):
if not self.file_copytext_set:
self.file_copytext_set = True
... | Raises OrderError if no package or file defined.
Raises CardinalityError if more than one. | Below is the the instruction that describes the task:
### Input:
Raises OrderError if no package or file defined.
Raises CardinalityError if more than one.
### Response:
def set_file_copyright(self, doc, text):
"""Raises OrderError if no package or file defined.
Raises CardinalityError if m... |
def preferred_height(self, cli, width, max_available_height):
"""
Return the preferred height of the float container.
(We don't care about the height of the floats, they should always fit
into the dimensions provided by the container.)
"""
return self.content.preferred_he... | Return the preferred height of the float container.
(We don't care about the height of the floats, they should always fit
into the dimensions provided by the container.) | Below is the the instruction that describes the task:
### Input:
Return the preferred height of the float container.
(We don't care about the height of the floats, they should always fit
into the dimensions provided by the container.)
### Response:
def preferred_height(self, cli, width, max_availab... |
def get_media_formats(self, media_id):
"""CR doesn't seem to provide the video_format and video_quality params
through any of the APIs so we have to scrape the video page
"""
url = (SCRAPER.API_URL + 'media-' + media_id).format(
protocol=SCRAPER.PROTOCOL_INSECURE)
for... | CR doesn't seem to provide the video_format and video_quality params
through any of the APIs so we have to scrape the video page | Below is the the instruction that describes the task:
### Input:
CR doesn't seem to provide the video_format and video_quality params
through any of the APIs so we have to scrape the video page
### Response:
def get_media_formats(self, media_id):
"""CR doesn't seem to provide the video_format and v... |
def _post(self, url, data=None):
"""
Handle authenticated POST requests
:param url: The url for the endpoint including path parameters
:type url: :py:class:`str`
:param data: The request body parameters
:type data: :py:data:`none` or :py:class:`dict`
:returns: Th... | Handle authenticated POST requests
:param url: The url for the endpoint including path parameters
:type url: :py:class:`str`
:param data: The request body parameters
:type data: :py:data:`none` or :py:class:`dict`
:returns: The JSON output from the API or an error message | Below is the the instruction that describes the task:
### Input:
Handle authenticated POST requests
:param url: The url for the endpoint including path parameters
:type url: :py:class:`str`
:param data: The request body parameters
:type data: :py:data:`none` or :py:class:`dict`
... |
def auth(self):
"""Authenticate using the SOAP interface.
Authentication is a two-step process. First a initial payload
is sent to the device requesting additional login information in the form
of a publickey, a challenge string and a cookie.
These values are then hashed by a MD... | Authenticate using the SOAP interface.
Authentication is a two-step process. First a initial payload
is sent to the device requesting additional login information in the form
of a publickey, a challenge string and a cookie.
These values are then hashed by a MD5 algorithm producing a pri... | Below is the the instruction that describes the task:
### Input:
Authenticate using the SOAP interface.
Authentication is a two-step process. First a initial payload
is sent to the device requesting additional login information in the form
of a publickey, a challenge string and a cookie.
... |
def add(self, name, value=None, quotes='"', pad_first=" ",
pad_before_eq="", pad_after_eq=""):
"""Add an attribute with the given *name* and *value*.
*name* and *value* can be anything parsable by
:func:`.utils.parse_anything`; *value* can be omitted if the attribute
is valu... | Add an attribute with the given *name* and *value*.
*name* and *value* can be anything parsable by
:func:`.utils.parse_anything`; *value* can be omitted if the attribute
is valueless. If *quotes* is not ``None``, it should be a string
(either ``"`` or ``'``) that *value* will be wrapped... | Below is the the instruction that describes the task:
### Input:
Add an attribute with the given *name* and *value*.
*name* and *value* can be anything parsable by
:func:`.utils.parse_anything`; *value* can be omitted if the attribute
is valueless. If *quotes* is not ``None``, it should be ... |
def plaintext_request(self, registration_id, data=None, collapse_key=None,
delay_while_idle=False, time_to_live=None, retries=5, dry_run=False):
"""
Makes a plaintext request to GCM servers
:param registration_id: string of the registration id
:param data: dict... | Makes a plaintext request to GCM servers
:param registration_id: string of the registration id
:param data: dict mapping of key-value pairs of messages
:return dict of response body from Google including multicast_id, success, failure, canonical_ids, etc
:raises GCMMissingRegistrationEx... | Below is the the instruction that describes the task:
### Input:
Makes a plaintext request to GCM servers
:param registration_id: string of the registration id
:param data: dict mapping of key-value pairs of messages
:return dict of response body from Google including multicast_id, success,... |
def number_of_pages(self, key, value):
"""Populate the ``number_of_pages`` key."""
result = maybe_int(force_single_element(value.get('a', '')))
if result and result > 0:
return result | Populate the ``number_of_pages`` key. | Below is the the instruction that describes the task:
### Input:
Populate the ``number_of_pages`` key.
### Response:
def number_of_pages(self, key, value):
"""Populate the ``number_of_pages`` key."""
result = maybe_int(force_single_element(value.get('a', '')))
if result and result > 0:
return r... |
def _find_modules(src):
"""Find all modules referenced by %module lines in `src`, a SWIG .i file.
Returns a list of all modules, and a flag set if SWIG directors have
been requested (SWIG will generate an additional header file in this
case.)"""
directors = 0
mnames = []
try:
... | Find all modules referenced by %module lines in `src`, a SWIG .i file.
Returns a list of all modules, and a flag set if SWIG directors have
been requested (SWIG will generate an additional header file in this
case.) | Below is the the instruction that describes the task:
### Input:
Find all modules referenced by %module lines in `src`, a SWIG .i file.
Returns a list of all modules, and a flag set if SWIG directors have
been requested (SWIG will generate an additional header file in this
case.)
### Response: ... |
def timeago_template(locale, index, ago_in):
'''
simple locale implement
'''
try:
LOCALE = __import__('timeago.locales.' + locale)
LOCALE = locale_module(LOCALE, locale)
except:
locale = setting.DEFAULT_LOCALE
LOCALE = __import__('timeago.locales.' + locale)
L... | simple locale implement | Below is the the instruction that describes the task:
### Input:
simple locale implement
### Response:
def timeago_template(locale, index, ago_in):
'''
simple locale implement
'''
try:
LOCALE = __import__('timeago.locales.' + locale)
LOCALE = locale_module(LOCALE, locale)
except... |
def load(self):
"""(Re)Load config file."""
try:
with open(self.config_file) as configfile:
self.config = yaml.load(configfile)
except TypeError:
# no config file (use environment variables)
pass
if self.config:
self.prefix ... | (Re)Load config file. | Below is the the instruction that describes the task:
### Input:
(Re)Load config file.
### Response:
def load(self):
"""(Re)Load config file."""
try:
with open(self.config_file) as configfile:
self.config = yaml.load(configfile)
except TypeError:
# no... |
def parameter(self):
"""Return the current best value of a parameter"""
D = {}
for source in PARAM_SOURCE_ORDER:
D.update(self.params[source])
return D | Return the current best value of a parameter | Below is the the instruction that describes the task:
### Input:
Return the current best value of a parameter
### Response:
def parameter(self):
"""Return the current best value of a parameter"""
D = {}
for source in PARAM_SOURCE_ORDER:
D.update(self.params[source])
retu... |
def _create_folder(self):
''' a helper method for creating a temporary audio clip folder '''
# import dependencies
import os
from labpack.platforms.localhost import localhostClient
from labpack.records.id import labID
# create folder in user app data
record_i... | a helper method for creating a temporary audio clip folder | Below is the the instruction that describes the task:
### Input:
a helper method for creating a temporary audio clip folder
### Response:
def _create_folder(self):
''' a helper method for creating a temporary audio clip folder '''
# import dependencies
import os
from labpack.pla... |
def y(self, y):
"""Project y as x"""
if y is None:
return None
if self._force_vertical:
return super(XLogView, self).y(y)
return super(HorizontalLogView, self).x(y) | Project y as x | Below is the the instruction that describes the task:
### Input:
Project y as x
### Response:
def y(self, y):
"""Project y as x"""
if y is None:
return None
if self._force_vertical:
return super(XLogView, self).y(y)
return super(HorizontalLogView, self).x(y) |
def op_match_funcdef_handle(self, original, loc, tokens):
"""Process infix match defs. Result must be passed to insert_docstring_handle."""
if len(tokens) == 3:
func, args = get_infix_items(tokens)
cond = None
elif len(tokens) == 4:
func, args = get_infix_item... | Process infix match defs. Result must be passed to insert_docstring_handle. | Below is the the instruction that describes the task:
### Input:
Process infix match defs. Result must be passed to insert_docstring_handle.
### Response:
def op_match_funcdef_handle(self, original, loc, tokens):
"""Process infix match defs. Result must be passed to insert_docstring_handle."""
if l... |
def update(self, status):
"""Sends a status update to the framework scheduler.
Retrying as necessary until an acknowledgement has been received or the
executor is terminated (in which case, a TASK_LOST status update will be
sent).
See Scheduler.statusUpdate for more information ... | Sends a status update to the framework scheduler.
Retrying as necessary until an acknowledgement has been received or the
executor is terminated (in which case, a TASK_LOST status update will be
sent).
See Scheduler.statusUpdate for more information about status update
acknowled... | Below is the the instruction that describes the task:
### Input:
Sends a status update to the framework scheduler.
Retrying as necessary until an acknowledgement has been received or the
executor is terminated (in which case, a TASK_LOST status update will be
sent).
See Scheduler.st... |
def CopyToDateTimeString(cls, time_elements_tuple, fraction_of_second):
"""Copies the time elements and fraction of second to a string.
Args:
time_elements_tuple (tuple[int, int, int, int, int, int]):
time elements, contains year, month, day of month, hours, minutes and
seconds.
... | Copies the time elements and fraction of second to a string.
Args:
time_elements_tuple (tuple[int, int, int, int, int, int]):
time elements, contains year, month, day of month, hours, minutes and
seconds.
fraction_of_second (decimal.Decimal): fraction of second, which must be a
... | Below is the the instruction that describes the task:
### Input:
Copies the time elements and fraction of second to a string.
Args:
time_elements_tuple (tuple[int, int, int, int, int, int]):
time elements, contains year, month, day of month, hours, minutes and
seconds.
fraction_... |
def _copy_chunk(src, dst, length):
"Copy length bytes from file src to file dst."
BUFSIZE = 128 * 1024
while length > 0:
l = min(BUFSIZE, length)
buf = src.read(l)
assert len(buf) == l
dst.write(buf)
length -= l | Copy length bytes from file src to file dst. | Below is the the instruction that describes the task:
### Input:
Copy length bytes from file src to file dst.
### Response:
def _copy_chunk(src, dst, length):
"Copy length bytes from file src to file dst."
BUFSIZE = 128 * 1024
while length > 0:
l = min(BUFSIZE, length)
buf = src.read(l)... |
def typify(value: Union[dict, list, set, str]):
""" Enhance block operation with native types.
Typify takes a blockchain operation or dict/list/value,
and then it parses and converts string types into native data types where appropriate.
"""
if type(value) == dict:
return walk_values(typify... | Enhance block operation with native types.
Typify takes a blockchain operation or dict/list/value,
and then it parses and converts string types into native data types where appropriate. | Below is the the instruction that describes the task:
### Input:
Enhance block operation with native types.
Typify takes a blockchain operation or dict/list/value,
and then it parses and converts string types into native data types where appropriate.
### Response:
def typify(value: Union[dict, list, set, ... |
def xyz_to_mat(foci, xyz_dims=None, mat_dims=None):
""" Convert an N x 3 array of XYZ coordinates to matrix indices. """
foci = np.hstack((foci, np.ones((foci.shape[0], 1))))
mat = np.array([[-0.5, 0, 0, 45], [0, 0.5, 0, 63], [0, 0, 0.5, 36]]).T
result = np.dot(foci, mat)[:, ::-1] # multiply and revers... | Convert an N x 3 array of XYZ coordinates to matrix indices. | Below is the the instruction that describes the task:
### Input:
Convert an N x 3 array of XYZ coordinates to matrix indices.
### Response:
def xyz_to_mat(foci, xyz_dims=None, mat_dims=None):
""" Convert an N x 3 array of XYZ coordinates to matrix indices. """
foci = np.hstack((foci, np.ones((foci.shape[0]... |
def enqueue(self, data):
""" Enqueue task with specified data. """
jsonified_data = json.dumps(data)
with self._db_conn() as conn:
return conn.execute(
'INSERT INTO %s (created, data) VALUES (%%(created)s, %%(data)s)' % self.table_name,
created=datetim... | Enqueue task with specified data. | Below is the the instruction that describes the task:
### Input:
Enqueue task with specified data.
### Response:
def enqueue(self, data):
""" Enqueue task with specified data. """
jsonified_data = json.dumps(data)
with self._db_conn() as conn:
return conn.execute(
... |
def mostDeviant(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by an integer N.
Draws the N most deviant metrics.
To find the deviants, the standard deviation (sigma) of each series
is taken and ranked. The top N standard deviations are returned.
Example:... | Takes one metric or a wildcard seriesList followed by an integer N.
Draws the N most deviant metrics.
To find the deviants, the standard deviation (sigma) of each series
is taken and ranked. The top N standard deviations are returned.
Example::
&target=mostDeviant(server*.instance*.memory.free... | Below is the the instruction that describes the task:
### Input:
Takes one metric or a wildcard seriesList followed by an integer N.
Draws the N most deviant metrics.
To find the deviants, the standard deviation (sigma) of each series
is taken and ranked. The top N standard deviations are returned.
... |
def expand_grid_coords(dataset, dim):
"""
Expand the coordinates along a dimension of the gridded
dataset into an ND-array matching the dimensionality of
the dataset.
"""
arrays = [dataset.interface.coords(dataset, d.name, True)
for d in dataset.kdims]
idx = dataset.get_dimensi... | Expand the coordinates along a dimension of the gridded
dataset into an ND-array matching the dimensionality of
the dataset. | Below is the the instruction that describes the task:
### Input:
Expand the coordinates along a dimension of the gridded
dataset into an ND-array matching the dimensionality of
the dataset.
### Response:
def expand_grid_coords(dataset, dim):
"""
Expand the coordinates along a dimension of the gridd... |
def load_raw_arrays(self,
columns,
start_date,
end_date,
assets):
"""
Parameters
----------
columns : list of str
'open', 'high', 'low', 'close', or 'volume'
start_date: Tim... | Parameters
----------
columns : list of str
'open', 'high', 'low', 'close', or 'volume'
start_date: Timestamp
Beginning of the window range.
end_date: Timestamp
End of the window range.
assets : list of int
The asset identifiers in the ... | Below is the the instruction that describes the task:
### Input:
Parameters
----------
columns : list of str
'open', 'high', 'low', 'close', or 'volume'
start_date: Timestamp
Beginning of the window range.
end_date: Timestamp
End of the window range.
... |
def measureSize(self, diff, chunkSize):
""" Spend some time to get an accurate size. """
self._fileSystemSync()
sendContext = self.butter.send(
self.getSendPath(diff.toVol),
self.getSendPath(diff.fromVol),
diff,
showProgress=self.showProgress is n... | Spend some time to get an accurate size. | Below is the the instruction that describes the task:
### Input:
Spend some time to get an accurate size.
### Response:
def measureSize(self, diff, chunkSize):
""" Spend some time to get an accurate size. """
self._fileSystemSync()
sendContext = self.butter.send(
self.getSendPa... |
def create_disposable_app(clientInfo, config={}):
"""
Use an existing disposable app if data exists or create a new one
and persist the data.
"""
file = _get_disposable_app_filename(clientInfo)
existing = _get_existing_disposable_app(file, clientInfo, config)
if existing:
if _check_a... | Use an existing disposable app if data exists or create a new one
and persist the data. | Below is the the instruction that describes the task:
### Input:
Use an existing disposable app if data exists or create a new one
and persist the data.
### Response:
def create_disposable_app(clientInfo, config={}):
"""
Use an existing disposable app if data exists or create a new one
and persist ... |
def read_file(filepath: str) -> str:
"""Read a file and return it as a string"""
# ? Check this is ok if absolute paths passed in
filepath = os.path.expanduser(filepath)
with open(filepath) as opened_file: # type: IO
file_read = opened_file.read() # type: str
return file_read | Read a file and return it as a string | Below is the the instruction that describes the task:
### Input:
Read a file and return it as a string
### Response:
def read_file(filepath: str) -> str:
"""Read a file and return it as a string"""
# ? Check this is ok if absolute paths passed in
filepath = os.path.expanduser(filepath)
with open(fi... |
def greenhall_sx(t, F, alpha):
""" Eqn (8) from Greenhall2004
"""
if F == float('inf'):
return greenhall_sw(t, alpha+2)
a = 2*greenhall_sw(t, alpha)
b = greenhall_sw(t-1.0/float(F), alpha)
c = greenhall_sw(t+1.0/float(F), alpha)
return pow(F, 2)*(a-b-c) | Eqn (8) from Greenhall2004 | Below is the the instruction that describes the task:
### Input:
Eqn (8) from Greenhall2004
### Response:
def greenhall_sx(t, F, alpha):
""" Eqn (8) from Greenhall2004
"""
if F == float('inf'):
return greenhall_sw(t, alpha+2)
a = 2*greenhall_sw(t, alpha)
b = greenhall_sw(t-1.0/float(F),... |
def get_installed_use(cp, use="USE"):
'''
.. versionadded:: 2015.8.0
Gets the installed USE flags from the VARDB.
@type: cp: string
@param cp: cat/pkg
@type use: string
@param use: 1 of ["USE", "PKGUSE"]
@rtype list
@returns [] or the list of IUSE flags
'''
portage = _get_p... | .. versionadded:: 2015.8.0
Gets the installed USE flags from the VARDB.
@type: cp: string
@param cp: cat/pkg
@type use: string
@param use: 1 of ["USE", "PKGUSE"]
@rtype list
@returns [] or the list of IUSE flags | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 2015.8.0
Gets the installed USE flags from the VARDB.
@type: cp: string
@param cp: cat/pkg
@type use: string
@param use: 1 of ["USE", "PKGUSE"]
@rtype list
@returns [] or the list of IUSE flags
### Respo... |
def tm(seq, dna_conc=50, salt_conc=50, parameters='cloning'):
'''Calculate nearest-neighbor melting temperature (Tm).
:param seq: Sequence for which to calculate the tm.
:type seq: coral.DNA
:param dna_conc: DNA concentration in nM.
:type dna_conc: float
:param salt_conc: Salt concentration in ... | Calculate nearest-neighbor melting temperature (Tm).
:param seq: Sequence for which to calculate the tm.
:type seq: coral.DNA
:param dna_conc: DNA concentration in nM.
:type dna_conc: float
:param salt_conc: Salt concentration in mM.
:type salt_conc: float
:param parameters: Nearest-neighbo... | Below is the the instruction that describes the task:
### Input:
Calculate nearest-neighbor melting temperature (Tm).
:param seq: Sequence for which to calculate the tm.
:type seq: coral.DNA
:param dna_conc: DNA concentration in nM.
:type dna_conc: float
:param salt_conc: Salt concentration in ... |
def _references(self, i, sequence=False):
"""Handle references."""
value = ''
c = next(i)
if c == '\\':
# \\
if sequence and self.bslash_abort:
raise PathNameException
value = r'\\'
if self.bslash_abort:
if ... | Handle references. | Below is the the instruction that describes the task:
### Input:
Handle references.
### Response:
def _references(self, i, sequence=False):
"""Handle references."""
value = ''
c = next(i)
if c == '\\':
# \\
if sequence and self.bslash_abort:
... |
def branches(self):
""" Returns a :class:`QuerySet` of all branch nodes (nodes with at least
one child).
:return: A :class:`QuerySet` of all leaf nodes (nodes with at least
one child).
"""
# We need to read the _cte_node_children attribute, so ensure it e... | Returns a :class:`QuerySet` of all branch nodes (nodes with at least
one child).
:return: A :class:`QuerySet` of all leaf nodes (nodes with at least
one child). | Below is the the instruction that describes the task:
### Input:
Returns a :class:`QuerySet` of all branch nodes (nodes with at least
one child).
:return: A :class:`QuerySet` of all leaf nodes (nodes with at least
one child).
### Response:
def branches(self):
""" Re... |
def as_completed(fs, timeout=None):
"""An iterator over the given futures that yields each as it completes.
Args:
fs: The sequence of Futures (possibly created by different Executors) to
iterate over.
timeout: The maximum number of seconds to wait. If None, then there
is... | An iterator over the given futures that yields each as it completes.
Args:
fs: The sequence of Futures (possibly created by different Executors) to
iterate over.
timeout: The maximum number of seconds to wait. If None, then there
is no limit on the wait time.
Returns:
... | Below is the the instruction that describes the task:
### Input:
An iterator over the given futures that yields each as it completes.
Args:
fs: The sequence of Futures (possibly created by different Executors) to
iterate over.
timeout: The maximum number of seconds to wait. If None,... |
def _lbd(self,*args,**kwargs):
"""Calculate l,b, and d"""
obs, ro, vo= self._parse_radec_kwargs(kwargs,dontpop=True)
X,Y,Z= self._helioXYZ(*args,**kwargs)
bad_indx= (X == 0.)*(Y == 0.)*(Z == 0.)
if True in bad_indx:
X[bad_indx]+= ro/10000.
return coords.XYZ_to... | Calculate l,b, and d | Below is the the instruction that describes the task:
### Input:
Calculate l,b, and d
### Response:
def _lbd(self,*args,**kwargs):
"""Calculate l,b, and d"""
obs, ro, vo= self._parse_radec_kwargs(kwargs,dontpop=True)
X,Y,Z= self._helioXYZ(*args,**kwargs)
bad_indx= (X == 0.)*(Y == 0.... |
def on_queue_declareok(self, method_frame):
"""
Invoked by pika when the Queue.Declare RPC call made in
setup_queue has completed. In this method we will bind the queue
and exchange together with the routing key by issuing the Queue.Bind
RPC command. When this command is complete... | Invoked by pika when the Queue.Declare RPC call made in
setup_queue has completed. In this method we will bind the queue
and exchange together with the routing key by issuing the Queue.Bind
RPC command. When this command is complete, the on_bindok method will
be invoked by pika.
... | Below is the the instruction that describes the task:
### Input:
Invoked by pika when the Queue.Declare RPC call made in
setup_queue has completed. In this method we will bind the queue
and exchange together with the routing key by issuing the Queue.Bind
RPC command. When this command is com... |
def scale_from_matrix(matrix):
"""Return scaling factor, origin and direction from scaling matrix.
>>> factor = random.random() * 10 - 5
>>> origin = numpy.random.random(3) - 0.5
>>> direct = numpy.random.random(3) - 0.5
>>> S0 = scale_matrix(factor, origin)
>>> factor, origin, direction = scal... | Return scaling factor, origin and direction from scaling matrix.
>>> factor = random.random() * 10 - 5
>>> origin = numpy.random.random(3) - 0.5
>>> direct = numpy.random.random(3) - 0.5
>>> S0 = scale_matrix(factor, origin)
>>> factor, origin, direction = scale_from_matrix(S0)
>>> S1 = scale_m... | Below is the the instruction that describes the task:
### Input:
Return scaling factor, origin and direction from scaling matrix.
>>> factor = random.random() * 10 - 5
>>> origin = numpy.random.random(3) - 0.5
>>> direct = numpy.random.random(3) - 0.5
>>> S0 = scale_matrix(factor, origin)
>>> f... |
async def CredentialContents(self, credentials, include_secrets):
'''
credentials : typing.Sequence[~CloudCredentialArg]
include_secrets : bool
Returns -> typing.Sequence[~CredentialContentResult]
'''
# map input types to rpc msg
_params = dict()
msg = dic... | credentials : typing.Sequence[~CloudCredentialArg]
include_secrets : bool
Returns -> typing.Sequence[~CredentialContentResult] | Below is the the instruction that describes the task:
### Input:
credentials : typing.Sequence[~CloudCredentialArg]
include_secrets : bool
Returns -> typing.Sequence[~CredentialContentResult]
### Response:
async def CredentialContents(self, credentials, include_secrets):
'''
credent... |
def RunValidationOutputToFilename(feed, options, output_filename):
"""Validate feed, save HTML at output_filename and return an exit code."""
try:
output_file = open(output_filename, 'w')
exit_code = RunValidationOutputToFile(feed, options, output_file)
output_file.close()
except IOError as e:
pri... | Validate feed, save HTML at output_filename and return an exit code. | Below is the the instruction that describes the task:
### Input:
Validate feed, save HTML at output_filename and return an exit code.
### Response:
def RunValidationOutputToFilename(feed, options, output_filename):
"""Validate feed, save HTML at output_filename and return an exit code."""
try:
output_file ... |
def separated(self, separator='-'):
"""Return a string representation of the identifier with its elements
separated by the given separator."""
return separator.join((part for part in self.elements() if part)) | Return a string representation of the identifier with its elements
separated by the given separator. | Below is the the instruction that describes the task:
### Input:
Return a string representation of the identifier with its elements
separated by the given separator.
### Response:
def separated(self, separator='-'):
"""Return a string representation of the identifier with its elements
separ... |
def inline(self) -> str:
"""
Return endpoint string
:return:
"""
return BMAEndpoint.API + "{DNS}{IPv4}{IPv6}{PORT}" \
.format(DNS=(" {0}".format(self.server) if self.server else ""),
IPv4=(" {0}".format(self.ipv4) if self.ipv4 else ""),
... | Return endpoint string
:return: | Below is the the instruction that describes the task:
### Input:
Return endpoint string
:return:
### Response:
def inline(self) -> str:
"""
Return endpoint string
:return:
"""
return BMAEndpoint.API + "{DNS}{IPv4}{IPv6}{PORT}" \
.format(DNS=(" {0}".form... |
def remove_handler(args):
"""usage: {program} remove <anchor-id> [<path>]
Remove an existing anchor.
"""
repo = _open_repo(args)
anchor_id, anchor = _get_anchor(repo, args['<anchor-id>'])
del repo[anchor_id]
return ExitCode.OK | usage: {program} remove <anchor-id> [<path>]
Remove an existing anchor. | Below is the the instruction that describes the task:
### Input:
usage: {program} remove <anchor-id> [<path>]
Remove an existing anchor.
### Response:
def remove_handler(args):
"""usage: {program} remove <anchor-id> [<path>]
Remove an existing anchor.
"""
repo = _open_repo(args)
anchor_i... |
def _read_hip_para(self, length, *, version):
"""Read HIP parameters.
Positional arguments:
* length -- int, length of parameters
Keyword arguments:
* version -- int, HIP version
Returns:
* dict -- extracted HIP parameters
"""
count... | Read HIP parameters.
Positional arguments:
* length -- int, length of parameters
Keyword arguments:
* version -- int, HIP version
Returns:
* dict -- extracted HIP parameters | Below is the the instruction that describes the task:
### Input:
Read HIP parameters.
Positional arguments:
* length -- int, length of parameters
Keyword arguments:
* version -- int, HIP version
Returns:
* dict -- extracted HIP parameters
### Response: ... |
def super_terms(self):
"""Return a dictionary mapping term names to their super terms"""
# If the doc already has super terms, we've already parsed something, so
# assume we parsed the declaration, and can use re-use the old decls.
if self.doc and self.doc.super_terms:
retur... | Return a dictionary mapping term names to their super terms | Below is the the instruction that describes the task:
### Input:
Return a dictionary mapping term names to their super terms
### Response:
def super_terms(self):
"""Return a dictionary mapping term names to their super terms"""
# If the doc already has super terms, we've already parsed something, ... |
def list_markets_by_currency(self, currency):
"""
Helper function to see which markets exist for a currency.
Endpoint: /public/getmarkets
Example ::
>>> Bittrex(None, None).list_markets_by_currency('LTC')
['BTC-LTC', 'ETH-LTC', 'USDT-LTC']
:param curren... | Helper function to see which markets exist for a currency.
Endpoint: /public/getmarkets
Example ::
>>> Bittrex(None, None).list_markets_by_currency('LTC')
['BTC-LTC', 'ETH-LTC', 'USDT-LTC']
:param currency: String literal for the currency (ex: LTC)
:type curren... | Below is the the instruction that describes the task:
### Input:
Helper function to see which markets exist for a currency.
Endpoint: /public/getmarkets
Example ::
>>> Bittrex(None, None).list_markets_by_currency('LTC')
['BTC-LTC', 'ETH-LTC', 'USDT-LTC']
:param cur... |
def _expand(self, line: str) -> str:
"""Expand shortcuts and aliases"""
# expand aliases
# make a copy of aliases so we can edit it
tmp_aliases = list(self.aliases.keys())
keep_expanding = bool(tmp_aliases)
while keep_expanding:
for cur_alias in tmp_aliases:
... | Expand shortcuts and aliases | Below is the the instruction that describes the task:
### Input:
Expand shortcuts and aliases
### Response:
def _expand(self, line: str) -> str:
"""Expand shortcuts and aliases"""
# expand aliases
# make a copy of aliases so we can edit it
tmp_aliases = list(self.aliases.keys())
... |
def failure_reason(self, failure_index=None):
"""Get the reason for a failure.
Args:
failure_index: Index of the fail to return the graph for (can be
negative). If None, the most appropriate failure is chosen
according to these rules:
- If the... | Get the reason for a failure.
Args:
failure_index: Index of the fail to return the graph for (can be
negative). If None, the most appropriate failure is chosen
according to these rules:
- If the fail is cyclic, the most recent fail (the one containing... | Below is the the instruction that describes the task:
### Input:
Get the reason for a failure.
Args:
failure_index: Index of the fail to return the graph for (can be
negative). If None, the most appropriate failure is chosen
according to these rules:
... |
def get_pubkey(self):
"""
Get the public key of the certificate signing request.
:return: The public key.
:rtype: :py:class:`PKey`
"""
pkey = PKey.__new__(PKey)
pkey._pkey = _lib.X509_REQ_get_pubkey(self._req)
_openssl_assert(pkey._pkey != _ffi.NULL)
... | Get the public key of the certificate signing request.
:return: The public key.
:rtype: :py:class:`PKey` | Below is the the instruction that describes the task:
### Input:
Get the public key of the certificate signing request.
:return: The public key.
:rtype: :py:class:`PKey`
### Response:
def get_pubkey(self):
"""
Get the public key of the certificate signing request.
:return:... |
def attributes(self, params=None):
"""
Gets the attributes from a Group/Indicator or Victim
Yields: attribute json
"""
if params is None:
params = {}
if not self.can_update():
self._tcex.handle_error(910, [self.type])
for a in self.tc_re... | Gets the attributes from a Group/Indicator or Victim
Yields: attribute json | Below is the the instruction that describes the task:
### Input:
Gets the attributes from a Group/Indicator or Victim
Yields: attribute json
### Response:
def attributes(self, params=None):
"""
Gets the attributes from a Group/Indicator or Victim
Yields: attribute json
""... |
def has_urls(self):
"Handy for templates."
if self.isbn_uk or self.isbn_us or self.official_url or self.notes_url:
return True
else:
return False | Handy for templates. | Below is the the instruction that describes the task:
### Input:
Handy for templates.
### Response:
def has_urls(self):
"Handy for templates."
if self.isbn_uk or self.isbn_us or self.official_url or self.notes_url:
return True
else:
return False |
def _postprocess_somatic(in_file, paired):
"""Post-process somatic calls to provide standard output.
- Converts SGT and NT into standard VCF GT fields
- Replace generic TUMOR NORMAL names in VCF with sample names.
"""
out_file = in_file.replace(".vcf.gz", "-fixed.vcf")
if not utils.file_exists(... | Post-process somatic calls to provide standard output.
- Converts SGT and NT into standard VCF GT fields
- Replace generic TUMOR NORMAL names in VCF with sample names. | Below is the the instruction that describes the task:
### Input:
Post-process somatic calls to provide standard output.
- Converts SGT and NT into standard VCF GT fields
- Replace generic TUMOR NORMAL names in VCF with sample names.
### Response:
def _postprocess_somatic(in_file, paired):
"""Post-proc... |
def downsample(self, factor):
"""
Compute a downsampled version of the skeleton by striding while
preserving endpoints.
factor: stride length for downsampling the saved skeleton paths.
Returns: downsampled PrecomputedSkeleton
"""
if int(factor) != factor or factor < 1:
raise ValueEr... | Compute a downsampled version of the skeleton by striding while
preserving endpoints.
factor: stride length for downsampling the saved skeleton paths.
Returns: downsampled PrecomputedSkeleton | Below is the the instruction that describes the task:
### Input:
Compute a downsampled version of the skeleton by striding while
preserving endpoints.
factor: stride length for downsampling the saved skeleton paths.
Returns: downsampled PrecomputedSkeleton
### Response:
def downsample(self, factor):... |
def draw_circle(self, color, world_loc, world_radius, thickness=0):
"""Draw a circle using world coordinates and radius."""
if world_radius > 0:
center = self.world_to_surf.fwd_pt(world_loc).round()
radius = max(1, int(self.world_to_surf.fwd_dist(world_radius)))
pygame.draw.circle(self.surf, c... | Draw a circle using world coordinates and radius. | Below is the the instruction that describes the task:
### Input:
Draw a circle using world coordinates and radius.
### Response:
def draw_circle(self, color, world_loc, world_radius, thickness=0):
"""Draw a circle using world coordinates and radius."""
if world_radius > 0:
center = self.world_to_surf... |
def signHash(self, message_hash, private_key):
'''
Sign the hash provided.
.. WARNING:: *Never* sign a hash that you didn't generate,
it can be an arbitrary transaction. For example, it might
send all of your account's ether to an attacker.
If you would like com... | Sign the hash provided.
.. WARNING:: *Never* sign a hash that you didn't generate,
it can be an arbitrary transaction. For example, it might
send all of your account's ether to an attacker.
If you would like compatibility with
:meth:`w3.eth.sign() <web3.eth.Eth.sign>`
... | Below is the the instruction that describes the task:
### Input:
Sign the hash provided.
.. WARNING:: *Never* sign a hash that you didn't generate,
it can be an arbitrary transaction. For example, it might
send all of your account's ether to an attacker.
If you would like c... |
def _nln_constraints(self, nb, nl):
""" Returns non-linear constraints for OPF.
"""
Pmis = NonLinearConstraint("Pmis", nb)
Qmis = NonLinearConstraint("Qmis", nb)
Sf = NonLinearConstraint("Sf", nl)
St = NonLinearConstraint("St", nl)
return Pmis, Qmis, Sf, St | Returns non-linear constraints for OPF. | Below is the the instruction that describes the task:
### Input:
Returns non-linear constraints for OPF.
### Response:
def _nln_constraints(self, nb, nl):
""" Returns non-linear constraints for OPF.
"""
Pmis = NonLinearConstraint("Pmis", nb)
Qmis = NonLinearConstraint("Qmis", nb)
... |
def get_sql(self, debug=False, use_cache=True):
"""
Generates the sql for this query and returns the sql as a string.
:type debug: bool
:param debug: If True, the sql will be returned in a format that is easier to read and debug.
Defaults to False
:type use_cache: b... | Generates the sql for this query and returns the sql as a string.
:type debug: bool
:param debug: If True, the sql will be returned in a format that is easier to read and debug.
Defaults to False
:type use_cache: bool
:param use_cache: If True, the query will returned the c... | Below is the the instruction that describes the task:
### Input:
Generates the sql for this query and returns the sql as a string.
:type debug: bool
:param debug: If True, the sql will be returned in a format that is easier to read and debug.
Defaults to False
:type use_cache: ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.