code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _plot_completeness(ax, comw, start_time, end_time):
'''
Adds completeness intervals to a plot
'''
comw = np.array(comw)
comp = np.column_stack([np.hstack([end_time, comw[:, 0], start_time]),
np.hstack([comw[0, 1], comw[:, 1], comw[-1, 1]])])
ax.step(comp[:-1, 0], ... | Adds completeness intervals to a plot | Below is the the instruction that describes the task:
### Input:
Adds completeness intervals to a plot
### Response:
def _plot_completeness(ax, comw, start_time, end_time):
'''
Adds completeness intervals to a plot
'''
comw = np.array(comw)
comp = np.column_stack([np.hstack([end_time, comw[:, 0... |
def ensure_image_is_hex(input_path):
"""Return a path to a hex version of a firmware image.
If the input file is already in hex format then input_path
is returned and nothing is done. If it is not in hex format
then an SCons action is added to convert it to hex and the
target output file path is r... | Return a path to a hex version of a firmware image.
If the input file is already in hex format then input_path
is returned and nothing is done. If it is not in hex format
then an SCons action is added to convert it to hex and the
target output file path is returned.
A cache is kept so that each f... | Below is the the instruction that describes the task:
### Input:
Return a path to a hex version of a firmware image.
If the input file is already in hex format then input_path
is returned and nothing is done. If it is not in hex format
then an SCons action is added to convert it to hex and the
tar... |
def get_row_metadata(gctx_file_path, convert_neg_666=True):
"""
Opens .gctx file and returns only row metadata
Input:
Mandatory:
- gctx_file_path (str): full path to gctx file you want to parse.
Optional:
- convert_neg_666 (bool): whether to convert -666 values to num
... | Opens .gctx file and returns only row metadata
Input:
Mandatory:
- gctx_file_path (str): full path to gctx file you want to parse.
Optional:
- convert_neg_666 (bool): whether to convert -666 values to num
Output:
- row_meta (pandas DataFrame): a DataFrame of all row me... | Below is the the instruction that describes the task:
### Input:
Opens .gctx file and returns only row metadata
Input:
Mandatory:
- gctx_file_path (str): full path to gctx file you want to parse.
Optional:
- convert_neg_666 (bool): whether to convert -666 values to num
Out... |
def disagg_prec_cascade(precip_daily,
cascade_options, hourly=True,level=9,
shift=0,
test=False):
"""Precipitation disaggregation with cascade model (Olsson, 1998)
Parameters
----------
precip_daily : pd.Series
daily data
... | Precipitation disaggregation with cascade model (Olsson, 1998)
Parameters
----------
precip_daily : pd.Series
daily data
hourly: Boolean (for an hourly resolution disaggregation)
if False, then returns 5-min disaggregated precipitation
(disaggregation level depending on the "le... | Below is the the instruction that describes the task:
### Input:
Precipitation disaggregation with cascade model (Olsson, 1998)
Parameters
----------
precip_daily : pd.Series
daily data
hourly: Boolean (for an hourly resolution disaggregation)
if False, then returns 5-min disaggrega... |
def mendelian_errors(args):
"""
%prog mendelian_errors STR-Mendelian-errors.csv
Plot Mendelian errors as calculated by mendelian(). File
`STR-Mendelian-errors.csv` looks like:
,Duos - Mendelian errors,Trios - Mendelian errors
SCA36,1.40%,0.60%
ULD,0.30%,1.50%
BPES,0.00%,1.80%
One... | %prog mendelian_errors STR-Mendelian-errors.csv
Plot Mendelian errors as calculated by mendelian(). File
`STR-Mendelian-errors.csv` looks like:
,Duos - Mendelian errors,Trios - Mendelian errors
SCA36,1.40%,0.60%
ULD,0.30%,1.50%
BPES,0.00%,1.80%
One TRED disease per line, followed by duo ... | Below is the the instruction that describes the task:
### Input:
%prog mendelian_errors STR-Mendelian-errors.csv
Plot Mendelian errors as calculated by mendelian(). File
`STR-Mendelian-errors.csv` looks like:
,Duos - Mendelian errors,Trios - Mendelian errors
SCA36,1.40%,0.60%
ULD,0.30%,1.50%
... |
def _update_scheme(self, scheme, ancestors):
""" Updates the current scheme based off special pre-defined keys and retruns a new updated scheme.
:param scheme: A :dict:, The scheme defining the validations.
:param ancestors: A :OrderedDict: that provides a history of its ancestors.
:rty... | Updates the current scheme based off special pre-defined keys and retruns a new updated scheme.
:param scheme: A :dict:, The scheme defining the validations.
:param ancestors: A :OrderedDict: that provides a history of its ancestors.
:rtype: A new :dict: with updated scheme values. | Below is the the instruction that describes the task:
### Input:
Updates the current scheme based off special pre-defined keys and retruns a new updated scheme.
:param scheme: A :dict:, The scheme defining the validations.
:param ancestors: A :OrderedDict: that provides a history of its ancestors.
... |
def BT(cpu, dest, src):
"""
Bit Test.
Selects the bit in a bit string (specified with the first operand, called the bit base) at the
bit-position designated by the bit offset (specified by the second operand) and stores the value
of the bit in the CF flag. The bit base operand c... | Bit Test.
Selects the bit in a bit string (specified with the first operand, called the bit base) at the
bit-position designated by the bit offset (specified by the second operand) and stores the value
of the bit in the CF flag. The bit base operand can be a register or a memory location; the b... | Below is the the instruction that describes the task:
### Input:
Bit Test.
Selects the bit in a bit string (specified with the first operand, called the bit base) at the
bit-position designated by the bit offset (specified by the second operand) and stores the value
of the bit in the CF fla... |
def unpause(self, id): # pylint: disable=invalid-name,redefined-builtin
"""Unpause a running result.
:param id: Result ID as an int.
"""
return self.service.post(self.base+str(id)+'/unpause/') | Unpause a running result.
:param id: Result ID as an int. | Below is the the instruction that describes the task:
### Input:
Unpause a running result.
:param id: Result ID as an int.
### Response:
def unpause(self, id): # pylint: disable=invalid-name,redefined-builtin
"""Unpause a running result.
:param id: Result ID as an int.
"""
... |
def WriteSymlink(self, src_arcname, dst_arcname):
"""Writes a symlink into the archive."""
info = self._tar_fd.tarinfo()
info.tarfile = self._tar_fd
info.name = SmartStr(dst_arcname)
info.size = 0
info.mtime = time.time()
info.type = tarfile.SYMTYPE
info.linkname = SmartStr(src_arcname)... | Writes a symlink into the archive. | Below is the the instruction that describes the task:
### Input:
Writes a symlink into the archive.
### Response:
def WriteSymlink(self, src_arcname, dst_arcname):
"""Writes a symlink into the archive."""
info = self._tar_fd.tarinfo()
info.tarfile = self._tar_fd
info.name = SmartStr(dst_arcname)
... |
def set_matrix(self, matrix):
"""Sets the pattern’s transformation matrix to :obj:`matrix`.
This matrix is a transformation from user space to pattern space.
When a pattern is first created
it always has the identity matrix for its transformation matrix,
which means that pattern... | Sets the pattern’s transformation matrix to :obj:`matrix`.
This matrix is a transformation from user space to pattern space.
When a pattern is first created
it always has the identity matrix for its transformation matrix,
which means that pattern space is initially identical to user spa... | Below is the the instruction that describes the task:
### Input:
Sets the pattern’s transformation matrix to :obj:`matrix`.
This matrix is a transformation from user space to pattern space.
When a pattern is first created
it always has the identity matrix for its transformation matrix,
... |
def can_access_objective_hierarchy(self):
"""Tests if this user can perform hierarchy queries.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known all methods in this
session will result in a PermissionDenied. This is intended as a
... | Tests if this user can perform hierarchy queries.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known all methods in this
session will result in a PermissionDenied. This is intended as a
hint to an an application that may not offer ... | Below is the the instruction that describes the task:
### Input:
Tests if this user can perform hierarchy queries.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known all methods in this
session will result in a PermissionDenied. This i... |
def select_io( hash ):
"""
Returns the relevant i/o for a method whose call is characterized by the hash
:param hash: The hash for the CallDescriptor
:rtype list(tuple( hash, stack, methodname, returnval, args, packet_num )):
"""
load_cache(True)
global CACHE_
res = []
record_used(... | Returns the relevant i/o for a method whose call is characterized by the hash
:param hash: The hash for the CallDescriptor
:rtype list(tuple( hash, stack, methodname, returnval, args, packet_num )): | Below is the the instruction that describes the task:
### Input:
Returns the relevant i/o for a method whose call is characterized by the hash
:param hash: The hash for the CallDescriptor
:rtype list(tuple( hash, stack, methodname, returnval, args, packet_num )):
### Response:
def select_io( hash ):
... |
def processAbf(abfFname,saveAs=False,dpi=100,show=True):
"""
automatically generate a single representative image for an ABF.
If saveAs is given (full path of a jpg of png file), the image will be saved.
Otherwise, the image will pop up in a matplotlib window.
"""
if not type(abfFname) is str or... | automatically generate a single representative image for an ABF.
If saveAs is given (full path of a jpg of png file), the image will be saved.
Otherwise, the image will pop up in a matplotlib window. | Below is the the instruction that describes the task:
### Input:
automatically generate a single representative image for an ABF.
If saveAs is given (full path of a jpg of png file), the image will be saved.
Otherwise, the image will pop up in a matplotlib window.
### Response:
def processAbf(abfFname,save... |
def iterSourceCode(paths):
"""
Iterate over all Python source files in C{paths}.
@param paths: A list of paths. Directories will be recursed into and
any .py files found will be yielded. Any non-directories will be
yielded as-is.
"""
for path in paths:
if os.path.isdir(pat... | Iterate over all Python source files in C{paths}.
@param paths: A list of paths. Directories will be recursed into and
any .py files found will be yielded. Any non-directories will be
yielded as-is. | Below is the the instruction that describes the task:
### Input:
Iterate over all Python source files in C{paths}.
@param paths: A list of paths. Directories will be recursed into and
any .py files found will be yielded. Any non-directories will be
yielded as-is.
### Response:
def iterSource... |
def run():
"""The entry point from the praw-multiprocess utility."""
parser = OptionParser(version='%prog {0}'.format(__version__))
parser.add_option('-a', '--addr', default='localhost',
help=('The address or host to listen on. Specify -a '
'0.0.0.0 to liste... | The entry point from the praw-multiprocess utility. | Below is the the instruction that describes the task:
### Input:
The entry point from the praw-multiprocess utility.
### Response:
def run():
"""The entry point from the praw-multiprocess utility."""
parser = OptionParser(version='%prog {0}'.format(__version__))
parser.add_option('-a', '--addr', defaul... |
def check_status(self, ignore=(), status=None):
"""
Checks status of each collection and shard to make sure that:
a) Cluster state is active
b) Number of docs matches across replicas for a given shard.
Returns a dict of results for custom alerting.
"""
self.SH... | Checks status of each collection and shard to make sure that:
a) Cluster state is active
b) Number of docs matches across replicas for a given shard.
Returns a dict of results for custom alerting. | Below is the the instruction that describes the task:
### Input:
Checks status of each collection and shard to make sure that:
a) Cluster state is active
b) Number of docs matches across replicas for a given shard.
Returns a dict of results for custom alerting.
### Response:
def check_s... |
def deserialize_object(buffers, g=None):
"""Reconstruct an object serialized by serialize_object from data buffers.
Parameters
----------
bufs : list of buffers/bytes
g : globals to be used when uncanning
Returns
-------
(newobj, bufs) : unpacked object, and the list of remaining un... | Reconstruct an object serialized by serialize_object from data buffers.
Parameters
----------
bufs : list of buffers/bytes
g : globals to be used when uncanning
Returns
-------
(newobj, bufs) : unpacked object, and the list of remaining unused buffers. | Below is the the instruction that describes the task:
### Input:
Reconstruct an object serialized by serialize_object from data buffers.
Parameters
----------
bufs : list of buffers/bytes
g : globals to be used when uncanning
Returns
-------
(newobj, bufs) : unpacked object, and the... |
def print_error(error: "GraphQLError") -> str:
"""Print a GraphQLError to a string.
The printed string will contain useful location information about the
error's position in the source.
"""
printed_locations: List[str] = []
print_location = printed_locations.append
if error.nodes:
f... | Print a GraphQLError to a string.
The printed string will contain useful location information about the
error's position in the source. | Below is the the instruction that describes the task:
### Input:
Print a GraphQLError to a string.
The printed string will contain useful location information about the
error's position in the source.
### Response:
def print_error(error: "GraphQLError") -> str:
"""Print a GraphQLError to a string.
... |
def make_position_choices(self):
"""Create choices for available positions
"""
choices = []
for pos in self.get_available_positions():
choices.append({
"ResultValue": pos,
"ResultText": pos,
})
return choices | Create choices for available positions | Below is the the instruction that describes the task:
### Input:
Create choices for available positions
### Response:
def make_position_choices(self):
"""Create choices for available positions
"""
choices = []
for pos in self.get_available_positions():
choices.append({
... |
def on_number(self, ctx, value):
''' Since this is defined both integer and double callbacks are useless '''
value = int(value) if value.isdigit() else float(value)
top = self._stack[-1]
if top is JSONCompositeType.OBJECT:
self.fire(JSONStreamer.VALUE_EVENT, value)
el... | Since this is defined both integer and double callbacks are useless | Below is the the instruction that describes the task:
### Input:
Since this is defined both integer and double callbacks are useless
### Response:
def on_number(self, ctx, value):
''' Since this is defined both integer and double callbacks are useless '''
value = int(value) if value.isdigit() else ... |
def _load_permissions(self):
"""Load permissions associated to actions."""
result = _P(needs=set(), excludes=set())
if not self.allow_by_default:
result.needs.update(self.explicit_needs)
for explicit_need in self.explicit_needs:
if explicit_need.method == 'action... | Load permissions associated to actions. | Below is the the instruction that describes the task:
### Input:
Load permissions associated to actions.
### Response:
def _load_permissions(self):
"""Load permissions associated to actions."""
result = _P(needs=set(), excludes=set())
if not self.allow_by_default:
result.needs.u... |
def completed_number(prefix, length):
"""
'prefix' is the start of the CC number as a string, any number of digits.
'length' is the length of the CC number to generate. Typically 13 or 16
"""
ccnumber = prefix
# generate digits
while len(ccnumber) < (length - 1):
digit = random.choic... | 'prefix' is the start of the CC number as a string, any number of digits.
'length' is the length of the CC number to generate. Typically 13 or 16 | Below is the the instruction that describes the task:
### Input:
'prefix' is the start of the CC number as a string, any number of digits.
'length' is the length of the CC number to generate. Typically 13 or 16
### Response:
def completed_number(prefix, length):
"""
'prefix' is the start of the CC numb... |
def condensed_coords(i, j, n):
"""Transform square distance matrix coordinates to the corresponding
index into a condensed, 1D form of the matrix.
Parameters
----------
i : int
Row index.
j : int
Column index.
n : int
Size of the square matrix (length of first or sec... | Transform square distance matrix coordinates to the corresponding
index into a condensed, 1D form of the matrix.
Parameters
----------
i : int
Row index.
j : int
Column index.
n : int
Size of the square matrix (length of first or second dimension).
Returns
-----... | Below is the the instruction that describes the task:
### Input:
Transform square distance matrix coordinates to the corresponding
index into a condensed, 1D form of the matrix.
Parameters
----------
i : int
Row index.
j : int
Column index.
n : int
Size of the square... |
def configure_upload(graph, ns, mappings, exclude_func=None):
"""
Register Upload endpoints for a resource object.
"""
convention = UploadConvention(graph, exclude_func)
convention.configure(ns, mappings) | Register Upload endpoints for a resource object. | Below is the the instruction that describes the task:
### Input:
Register Upload endpoints for a resource object.
### Response:
def configure_upload(graph, ns, mappings, exclude_func=None):
"""
Register Upload endpoints for a resource object.
"""
convention = UploadConvention(graph, exclude_func)
... |
def contains_ignoring_case(self, *items):
"""Asserts that val is string and contains the given item or items."""
if len(items) == 0:
raise ValueError('one or more args must be given')
if isinstance(self.val, str_types):
if len(items) == 1:
if not isinstanc... | Asserts that val is string and contains the given item or items. | Below is the the instruction that describes the task:
### Input:
Asserts that val is string and contains the given item or items.
### Response:
def contains_ignoring_case(self, *items):
"""Asserts that val is string and contains the given item or items."""
if len(items) == 0:
raise Valu... |
def predict(self, X):
"""Predict the closest cluster each sample in X belongs to.
In the vector quantization literature, `cluster_centers_` is called
the code book and each value returned by `predict` is the index of
the closest code in the code book.
Parameters
-------... | Predict the closest cluster each sample in X belongs to.
In the vector quantization literature, `cluster_centers_` is called
the code book and each value returned by `predict` is the index of
the closest code in the code book.
Parameters
----------
X : array-like, shape... | Below is the the instruction that describes the task:
### Input:
Predict the closest cluster each sample in X belongs to.
In the vector quantization literature, `cluster_centers_` is called
the code book and each value returned by `predict` is the index of
the closest code in the code book.... |
def check_completeness(self):
"""Raise a |RuntimeError| if the |IOSequence.series| contains at
least one |numpy.nan| value, if option |Options.checkseries| is
enabled.
>>> from hydpy import pub
>>> pub.timegrids = '2000-01-01', '2000-01-11', '1d'
>>> from hydpy.core.sequ... | Raise a |RuntimeError| if the |IOSequence.series| contains at
least one |numpy.nan| value, if option |Options.checkseries| is
enabled.
>>> from hydpy import pub
>>> pub.timegrids = '2000-01-01', '2000-01-11', '1d'
>>> from hydpy.core.sequencetools import IOSequence
>>> c... | Below is the the instruction that describes the task:
### Input:
Raise a |RuntimeError| if the |IOSequence.series| contains at
least one |numpy.nan| value, if option |Options.checkseries| is
enabled.
>>> from hydpy import pub
>>> pub.timegrids = '2000-01-01', '2000-01-11', '1d'
... |
def cprint(text, fg=grey, bg=blackbg, w=norm, cr=False, encoding='utf8'):
''' Print a string in a specified color style and then return to normal.
def cprint(text, fg=white, bg=blackbg, w=norm, cr=True):
'''
colorstart(fg, bg, w)
out(text)
colorend(cr) | Print a string in a specified color style and then return to normal.
def cprint(text, fg=white, bg=blackbg, w=norm, cr=True): | Below is the the instruction that describes the task:
### Input:
Print a string in a specified color style and then return to normal.
def cprint(text, fg=white, bg=blackbg, w=norm, cr=True):
### Response:
def cprint(text, fg=grey, bg=blackbg, w=norm, cr=False, encoding='utf8'):
''' Print a string in a ... |
def createReferenceURL(self, pid, name, ref_url, path="", validate=True):
"""Create a Referenced Content File (.url)
:param pid: The HydroShare ID of the resource for which the file should be created
:param name: Filename for the referenced file
... | Create a Referenced Content File (.url)
:param pid: The HydroShare ID of the resource for which the file should be created
:param name: Filename for the referenced file
:param ref_url: url to be used in the referenced file
:... | Below is the the instruction that describes the task:
### Input:
Create a Referenced Content File (.url)
:param pid: The HydroShare ID of the resource for which the file should be created
:param name: Filename for the referenced file
:param ref... |
def text_bounding_box(self, size_pt, text):
"""
Return the bounding box of the given text
at the given font size.
:param int size_pt: the font size in points
:param string text: the text
:rtype: tuple (width, height)
"""
if size_pt == 12:
mul... | Return the bounding box of the given text
at the given font size.
:param int size_pt: the font size in points
:param string text: the text
:rtype: tuple (width, height) | Below is the the instruction that describes the task:
### Input:
Return the bounding box of the given text
at the given font size.
:param int size_pt: the font size in points
:param string text: the text
:rtype: tuple (width, height)
### Response:
def text_bounding_box(self, size_... |
def get_width(self, c, default=0, match_only=None):
"""
Get the display width of a component. Wraps `getattr()`.
Development note: Cannot define this as a `partial()` because I want
to maintain the order of arguments in `getattr()`.
Args:
c (component): The componen... | Get the display width of a component. Wraps `getattr()`.
Development note: Cannot define this as a `partial()` because I want
to maintain the order of arguments in `getattr()`.
Args:
c (component): The component to look up.
default (float): The width to return in the ev... | Below is the the instruction that describes the task:
### Input:
Get the display width of a component. Wraps `getattr()`.
Development note: Cannot define this as a `partial()` because I want
to maintain the order of arguments in `getattr()`.
Args:
c (component): The component t... |
def for_user(cls, user):
''' Returns the user's current cart, or creates a new cart
if there isn't one ready yet. '''
try:
existing = commerce.Cart.objects.get(
user=user,
status=commerce.Cart.STATUS_ACTIVE,
)
except ObjectDoesNotE... | Returns the user's current cart, or creates a new cart
if there isn't one ready yet. | Below is the the instruction that describes the task:
### Input:
Returns the user's current cart, or creates a new cart
if there isn't one ready yet.
### Response:
def for_user(cls, user):
''' Returns the user's current cart, or creates a new cart
if there isn't one ready yet. '''
... |
def clean_account(self):
"""Ensure this is an income account"""
account = self.cleaned_data['account']
if not account:
return
if account.type != Account.TYPES.income:
raise ValidationError('Account must be an income account')
try:
account.hou... | Ensure this is an income account | Below is the the instruction that describes the task:
### Input:
Ensure this is an income account
### Response:
def clean_account(self):
"""Ensure this is an income account"""
account = self.cleaned_data['account']
if not account:
return
if account.type != Account.TYPES... |
def get_lock_requests(self):
"""Take the current context, and the current patch locks, and determine
the effective requests that will be added to the main request.
Returns:
A dict of (PatchLock, [Requirement]) tuples. Each requirement will be
a weak package reference. If... | Take the current context, and the current patch locks, and determine
the effective requests that will be added to the main request.
Returns:
A dict of (PatchLock, [Requirement]) tuples. Each requirement will be
a weak package reference. If there is no current context, an empty
... | Below is the the instruction that describes the task:
### Input:
Take the current context, and the current patch locks, and determine
the effective requests that will be added to the main request.
Returns:
A dict of (PatchLock, [Requirement]) tuples. Each requirement will be
... |
def _determinebase_address(self):
"""
The basic idea is simple: start from a specific point, try to construct
functions as much as we can, and maintain a function distribution graph
and a call graph simultaneously. Repeat searching until we come to the
end that there is no new fu... | The basic idea is simple: start from a specific point, try to construct
functions as much as we can, and maintain a function distribution graph
and a call graph simultaneously. Repeat searching until we come to the
end that there is no new function to be found.
A function should start wi... | Below is the the instruction that describes the task:
### Input:
The basic idea is simple: start from a specific point, try to construct
functions as much as we can, and maintain a function distribution graph
and a call graph simultaneously. Repeat searching until we come to the
end that the... |
def wantFile(self, file):
"""Is the file a wanted test file?
The file must be a python source file and match testMatch or
include, and not match exclude. Files that match ignore are *never*
wanted, regardless of plugin, testMatch, include or exclude settings.
"""
# never... | Is the file a wanted test file?
The file must be a python source file and match testMatch or
include, and not match exclude. Files that match ignore are *never*
wanted, regardless of plugin, testMatch, include or exclude settings. | Below is the the instruction that describes the task:
### Input:
Is the file a wanted test file?
The file must be a python source file and match testMatch or
include, and not match exclude. Files that match ignore are *never*
wanted, regardless of plugin, testMatch, include or exclude setti... |
def next(self, data):
"""
Derive a new set of internal and output data from given input data and the data
stored internally.
Use the key derivation function to derive new data. The kdf gets supplied with the
current key and the data passed to this method.
:param data: A... | Derive a new set of internal and output data from given input data and the data
stored internally.
Use the key derivation function to derive new data. The kdf gets supplied with the
current key and the data passed to this method.
:param data: A bytes-like object encoding the data to pa... | Below is the the instruction that describes the task:
### Input:
Derive a new set of internal and output data from given input data and the data
stored internally.
Use the key derivation function to derive new data. The kdf gets supplied with the
current key and the data passed to this meth... |
async def action_handler(self):
"""
Call vtep controller in sequence, merge mutiple calls if possible
When a bind relationship is updated, we always send all logical ports to a logicalswitch,
to make sure it recovers from some failed updates (so called idempotency). When multipl... | Call vtep controller in sequence, merge mutiple calls if possible
When a bind relationship is updated, we always send all logical ports to a logicalswitch,
to make sure it recovers from some failed updates (so called idempotency). When multiple
calls are pending, we only need to send th... | Below is the the instruction that describes the task:
### Input:
Call vtep controller in sequence, merge mutiple calls if possible
When a bind relationship is updated, we always send all logical ports to a logicalswitch,
to make sure it recovers from some failed updates (so called idempoten... |
def build(self):
"""
The decoder computational graph consists of three components:
(1) the input node `decoder_input`
(2) the embedding node `decoder_embed`
(3) the recurrent (RNN) part `decoder_rnn`
(4) the output of th... | The decoder computational graph consists of three components:
(1) the input node `decoder_input`
(2) the embedding node `decoder_embed`
(3) the recurrent (RNN) part `decoder_rnn`
(4) the output of the decoder RNN `decoder_output`... | Below is the the instruction that describes the task:
### Input:
The decoder computational graph consists of three components:
(1) the input node `decoder_input`
(2) the embedding node `decoder_embed`
(3) the recurrent (RNN) part `decoder_r... |
def updateNodeCapabilities(self, nodeId, node, vendorSpecific=None):
"""See Also: updateNodeCapabilitiesResponse()
Args:
nodeId:
node:
vendorSpecific:
Returns:
"""
response = self.updateNodeCapabilitiesResponse(nodeId, node, vendorSpecific)
... | See Also: updateNodeCapabilitiesResponse()
Args:
nodeId:
node:
vendorSpecific:
Returns: | Below is the the instruction that describes the task:
### Input:
See Also: updateNodeCapabilitiesResponse()
Args:
nodeId:
node:
vendorSpecific:
Returns:
### Response:
def updateNodeCapabilities(self, nodeId, node, vendorSpecific=None):
"""See Also: updateNode... |
def update_preference_type(self, type, address, notification, notification_preferences_frequency):
"""
Update a preference.
Change the preference for a single notification for a single communication channel
"""
path = {}
data = {}
params = {}
#... | Update a preference.
Change the preference for a single notification for a single communication channel | Below is the the instruction that describes the task:
### Input:
Update a preference.
Change the preference for a single notification for a single communication channel
### Response:
def update_preference_type(self, type, address, notification, notification_preferences_frequency):
"""
... |
def geocoding(ctx, query, forward, include_headers, lat, lon,
place_type, output, dataset, country, bbox, features, limit):
"""This command returns places matching an address (forward mode) or
places matching coordinates (reverse mode).
In forward (the default) mode the query argument shall b... | This command returns places matching an address (forward mode) or
places matching coordinates (reverse mode).
In forward (the default) mode the query argument shall be an address
such as '1600 pennsylvania ave nw'.
$ mapbox geocoding '1600 pennsylvania ave nw'
In reverse mode the query argument... | Below is the the instruction that describes the task:
### Input:
This command returns places matching an address (forward mode) or
places matching coordinates (reverse mode).
In forward (the default) mode the query argument shall be an address
such as '1600 pennsylvania ave nw'.
$ mapbox geocodi... |
def setup(cls, cron_cfg="cron"):
""" Set up the runtime environment.
"""
random.seed()
logging_cfg = cls.LOGGING_CFG
if "%s" in logging_cfg:
logging_cfg = logging_cfg % (cron_cfg if "--cron" in sys.argv[1:] else "scripts",)
logging_cfg = os.path.expanduser(log... | Set up the runtime environment. | Below is the the instruction that describes the task:
### Input:
Set up the runtime environment.
### Response:
def setup(cls, cron_cfg="cron"):
""" Set up the runtime environment.
"""
random.seed()
logging_cfg = cls.LOGGING_CFG
if "%s" in logging_cfg:
logging_cfg... |
def router_add(self, params):
"""add new router (mongos) into existing configuration"""
if self.uses_rs_configdb:
# Replica set configdb.
rs_id = self._configsvrs[0]
config_members = ReplicaSets().members(rs_id)
configdb = '%s/%s' % (
rs_id... | add new router (mongos) into existing configuration | Below is the the instruction that describes the task:
### Input:
add new router (mongos) into existing configuration
### Response:
def router_add(self, params):
"""add new router (mongos) into existing configuration"""
if self.uses_rs_configdb:
# Replica set configdb.
rs_id ... |
def create(self):
"""
create the server.
"""
logger.info("creating server")
self.library.Srv_Create.restype = snap7.snap7types.S7Object
self.pointer = snap7.snap7types.S7Object(self.library.Srv_Create()) | create the server. | Below is the the instruction that describes the task:
### Input:
create the server.
### Response:
def create(self):
"""
create the server.
"""
logger.info("creating server")
self.library.Srv_Create.restype = snap7.snap7types.S7Object
self.pointer = snap7.snap7types.S... |
def autoExpand(self, level=None):
"""
Returns whether or not to expand for the inputed level.
:param level | <int> || None
:return <bool>
"""
return self._autoExpand.get(level, self._autoExpand.get(None, False)) | Returns whether or not to expand for the inputed level.
:param level | <int> || None
:return <bool> | Below is the the instruction that describes the task:
### Input:
Returns whether or not to expand for the inputed level.
:param level | <int> || None
:return <bool>
### Response:
def autoExpand(self, level=None):
"""
Returns whether or not to expand ... |
def click_text(self, text, exact_match=False):
"""Click text identified by ``text``.
By default tries to click first text involves given ``text``, if you would
like to click exactly matching text, then set ``exact_match`` to `True`.
If there are multiple use of ``text`` and you ... | Click text identified by ``text``.
By default tries to click first text involves given ``text``, if you would
like to click exactly matching text, then set ``exact_match`` to `True`.
If there are multiple use of ``text`` and you do not want first one,
use `locator` with `Get Web... | Below is the the instruction that describes the task:
### Input:
Click text identified by ``text``.
By default tries to click first text involves given ``text``, if you would
like to click exactly matching text, then set ``exact_match`` to `True`.
If there are multiple use of ``text`... |
def exists(self, **kwargs):
"""Providing a partition is not necessary on topology; causes errors"""
kwargs.pop('partition', None)
kwargs['transform_name'] = True
return self._exists(**kwargs) | Providing a partition is not necessary on topology; causes errors | Below is the the instruction that describes the task:
### Input:
Providing a partition is not necessary on topology; causes errors
### Response:
def exists(self, **kwargs):
"""Providing a partition is not necessary on topology; causes errors"""
kwargs.pop('partition', None)
kwargs['transfor... |
async def reset(self, von_wallet: Wallet, seed: str = None) -> Wallet:
"""
Close and delete (open) VON anchor wallet and then create, open, and return
replacement on current link secret.
Note that this operation effectively destroys private keys for keyed data
structures such as... | Close and delete (open) VON anchor wallet and then create, open, and return
replacement on current link secret.
Note that this operation effectively destroys private keys for keyed data
structures such as credential offers or credential definitions.
Raise WalletState if the wallet is c... | Below is the the instruction that describes the task:
### Input:
Close and delete (open) VON anchor wallet and then create, open, and return
replacement on current link secret.
Note that this operation effectively destroys private keys for keyed data
structures such as credential offers or ... |
def get_model_details(self, model_name):
"""Get details of the specified model from CloudML Service.
Args:
model_name: the name of the model. It can be a model full name
("projects/[project_id]/models/[model_name]") or just [model_name].
Returns: a dictionary of the model details.
"""... | Get details of the specified model from CloudML Service.
Args:
model_name: the name of the model. It can be a model full name
("projects/[project_id]/models/[model_name]") or just [model_name].
Returns: a dictionary of the model details. | Below is the the instruction that describes the task:
### Input:
Get details of the specified model from CloudML Service.
Args:
model_name: the name of the model. It can be a model full name
("projects/[project_id]/models/[model_name]") or just [model_name].
Returns: a dictionary of the m... |
def rebuild(self):
"""Rebuild RIFF tree and index from streams."""
movi = self.riff.find('LIST', 'movi')
movi.chunks = self.combine_streams()
self.rebuild_index() | Rebuild RIFF tree and index from streams. | Below is the the instruction that describes the task:
### Input:
Rebuild RIFF tree and index from streams.
### Response:
def rebuild(self):
"""Rebuild RIFF tree and index from streams."""
movi = self.riff.find('LIST', 'movi')
movi.chunks = self.combine_streams()
self.rebuild_index() |
def asRGB(self):
"""
Return image as RGB pixels.
RGB colour images are passed through unchanged;
greyscales are expanded into RGB triplets
(there is a small speed overhead for doing this).
An alpha channel in the source image will raise an exception.
The retur... | Return image as RGB pixels.
RGB colour images are passed through unchanged;
greyscales are expanded into RGB triplets
(there is a small speed overhead for doing this).
An alpha channel in the source image will raise an exception.
The return values are as for the :meth:`read` ... | Below is the the instruction that describes the task:
### Input:
Return image as RGB pixels.
RGB colour images are passed through unchanged;
greyscales are expanded into RGB triplets
(there is a small speed overhead for doing this).
An alpha channel in the source image will raise ... |
def markAsSpam(self, thread_id=None):
"""
Mark a thread as spam and delete it
:param thread_id: User/Group ID to mark as spam. See :ref:`intro_threads`
:return: Whether the request was successful
:raises: FBchatException if request failed
"""
thread_id, thread_ty... | Mark a thread as spam and delete it
:param thread_id: User/Group ID to mark as spam. See :ref:`intro_threads`
:return: Whether the request was successful
:raises: FBchatException if request failed | Below is the the instruction that describes the task:
### Input:
Mark a thread as spam and delete it
:param thread_id: User/Group ID to mark as spam. See :ref:`intro_threads`
:return: Whether the request was successful
:raises: FBchatException if request failed
### Response:
def markAsSpam... |
def create_failure(self, exception=None):
"""
This returns an object implementing IFailedFuture.
If exception is None (the default) we MUST be called within an
"except" block (such that sys.exc_info() returns useful
information).
"""
if exception:
ret... | This returns an object implementing IFailedFuture.
If exception is None (the default) we MUST be called within an
"except" block (such that sys.exc_info() returns useful
information). | Below is the the instruction that describes the task:
### Input:
This returns an object implementing IFailedFuture.
If exception is None (the default) we MUST be called within an
"except" block (such that sys.exc_info() returns useful
information).
### Response:
def create_failure(self, ex... |
def _set_autoupload_param(self, v, load=False):
"""
Setter method for autoupload_param, mapped from YANG variable /support/autoupload_param (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_autoupload_param is considered as a private
method. Backends lookin... | Setter method for autoupload_param, mapped from YANG variable /support/autoupload_param (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_autoupload_param is considered as a private
method. Backends looking to populate this variable should
do so via calling thi... | Below is the the instruction that describes the task:
### Input:
Setter method for autoupload_param, mapped from YANG variable /support/autoupload_param (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_autoupload_param is considered as a private
method. Backen... |
def _check_update_(self):
"""Check if the current version of the library is outdated."""
try:
data = requests.get("https://pypi.python.org/pypi/jira/json", timeout=2.001).json()
released_version = data['info']['version']
if parse_version(released_version) > parse_ver... | Check if the current version of the library is outdated. | Below is the the instruction that describes the task:
### Input:
Check if the current version of the library is outdated.
### Response:
def _check_update_(self):
"""Check if the current version of the library is outdated."""
try:
data = requests.get("https://pypi.python.org/pypi/jira/js... |
def _get_result(self, resource):
"""
Converts the given resource to a result to be returned from the view.
Unless a custom renderer is employed, this will involve creating
a representer and using it to convert the resource to a string.
:param resource: Resource to convert.
... | Converts the given resource to a result to be returned from the view.
Unless a custom renderer is employed, this will involve creating
a representer and using it to convert the resource to a string.
:param resource: Resource to convert.
:type resource: Object implementing
:cla... | Below is the the instruction that describes the task:
### Input:
Converts the given resource to a result to be returned from the view.
Unless a custom renderer is employed, this will involve creating
a representer and using it to convert the resource to a string.
:param resource: Resource t... |
def weight_unit(self, weight_unit):
"""Sets the weight_unit of this MeasurementSettings.
:param weight_unit: The weight_unit of this MeasurementSettings.
:type: str
"""
allowed_values = ["pound", "kilogram"] # noqa: E501
if weight_unit is not None and weight_unit not i... | Sets the weight_unit of this MeasurementSettings.
:param weight_unit: The weight_unit of this MeasurementSettings.
:type: str | Below is the the instruction that describes the task:
### Input:
Sets the weight_unit of this MeasurementSettings.
:param weight_unit: The weight_unit of this MeasurementSettings.
:type: str
### Response:
def weight_unit(self, weight_unit):
"""Sets the weight_unit of this MeasurementSetti... |
def notify3_d_event(self, type_p, data):
"""Notifies framebuffer about 3D backend event.
in type_p of type int
event type. Currently only VBOX3D_NOTIFY_EVENT_TYPE_VISIBLE_3DDATA is supported.
in data of type str
event-specific data, depends on the supplied event type
... | Notifies framebuffer about 3D backend event.
in type_p of type int
event type. Currently only VBOX3D_NOTIFY_EVENT_TYPE_VISIBLE_3DDATA is supported.
in data of type str
event-specific data, depends on the supplied event type | Below is the the instruction that describes the task:
### Input:
Notifies framebuffer about 3D backend event.
in type_p of type int
event type. Currently only VBOX3D_NOTIFY_EVENT_TYPE_VISIBLE_3DDATA is supported.
in data of type str
event-specific data, depends on the suppl... |
def backward_word(event):
"""
Move back to the start of the current or previous word. Words are composed
of letters and digits.
"""
buff = event.current_buffer
pos = buff.document.find_previous_word_beginning(count=event.arg)
if pos:
buff.cursor_position += pos | Move back to the start of the current or previous word. Words are composed
of letters and digits. | Below is the the instruction that describes the task:
### Input:
Move back to the start of the current or previous word. Words are composed
of letters and digits.
### Response:
def backward_word(event):
"""
Move back to the start of the current or previous word. Words are composed
of letters and di... |
def stream_bloom_filters(dataset, # type: Iterable[Sequence[Text]]
keys, # type: Sequence[Sequence[bytes]]
schema # type: Schema
):
# type: (...) -> Iterable[Tuple[bitarray, Text, int]]
""" Compute composite Bloom filters (CLKs) ... | Compute composite Bloom filters (CLKs) for every record in an
iterable dataset.
:param dataset: An iterable of indexable records.
:param schema: An instantiated Schema instance
:param keys: A tuple of two lists of secret keys used in the HMAC.
:return: Generator yielding bloom f... | Below is the the instruction that describes the task:
### Input:
Compute composite Bloom filters (CLKs) for every record in an
iterable dataset.
:param dataset: An iterable of indexable records.
:param schema: An instantiated Schema instance
:param keys: A tuple of two lists of secr... |
def to_line_string(self, closed=True):
"""
Convert this polygon's `exterior` to a ``LineString`` instance.
Parameters
----------
closed : bool, optional
Whether to close the line string, i.e. to add the first point of
the `exterior` also as the last point... | Convert this polygon's `exterior` to a ``LineString`` instance.
Parameters
----------
closed : bool, optional
Whether to close the line string, i.e. to add the first point of
the `exterior` also as the last point at the end of the line string.
This has no eff... | Below is the the instruction that describes the task:
### Input:
Convert this polygon's `exterior` to a ``LineString`` instance.
Parameters
----------
closed : bool, optional
Whether to close the line string, i.e. to add the first point of
the `exterior` also as the ... |
async def _dhcp_handler(self):
"""
Mini DHCP server, respond DHCP packets from OpenFlow
"""
conn = self._connection
ofdef = self._connection.openflowdef
l3 = self._parent._gettableindex('l3input', self._connection.protocol.vhost)
dhcp_packet_matcher = OpenflowAsyn... | Mini DHCP server, respond DHCP packets from OpenFlow | Below is the the instruction that describes the task:
### Input:
Mini DHCP server, respond DHCP packets from OpenFlow
### Response:
async def _dhcp_handler(self):
"""
Mini DHCP server, respond DHCP packets from OpenFlow
"""
conn = self._connection
ofdef = self._connection.op... |
def _validate_inputs(actual_inputs, required_inputs, keypath=None):
"""
Validate inputs. Raise exception if something is missing.
args:
actual_inputs: the object/dictionary passed to a subclass of
PublishablePayload
required_inputs: the object/dictionary containing key... | Validate inputs. Raise exception if something is missing.
args:
actual_inputs: the object/dictionary passed to a subclass of
PublishablePayload
required_inputs: the object/dictionary containing keys (and subkeys)
for required fields. (See get_common_payload_templat... | Below is the the instruction that describes the task:
### Input:
Validate inputs. Raise exception if something is missing.
args:
actual_inputs: the object/dictionary passed to a subclass of
PublishablePayload
required_inputs: the object/dictionary containing keys (and subkey... |
def for_version(self, version_guid):
"""
Return a UsageLocator for the same block in a different version of the library.
"""
return self.replace(library_key=self.library_key.for_version(version_guid)) | Return a UsageLocator for the same block in a different version of the library. | Below is the the instruction that describes the task:
### Input:
Return a UsageLocator for the same block in a different version of the library.
### Response:
def for_version(self, version_guid):
"""
Return a UsageLocator for the same block in a different version of the library.
"""
... |
def init_debug():
"""Initialise debug_stats and QueueLength (this is not a reset)"""
global debug_stats
global QueueLength
if debug_stats is None:
list_defaultdict = partial(defaultdict, list)
debug_stats = defaultdict(list_defaultdict)
QueueLength = [] | Initialise debug_stats and QueueLength (this is not a reset) | Below is the the instruction that describes the task:
### Input:
Initialise debug_stats and QueueLength (this is not a reset)
### Response:
def init_debug():
"""Initialise debug_stats and QueueLength (this is not a reset)"""
global debug_stats
global QueueLength
if debug_stats is None:
list... |
def _load_config(config_filepath: str) -> Dict[str, Any]:
"""
Loads YAML config file to dictionary
:returns: dict from YAML config file
"""
try:
config: Dict[str, Any] = yaml.load(stream=open(config_filepath, "r"))
except Exception as e:
raise Exc... | Loads YAML config file to dictionary
:returns: dict from YAML config file | Below is the the instruction that describes the task:
### Input:
Loads YAML config file to dictionary
:returns: dict from YAML config file
### Response:
def _load_config(config_filepath: str) -> Dict[str, Any]:
"""
Loads YAML config file to dictionary
:returns: dict from YAML conf... |
def add_clause(self, clause):
"""Add a new clause to the existing query.
:param clause: The clause to add
:type clause: MongoClause
:return: None
"""
if clause.query_loc == MongoClause.LOC_MAIN:
self._main.append(clause)
elif clause.query_loc == Mongo... | Add a new clause to the existing query.
:param clause: The clause to add
:type clause: MongoClause
:return: None | Below is the the instruction that describes the task:
### Input:
Add a new clause to the existing query.
:param clause: The clause to add
:type clause: MongoClause
:return: None
### Response:
def add_clause(self, clause):
"""Add a new clause to the existing query.
:param c... |
def _exec_command(adb_cmd):
"""
Format adb command and execute it in shell
:param adb_cmd: list adb command to execute
:return: string '0' and shell command output if successful, otherwise
raise CalledProcessError exception and return error code
"""
t = tempfile.TemporaryFile()
final_adb... | Format adb command and execute it in shell
:param adb_cmd: list adb command to execute
:return: string '0' and shell command output if successful, otherwise
raise CalledProcessError exception and return error code | Below is the the instruction that describes the task:
### Input:
Format adb command and execute it in shell
:param adb_cmd: list adb command to execute
:return: string '0' and shell command output if successful, otherwise
raise CalledProcessError exception and return error code
### Response:
def _exec_... |
def _realloc(self, ptr, size):
"""
Handler for any libc `realloc` SimProcedure call. If the heap has faithful support for `realloc`, it ought to be
implemented in a `realloc` function (as opposed to the `_realloc` function).
:param ptr: the location in memory to be reallocated
:... | Handler for any libc `realloc` SimProcedure call. If the heap has faithful support for `realloc`, it ought to be
implemented in a `realloc` function (as opposed to the `_realloc` function).
:param ptr: the location in memory to be reallocated
:param size: the new size desired for the allocation | Below is the the instruction that describes the task:
### Input:
Handler for any libc `realloc` SimProcedure call. If the heap has faithful support for `realloc`, it ought to be
implemented in a `realloc` function (as opposed to the `_realloc` function).
:param ptr: the location in memory to be rea... |
def remove_record(self, common_name):
"""Delete the record associated with this common name"""
bundle = self.get_files(common_name)
num_signees = len(Counter(bundle.record['signees']))
if bundle.is_ca() and num_signees > 0:
raise CertificateAuthorityInUseError(
... | Delete the record associated with this common name | Below is the the instruction that describes the task:
### Input:
Delete the record associated with this common name
### Response:
def remove_record(self, common_name):
"""Delete the record associated with this common name"""
bundle = self.get_files(common_name)
num_signees = len(Counter(bu... |
def thread_stopped(self):
""" :meth:`.WThreadTask._polling_iteration` implementation
"""
if self.__current_task is not None:
task = self.__task_chain[self.__current_task]
task.stop()
self.__current_task = None | :meth:`.WThreadTask._polling_iteration` implementation | Below is the the instruction that describes the task:
### Input:
:meth:`.WThreadTask._polling_iteration` implementation
### Response:
def thread_stopped(self):
""" :meth:`.WThreadTask._polling_iteration` implementation
"""
if self.__current_task is not None:
task = self.__task_chain[self.__current_task]
... |
def wrap_httplib_request(request_func):
"""Wrap the httplib request function to trace. Create a new span and update
and close the span in the response later.
"""
def call(self, method, url, body, headers, *args, **kwargs):
_tracer = execution_context.get_opencensus_tracer()
blacklist_ho... | Wrap the httplib request function to trace. Create a new span and update
and close the span in the response later. | Below is the the instruction that describes the task:
### Input:
Wrap the httplib request function to trace. Create a new span and update
and close the span in the response later.
### Response:
def wrap_httplib_request(request_func):
"""Wrap the httplib request function to trace. Create a new span and upda... |
def get_existing_path(path, topmost_path=None):
"""Get the longest parent path in `path` that exists.
If `path` exists, it is returned.
Args:
path (str): Path to test
topmost_path (str): Do not test this path or above
Returns:
str: Existing path, or None if no path was found.
... | Get the longest parent path in `path` that exists.
If `path` exists, it is returned.
Args:
path (str): Path to test
topmost_path (str): Do not test this path or above
Returns:
str: Existing path, or None if no path was found. | Below is the the instruction that describes the task:
### Input:
Get the longest parent path in `path` that exists.
If `path` exists, it is returned.
Args:
path (str): Path to test
topmost_path (str): Do not test this path or above
Returns:
str: Existing path, or None if no pa... |
def output(data, **kwargs): # pylint: disable=unused-argument
'''
Print the output data in JSON
'''
try:
if 'output_indent' not in __opts__:
return salt.utils.json.dumps(data, default=repr, indent=4)
indent = __opts__.get('output_indent')
sort_keys = False
... | Print the output data in JSON | Below is the the instruction that describes the task:
### Input:
Print the output data in JSON
### Response:
def output(data, **kwargs): # pylint: disable=unused-argument
'''
Print the output data in JSON
'''
try:
if 'output_indent' not in __opts__:
return salt.utils.json.dumps... |
def get_class_members(self, cls_name, cls):
"""Returns the list of class members to document in `cls`.
This function filters the class member to ONLY return those
defined by the class. It drops the inherited ones.
Args:
cls_name: Qualified name of `cls`.
cls: An inspect object of type 'cl... | Returns the list of class members to document in `cls`.
This function filters the class member to ONLY return those
defined by the class. It drops the inherited ones.
Args:
cls_name: Qualified name of `cls`.
cls: An inspect object of type 'class'.
Yields:
name, member tuples. | Below is the the instruction that describes the task:
### Input:
Returns the list of class members to document in `cls`.
This function filters the class member to ONLY return those
defined by the class. It drops the inherited ones.
Args:
cls_name: Qualified name of `cls`.
cls: An inspect ... |
def RelaxNGSetSchema(self, schema):
"""Use RelaxNG to validate the document as it is processed.
Activation is only possible before the first Read(). if
@schema is None, then RelaxNG validation is desactivated. @
The @schema should not be freed until the reader is
dealloc... | Use RelaxNG to validate the document as it is processed.
Activation is only possible before the first Read(). if
@schema is None, then RelaxNG validation is desactivated. @
The @schema should not be freed until the reader is
deallocated or its use has been deactivated. | Below is the the instruction that describes the task:
### Input:
Use RelaxNG to validate the document as it is processed.
Activation is only possible before the first Read(). if
@schema is None, then RelaxNG validation is desactivated. @
The @schema should not be freed until the reader... |
def parse(self, data):
"""Parse a 9 bytes packet in the Temperature format and return a
dictionary containing the data extracted. An example of a return value
would be:
.. code-block:: python
{
'id': "0x2EB2",
'packet_length': 8,
... | Parse a 9 bytes packet in the Temperature format and return a
dictionary containing the data extracted. An example of a return value
would be:
.. code-block:: python
{
'id': "0x2EB2",
'packet_length': 8,
'packet_type': 80,
... | Below is the the instruction that describes the task:
### Input:
Parse a 9 bytes packet in the Temperature format and return a
dictionary containing the data extracted. An example of a return value
would be:
.. code-block:: python
{
'id': "0x2EB2",
... |
def repeat(
df,
column: str,
*,
times: int,
new_column: str = None
):
"""
Duplicate each string in `column` by indicated number of time
See [pandas doc](
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.repeat.html) for more information... | Duplicate each string in `column` by indicated number of time
See [pandas doc](
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.repeat.html) for more information
---
### Parameters
*mandatory :*
- `column` (*str*): the column
- `times` (*int*): times to repeat... | Below is the the instruction that describes the task:
### Input:
Duplicate each string in `column` by indicated number of time
See [pandas doc](
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.repeat.html) for more information
---
### Parameters
*mandatory :*
... |
def while_do(self, classical_reg, q_program):
"""
While a classical register at index classical_reg is 1, loop q_program
Equivalent to the following construction:
.. code::
WHILE [c]:
instr...
=>
LABEL @START
JUMP-UNLE... | While a classical register at index classical_reg is 1, loop q_program
Equivalent to the following construction:
.. code::
WHILE [c]:
instr...
=>
LABEL @START
JUMP-UNLESS @END [c]
instr...
JUMP @START
... | Below is the the instruction that describes the task:
### Input:
While a classical register at index classical_reg is 1, loop q_program
Equivalent to the following construction:
.. code::
WHILE [c]:
instr...
=>
LABEL @START
JUMP-U... |
def _db_install(self, db_name):
""" Install nipap database schema
"""
self._logger.info("Installing NIPAP database schemas into db")
self._execute(db_schema.ip_net % (db_name))
self._execute(db_schema.functions)
self._execute(db_schema.triggers) | Install nipap database schema | Below is the the instruction that describes the task:
### Input:
Install nipap database schema
### Response:
def _db_install(self, db_name):
""" Install nipap database schema
"""
self._logger.info("Installing NIPAP database schemas into db")
self._execute(db_schema.ip_net % (db_name... |
def pic_loggedrequiredremoterelease_v2(self):
"""Update the receiver link sequence."""
log = self.sequences.logs.fastaccess
rec = self.sequences.receivers.fastaccess
log.loggedrequiredremoterelease[0] = rec.s[0] | Update the receiver link sequence. | Below is the the instruction that describes the task:
### Input:
Update the receiver link sequence.
### Response:
def pic_loggedrequiredremoterelease_v2(self):
"""Update the receiver link sequence."""
log = self.sequences.logs.fastaccess
rec = self.sequences.receivers.fastaccess
log.loggedrequiredr... |
def apply_tile_to_image(image, size, tile, tile_size, tile_corner):
"""
Copies a tile with a given offset onto an image
:param image: The image the file is to be copied onto (as a list of (R,G,B) tuples)
:param size: The size of the image as a tuple (width, height)
:param tile: The tile to be copied... | Copies a tile with a given offset onto an image
:param image: The image the file is to be copied onto (as a list of (R,G,B) tuples)
:param size: The size of the image as a tuple (width, height)
:param tile: The tile to be copied over (as a list of (R,G,B) tuples)
:param tile_size: The size of the tile a... | Below is the the instruction that describes the task:
### Input:
Copies a tile with a given offset onto an image
:param image: The image the file is to be copied onto (as a list of (R,G,B) tuples)
:param size: The size of the image as a tuple (width, height)
:param tile: The tile to be copied over (as a... |
def dropEvent(self, event):
"""Allow user to drop supported files"""
urls = mimedata2url(event.mimeData())
if urls:
event.setDropAction(Qt.CopyAction)
event.accept()
self.sig_files_dropped.emit(urls)
else:
event.ignore() | Allow user to drop supported files | Below is the the instruction that describes the task:
### Input:
Allow user to drop supported files
### Response:
def dropEvent(self, event):
"""Allow user to drop supported files"""
urls = mimedata2url(event.mimeData())
if urls:
event.setDropAction(Qt.CopyAction)
... |
def get(self, id, seq, line): # pylint: disable=invalid-name,redefined-builtin
"""Get a highlight.
:param id: Result ID as an int.
:param seq: TestResult sequence ID as an int.
:param line: Line number in TestResult's logfile as an int.
:return: :class:`highlights.Highlight <hig... | Get a highlight.
:param id: Result ID as an int.
:param seq: TestResult sequence ID as an int.
:param line: Line number in TestResult's logfile as an int.
:return: :class:`highlights.Highlight <highlights.Highlight>` object | Below is the the instruction that describes the task:
### Input:
Get a highlight.
:param id: Result ID as an int.
:param seq: TestResult sequence ID as an int.
:param line: Line number in TestResult's logfile as an int.
:return: :class:`highlights.Highlight <highlights.Highlight>` o... |
def load_object(import_path):
"""
Shamelessly stolen from https://github.com/ojii/django-load
Loads an object from an 'import_path', like in MIDDLEWARE_CLASSES and the
likes.
Import paths should be: "mypackage.mymodule.MyObject". It then imports the
module up until the last dot and tries t... | Shamelessly stolen from https://github.com/ojii/django-load
Loads an object from an 'import_path', like in MIDDLEWARE_CLASSES and the
likes.
Import paths should be: "mypackage.mymodule.MyObject". It then imports the
module up until the last dot and tries to get the attribute after that dot
fro... | Below is the the instruction that describes the task:
### Input:
Shamelessly stolen from https://github.com/ojii/django-load
Loads an object from an 'import_path', like in MIDDLEWARE_CLASSES and the
likes.
Import paths should be: "mypackage.mymodule.MyObject". It then imports the
module up unt... |
def run_dot(self, args, name, parts=0, urls={},
graph_options={}, node_options={}, edge_options={}):
"""
Run graphviz 'dot' over this graph, returning whatever 'dot'
writes to stdout.
*args* will be passed along as commandline arguments.
*name* is the name of th... | Run graphviz 'dot' over this graph, returning whatever 'dot'
writes to stdout.
*args* will be passed along as commandline arguments.
*name* is the name of the graph
*urls* is a dictionary mapping class names to http urls
Raises DotException for any of the many os and
... | Below is the the instruction that describes the task:
### Input:
Run graphviz 'dot' over this graph, returning whatever 'dot'
writes to stdout.
*args* will be passed along as commandline arguments.
*name* is the name of the graph
*urls* is a dictionary mapping class names to http ... |
def retry(self, queue=None, delay=None, max_retries=None):
""" Marks the current job as needing to be retried. Interrupts it. """
max_retries = max_retries
if max_retries is None:
max_retries = self.max_retries
if self.data.get("retry_count", 0) >= max_retries:
... | Marks the current job as needing to be retried. Interrupts it. | Below is the the instruction that describes the task:
### Input:
Marks the current job as needing to be retried. Interrupts it.
### Response:
def retry(self, queue=None, delay=None, max_retries=None):
""" Marks the current job as needing to be retried. Interrupts it. """
max_retries = max_retries
... |
def resize(self, width, height, **kwargs):
"""Resizes the image to the supplied width/height. Returns the
instance. Supports the following optional keyword arguments:
mode - The resizing mode to use, see Image.MODES
filter - The filter to use: see Image.FILTERS
background - The ... | Resizes the image to the supplied width/height. Returns the
instance. Supports the following optional keyword arguments:
mode - The resizing mode to use, see Image.MODES
filter - The filter to use: see Image.FILTERS
background - The hexadecimal background fill color, RGB or ARGB
... | Below is the the instruction that describes the task:
### Input:
Resizes the image to the supplied width/height. Returns the
instance. Supports the following optional keyword arguments:
mode - The resizing mode to use, see Image.MODES
filter - The filter to use: see Image.FILTERS
ba... |
def update_configuration(self, timeout=-1):
"""
Reapplies the appliance's configuration on the enclosure. This includes running the same configure steps
that were performed as part of the enclosure add.
Args:
timeout: Timeout in seconds. Wait for task completion by default. ... | Reapplies the appliance's configuration on the enclosure. This includes running the same configure steps
that were performed as part of the enclosure add.
Args:
timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
in OneV... | Below is the the instruction that describes the task:
### Input:
Reapplies the appliance's configuration on the enclosure. This includes running the same configure steps
that were performed as part of the enclosure add.
Args:
timeout: Timeout in seconds. Wait for task completion by defa... |
def _in_conf_dir(filename):
"""
Put the `filename` to the configuration directory context / path.
"""
return os.path.join(
os.path.dirname(__file__),
"templates/conf",
filename
) | Put the `filename` to the configuration directory context / path. | Below is the the instruction that describes the task:
### Input:
Put the `filename` to the configuration directory context / path.
### Response:
def _in_conf_dir(filename):
"""
Put the `filename` to the configuration directory context / path.
"""
return os.path.join(
os.path.dirname(__file_... |
def diff_with_target(self, binary_im):
""" Creates a color image to visualize the overlap between two images.
Nonzero pixels that match in both images are green.
Nonzero pixels of this image that aren't in the other image are yellow
Nonzero pixels of the other image that aren't in this i... | Creates a color image to visualize the overlap between two images.
Nonzero pixels that match in both images are green.
Nonzero pixels of this image that aren't in the other image are yellow
Nonzero pixels of the other image that aren't in this image are red
Parameters
----------... | Below is the the instruction that describes the task:
### Input:
Creates a color image to visualize the overlap between two images.
Nonzero pixels that match in both images are green.
Nonzero pixels of this image that aren't in the other image are yellow
Nonzero pixels of the other image tha... |
def plugins(self, deduplicate=False):
'''
Returns a flattened list of all plugins used by page components.
'''
plugins = []
for c in self.components:
if hasattr(c, 'plugins'):
plugins += c.plugins()
elif isinstance(c, Lib):
... | Returns a flattened list of all plugins used by page components. | Below is the the instruction that describes the task:
### Input:
Returns a flattened list of all plugins used by page components.
### Response:
def plugins(self, deduplicate=False):
'''
Returns a flattened list of all plugins used by page components.
'''
plugins = []
for... |
def reset_crops(self):
"""
Reset all known crops to the default crop.
If settings.ASSET_CELERY is specified then
the task will be run async
"""
if self._can_crop():
if settings.CELERY or settings.USE_CELERY_DECORATOR:
# this means that we are... | Reset all known crops to the default crop.
If settings.ASSET_CELERY is specified then
the task will be run async | Below is the the instruction that describes the task:
### Input:
Reset all known crops to the default crop.
If settings.ASSET_CELERY is specified then
the task will be run async
### Response:
def reset_crops(self):
"""
Reset all known crops to the default crop.
If settings... |
def header(self, name, value):
"""
Defines a URL path to match.
Only call this method if the URL has no path already defined.
Arguments:
path (str): URL path value to match. E.g: ``/api/users``.
Returns:
self: current Mock instance.
"""
... | Defines a URL path to match.
Only call this method if the URL has no path already defined.
Arguments:
path (str): URL path value to match. E.g: ``/api/users``.
Returns:
self: current Mock instance. | Below is the the instruction that describes the task:
### Input:
Defines a URL path to match.
Only call this method if the URL has no path already defined.
Arguments:
path (str): URL path value to match. E.g: ``/api/users``.
Returns:
self: current Mock instance.
##... |
def clean_doi(doi_string):
"""
Use regex to extract all DOI ids from string (i.e. 10.1029/2005pa001215)
:param str doi_string: Raw DOI string value from input file. Often not properly formatted.
:return list: DOI ids. May contain 0, 1, or multiple ids.
"""
regex = re.compile(r'\b(10[.][0-9]{3,}... | Use regex to extract all DOI ids from string (i.e. 10.1029/2005pa001215)
:param str doi_string: Raw DOI string value from input file. Often not properly formatted.
:return list: DOI ids. May contain 0, 1, or multiple ids. | Below is the the instruction that describes the task:
### Input:
Use regex to extract all DOI ids from string (i.e. 10.1029/2005pa001215)
:param str doi_string: Raw DOI string value from input file. Often not properly formatted.
:return list: DOI ids. May contain 0, 1, or multiple ids.
### Response:
def c... |
def find_charged(self, mol):
"""Looks for positive charges in arginine, histidine or lysine, for negative in aspartic and glutamic acid."""
data = namedtuple('pcharge', 'atoms atoms_orig_idx type center restype resnr reschain')
a_set = []
# Iterate through all residue, exclude those in c... | Looks for positive charges in arginine, histidine or lysine, for negative in aspartic and glutamic acid. | Below is the the instruction that describes the task:
### Input:
Looks for positive charges in arginine, histidine or lysine, for negative in aspartic and glutamic acid.
### Response:
def find_charged(self, mol):
"""Looks for positive charges in arginine, histidine or lysine, for negative in aspartic and g... |
def get_ancestor_item(self, tree_alias, base_item):
"""Climbs up the site tree to resolve root item for chosen one.
:param str|unicode tree_alias:
:param TreeItemBase base_item:
:rtype: TreeItemBase
"""
parent = None
if hasattr(base_item, 'parent') and base_item... | Climbs up the site tree to resolve root item for chosen one.
:param str|unicode tree_alias:
:param TreeItemBase base_item:
:rtype: TreeItemBase | Below is the the instruction that describes the task:
### Input:
Climbs up the site tree to resolve root item for chosen one.
:param str|unicode tree_alias:
:param TreeItemBase base_item:
:rtype: TreeItemBase
### Response:
def get_ancestor_item(self, tree_alias, base_item):
"""Clim... |
def node_path(self, node):
"""Return two lists describing the path from this node to another
Parameters
----------
node : instance of Node
The other node.
Returns
-------
p1 : list
First path (see below).
p2 : list
Sec... | Return two lists describing the path from this node to another
Parameters
----------
node : instance of Node
The other node.
Returns
-------
p1 : list
First path (see below).
p2 : list
Second path (see below).
Notes
... | Below is the the instruction that describes the task:
### Input:
Return two lists describing the path from this node to another
Parameters
----------
node : instance of Node
The other node.
Returns
-------
p1 : list
First path (see below).
... |
def rounder(input_number, digit=5):
"""
Round input number and convert to str.
:param input_number: input number
:type input_number : anything
:param digit: scale (the number of digits to the right of the decimal point in a number.)
:type digit : int
:return: round number as str
"""
... | Round input number and convert to str.
:param input_number: input number
:type input_number : anything
:param digit: scale (the number of digits to the right of the decimal point in a number.)
:type digit : int
:return: round number as str | Below is the the instruction that describes the task:
### Input:
Round input number and convert to str.
:param input_number: input number
:type input_number : anything
:param digit: scale (the number of digits to the right of the decimal point in a number.)
:type digit : int
:return: round numb... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.