code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def setupWorkerTransition():
"""Hook Twisted deprecation machinery to use custom warning class
for Worker API deprecation warnings."""
default_warn_method = getWarningMethod()
def custom_warn_method(message, category, stacklevel):
if stacklevel is not None:
stacklevel += 1
... | Hook Twisted deprecation machinery to use custom warning class
for Worker API deprecation warnings. | Below is the the instruction that describes the task:
### Input:
Hook Twisted deprecation machinery to use custom warning class
for Worker API deprecation warnings.
### Response:
def setupWorkerTransition():
"""Hook Twisted deprecation machinery to use custom warning class
for Worker API deprecation wa... |
def get_string_from_view(self, request, view_name, url_kwargs,
render_type='string'):
"""
Returns a string that is a rendering of the view given a
request, view_name, and the original url_kwargs. Makes the
following changes the view before... | Returns a string that is a rendering of the view given a
request, view_name, and the original url_kwargs. Makes the
following changes the view before rendering:
* Sets can_submit to False.
* Adds action_url to the context. This is the url where \
this view actually lives.
... | Below is the the instruction that describes the task:
### Input:
Returns a string that is a rendering of the view given a
request, view_name, and the original url_kwargs. Makes the
following changes the view before rendering:
* Sets can_submit to False.
* Adds action_url to the cont... |
def teff(cluster):
"""
Calculate Teff for main sequence stars ranging from Teff 3500K - 8000K. Use
[Fe/H] of the cluster, if available.
Returns a list of Teff values.
"""
b_vs, _ = cluster.stars()
teffs = []
for b_v in b_vs:
b_v -= cluster.eb_v
if b_v > -0.04:
... | Calculate Teff for main sequence stars ranging from Teff 3500K - 8000K. Use
[Fe/H] of the cluster, if available.
Returns a list of Teff values. | Below is the the instruction that describes the task:
### Input:
Calculate Teff for main sequence stars ranging from Teff 3500K - 8000K. Use
[Fe/H] of the cluster, if available.
Returns a list of Teff values.
### Response:
def teff(cluster):
"""
Calculate Teff for main sequence stars ranging from ... |
def loadSignal(self, name, start=None, end=None):
"""
Loads the named entry from the upload cache as a signal.
:param name: the name.
:param start: the time to start from in HH:mm:ss.SSS format
:param end: the time to end at in HH:mm:ss.SSS format.
:return: the signal if ... | Loads the named entry from the upload cache as a signal.
:param name: the name.
:param start: the time to start from in HH:mm:ss.SSS format
:param end: the time to end at in HH:mm:ss.SSS format.
:return: the signal if the named upload exists. | Below is the the instruction that describes the task:
### Input:
Loads the named entry from the upload cache as a signal.
:param name: the name.
:param start: the time to start from in HH:mm:ss.SSS format
:param end: the time to end at in HH:mm:ss.SSS format.
:return: the signal if t... |
def get_obj(app_label, model_name, object_id):
"""
Function used to get a object
:param app_label: A valid Django Model or a string with format: <app_label>.<model_name>
:param model_name: Key into kwargs that contains de data: new_person
:param object_id:
:return: instance
"""
try:
... | Function used to get a object
:param app_label: A valid Django Model or a string with format: <app_label>.<model_name>
:param model_name: Key into kwargs that contains de data: new_person
:param object_id:
:return: instance | Below is the the instruction that describes the task:
### Input:
Function used to get a object
:param app_label: A valid Django Model or a string with format: <app_label>.<model_name>
:param model_name: Key into kwargs that contains de data: new_person
:param object_id:
:return: instance
### Respons... |
def annealing_cos(start:Number, end:Number, pct:float)->Number:
"Cosine anneal from `start` to `end` as pct goes from 0.0 to 1.0."
cos_out = np.cos(np.pi * pct) + 1
return end + (start-end)/2 * cos_out | Cosine anneal from `start` to `end` as pct goes from 0.0 to 1.0. | Below is the the instruction that describes the task:
### Input:
Cosine anneal from `start` to `end` as pct goes from 0.0 to 1.0.
### Response:
def annealing_cos(start:Number, end:Number, pct:float)->Number:
"Cosine anneal from `start` to `end` as pct goes from 0.0 to 1.0."
cos_out = np.cos(np.pi * pct) + ... |
def run(self, executable_input, project=None, folder=None, name=None, tags=None, properties=None, details=None,
instance_type=None, stage_instance_types=None, stage_folders=None, rerun_stages=None, cluster_spec=None,
depends_on=None, allow_ssh=None, debug=None, delay_workspace_destruction=None, ... | :param executable_input: Hash of the executable's input arguments
:type executable_input: dict
:param project: Project ID of the project context
:type project: string
:param folder: Folder in which executable's outputs will be placed in *project*
:type folder: string
:par... | Below is the the instruction that describes the task:
### Input:
:param executable_input: Hash of the executable's input arguments
:type executable_input: dict
:param project: Project ID of the project context
:type project: string
:param folder: Folder in which executable's outputs ... |
def append_string(t, string):
"""Append a string to a node, as text or tail of last child."""
node = t.tree
if string:
if len(node) == 0:
if node.text is not None:
node.text += string
else:
node.text = string
else: # Get last child
... | Append a string to a node, as text or tail of last child. | Below is the the instruction that describes the task:
### Input:
Append a string to a node, as text or tail of last child.
### Response:
def append_string(t, string):
"""Append a string to a node, as text or tail of last child."""
node = t.tree
if string:
if len(node) == 0:
if node.... |
def getNorthSouthClone(self, i):
"""
Returns the adjacent clone name from both sides.
"""
north = self.getAdjacentClone(i, south=False)
south = self.getAdjacentClone(i)
return north, south | Returns the adjacent clone name from both sides. | Below is the the instruction that describes the task:
### Input:
Returns the adjacent clone name from both sides.
### Response:
def getNorthSouthClone(self, i):
"""
Returns the adjacent clone name from both sides.
"""
north = self.getAdjacentClone(i, south=False)
south = sel... |
def in_virtual_env():
"""
returns True if you are running inside a python virtual environment.
(DOES NOT WORK IF IN IPYTHON AND USING A VIRTUALENV)
sys.prefix gives the location of the virtualenv
Notes:
It seems IPython does not respect virtual environments properly.
TODO: find a s... | returns True if you are running inside a python virtual environment.
(DOES NOT WORK IF IN IPYTHON AND USING A VIRTUALENV)
sys.prefix gives the location of the virtualenv
Notes:
It seems IPython does not respect virtual environments properly.
TODO: find a solution
http://stackoverfl... | Below is the the instruction that describes the task:
### Input:
returns True if you are running inside a python virtual environment.
(DOES NOT WORK IF IN IPYTHON AND USING A VIRTUALENV)
sys.prefix gives the location of the virtualenv
Notes:
It seems IPython does not respect virtual environmen... |
def get_string():
"""A better str(_get_keycodes()) method"""
keycodes = _get_keycodes()
initial_code, codes = keycodes[0], keycodes[1:]
initial_char = chr(initial_code)
if initial_code == 27:
initial_char = '\\e'
elif not ascii.isgraph(initial_char):
initial_char = '\\x%x' % init... | A better str(_get_keycodes()) method | Below is the the instruction that describes the task:
### Input:
A better str(_get_keycodes()) method
### Response:
def get_string():
"""A better str(_get_keycodes()) method"""
keycodes = _get_keycodes()
initial_code, codes = keycodes[0], keycodes[1:]
initial_char = chr(initial_code)
if initial... |
def ConsumeRange(self, start, end):
"""Consumes an entire range, or part thereof.
If the finger has no ranges left, or the curent range start is higher
than the end of the consumed block, nothing happens. Otherwise,
the current range is adjusted for the consumed block, or removed,
if the entire blo... | Consumes an entire range, or part thereof.
If the finger has no ranges left, or the curent range start is higher
than the end of the consumed block, nothing happens. Otherwise,
the current range is adjusted for the consumed block, or removed,
if the entire block is consumed. For things to work, the con... | Below is the the instruction that describes the task:
### Input:
Consumes an entire range, or part thereof.
If the finger has no ranges left, or the curent range start is higher
than the end of the consumed block, nothing happens. Otherwise,
the current range is adjusted for the consumed block, or remo... |
def get_query(self, show=True, proxy=None, timeout=0):
"""
GET MediaWiki:API action=query selected data
https://en.wikipedia.org/w/api.php?action=help&modules=query
Required {params}: title OR pageid
- title: <str> article title
- pageid: <int> Wikipedia database ID
... | GET MediaWiki:API action=query selected data
https://en.wikipedia.org/w/api.php?action=help&modules=query
Required {params}: title OR pageid
- title: <str> article title
- pageid: <int> Wikipedia database ID
Optional arguments:
- [show]: <bool> echo page data if true
... | Below is the the instruction that describes the task:
### Input:
GET MediaWiki:API action=query selected data
https://en.wikipedia.org/w/api.php?action=help&modules=query
Required {params}: title OR pageid
- title: <str> article title
- pageid: <int> Wikipedia database ID
O... |
def _update(qs):
"""
Increment the sort_order in a queryset.
Handle IntegrityErrors caused by unique constraints.
"""
try:
with transaction.atomic():
qs.update(sort_order=models.F('sort_order') + 1)
except IntegrityError:
for obj i... | Increment the sort_order in a queryset.
Handle IntegrityErrors caused by unique constraints. | Below is the the instruction that describes the task:
### Input:
Increment the sort_order in a queryset.
Handle IntegrityErrors caused by unique constraints.
### Response:
def _update(qs):
"""
Increment the sort_order in a queryset.
Handle IntegrityErrors caused by unique constrai... |
def initialize_openstack(func):
'''
Initialize and refresh openstack connection
'''
async def wrap(self, *args, **kwargs):
if not hasattr(self, 'auth') or not self.auth.is_token_valid():
self.auth = AuthPassword(auth_url=self.config['auth_url'],
... | Initialize and refresh openstack connection | Below is the the instruction that describes the task:
### Input:
Initialize and refresh openstack connection
### Response:
def initialize_openstack(func):
'''
Initialize and refresh openstack connection
'''
async def wrap(self, *args, **kwargs):
if not hasattr(self,... |
def run(self):
"""Start the recurring task."""
if self.init_sec:
sleep(self.init_sec)
self._functime = time()
while self._running:
start = time()
self._func()
self._functime += self.interval_sec
if self._functime - start > 0:
... | Start the recurring task. | Below is the the instruction that describes the task:
### Input:
Start the recurring task.
### Response:
def run(self):
"""Start the recurring task."""
if self.init_sec:
sleep(self.init_sec)
self._functime = time()
while self._running:
start = time()
... |
def uniqueId(self, prefix=""):
"""
Generate a unique integer id (unique within the entire client session).
Useful for temporary DOM ids.
"""
_IdCounter.count += 1
id = _IdCounter.count
if prefix:
return self._wrap(prefix + str(id))
else:
... | Generate a unique integer id (unique within the entire client session).
Useful for temporary DOM ids. | Below is the the instruction that describes the task:
### Input:
Generate a unique integer id (unique within the entire client session).
Useful for temporary DOM ids.
### Response:
def uniqueId(self, prefix=""):
"""
Generate a unique integer id (unique within the entire client session).
... |
def _write_arg_to_bytes(builder, arg, args, name=None):
"""
Writes the .__bytes__() code for the given argument
:param builder: The source code builder
:param arg: The argument to write
:param args: All the other arguments in TLObject same __bytes__.
This is required to determine th... | Writes the .__bytes__() code for the given argument
:param builder: The source code builder
:param arg: The argument to write
:param args: All the other arguments in TLObject same __bytes__.
This is required to determine the flags value
:param name: The name of the argument. Defaults to... | Below is the the instruction that describes the task:
### Input:
Writes the .__bytes__() code for the given argument
:param builder: The source code builder
:param arg: The argument to write
:param args: All the other arguments in TLObject same __bytes__.
This is required to determine t... |
def extended_help_option(extended_help=None, *param_decls, **attrs):
"""
Based on the click.help_option code.
Adds a ``--extended-help`` option which immediately ends the program
printing out the extended extended-help page. Defaults to using the
callback's doc string, but can be given an explicit ... | Based on the click.help_option code.
Adds a ``--extended-help`` option which immediately ends the program
printing out the extended extended-help page. Defaults to using the
callback's doc string, but can be given an explicit value as well.
This is intended for use as a decorator on a command to provi... | Below is the the instruction that describes the task:
### Input:
Based on the click.help_option code.
Adds a ``--extended-help`` option which immediately ends the program
printing out the extended extended-help page. Defaults to using the
callback's doc string, but can be given an explicit value as wel... |
def find_cycle(graph):
"""
Find a cycle in the given graph.
This function will return a list of nodes which form a cycle in the graph or an empty list if
no cycle exists.
@type graph: graph, digraph
@param graph: Graph.
@rtype: list
@return: List of nodes.
"""
... | Find a cycle in the given graph.
This function will return a list of nodes which form a cycle in the graph or an empty list if
no cycle exists.
@type graph: graph, digraph
@param graph: Graph.
@rtype: list
@return: List of nodes. | Below is the the instruction that describes the task:
### Input:
Find a cycle in the given graph.
This function will return a list of nodes which form a cycle in the graph or an empty list if
no cycle exists.
@type graph: graph, digraph
@param graph: Graph.
@rtype: list
@retur... |
def parse_string(xml):
""" Returns a slash-formatted string from the given XML representation.
The return value is a TokenString (for MBSP) or TaggedString (for Pattern).
"""
string = ""
# Traverse all the <sentence> elements in the XML.
dom = XML(xml)
for sentence in dom(XML_SENTENCE):
... | Returns a slash-formatted string from the given XML representation.
The return value is a TokenString (for MBSP) or TaggedString (for Pattern). | Below is the the instruction that describes the task:
### Input:
Returns a slash-formatted string from the given XML representation.
The return value is a TokenString (for MBSP) or TaggedString (for Pattern).
### Response:
def parse_string(xml):
""" Returns a slash-formatted string from the given XML r... |
def _GetNextLogCountPerToken(token):
"""Wrapper for _log_counter_per_token.
Args:
token: The token for which to look up the count.
Returns:
The number of times this function has been called with
*token* as an argument (starting at 0)
"""
global _log_counter_per_token # pylint: disable... | Wrapper for _log_counter_per_token.
Args:
token: The token for which to look up the count.
Returns:
The number of times this function has been called with
*token* as an argument (starting at 0) | Below is the the instruction that describes the task:
### Input:
Wrapper for _log_counter_per_token.
Args:
token: The token for which to look up the count.
Returns:
The number of times this function has been called with
*token* as an argument (starting at 0)
### Response:
def _GetNextLogCount... |
def set_perplexity(self, new_perplexity):
"""Change the perplexity of the affinity matrix.
Note that we only allow lowering the perplexity or restoring it to its
original value. This restriction exists because setting a higher
perplexity value requires recomputing all the nearest neighb... | Change the perplexity of the affinity matrix.
Note that we only allow lowering the perplexity or restoring it to its
original value. This restriction exists because setting a higher
perplexity value requires recomputing all the nearest neighbors, which
can take a long time. To avoid pot... | Below is the the instruction that describes the task:
### Input:
Change the perplexity of the affinity matrix.
Note that we only allow lowering the perplexity or restoring it to its
original value. This restriction exists because setting a higher
perplexity value requires recomputing all th... |
def getValue(self, key):
"""
Some devices allow to directly get values for specific parameters.
"""
LOG.debug("HMGeneric.getValue: address = '%s', key = '%s'" % (self._ADDRESS, key))
try:
returnvalue = self._proxy.getValue(self._ADDRESS, key)
self._VALUES[... | Some devices allow to directly get values for specific parameters. | Below is the the instruction that describes the task:
### Input:
Some devices allow to directly get values for specific parameters.
### Response:
def getValue(self, key):
"""
Some devices allow to directly get values for specific parameters.
"""
LOG.debug("HMGeneric.getValue: addres... |
def validate_email_domain(email):
""" Validates email domain by blacklist. """
try:
domain = email.split('@', 1)[1].lower().strip()
except IndexError:
return
if domain in dju_settings.DJU_EMAIL_DOMAIN_BLACK_LIST:
raise ValidationError(_(u'Email with domain "%(domain)s" is disallo... | Validates email domain by blacklist. | Below is the the instruction that describes the task:
### Input:
Validates email domain by blacklist.
### Response:
def validate_email_domain(email):
""" Validates email domain by blacklist. """
try:
domain = email.split('@', 1)[1].lower().strip()
except IndexError:
return
if domain... |
def setCollectors(self, collectors):
"""
Sets the collector methods that will be used for this schema.
:param collectors | [<orb.Collectors>, ..]
"""
self.__collectors = {}
for name, collector in collectors.items():
self.__collectors[name] = coll... | Sets the collector methods that will be used for this schema.
:param collectors | [<orb.Collectors>, ..] | Below is the the instruction that describes the task:
### Input:
Sets the collector methods that will be used for this schema.
:param collectors | [<orb.Collectors>, ..]
### Response:
def setCollectors(self, collectors):
"""
Sets the collector methods that will be used for thi... |
def get_domain(self):
"""
:returns: opposite vertices of the bounding prism for this
object in the form of ndarray([min], [max])
.. note:: This method automatically stores the solution in order
to do not repeat calculations if the user needs to call it
... | :returns: opposite vertices of the bounding prism for this
object in the form of ndarray([min], [max])
.. note:: This method automatically stores the solution in order
to do not repeat calculations if the user needs to call it
more than once. | Below is the the instruction that describes the task:
### Input:
:returns: opposite vertices of the bounding prism for this
object in the form of ndarray([min], [max])
.. note:: This method automatically stores the solution in order
to do not repeat calculations if the ... |
def compute_distance(x_ori, x_pert, constraint='l2'):
""" Compute the distance between two images. """
if constraint == 'l2':
dist = np.linalg.norm(x_ori - x_pert)
elif constraint == 'linf':
dist = np.max(abs(x_ori - x_pert))
return dist | Compute the distance between two images. | Below is the the instruction that describes the task:
### Input:
Compute the distance between two images.
### Response:
def compute_distance(x_ori, x_pert, constraint='l2'):
""" Compute the distance between two images. """
if constraint == 'l2':
dist = np.linalg.norm(x_ori - x_pert)
elif constraint == 'l... |
def sortByTotal(requestContext, seriesList):
"""
Takes one metric or a wildcard seriesList.
Sorts the list of metrics by the sum of values across the time period
specified.
"""
return list(sorted(seriesList, key=safeSum, reverse=True)) | Takes one metric or a wildcard seriesList.
Sorts the list of metrics by the sum of values across the time period
specified. | Below is the the instruction that describes the task:
### Input:
Takes one metric or a wildcard seriesList.
Sorts the list of metrics by the sum of values across the time period
specified.
### Response:
def sortByTotal(requestContext, seriesList):
"""
Takes one metric or a wildcard seriesList.
... |
def seek_end(fileobj, offset):
"""Like fileobj.seek(-offset, 2), but will not try to go beyond the start
Needed since file objects from BytesIO will not raise IOError and
file objects from open() will raise IOError if going to a negative offset.
To make things easier for custom implementations, instead... | Like fileobj.seek(-offset, 2), but will not try to go beyond the start
Needed since file objects from BytesIO will not raise IOError and
file objects from open() will raise IOError if going to a negative offset.
To make things easier for custom implementations, instead of allowing
both behaviors, we ju... | Below is the the instruction that describes the task:
### Input:
Like fileobj.seek(-offset, 2), but will not try to go beyond the start
Needed since file objects from BytesIO will not raise IOError and
file objects from open() will raise IOError if going to a negative offset.
To make things easier for ... |
def prepare_bam(bam_in, precursors):
"""
Clean BAM file to keep only position inside the bigger cluster
"""
# use pybedtools to keep valid positions
# intersect option with -b bigger_cluster_loci
a = pybedtools.BedTool(bam_in)
b = pybedtools.BedTool(precursors)
c = a.intersect(b, u=True)... | Clean BAM file to keep only position inside the bigger cluster | Below is the the instruction that describes the task:
### Input:
Clean BAM file to keep only position inside the bigger cluster
### Response:
def prepare_bam(bam_in, precursors):
"""
Clean BAM file to keep only position inside the bigger cluster
"""
# use pybedtools to keep valid positions
# in... |
async def main(self):
"""
Main coroutine
"""
try:
lastkeys = set()
dataupdate = FlowUpdaterNotification.createMatcher(self, FlowUpdaterNotification.DATAUPDATED)
startwalk = FlowUpdaterNotification.createMatcher(self, FlowUpdaterNotification.STARTWALK)
... | Main coroutine | Below is the the instruction that describes the task:
### Input:
Main coroutine
### Response:
async def main(self):
"""
Main coroutine
"""
try:
lastkeys = set()
dataupdate = FlowUpdaterNotification.createMatcher(self, FlowUpdaterNotification.DATAUPDATED)
... |
async def get_proxies(self):
"""Receive proxies from the provider and return them.
:return: :attr:`.proxies`
"""
log.debug('Try to get proxies from %s' % self.domain)
async with aiohttp.ClientSession(
headers=get_headers(), cookies=self._cookies, loop=self._loop
... | Receive proxies from the provider and return them.
:return: :attr:`.proxies` | Below is the the instruction that describes the task:
### Input:
Receive proxies from the provider and return them.
:return: :attr:`.proxies`
### Response:
async def get_proxies(self):
"""Receive proxies from the provider and return them.
:return: :attr:`.proxies`
"""
log.... |
def catch_error(response):
'''
Checks for Errors in a Response.
401 or 403 - Security Rules Violation.
404 or 417 - Firebase NOT Found.
response - (Request.Response) - response from a request.
'''
status = response.status_code
if status == 401 or status ==... | Checks for Errors in a Response.
401 or 403 - Security Rules Violation.
404 or 417 - Firebase NOT Found.
response - (Request.Response) - response from a request. | Below is the the instruction that describes the task:
### Input:
Checks for Errors in a Response.
401 or 403 - Security Rules Violation.
404 or 417 - Firebase NOT Found.
response - (Request.Response) - response from a request.
### Response:
def catch_error(response):
'''
Che... |
def extendedMeasurementOrder():
"""EXTENDED MEASUREMENT ORDER Section 9.1.51"""
a = L2PseudoLength(l2pLength=0x12)
b = TpPd(pd=0x6)
c = MessageType(mesType=0x37) # 00110111
d = ExtendedMeasurementFrequencyList()
packet = a / b / c / d
return packet | EXTENDED MEASUREMENT ORDER Section 9.1.51 | Below is the the instruction that describes the task:
### Input:
EXTENDED MEASUREMENT ORDER Section 9.1.51
### Response:
def extendedMeasurementOrder():
"""EXTENDED MEASUREMENT ORDER Section 9.1.51"""
a = L2PseudoLength(l2pLength=0x12)
b = TpPd(pd=0x6)
c = MessageType(mesType=0x37) # 00110111
... |
def off(self, event):
'Remove an event handler'
try:
self._once_events.remove(event)
except KeyError:
pass
self._callback_by_event.pop(event, None) | Remove an event handler | Below is the the instruction that describes the task:
### Input:
Remove an event handler
### Response:
def off(self, event):
'Remove an event handler'
try:
self._once_events.remove(event)
except KeyError:
pass
self._callback_by_event.pop(event, None) |
def compile(stream_spec, cmd='ffmpeg', overwrite_output=False):
"""Build command-line for invoking ffmpeg.
The :meth:`run` function uses this to build the commnad line
arguments and should work in most cases, but calling this function
directly is useful for debugging or if you need to invoke ffmpeg
... | Build command-line for invoking ffmpeg.
The :meth:`run` function uses this to build the commnad line
arguments and should work in most cases, but calling this function
directly is useful for debugging or if you need to invoke ffmpeg
manually for whatever reason.
This is the same as calling :meth:`... | Below is the the instruction that describes the task:
### Input:
Build command-line for invoking ffmpeg.
The :meth:`run` function uses this to build the commnad line
arguments and should work in most cases, but calling this function
directly is useful for debugging or if you need to invoke ffmpeg
m... |
def modprobe(state, host, name, present=True, force=False):
'''
Load/unload kernel modules.
+ name: name of the module to manage
+ present: whether the module should be loaded or not
+ force: whether to force any add/remove modules
'''
modules = host.fact.kernel_modules
is_present = na... | Load/unload kernel modules.
+ name: name of the module to manage
+ present: whether the module should be loaded or not
+ force: whether to force any add/remove modules | Below is the the instruction that describes the task:
### Input:
Load/unload kernel modules.
+ name: name of the module to manage
+ present: whether the module should be loaded or not
+ force: whether to force any add/remove modules
### Response:
def modprobe(state, host, name, present=True, force=Fal... |
def walk(self, action, user_data=None):
"""
Walk the hierarchy, applying action to each filename.
Args:
action: callable, the callable to invoke for each filename,
will be invoked with the filename, the subfiles, and
the level in the sitemap.
... | Walk the hierarchy, applying action to each filename.
Args:
action: callable, the callable to invoke for each filename,
will be invoked with the filename, the subfiles, and
the level in the sitemap. | Below is the the instruction that describes the task:
### Input:
Walk the hierarchy, applying action to each filename.
Args:
action: callable, the callable to invoke for each filename,
will be invoked with the filename, the subfiles, and
the level in the sitemap.... |
def get_gnupg_components(sp=subprocess):
"""Parse GnuPG components' paths."""
args = [util.which('gpgconf'), '--list-components']
output = check_output(args=args, sp=sp)
components = dict(re.findall('(.*):.*:(.*)', output.decode('utf-8')))
log.debug('gpgconf --list-components: %s', components)
r... | Parse GnuPG components' paths. | Below is the the instruction that describes the task:
### Input:
Parse GnuPG components' paths.
### Response:
def get_gnupg_components(sp=subprocess):
"""Parse GnuPG components' paths."""
args = [util.which('gpgconf'), '--list-components']
output = check_output(args=args, sp=sp)
components = dict(r... |
def load_settings(self, settings):
"""Load settings from file"""
with open(settings) as settings_file:
settings_dict = simplejson.load(settings_file)
for key, value in settings_dict.items():
self.__setattr__(key, value) | Load settings from file | Below is the the instruction that describes the task:
### Input:
Load settings from file
### Response:
def load_settings(self, settings):
"""Load settings from file"""
with open(settings) as settings_file:
settings_dict = simplejson.load(settings_file)
for key, value in settings... |
def get_full_durable_object(arn, event_time, durable_model):
"""
Utility method to fetch items from the Durable table if they are too big for SNS/SQS.
:param record:
:param durable_model:
:return:
"""
LOG.debug(f'[-->] Item with ARN: {arn} was too big for SNS -- fetching it from the Durable... | Utility method to fetch items from the Durable table if they are too big for SNS/SQS.
:param record:
:param durable_model:
:return: | Below is the the instruction that describes the task:
### Input:
Utility method to fetch items from the Durable table if they are too big for SNS/SQS.
:param record:
:param durable_model:
:return:
### Response:
def get_full_durable_object(arn, event_time, durable_model):
"""
Utility method to ... |
def find_keyword_in_context(tokens, keyword, contextsize=1):
"""Find a keyword in a particular sequence of tokens, and return the local context. Contextsize is the number of words to the left and right. The keyword may have multiple word, in which case it should to passed as a tuple or list"""
if isinstance(key... | Find a keyword in a particular sequence of tokens, and return the local context. Contextsize is the number of words to the left and right. The keyword may have multiple word, in which case it should to passed as a tuple or list | Below is the the instruction that describes the task:
### Input:
Find a keyword in a particular sequence of tokens, and return the local context. Contextsize is the number of words to the left and right. The keyword may have multiple word, in which case it should to passed as a tuple or list
### Response:
def find... |
def delete_nic(self, instance_id, port_id):
"""Delete a Network Interface Controller"""
self.client.servers.interface_detach(instance_id, port_id)
return True | Delete a Network Interface Controller | Below is the the instruction that describes the task:
### Input:
Delete a Network Interface Controller
### Response:
def delete_nic(self, instance_id, port_id):
"""Delete a Network Interface Controller"""
self.client.servers.interface_detach(instance_id, port_id)
return True |
def init_glance_consumer(self, mq):
"""
Init openstack glance mq
1. Check if enable listening glance notification
2. Create consumer
:param mq: class ternya.mq.MQ
"""
if not self.enable_component_notification(Openstack.Glance):
log.debug("disable lis... | Init openstack glance mq
1. Check if enable listening glance notification
2. Create consumer
:param mq: class ternya.mq.MQ | Below is the the instruction that describes the task:
### Input:
Init openstack glance mq
1. Check if enable listening glance notification
2. Create consumer
:param mq: class ternya.mq.MQ
### Response:
def init_glance_consumer(self, mq):
"""
Init openstack glance mq
... |
def _new_DatetimeIndex(cls, d):
""" This is called upon unpickling, rather than the default which doesn't
have arguments and breaks __new__ """
if "data" in d and not isinstance(d["data"], DatetimeIndex):
# Avoid need to verify integrity by calling simple_new directly
data = d.pop("data")
... | This is called upon unpickling, rather than the default which doesn't
have arguments and breaks __new__ | Below is the the instruction that describes the task:
### Input:
This is called upon unpickling, rather than the default which doesn't
have arguments and breaks __new__
### Response:
def _new_DatetimeIndex(cls, d):
""" This is called upon unpickling, rather than the default which doesn't
have arguments... |
def regression():
"""
Run regression testing - lint and then run all tests.
"""
# HACK: Start using hitchbuildpy to get around this.
Command("touch", DIR.project.joinpath("pathquery", "__init__.py").abspath()).run()
storybook = _storybook({}).only_uninherited()
#storybook.with_params(**{"pyt... | Run regression testing - lint and then run all tests. | Below is the the instruction that describes the task:
### Input:
Run regression testing - lint and then run all tests.
### Response:
def regression():
"""
Run regression testing - lint and then run all tests.
"""
# HACK: Start using hitchbuildpy to get around this.
Command("touch", DIR.project.... |
def parse_header_line(self, line):
"""docstring for parse_header_line"""
self.header = line[1:].rstrip().split('\t')
if len(self.header) < 9:
self.header = line[1:].rstrip().split()
self.individuals = self.header[9:] | docstring for parse_header_line | Below is the the instruction that describes the task:
### Input:
docstring for parse_header_line
### Response:
def parse_header_line(self, line):
"""docstring for parse_header_line"""
self.header = line[1:].rstrip().split('\t')
if len(self.header) < 9:
self.header = line[1:].rst... |
def fetch_suvi_l1b(self, product, correct=True, median_kernel=5):
"""
Given a product keyword, downloads the SUVI l1b image into the current directory.
NOTE: the suvi_l1b_url must be properly set for the Fetcher object
:param product: the keyword for the product, e.g. suvi-l1b-fe094
... | Given a product keyword, downloads the SUVI l1b image into the current directory.
NOTE: the suvi_l1b_url must be properly set for the Fetcher object
:param product: the keyword for the product, e.g. suvi-l1b-fe094
:param correct: remove nans and negatives
:return: tuple of product name, ... | Below is the the instruction that describes the task:
### Input:
Given a product keyword, downloads the SUVI l1b image into the current directory.
NOTE: the suvi_l1b_url must be properly set for the Fetcher object
:param product: the keyword for the product, e.g. suvi-l1b-fe094
:param correc... |
def current(sam=False):
'''
Get the username that salt-minion is running under. If salt-minion is
running as a service it should return the Local System account. If salt is
running from a command prompt it should return the username that started the
command prompt.
.. versionadded:: 2015.5.6
... | Get the username that salt-minion is running under. If salt-minion is
running as a service it should return the Local System account. If salt is
running from a command prompt it should return the username that started the
command prompt.
.. versionadded:: 2015.5.6
Args:
sam (bool, optional... | Below is the the instruction that describes the task:
### Input:
Get the username that salt-minion is running under. If salt-minion is
running as a service it should return the Local System account. If salt is
running from a command prompt it should return the username that started the
command prompt.
... |
def json(self):
"""
Return JSON representation of object.
"""
data = {}
for item in self._data:
if isinstance(self._data[item], filetree):
data[item] = self._data[item].json()
else:
data[item] = self._data[item]
retu... | Return JSON representation of object. | Below is the the instruction that describes the task:
### Input:
Return JSON representation of object.
### Response:
def json(self):
"""
Return JSON representation of object.
"""
data = {}
for item in self._data:
if isinstance(self._data[item], filetree):
... |
def submit(self):
"""
Partitions the file into chunks and submits them into group of 4
for upload on the api upload pool.
:return: Futures
"""
futures = []
while self.submitted < 4 and not self.done():
part = self.parts.pop(0)
part_number ... | Partitions the file into chunks and submits them into group of 4
for upload on the api upload pool.
:return: Futures | Below is the the instruction that describes the task:
### Input:
Partitions the file into chunks and submits them into group of 4
for upload on the api upload pool.
:return: Futures
### Response:
def submit(self):
"""
Partitions the file into chunks and submits them into group of 4... |
def install_dir(self):
"""Returns application installation path.
.. note::
If fails this falls back to a restricted interface, which can only be used by approved apps.
:rtype: str
"""
max_len = 500
directory = self._get_str(self._iface.get_install_dir, [se... | Returns application installation path.
.. note::
If fails this falls back to a restricted interface, which can only be used by approved apps.
:rtype: str | Below is the the instruction that describes the task:
### Input:
Returns application installation path.
.. note::
If fails this falls back to a restricted interface, which can only be used by approved apps.
:rtype: str
### Response:
def install_dir(self):
"""Returns applicati... |
def startall(self, wait=False, **kwdargs):
"""Start all of the threads in the thread pool. If _wait_ is True
then don't return until all threads are up and running. Any extra
keyword arguments are passed to the worker thread constructor.
"""
self.logger.debug("startall called")... | Start all of the threads in the thread pool. If _wait_ is True
then don't return until all threads are up and running. Any extra
keyword arguments are passed to the worker thread constructor. | Below is the the instruction that describes the task:
### Input:
Start all of the threads in the thread pool. If _wait_ is True
then don't return until all threads are up and running. Any extra
keyword arguments are passed to the worker thread constructor.
### Response:
def startall(self, wait=Fa... |
def input_validate_aead(aead, name='aead', expected_len=None, max_aead_len = pyhsm.defines.YSM_AEAD_MAX_SIZE):
""" Input validation for YHSM_GeneratedAEAD or string. """
if isinstance(aead, pyhsm.aead_cmd.YHSM_GeneratedAEAD):
aead = aead.data
if expected_len != None:
return input_validate_st... | Input validation for YHSM_GeneratedAEAD or string. | Below is the the instruction that describes the task:
### Input:
Input validation for YHSM_GeneratedAEAD or string.
### Response:
def input_validate_aead(aead, name='aead', expected_len=None, max_aead_len = pyhsm.defines.YSM_AEAD_MAX_SIZE):
""" Input validation for YHSM_GeneratedAEAD or string. """
if isin... |
def compute_cost(A2, Y):
"""
Computes the cross-entropy cost given in equation (13)
Arguments:
A2 -- The sigmoid output of the second activation, of shape (1, number of examples)
Y -- "true" labels vector of shape (1, number of examples)
parameters -- python dictionary containing your parameter... | Computes the cross-entropy cost given in equation (13)
Arguments:
A2 -- The sigmoid output of the second activation, of shape (1, number of examples)
Y -- "true" labels vector of shape (1, number of examples)
parameters -- python dictionary containing your parameters W1, b1, W2 and b2
Returns:
... | Below is the the instruction that describes the task:
### Input:
Computes the cross-entropy cost given in equation (13)
Arguments:
A2 -- The sigmoid output of the second activation, of shape (1, number of examples)
Y -- "true" labels vector of shape (1, number of examples)
parameters -- python dict... |
def jsonarrlen(self, name, path=Path.rootPath()):
"""
Returns the length of the array JSON value under ``path`` at key
``name``
"""
return self.execute_command('JSON.ARRLEN', name, str_path(path)) | Returns the length of the array JSON value under ``path`` at key
``name`` | Below is the the instruction that describes the task:
### Input:
Returns the length of the array JSON value under ``path`` at key
``name``
### Response:
def jsonarrlen(self, name, path=Path.rootPath()):
"""
Returns the length of the array JSON value under ``path`` at key
``name``
... |
def _model_to_sbml(cobra_model, f_replace=None, units=True):
"""Convert Cobra model to SBMLDocument.
Parameters
----------
cobra_model : cobra.core.Model
Cobra model instance
f_replace : dict of replacement functions
Replacement to apply on identifiers.
units : boolean
S... | Convert Cobra model to SBMLDocument.
Parameters
----------
cobra_model : cobra.core.Model
Cobra model instance
f_replace : dict of replacement functions
Replacement to apply on identifiers.
units : boolean
Should the FLUX_UNITS be written in the SBMLDocument.
Returns
... | Below is the the instruction that describes the task:
### Input:
Convert Cobra model to SBMLDocument.
Parameters
----------
cobra_model : cobra.core.Model
Cobra model instance
f_replace : dict of replacement functions
Replacement to apply on identifiers.
units : boolean
... |
def p_file_comments_on_lics(self, f_term, predicate):
"""Sets file license comment."""
try:
for _, _, comment in self.graph.triples((f_term, predicate, None)):
self.builder.set_file_license_comment(self.doc, six.text_type(comment))
except CardinalityError:
... | Sets file license comment. | Below is the the instruction that describes the task:
### Input:
Sets file license comment.
### Response:
def p_file_comments_on_lics(self, f_term, predicate):
"""Sets file license comment."""
try:
for _, _, comment in self.graph.triples((f_term, predicate, None)):
self.... |
def pseudotime(starting_node, edges, fitted_vals):
"""
Args:
starting_node (int): index of the starting node
edges (list): list of tuples (node1, node2)
fitted_vals (array): output of lineage (2 x cells)
Returns:
A 1d array containing the pseudotime value of each cell.
"... | Args:
starting_node (int): index of the starting node
edges (list): list of tuples (node1, node2)
fitted_vals (array): output of lineage (2 x cells)
Returns:
A 1d array containing the pseudotime value of each cell. | Below is the the instruction that describes the task:
### Input:
Args:
starting_node (int): index of the starting node
edges (list): list of tuples (node1, node2)
fitted_vals (array): output of lineage (2 x cells)
Returns:
A 1d array containing the pseudotime value of each cell.... |
def get_probs_for_labels(labels, prediction_results):
""" Given ML Workbench prediction results, get probs of each label for each instance.
The prediction results are like:
[
{'predicted': 'daisy', 'probability': 0.8, 'predicted_2': 'rose', 'probability_2': 0.1},
{'predicted': 'sunflower', 'probability':... | Given ML Workbench prediction results, get probs of each label for each instance.
The prediction results are like:
[
{'predicted': 'daisy', 'probability': 0.8, 'predicted_2': 'rose', 'probability_2': 0.1},
{'predicted': 'sunflower', 'probability': 0.9, 'predicted_2': 'daisy', 'probability_2': 0.01},
..... | Below is the the instruction that describes the task:
### Input:
Given ML Workbench prediction results, get probs of each label for each instance.
The prediction results are like:
[
{'predicted': 'daisy', 'probability': 0.8, 'predicted_2': 'rose', 'probability_2': 0.1},
{'predicted': 'sunflower', 'prob... |
def last_string(self):
"""The last entry in code_builder, or ``None`` if none so far."""
cb = self.code_builder
len_cb = len(cb)
if len_cb > 0:
return cb[len_cb - 1]
else:
return None | The last entry in code_builder, or ``None`` if none so far. | Below is the the instruction that describes the task:
### Input:
The last entry in code_builder, or ``None`` if none so far.
### Response:
def last_string(self):
"""The last entry in code_builder, or ``None`` if none so far."""
cb = self.code_builder
len_cb = len(cb)
if len_cb > 0:
... |
def _todo_do_update(self, line):
"update [:tablename] {hashkey[,rangekey]} [!fieldname:expectedvalue] [-add|-delete] [+ALL_OLD|ALL_NEW|UPDATED_OLD|UPDATED_NEW] {attributes}"
table, line = self.get_table_params(line)
hkey, line = line.split(" ", 1)
expected, attr = self.get_expected(line)... | update [:tablename] {hashkey[,rangekey]} [!fieldname:expectedvalue] [-add|-delete] [+ALL_OLD|ALL_NEW|UPDATED_OLD|UPDATED_NEW] {attributes} | Below is the the instruction that describes the task:
### Input:
update [:tablename] {hashkey[,rangekey]} [!fieldname:expectedvalue] [-add|-delete] [+ALL_OLD|ALL_NEW|UPDATED_OLD|UPDATED_NEW] {attributes}
### Response:
def _todo_do_update(self, line):
"update [:tablename] {hashkey[,rangekey]} [!fieldname:ex... |
def replace_namespaced_service_account(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_service_account # noqa: E501
replace the specified ServiceAccount # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP reque... | replace_namespaced_service_account # noqa: E501
replace the specified ServiceAccount # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_service_account(name, namespa... | Below is the the instruction that describes the task:
### Input:
replace_namespaced_service_account # noqa: E501
replace the specified ServiceAccount # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
... |
def list_sessions(logged_in_users_only=False):
'''
List information about the sessions.
.. versionadded:: 2016.11.0
:param logged_in_users_only: If True, only return sessions with users logged in.
:return: A list containing dictionaries of session information.
CLI Example:
.. code-block:... | List information about the sessions.
.. versionadded:: 2016.11.0
:param logged_in_users_only: If True, only return sessions with users logged in.
:return: A list containing dictionaries of session information.
CLI Example:
.. code-block:: bash
salt '*' rdp.list_sessions | Below is the the instruction that describes the task:
### Input:
List information about the sessions.
.. versionadded:: 2016.11.0
:param logged_in_users_only: If True, only return sessions with users logged in.
:return: A list containing dictionaries of session information.
CLI Example:
.. c... |
def bulkWrite(self, endpoint, buffer, timeout = 100):
r"""Perform a bulk write request to the endpoint specified.
Arguments:
endpoint: endpoint number.
buffer: sequence data buffer to write.
This parameter can be any sequence type.
... | r"""Perform a bulk write request to the endpoint specified.
Arguments:
endpoint: endpoint number.
buffer: sequence data buffer to write.
This parameter can be any sequence type.
timeout: operation timeout in milliseconds. (default: 100... | Below is the the instruction that describes the task:
### Input:
r"""Perform a bulk write request to the endpoint specified.
Arguments:
endpoint: endpoint number.
buffer: sequence data buffer to write.
This parameter can be any sequence type.
... |
def _deliver_message(self, msg):
"""
Deliver the message to the subscripted actions
"""
my_subscribed_actions = self.subscriptions.get(msg.sender, [])
for action in my_subscribed_actions:
if Global.CONFIG_MANAGER.tracing_mode:
Global.LOGGER.debug(f"del... | Deliver the message to the subscripted actions | Below is the the instruction that describes the task:
### Input:
Deliver the message to the subscripted actions
### Response:
def _deliver_message(self, msg):
"""
Deliver the message to the subscripted actions
"""
my_subscribed_actions = self.subscriptions.get(msg.sender, [])
... |
def save_model(self, request, obj, form, change):
"""Saves TreeItem model under certain Tree.
Handles item's parent assignment exception.
"""
if change:
# No, you're not allowed to make item parent of itself
if obj.parent is not None and obj.parent.id == obj.id:
... | Saves TreeItem model under certain Tree.
Handles item's parent assignment exception. | Below is the the instruction that describes the task:
### Input:
Saves TreeItem model under certain Tree.
Handles item's parent assignment exception.
### Response:
def save_model(self, request, obj, form, change):
"""Saves TreeItem model under certain Tree.
Handles item's parent assignment ... |
def text_pieces(self, method, uplaces=2, use_exponent=True):
"""Return (main, dhigh, dlow, sharedexponent), all as strings. The
delta terms do not have sign indicators. Any item except the first
may be None.
`method` is passed to Uval.repvals() to compute representative
statisti... | Return (main, dhigh, dlow, sharedexponent), all as strings. The
delta terms do not have sign indicators. Any item except the first
may be None.
`method` is passed to Uval.repvals() to compute representative
statistical limits. | Below is the the instruction that describes the task:
### Input:
Return (main, dhigh, dlow, sharedexponent), all as strings. The
delta terms do not have sign indicators. Any item except the first
may be None.
`method` is passed to Uval.repvals() to compute representative
statistical... |
def get_precision(self):
"""
Get the current precision from the sensor.
:returns: sensor resolution from 9-12 bits
:rtype: int
"""
config_str = self.raw_sensor_strings[1].split()[4] # Byte 5 is the config register
bit_base = int(config_str, 16) >> 5 ... | Get the current precision from the sensor.
:returns: sensor resolution from 9-12 bits
:rtype: int | Below is the the instruction that describes the task:
### Input:
Get the current precision from the sensor.
:returns: sensor resolution from 9-12 bits
:rtype: int
### Response:
def get_precision(self):
"""
Get the current precision from the sensor.
:returns... |
def uniform_unit_scaling(tensor: torch.Tensor, nonlinearity: str = "linear"):
"""
An initaliser which preserves output variance for approximately gaussian
distributed inputs. This boils down to initialising layers using a uniform
distribution in the range ``(-sqrt(3/dim[0]) * scale, sqrt(3 / dim[0]) * s... | An initaliser which preserves output variance for approximately gaussian
distributed inputs. This boils down to initialising layers using a uniform
distribution in the range ``(-sqrt(3/dim[0]) * scale, sqrt(3 / dim[0]) * scale)``, where
``dim[0]`` is equal to the input dimension of the parameter and the ``s... | Below is the the instruction that describes the task:
### Input:
An initaliser which preserves output variance for approximately gaussian
distributed inputs. This boils down to initialising layers using a uniform
distribution in the range ``(-sqrt(3/dim[0]) * scale, sqrt(3 / dim[0]) * scale)``, where
``... |
def task_view_generator(job_descriptor):
"""Generator that yields a task-specific view of the job.
This generator exists to make it easy for callers to iterate over the tasks
in a JobDescriptor. Each pass yields a new JobDescriptor with a single task.
Args:
job_descriptor: A JobDescriptor with 1 or more t... | Generator that yields a task-specific view of the job.
This generator exists to make it easy for callers to iterate over the tasks
in a JobDescriptor. Each pass yields a new JobDescriptor with a single task.
Args:
job_descriptor: A JobDescriptor with 1 or more tasks.
Yields:
A JobDescriptor with a si... | Below is the the instruction that describes the task:
### Input:
Generator that yields a task-specific view of the job.
This generator exists to make it easy for callers to iterate over the tasks
in a JobDescriptor. Each pass yields a new JobDescriptor with a single task.
Args:
job_descriptor: A JobDesc... |
def add(self, si):
'''puts `si` into the currently open chunk, which it creates if
necessary. If this item causes the chunk to cross chunk_max,
then the chunk closed after adding.
'''
if self.o_chunk is None:
if os.path.exists(self.t_path):
os.remove... | puts `si` into the currently open chunk, which it creates if
necessary. If this item causes the chunk to cross chunk_max,
then the chunk closed after adding. | Below is the the instruction that describes the task:
### Input:
puts `si` into the currently open chunk, which it creates if
necessary. If this item causes the chunk to cross chunk_max,
then the chunk closed after adding.
### Response:
def add(self, si):
'''puts `si` into the currently op... |
def QA_SU_save_future_min(client=DATABASE, ui_log=None, ui_progress=None):
"""save future_min
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
future_list = [
item for item in QA_fetch_get_future_list().code.unique().tolist()
if str(item)[-2:] in ['... | save future_min
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE}) | Below is the the instruction that describes the task:
### Input:
save future_min
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
### Response:
def QA_SU_save_future_min(client=DATABASE, ui_log=None, ui_progress=None):
"""save future_min
Keyword Arguments:
cli... |
def _read_mode_tsopt(self, size, kind):
"""Read Timestamps option.
Positional arguments:
* size - int, length of option
* kind - int, 8 (Timestamps)
Returns:
* dict -- extracted Timestamps (TS) option
Structure of TCP TSopt [RFC 7323]:
+... | Read Timestamps option.
Positional arguments:
* size - int, length of option
* kind - int, 8 (Timestamps)
Returns:
* dict -- extracted Timestamps (TS) option
Structure of TCP TSopt [RFC 7323]:
+-------+-------+---------------------+-------------... | Below is the the instruction that describes the task:
### Input:
Read Timestamps option.
Positional arguments:
* size - int, length of option
* kind - int, 8 (Timestamps)
Returns:
* dict -- extracted Timestamps (TS) option
Structure of TCP TSopt [RFC 73... |
def send(self, api_key=None, secret=None, list_data=None, auth=False, **kwargs):
"""Sends the given Payload to the API via the websocket connection.
:param kwargs: payload paarameters as key=value pairs
:return:
"""
if auth:
nonce = str(int(time.time() * 10000000))
... | Sends the given Payload to the API via the websocket connection.
:param kwargs: payload paarameters as key=value pairs
:return: | Below is the the instruction that describes the task:
### Input:
Sends the given Payload to the API via the websocket connection.
:param kwargs: payload paarameters as key=value pairs
:return:
### Response:
def send(self, api_key=None, secret=None, list_data=None, auth=False, **kwargs):
""... |
def start(self):
"""
Starts the download.
:raises SbgError: If download is not in PREPARING state.
"""
if self._status == TransferState.PREPARING:
self._running.set()
super(Download, self).start()
self._status = TransferState.RUNNING
... | Starts the download.
:raises SbgError: If download is not in PREPARING state. | Below is the the instruction that describes the task:
### Input:
Starts the download.
:raises SbgError: If download is not in PREPARING state.
### Response:
def start(self):
"""
Starts the download.
:raises SbgError: If download is not in PREPARING state.
"""
if self... |
def _generate_name(self, space, service_name, plan_name):
"""
Can generate a name based on the space, service name and plan.
"""
return str.join('-', [space, service_name, plan_name]).lower() | Can generate a name based on the space, service name and plan. | Below is the the instruction that describes the task:
### Input:
Can generate a name based on the space, service name and plan.
### Response:
def _generate_name(self, space, service_name, plan_name):
"""
Can generate a name based on the space, service name and plan.
"""
return str.j... |
def decode_solution(self, encoded_solution):
"""Return solution from an encoded representation."""
return self._decode_function(encoded_solution, *self._decode_args,
**self._decode_kwargs) | Return solution from an encoded representation. | Below is the the instruction that describes the task:
### Input:
Return solution from an encoded representation.
### Response:
def decode_solution(self, encoded_solution):
"""Return solution from an encoded representation."""
return self._decode_function(encoded_solution, *self._decode_args,
... |
def solve_with_sdpa(sdp, solverparameters=None):
"""Helper function to write out the SDP problem to a temporary
file, call the solver, and parse the output.
:param sdp: The SDP relaxation to be solved.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param solverparameters: Optional parameters to SDPA.
:ty... | Helper function to write out the SDP problem to a temporary
file, call the solver, and parse the output.
:param sdp: The SDP relaxation to be solved.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param solverparameters: Optional parameters to SDPA.
:type solverparameters: dict of str.
:returns: tuple of... | Below is the the instruction that describes the task:
### Input:
Helper function to write out the SDP problem to a temporary
file, call the solver, and parse the output.
:param sdp: The SDP relaxation to be solved.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param solverparameters: Optional parameters to ... |
def decode(self, bytes, raw=False):
"""decode(bytearray, raw=False) -> value
Decodes the given bytearray according to this PrimitiveType
definition.
NOTE: The parameter ``raw`` is present to adhere to the
``decode()`` inteface, but has no effect for PrimitiveType
defini... | decode(bytearray, raw=False) -> value
Decodes the given bytearray according to this PrimitiveType
definition.
NOTE: The parameter ``raw`` is present to adhere to the
``decode()`` inteface, but has no effect for PrimitiveType
definitions. | Below is the the instruction that describes the task:
### Input:
decode(bytearray, raw=False) -> value
Decodes the given bytearray according to this PrimitiveType
definition.
NOTE: The parameter ``raw`` is present to adhere to the
``decode()`` inteface, but has no effect for Primit... |
def open_conn(host, db, user, password, retries=0, sleep=0.5):
'''
Return an open mysql db connection using the given credentials. Use
`retries` and `sleep` to be robust to the occassional transient connection
failure.
retries: if an exception when getting the connection, try again at most this ma... | Return an open mysql db connection using the given credentials. Use
`retries` and `sleep` to be robust to the occassional transient connection
failure.
retries: if an exception when getting the connection, try again at most this many times.
sleep: pause between retries for this many seconds. a float ... | Below is the the instruction that describes the task:
### Input:
Return an open mysql db connection using the given credentials. Use
`retries` and `sleep` to be robust to the occassional transient connection
failure.
retries: if an exception when getting the connection, try again at most this many tim... |
def hide_routemap_holder_route_map_content_match_ip_route_source_prefix_list_rmrs(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hide_routemap_holder = ET.SubElement(config, "hide-routemap-holder", xmlns="urn:brocade.com:mgmt:brocade-ip-policy")
route_m... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def hide_routemap_holder_route_map_content_match_ip_route_source_prefix_list_rmrs(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hide_routemap_holder = ET.Su... |
def send(self, command, tab_key, params=None):
'''
Send command `command` with optional parameters `params` to the
remote chrome instance.
The command `id` is automatically added to the outgoing message.
return value is the command id, which can be used to match a command
to it's associated response.
''... | Send command `command` with optional parameters `params` to the
remote chrome instance.
The command `id` is automatically added to the outgoing message.
return value is the command id, which can be used to match a command
to it's associated response. | Below is the the instruction that describes the task:
### Input:
Send command `command` with optional parameters `params` to the
remote chrome instance.
The command `id` is automatically added to the outgoing message.
return value is the command id, which can be used to match a command
to it's associated ... |
def get_or_create_node(self, graph: BELGraph, node: BaseEntity) -> Optional[Node]:
"""Create an entry and object for given node if it does not exist."""
sha512 = node.as_sha512()
if sha512 in self.object_cache_node:
return self.object_cache_node[sha512]
node_model = self.get... | Create an entry and object for given node if it does not exist. | Below is the the instruction that describes the task:
### Input:
Create an entry and object for given node if it does not exist.
### Response:
def get_or_create_node(self, graph: BELGraph, node: BaseEntity) -> Optional[Node]:
"""Create an entry and object for given node if it does not exist."""
sha... |
def draw_marked_line(self, data, coordinates, linestyle, markerstyle,
label, mplobj=None):
"""Draw a line that also has markers.
If this isn't reimplemented by a renderer object, by default, it will
make a call to BOTH draw_line and draw_markers when both markerstyle
... | Draw a line that also has markers.
If this isn't reimplemented by a renderer object, by default, it will
make a call to BOTH draw_line and draw_markers when both markerstyle
and linestyle are not None in the same Line2D object. | Below is the the instruction that describes the task:
### Input:
Draw a line that also has markers.
If this isn't reimplemented by a renderer object, by default, it will
make a call to BOTH draw_line and draw_markers when both markerstyle
and linestyle are not None in the same Line2D object... |
def lock_multi(self, keys, ttl=0):
"""Lock multiple keys. Multi variant of :meth:`lock`
:param keys: the keys to lock
:type keys: :ref:`iterable<argtypes>`
:param int ttl: The lock timeout for all keys
:return: a :class:`~.MultiResult` object
.. seealso:: :meth:`lock`
... | Lock multiple keys. Multi variant of :meth:`lock`
:param keys: the keys to lock
:type keys: :ref:`iterable<argtypes>`
:param int ttl: The lock timeout for all keys
:return: a :class:`~.MultiResult` object
.. seealso:: :meth:`lock` | Below is the the instruction that describes the task:
### Input:
Lock multiple keys. Multi variant of :meth:`lock`
:param keys: the keys to lock
:type keys: :ref:`iterable<argtypes>`
:param int ttl: The lock timeout for all keys
:return: a :class:`~.MultiResult` object
.. ... |
def _print(self, char):
"""
Print a character at the current cursor position and advance the
cursor.
"""
# Don't make bugs where we try to print a screen.
assert len(char) == 1
try:
try:
# Python 3
char = self.decoder... | Print a character at the current cursor position and advance the
cursor. | Below is the the instruction that describes the task:
### Input:
Print a character at the current cursor position and advance the
cursor.
### Response:
def _print(self, char):
"""
Print a character at the current cursor position and advance the
cursor.
"""
# Don't m... |
def list_all_braintree_gateways(cls, **kwargs):
"""List BraintreeGateways
Return a list of BraintreeGateways
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_braintree_gateways(async=T... | List BraintreeGateways
Return a list of BraintreeGateways
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_braintree_gateways(async=True)
>>> result = thread.get()
:param asyn... | Below is the the instruction that describes the task:
### Input:
List BraintreeGateways
Return a list of BraintreeGateways
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_braintree_gatewa... |
def model_fn(features, labels, mode, params):
"""
Create the model for estimator api
Args:
features: tensor with shape
[BATCH_SIZE, go.N, go.N, features_lib.NEW_FEATURES_PLANES]
labels: dict from string to tensor with shape
'pi_tensor': [BATCH_SIZE, go.N * go.N + 1]
... | Create the model for estimator api
Args:
features: tensor with shape
[BATCH_SIZE, go.N, go.N, features_lib.NEW_FEATURES_PLANES]
labels: dict from string to tensor with shape
'pi_tensor': [BATCH_SIZE, go.N * go.N + 1]
'value_tensor': [BATCH_SIZE]
mode: a t... | Below is the the instruction that describes the task:
### Input:
Create the model for estimator api
Args:
features: tensor with shape
[BATCH_SIZE, go.N, go.N, features_lib.NEW_FEATURES_PLANES]
labels: dict from string to tensor with shape
'pi_tensor': [BATCH_SIZE, go.N *... |
def lowpass(data,filterSize=None):
"""
minimal complexity low-pass filtering.
Filter size is how "wide" the filter will be.
Sigma will be 1/10 of this filter width.
If filter size isn't given, it will be 1/10 of the data size.
"""
if filterSize is None:
filterSize=len(data)/10
ke... | minimal complexity low-pass filtering.
Filter size is how "wide" the filter will be.
Sigma will be 1/10 of this filter width.
If filter size isn't given, it will be 1/10 of the data size. | Below is the the instruction that describes the task:
### Input:
minimal complexity low-pass filtering.
Filter size is how "wide" the filter will be.
Sigma will be 1/10 of this filter width.
If filter size isn't given, it will be 1/10 of the data size.
### Response:
def lowpass(data,filterSize=None):
... |
async def send_message():
"""Example of sending a message."""
jar = aiohttp.CookieJar(unsafe=True)
websession = aiohttp.ClientSession(cookie_jar=jar)
modem = eternalegypt.Modem(hostname=sys.argv[1], websession=websession)
await modem.login(password=sys.argv[2])
await modem.sms(phone=sys.argv[3... | Example of sending a message. | Below is the the instruction that describes the task:
### Input:
Example of sending a message.
### Response:
async def send_message():
"""Example of sending a message."""
jar = aiohttp.CookieJar(unsafe=True)
websession = aiohttp.ClientSession(cookie_jar=jar)
modem = eternalegypt.Modem(hostname=sys... |
def list_hosted_zones(self, page_chunks=100):
"""
List all hosted zones associated with this connection's account. Since
this method returns a generator, you can pull as many or as few
entries as you'd like, without having to query and receive every
hosted zone you may have.
... | List all hosted zones associated with this connection's account. Since
this method returns a generator, you can pull as many or as few
entries as you'd like, without having to query and receive every
hosted zone you may have.
:keyword int page_chunks: This API call is "paginated" behind... | Below is the the instruction that describes the task:
### Input:
List all hosted zones associated with this connection's account. Since
this method returns a generator, you can pull as many or as few
entries as you'd like, without having to query and receive every
hosted zone you may have.
... |
def get_matched_token(self, match):
"""Find which token has been matched by compound regex"""
match_groupdict = match.groupdict()
for group in self.groups:
if match_groupdict[group] is not None:
token, match_type = self.groups[group]
return (token, mat... | Find which token has been matched by compound regex | Below is the the instruction that describes the task:
### Input:
Find which token has been matched by compound regex
### Response:
def get_matched_token(self, match):
"""Find which token has been matched by compound regex"""
match_groupdict = match.groupdict()
for group in self.groups:
... |
def send_packet(self, pk, expected_reply=(), resend=False, timeout=0.2):
"""
Send a packet through the link interface.
pk -- Packet to send
expect_answer -- True if a packet from the Crazyflie is expected to
be sent back, otherwise false
"""
sel... | Send a packet through the link interface.
pk -- Packet to send
expect_answer -- True if a packet from the Crazyflie is expected to
be sent back, otherwise false | Below is the the instruction that describes the task:
### Input:
Send a packet through the link interface.
pk -- Packet to send
expect_answer -- True if a packet from the Crazyflie is expected to
be sent back, otherwise false
### Response:
def send_packet(self, pk, expecte... |
def setIsolateHidden(self, state):
"""
Sets whether or not this item is hidden due to isolation.
:param state | <bool>
"""
self._isolatedHidden = state
super(XNode, self).setVisible(self.isVisible()) | Sets whether or not this item is hidden due to isolation.
:param state | <bool> | Below is the the instruction that describes the task:
### Input:
Sets whether or not this item is hidden due to isolation.
:param state | <bool>
### Response:
def setIsolateHidden(self, state):
"""
Sets whether or not this item is hidden due to isolation.
:par... |
def select_address_family(host, port):
"""Return ``AF_INET4``, ``AF_INET6``, or ``AF_UNIX`` depending on
the host and port."""
# disabled due to problems with current ipv6 implementations
# and various operating systems. Probably this code also is
# not supposed to work, but I can't come up with an... | Return ``AF_INET4``, ``AF_INET6``, or ``AF_UNIX`` depending on
the host and port. | Below is the the instruction that describes the task:
### Input:
Return ``AF_INET4``, ``AF_INET6``, or ``AF_UNIX`` depending on
the host and port.
### Response:
def select_address_family(host, port):
"""Return ``AF_INET4``, ``AF_INET6``, or ``AF_UNIX`` depending on
the host and port."""
# disabled ... |
def tag(self, tag: str, overwrite: bool = False) -> None:
"""
Tags the current commit
:param tag: tag
:type tag: str
:param overwrite: overwrite existing tag
:type overwrite: bool
"""
LOGGER.info('tagging repo: %s', tag)
try:
self.repo... | Tags the current commit
:param tag: tag
:type tag: str
:param overwrite: overwrite existing tag
:type overwrite: bool | Below is the the instruction that describes the task:
### Input:
Tags the current commit
:param tag: tag
:type tag: str
:param overwrite: overwrite existing tag
:type overwrite: bool
### Response:
def tag(self, tag: str, overwrite: bool = False) -> None:
"""
Tags th... |
def save(self, *args, **kwargs):
"""
Custom save method does the following things:
* converts geometry collections of just 1 item to that item (eg: a collection of 1 Point becomes a Point)
* intercepts changes to status and fires node_status_changed signal
* set defau... | Custom save method does the following things:
* converts geometry collections of just 1 item to that item (eg: a collection of 1 Point becomes a Point)
* intercepts changes to status and fires node_status_changed signal
* set default status | Below is the the instruction that describes the task:
### Input:
Custom save method does the following things:
* converts geometry collections of just 1 item to that item (eg: a collection of 1 Point becomes a Point)
* intercepts changes to status and fires node_status_changed signal
... |
def is_already_running(self):
"""Return True if lock exists and has not timed out."""
redis_key = self.CELERY_LOCK.format(task_id=self.task_identifier)
return self.celery_self.backend.client.exists(redis_key) | Return True if lock exists and has not timed out. | Below is the the instruction that describes the task:
### Input:
Return True if lock exists and has not timed out.
### Response:
def is_already_running(self):
"""Return True if lock exists and has not timed out."""
redis_key = self.CELERY_LOCK.format(task_id=self.task_identifier)
return sel... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.