code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def htmlDocContentDumpFormatOutput(self, cur, encoding, format):
"""Dump an HTML document. """
if cur is None: cur__o = None
else: cur__o = cur._o
libxml2mod.htmlDocContentDumpFormatOutput(self._o, cur__o, encoding, format) | Dump an HTML document. | Below is the the instruction that describes the task:
### Input:
Dump an HTML document.
### Response:
def htmlDocContentDumpFormatOutput(self, cur, encoding, format):
"""Dump an HTML document. """
if cur is None: cur__o = None
else: cur__o = cur._o
libxml2mod.htmlDocContentDumpForma... |
def _su_scripts_regex(self):
"""
:return:
[compiled regex, function]
"""
sups = re.escape(''.join([k for k in self.superscripts.keys()]))
subs = re.escape(''.join([k for k in self.subscripts.keys()])) # language=PythonRegExp
su_regex = (r'\\([{su_}])|([{sub}]... | :return:
[compiled regex, function] | Below is the the instruction that describes the task:
### Input:
:return:
[compiled regex, function]
### Response:
def _su_scripts_regex(self):
"""
:return:
[compiled regex, function]
"""
sups = re.escape(''.join([k for k in self.superscripts.keys()]))
... |
def mni2tal(xin):
"""
mni2tal for converting from ch2/mni space to tal - very approximate.
This is a standard approach but it's not very accurate.
ANTsR function: `mni2tal`
Arguments
---------
xin : tuple
point in mni152 space.
Returns
-------
tuple
Example
-... | mni2tal for converting from ch2/mni space to tal - very approximate.
This is a standard approach but it's not very accurate.
ANTsR function: `mni2tal`
Arguments
---------
xin : tuple
point in mni152 space.
Returns
-------
tuple
Example
-------
>>> import ants
... | Below is the the instruction that describes the task:
### Input:
mni2tal for converting from ch2/mni space to tal - very approximate.
This is a standard approach but it's not very accurate.
ANTsR function: `mni2tal`
Arguments
---------
xin : tuple
point in mni152 space.
Returns
... |
def calculate_checksum(isbn):
"""Calculate ISBN checksum.
Args:
isbn (str): SBN, ISBN-10 or ISBN-13
Returns:
``str``: Checksum for given ISBN or SBN
"""
isbn = [int(i) for i in _isbn_cleanse(isbn, checksum=False)]
if len(isbn) == 9:
products = [x * y for x, y in zip(is... | Calculate ISBN checksum.
Args:
isbn (str): SBN, ISBN-10 or ISBN-13
Returns:
``str``: Checksum for given ISBN or SBN | Below is the the instruction that describes the task:
### Input:
Calculate ISBN checksum.
Args:
isbn (str): SBN, ISBN-10 or ISBN-13
Returns:
``str``: Checksum for given ISBN or SBN
### Response:
def calculate_checksum(isbn):
"""Calculate ISBN checksum.
Args:
isbn (str): S... |
def begin_transaction(self, transaction_type, trace_parent=None):
"""Register the start of a transaction on the client
"""
return self.tracer.begin_transaction(transaction_type, trace_parent=trace_parent) | Register the start of a transaction on the client | Below is the the instruction that describes the task:
### Input:
Register the start of a transaction on the client
### Response:
def begin_transaction(self, transaction_type, trace_parent=None):
"""Register the start of a transaction on the client
"""
return self.tracer.begin_transaction(tr... |
def modify(self, fd, eventmask):
"""
Change the bit-mask of events associated with a previously-registered
descriptor.
:param fd:
The descriptor to modify.
:param eventmask:
New bit-mask of events that will be monitored.
:raises ValueError:
... | Change the bit-mask of events associated with a previously-registered
descriptor.
:param fd:
The descriptor to modify.
:param eventmask:
New bit-mask of events that will be monitored.
:raises ValueError:
If :meth:`closed()` is True
:raises OSE... | Below is the the instruction that describes the task:
### Input:
Change the bit-mask of events associated with a previously-registered
descriptor.
:param fd:
The descriptor to modify.
:param eventmask:
New bit-mask of events that will be monitored.
:raises Va... |
def _kafka_failure(self, item, spider, response):
'''
Callback for failed send
'''
item['success'] = False
item['exception'] = traceback.format_exc()
item['spiderid'] = spider.name
item = self._clean_item(item)
self.logger.error("Failed to send page to Kaf... | Callback for failed send | Below is the the instruction that describes the task:
### Input:
Callback for failed send
### Response:
def _kafka_failure(self, item, spider, response):
'''
Callback for failed send
'''
item['success'] = False
item['exception'] = traceback.format_exc()
item['spideri... |
def _categorize_file_diffs(self, file_diffs):
"""Partition file changes into admissible and inadmissible changes"""
# TODO move this into a new validator
candidate_feature_diffs = []
valid_init_diffs = []
inadmissible_files = []
for diff in file_diffs:
valid,... | Partition file changes into admissible and inadmissible changes | Below is the the instruction that describes the task:
### Input:
Partition file changes into admissible and inadmissible changes
### Response:
def _categorize_file_diffs(self, file_diffs):
"""Partition file changes into admissible and inadmissible changes"""
# TODO move this into a new validator
... |
def caller_path(steps=1):
"""Return the path to the source file of the current frames' caller."""
frame = sys._getframe(steps + 1)
try:
path = os.path.dirname(frame.f_code.co_filename)
finally:
del frame
if not path:
path = os.getcwd()
return os.path.realpath(path) | Return the path to the source file of the current frames' caller. | Below is the the instruction that describes the task:
### Input:
Return the path to the source file of the current frames' caller.
### Response:
def caller_path(steps=1):
"""Return the path to the source file of the current frames' caller."""
frame = sys._getframe(steps + 1)
try:
path = os.pat... |
def delete(self, count=1):
"""
Delete specified number of characters and Return the deleted text.
"""
if self.cursor_position < len(self.text):
deleted = self.document.text_after_cursor[:count]
self.text = self.text[:self.cursor_position] + \
self.... | Delete specified number of characters and Return the deleted text. | Below is the the instruction that describes the task:
### Input:
Delete specified number of characters and Return the deleted text.
### Response:
def delete(self, count=1):
"""
Delete specified number of characters and Return the deleted text.
"""
if self.cursor_position < len(self.... |
def create_from_config(self, config):
"""Create a template object file defined in the config object
"""
configService = ConfigService()
template = TemplateService()
template.output = config["output"]["location"]
template_file = configService.get_template_from_config(co... | Create a template object file defined in the config object | Below is the the instruction that describes the task:
### Input:
Create a template object file defined in the config object
### Response:
def create_from_config(self, config):
"""Create a template object file defined in the config object
"""
configService = ConfigService()
template... |
def copy(self):
"""
Deep Copy of a LabeledTree
"""
return LabeledTree(
udepth = self.udepth,
depth = self.depth,
text = self.text,
label = self.label,
children = self.children.copy() if self.children != None else [],
... | Deep Copy of a LabeledTree | Below is the the instruction that describes the task:
### Input:
Deep Copy of a LabeledTree
### Response:
def copy(self):
"""
Deep Copy of a LabeledTree
"""
return LabeledTree(
udepth = self.udepth,
depth = self.depth,
text = self.text,
... |
def jac(self, xy=None):
"""Get the Jacobian at (x, y).
"""
if xy is not None:
self.set_xy(xy)
ux = numpy.dot(self.ax, self.xy_list[: len(self.ax)])
vx = numpy.dot(self.bx, self.xy_list[: len(self.bx)])
uy = numpy.dot(self.ay, self.xy_list[: len(self.ay)])
... | Get the Jacobian at (x, y). | Below is the the instruction that describes the task:
### Input:
Get the Jacobian at (x, y).
### Response:
def jac(self, xy=None):
"""Get the Jacobian at (x, y).
"""
if xy is not None:
self.set_xy(xy)
ux = numpy.dot(self.ax, self.xy_list[: len(self.ax)])
vx = nu... |
def add(self, effect=None, act=None, obj=None,
policy=None, policies=None):
"""Insert an individual (effect, action, object) triple or all
triples for a policy or list of policies.
"""
if policies is not None:
for p in policies:
self.add(policy=p)... | Insert an individual (effect, action, object) triple or all
triples for a policy or list of policies. | Below is the the instruction that describes the task:
### Input:
Insert an individual (effect, action, object) triple or all
triples for a policy or list of policies.
### Response:
def add(self, effect=None, act=None, obj=None,
policy=None, policies=None):
"""Insert an individual (effec... |
def sendmail(subject, text, mailto, sender=None):
"""
Sends an e-mail with unix sendmail.
Args:
subject: String with the subject of the mail.
text: String with the body of the mail.
mailto: String or list of string with the recipients.
sender: string with the sender address.... | Sends an e-mail with unix sendmail.
Args:
subject: String with the subject of the mail.
text: String with the body of the mail.
mailto: String or list of string with the recipients.
sender: string with the sender address.
If sender is None, username@hostname is used.
... | Below is the the instruction that describes the task:
### Input:
Sends an e-mail with unix sendmail.
Args:
subject: String with the subject of the mail.
text: String with the body of the mail.
mailto: String or list of string with the recipients.
sender: string with the sender a... |
def offset(self, offset):
"""
Apply an OFFSET to the query and return the newly resulting Query.
"""
query = self._copy()
query._offset = offset
return query | Apply an OFFSET to the query and return the newly resulting Query. | Below is the the instruction that describes the task:
### Input:
Apply an OFFSET to the query and return the newly resulting Query.
### Response:
def offset(self, offset):
"""
Apply an OFFSET to the query and return the newly resulting Query.
"""
query = self._copy()
query._... |
def inq_convolution(inp, outmaps, kernel,
pad=None, stride=None, dilation=None, group=1,
num_bits=4, inq_iterations=(), selection_algorithm='random',
seed=-1, w_init=None, i_init=None, b_init=None,
base_axis=1, fix_parameters=False, rng=Non... | Incremental Network Quantization Convolution Layer
During training, the weights are sequentially quantized to power-of-two
values, which allows the training of a multiplierless network.
Using `inq_iterations`, one can specify after how many forward passes
half of the learnable weights are fixed and qu... | Below is the the instruction that describes the task:
### Input:
Incremental Network Quantization Convolution Layer
During training, the weights are sequentially quantized to power-of-two
values, which allows the training of a multiplierless network.
Using `inq_iterations`, one can specify after how m... |
def wrap_handler(cls, handler, protocol, **kwargs):
''' Wrap a request handler with the matching protocol handler '''
def _wrapper(request, *args, **kwargs):
instance = cls(request=request, **kwargs)
if protocol == Resource.Protocol.http:
return instance._wrap_htt... | Wrap a request handler with the matching protocol handler | Below is the the instruction that describes the task:
### Input:
Wrap a request handler with the matching protocol handler
### Response:
def wrap_handler(cls, handler, protocol, **kwargs):
''' Wrap a request handler with the matching protocol handler '''
def _wrapper(request, *args, **kwargs):
... |
def _compute_anom_score(self, lag_window_points, point):
"""
Compute anomaly score for a single data point.
Anomaly score for a single data point(t,v) equals: abs(v - ema(lagging window)).
:param list lag_window_points: values in the lagging window.
:param float point: data point... | Compute anomaly score for a single data point.
Anomaly score for a single data point(t,v) equals: abs(v - ema(lagging window)).
:param list lag_window_points: values in the lagging window.
:param float point: data point value.
:return float: the anomaly score. | Below is the the instruction that describes the task:
### Input:
Compute anomaly score for a single data point.
Anomaly score for a single data point(t,v) equals: abs(v - ema(lagging window)).
:param list lag_window_points: values in the lagging window.
:param float point: data point value.
... |
def question(title="", text="", width=DEFAULT_WIDTH, height=DEFAULT_HEIGHT, timeout=None):
"""
Display a question, possible answer are yes/no.
:param text: text inside the window
:type text: str
:param title: title of the window
:type title: str
:param width: window width
:type width: i... | Display a question, possible answer are yes/no.
:param text: text inside the window
:type text: str
:param title: title of the window
:type title: str
:param width: window width
:type width: int
:param height: window height
:type height: int
:param timeout: close the window after n ... | Below is the the instruction that describes the task:
### Input:
Display a question, possible answer are yes/no.
:param text: text inside the window
:type text: str
:param title: title of the window
:type title: str
:param width: window width
:type width: int
:param height: window heigh... |
async def populate(self, agent_cls, *args, **kwargs):
'''Populate all the slave grid environments with agents. Assumes that
no agents have been spawned yet to the slave environment grids. This
excludes the slave environment managers as they are not in the grids.)
'''
n = self.gs[... | Populate all the slave grid environments with agents. Assumes that
no agents have been spawned yet to the slave environment grids. This
excludes the slave environment managers as they are not in the grids.) | Below is the the instruction that describes the task:
### Input:
Populate all the slave grid environments with agents. Assumes that
no agents have been spawned yet to the slave environment grids. This
excludes the slave environment managers as they are not in the grids.)
### Response:
async def pop... |
def _update_deferred(self, event):
"""
This does the actual work of updating channel metadata. This is called
by the update(), and runs this method in another thread.
"""
if isinstance(event, ChannelCreated):
i = event.channel[u'id']
event.channel[u'is_archived'] = event.channel[u'is_member'] = False
... | This does the actual work of updating channel metadata. This is called
by the update(), and runs this method in another thread. | Below is the the instruction that describes the task:
### Input:
This does the actual work of updating channel metadata. This is called
by the update(), and runs this method in another thread.
### Response:
def _update_deferred(self, event):
"""
This does the actual work of updating channel metadata. This ... |
def list_projects(self, max_results=None, page_token=None, retry=DEFAULT_RETRY):
"""List projects for the project associated with this client.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/projects/list
:type max_results: int
:param max_results: (Optional) maximu... | List projects for the project associated with this client.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/projects/list
:type max_results: int
:param max_results: (Optional) maximum number of projects to return,
If not passed, defaults to a val... | Below is the the instruction that describes the task:
### Input:
List projects for the project associated with this client.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/projects/list
:type max_results: int
:param max_results: (Optional) maximum number of projects to... |
def add_option(self, group):
""" Add option for self to the parser group object. """
group.add_argument(
"--{0}".format(self.option), action="store_true", help=self.name) | Add option for self to the parser group object. | Below is the the instruction that describes the task:
### Input:
Add option for self to the parser group object.
### Response:
def add_option(self, group):
""" Add option for self to the parser group object. """
group.add_argument(
"--{0}".format(self.option), action="store_true", help=... |
def get_ngrams(self, minimum, maximum, skip_sizes=None):
"""Returns a generator supplying the n-grams (`minimum` <= n
<= `maximum`) for this text.
Each iteration of the generator supplies a tuple consisting of
the size of the n-grams and a `collections.Counter` of the
n-grams.
... | Returns a generator supplying the n-grams (`minimum` <= n
<= `maximum`) for this text.
Each iteration of the generator supplies a tuple consisting of
the size of the n-grams and a `collections.Counter` of the
n-grams.
:param minimum: minimum n-gram size
:type minimum: `... | Below is the the instruction that describes the task:
### Input:
Returns a generator supplying the n-grams (`minimum` <= n
<= `maximum`) for this text.
Each iteration of the generator supplies a tuple consisting of
the size of the n-grams and a `collections.Counter` of the
n-grams.
... |
def get_yarn_applications(self, start_time, end_time, filter_str="", limit=100,
offset=0):
"""
Returns a list of YARN applications that satisfy the filter
@type start_time: datetime.datetime. Note that the datetime must either be
time zone aware or specified in the server time zo... | Returns a list of YARN applications that satisfy the filter
@type start_time: datetime.datetime. Note that the datetime must either be
time zone aware or specified in the server time zone. See
the python datetime documentation for more details about
... | Below is the the instruction that describes the task:
### Input:
Returns a list of YARN applications that satisfy the filter
@type start_time: datetime.datetime. Note that the datetime must either be
time zone aware or specified in the server time zone. See
the python... |
def serialise_to_nrml(self, filename, use_defaults=False):
'''
Writes the source model to a nrml source model file given by the
filename
:param str filename:
Path to output file
:param bool use_defaults:
Boolean to indicate whether to use default values ... | Writes the source model to a nrml source model file given by the
filename
:param str filename:
Path to output file
:param bool use_defaults:
Boolean to indicate whether to use default values (True) or not.
If set to False, ValueErrors will be raised when an ... | Below is the the instruction that describes the task:
### Input:
Writes the source model to a nrml source model file given by the
filename
:param str filename:
Path to output file
:param bool use_defaults:
Boolean to indicate whether to use default values (True) or ... |
def sentence2freqt(docgraph, root, successors=None, include_pos=False,
escape_func=FREQT_ESCAPE_FUNC):
"""convert a sentence subgraph into a FREQT string."""
if successors is None:
successors = sorted_bfs_successors(docgraph, root)
if root in successors: # root node has children... | convert a sentence subgraph into a FREQT string. | Below is the the instruction that describes the task:
### Input:
convert a sentence subgraph into a FREQT string.
### Response:
def sentence2freqt(docgraph, root, successors=None, include_pos=False,
escape_func=FREQT_ESCAPE_FUNC):
"""convert a sentence subgraph into a FREQT string."""
if... |
def _load(self, scale=1.0):
"""Load the ABI relative spectral responses
"""
LOG.debug("File: %s", str(self.requested_band_filename))
data = np.genfromtxt(self.requested_band_filename,
unpack=True,
names=['wavelength',
... | Load the ABI relative spectral responses | Below is the the instruction that describes the task:
### Input:
Load the ABI relative spectral responses
### Response:
def _load(self, scale=1.0):
"""Load the ABI relative spectral responses
"""
LOG.debug("File: %s", str(self.requested_band_filename))
data = np.genfromtxt(self.re... |
def calculate_permute_output_shapes(operator):
'''
Allowed input/output patterns are
1. [N, C, H, W] ---> [N', C', H', W']
Note that here [N', C', H', W'] means all possible permutations of [N, C, H, W]
'''
check_input_and_output_numbers(operator, input_count_range=1, output_count_range=1)
... | Allowed input/output patterns are
1. [N, C, H, W] ---> [N', C', H', W']
Note that here [N', C', H', W'] means all possible permutations of [N, C, H, W] | Below is the the instruction that describes the task:
### Input:
Allowed input/output patterns are
1. [N, C, H, W] ---> [N', C', H', W']
Note that here [N', C', H', W'] means all possible permutations of [N, C, H, W]
### Response:
def calculate_permute_output_shapes(operator):
'''
Allowed inpu... |
def copy_file(self, filepath):
"""
Returns flag which says to copy rather than link a file.
"""
copy_file = False
try:
copy_file = self.data[filepath]['copy']
except KeyError:
return False
return copy_file | Returns flag which says to copy rather than link a file. | Below is the the instruction that describes the task:
### Input:
Returns flag which says to copy rather than link a file.
### Response:
def copy_file(self, filepath):
"""
Returns flag which says to copy rather than link a file.
"""
copy_file = False
try:
copy_fil... |
def crypto_sign_keypair():
"""
Returns a randomly generated public key and secret key.
:rtype: (bytes(public_key), bytes(secret_key))
"""
pk = ffi.new("unsigned char[]", crypto_sign_PUBLICKEYBYTES)
sk = ffi.new("unsigned char[]", crypto_sign_SECRETKEYBYTES)
rc = lib.crypto_sign_keypair(pk,... | Returns a randomly generated public key and secret key.
:rtype: (bytes(public_key), bytes(secret_key)) | Below is the the instruction that describes the task:
### Input:
Returns a randomly generated public key and secret key.
:rtype: (bytes(public_key), bytes(secret_key))
### Response:
def crypto_sign_keypair():
"""
Returns a randomly generated public key and secret key.
:rtype: (bytes(public_key), ... |
def _transition_stage(self, step, total_steps, brightness=None):
"""
Get a transition stage at a specific step.
:param step: The current step.
:param total_steps: The total number of steps.
:param brightness: The brightness to transition to (0.0-1.0).
:return: The stage ... | Get a transition stage at a specific step.
:param step: The current step.
:param total_steps: The total number of steps.
:param brightness: The brightness to transition to (0.0-1.0).
:return: The stage at the specific step. | Below is the the instruction that describes the task:
### Input:
Get a transition stage at a specific step.
:param step: The current step.
:param total_steps: The total number of steps.
:param brightness: The brightness to transition to (0.0-1.0).
:return: The stage at the specific ... |
def _index_fs(self):
"""Returns a deque object full of local file system items.
:returns: ``deque``
"""
indexed_objects = self._return_deque()
directory = self.job_args.get('directory')
if directory:
indexed_objects = self._return_deque(
deq... | Returns a deque object full of local file system items.
:returns: ``deque`` | Below is the the instruction that describes the task:
### Input:
Returns a deque object full of local file system items.
:returns: ``deque``
### Response:
def _index_fs(self):
"""Returns a deque object full of local file system items.
:returns: ``deque``
"""
indexed_objec... |
def delete(self, list_id, webhook_id):
"""
Delete a specific webhook in a list.
:param list_id: The unique id for the list.
:type list_id: :py:class:`str`
:param webhook_id: The unique id for the webhook.
:type webhook_id: :py:class:`str`
"""
self.list_id... | Delete a specific webhook in a list.
:param list_id: The unique id for the list.
:type list_id: :py:class:`str`
:param webhook_id: The unique id for the webhook.
:type webhook_id: :py:class:`str` | Below is the the instruction that describes the task:
### Input:
Delete a specific webhook in a list.
:param list_id: The unique id for the list.
:type list_id: :py:class:`str`
:param webhook_id: The unique id for the webhook.
:type webhook_id: :py:class:`str`
### Response:
def del... |
def main():
"""Event display for an event of station 503
Date Time Timestamp Nanoseconds
2012-03-29 10:51:36 1333018296 870008589
Number of MIPs
35.0 51.9 35.8 78.9
Arrival time
15.0 17.5 20.0 27.5
"""
# Detector positions in ENU relative to the station GPS... | Event display for an event of station 503
Date Time Timestamp Nanoseconds
2012-03-29 10:51:36 1333018296 870008589
Number of MIPs
35.0 51.9 35.8 78.9
Arrival time
15.0 17.5 20.0 27.5 | Below is the the instruction that describes the task:
### Input:
Event display for an event of station 503
Date Time Timestamp Nanoseconds
2012-03-29 10:51:36 1333018296 870008589
Number of MIPs
35.0 51.9 35.8 78.9
Arrival time
15.0 17.5 20.0 27.5
### Response:
def... |
def check_ace(path, objectType, user, permission=None, acetype=None, propagation=None, exactPermissionMatch=False):
'''
Checks a path to verify the ACE (access control entry) specified exists
Args:
path: path to the file/reg key
objectType: The type of object (FILE, DIRECTORY, REGISTRY)
... | Checks a path to verify the ACE (access control entry) specified exists
Args:
path: path to the file/reg key
objectType: The type of object (FILE, DIRECTORY, REGISTRY)
user: user that the ACL is for
permission: permission to test for (READ, FULLCONTROL, etc)
acetype: the... | Below is the the instruction that describes the task:
### Input:
Checks a path to verify the ACE (access control entry) specified exists
Args:
path: path to the file/reg key
objectType: The type of object (FILE, DIRECTORY, REGISTRY)
user: user that the ACL is for
permission: ... |
def _isCompatible(self, other, reporter):
"""
This is the environment implementation of
:meth:`BaseFont.isCompatible`.
Subclasses may override this method.
"""
font1 = self
font2 = other
# incompatible guidelines
guidelines1 = set(font1.guideline... | This is the environment implementation of
:meth:`BaseFont.isCompatible`.
Subclasses may override this method. | Below is the the instruction that describes the task:
### Input:
This is the environment implementation of
:meth:`BaseFont.isCompatible`.
Subclasses may override this method.
### Response:
def _isCompatible(self, other, reporter):
"""
This is the environment implementation of
... |
def remove_duplicates(seq):
"""
Return unique elements from list while preserving order.
From https://stackoverflow.com/a/480227/2589328
"""
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))] | Return unique elements from list while preserving order.
From https://stackoverflow.com/a/480227/2589328 | Below is the the instruction that describes the task:
### Input:
Return unique elements from list while preserving order.
From https://stackoverflow.com/a/480227/2589328
### Response:
def remove_duplicates(seq):
"""
Return unique elements from list while preserving order.
From https://stackoverflow... |
def CheckForNonStandardConstructs(filename, clean_lines, linenum,
nesting_state, error):
r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
Complain about several constructs which gcc-2 accepts, but which are
not standard C++. Warning about these in lint ... | r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
Complain about several constructs which gcc-2 accepts, but which are
not standard C++. Warning about these in lint is one way to ease the
transition to new compilers.
- put storage class first (e.g. "static const" instead of "const stat... | Below is the the instruction that describes the task:
### Input:
r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
Complain about several constructs which gcc-2 accepts, but which are
not standard C++. Warning about these in lint is one way to ease the
transition to new compilers.
... |
def _initialize(self):
""" Open from caffe weights """
self._graph = tf.Graph()
with self._graph.as_default():
self._input_node = tf.placeholder(tf.float32, (self._batch_size, self._im_height, self._im_width, self._num_channels))
weights = self.build_alexnet_weights()
... | Open from caffe weights | Below is the the instruction that describes the task:
### Input:
Open from caffe weights
### Response:
def _initialize(self):
""" Open from caffe weights """
self._graph = tf.Graph()
with self._graph.as_default():
self._input_node = tf.placeholder(tf.float32, (self._batch_size, ... |
def ReadFileObject(self, definitions_registry, file_object):
"""Reads data type definitions from a file-like object into the registry.
Args:
definitions_registry (DataTypeDefinitionsRegistry): data type definitions
registry.
file_object (file): file-like object to read from.
Raises:
... | Reads data type definitions from a file-like object into the registry.
Args:
definitions_registry (DataTypeDefinitionsRegistry): data type definitions
registry.
file_object (file): file-like object to read from.
Raises:
FormatError: if the definitions values are missing or if the f... | Below is the the instruction that describes the task:
### Input:
Reads data type definitions from a file-like object into the registry.
Args:
definitions_registry (DataTypeDefinitionsRegistry): data type definitions
registry.
file_object (file): file-like object to read from.
Raises:... |
def entries(self, query=None):
"""Fetches all Entries from the Space (up to the set limit, can be modified in `query`).
API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/entries/entries-collection/get-all-entries-of-a-space
:param query: (opt... | Fetches all Entries from the Space (up to the set limit, can be modified in `query`).
API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/entries/entries-collection/get-all-entries-of-a-space
:param query: (optional) Dict with API options.
:ret... | Below is the the instruction that describes the task:
### Input:
Fetches all Entries from the Space (up to the set limit, can be modified in `query`).
API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/entries/entries-collection/get-all-entries-of-a-space
... |
def _detect(self):
""" Detect shadowing local variables
Recursively visit the calls
Returns:
list: {'vuln', 'filename,'contract','func', 'shadow'}
"""
results = []
for contract in self.contracts:
shadows = self.detect_shadowing_definitions(contr... | Detect shadowing local variables
Recursively visit the calls
Returns:
list: {'vuln', 'filename,'contract','func', 'shadow'} | Below is the the instruction that describes the task:
### Input:
Detect shadowing local variables
Recursively visit the calls
Returns:
list: {'vuln', 'filename,'contract','func', 'shadow'}
### Response:
def _detect(self):
""" Detect shadowing local variables
Recursivel... |
def find(self):
"""
根据查询条件,获取包含所有满足条件的对象。
:rtype: list
"""
content = self._do_request(self.dump())
objs = []
for result in content['results']:
obj = self._new_object()
obj._update_data(self._process_result(result))
objs.append... | 根据查询条件,获取包含所有满足条件的对象。
:rtype: list | Below is the the instruction that describes the task:
### Input:
根据查询条件,获取包含所有满足条件的对象。
:rtype: list
### Response:
def find(self):
"""
根据查询条件,获取包含所有满足条件的对象。
:rtype: list
"""
content = self._do_request(self.dump())
objs = []
for result in content['re... |
def cli(ctx, board, scons, project_dir, sayyes):
"""Manage apio projects."""
if scons:
Project().create_sconstruct(project_dir, sayyes)
elif board:
Project().create_ini(board, project_dir, sayyes)
else:
click.secho(ctx.get_help()) | Manage apio projects. | Below is the the instruction that describes the task:
### Input:
Manage apio projects.
### Response:
def cli(ctx, board, scons, project_dir, sayyes):
"""Manage apio projects."""
if scons:
Project().create_sconstruct(project_dir, sayyes)
elif board:
Project().create_ini(board, project_d... |
def load_gpi(self, gpi_path):
"""
Loads a GPI as a file from the `config.gpi_authority_path`
"""
if self.config.gpi_authority_path is not None:
gpis = dict()
parser = entityparser.GpiParser()
with open(self.config.gpi_authority_path) as gpi_f:
entities = parser.parse(... | Loads a GPI as a file from the `config.gpi_authority_path` | Below is the the instruction that describes the task:
### Input:
Loads a GPI as a file from the `config.gpi_authority_path`
### Response:
def load_gpi(self, gpi_path):
"""
Loads a GPI as a file from the `config.gpi_authority_path`
"""
if self.config.gpi_authority_path is not None:
gpis = di... |
def get_instance(self, payload):
"""
Build an instance of EnvironmentInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.serverless.v1.service.environment.EnvironmentInstance
:rtype: twilio.rest.serverless.v1.service.environment.EnvironmentInstance... | Build an instance of EnvironmentInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.serverless.v1.service.environment.EnvironmentInstance
:rtype: twilio.rest.serverless.v1.service.environment.EnvironmentInstance | Below is the the instruction that describes the task:
### Input:
Build an instance of EnvironmentInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.serverless.v1.service.environment.EnvironmentInstance
:rtype: twilio.rest.serverless.v1.service.environment.Env... |
def download(self,
tool: Tool,
force=False) -> bool:
"""
Attempts to download the Docker image for a given tool from
`DockerHub <https://hub.docker.com>`_. If the force parameter is set to
True, any existing image will be overwritten.
Returns:
... | Attempts to download the Docker image for a given tool from
`DockerHub <https://hub.docker.com>`_. If the force parameter is set to
True, any existing image will be overwritten.
Returns:
`True` if successfully downloaded, else `False`. | Below is the the instruction that describes the task:
### Input:
Attempts to download the Docker image for a given tool from
`DockerHub <https://hub.docker.com>`_. If the force parameter is set to
True, any existing image will be overwritten.
Returns:
`True` if successfully down... |
def daterange_(self, datecol, date_start, op, **args):
"""
Returns a DataSwim instance with rows in a date range
"""
df = self._daterange(datecol, date_start, op, **args)
if df is None:
self.err("Can not select date range data")
return self._duplicate_(df) | Returns a DataSwim instance with rows in a date range | Below is the the instruction that describes the task:
### Input:
Returns a DataSwim instance with rows in a date range
### Response:
def daterange_(self, datecol, date_start, op, **args):
"""
Returns a DataSwim instance with rows in a date range
"""
df = self._daterange(datecol, dat... |
def init_states(batch_size, num_lstm_layer, num_hidden):
"""
Returns name and shape of init states of LSTM network
Parameters
----------
batch_size: list of tuple of str and tuple of int and int
num_lstm_layer: int
num_hidden: int
Returns
-------
list of tuple of str and tuple ... | Returns name and shape of init states of LSTM network
Parameters
----------
batch_size: list of tuple of str and tuple of int and int
num_lstm_layer: int
num_hidden: int
Returns
-------
list of tuple of str and tuple of int and int | Below is the the instruction that describes the task:
### Input:
Returns name and shape of init states of LSTM network
Parameters
----------
batch_size: list of tuple of str and tuple of int and int
num_lstm_layer: int
num_hidden: int
Returns
-------
list of tuple of str and tuple ... |
def update_html_symlink(html_dir):
""""Maintail symlink: "today.html", "yesterday.html" """
today = datetime.date.today()
yesterday = datetime.date.today() - datetime.timedelta(days=1)
for from_date, alias_name in (
(today, 'today.html'), (yesterday, 'yesterday.html')):
from_date_fi... | Maintail symlink: "today.html", "yesterday.html" | Below is the the instruction that describes the task:
### Input:
Maintail symlink: "today.html", "yesterday.html"
### Response:
def update_html_symlink(html_dir):
""""Maintail symlink: "today.html", "yesterday.html" """
today = datetime.date.today()
yesterday = datetime.date.today() - datetime.timedelt... |
def get_commit_message(self, commit_sha):
"""
Return the commit message for the current commit hash,
replace #<PRID> with GH-<PRID>
"""
cmd = ["git", "show", "-s", "--format=%B", commit_sha]
output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
message =... | Return the commit message for the current commit hash,
replace #<PRID> with GH-<PRID> | Below is the the instruction that describes the task:
### Input:
Return the commit message for the current commit hash,
replace #<PRID> with GH-<PRID>
### Response:
def get_commit_message(self, commit_sha):
"""
Return the commit message for the current commit hash,
replace #<PRID> w... |
def securityEventDF(symbol=None, token='', version=''):
'''The Security event message is used to indicate events that apply to a security. A Security event message will be sent whenever such event occurs
https://iexcloud.io/docs/api/#deep-security-event
Args:
symbol (string); Ticker to request
... | The Security event message is used to indicate events that apply to a security. A Security event message will be sent whenever such event occurs
https://iexcloud.io/docs/api/#deep-security-event
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API... | Below is the the instruction that describes the task:
### Input:
The Security event message is used to indicate events that apply to a security. A Security event message will be sent whenever such event occurs
https://iexcloud.io/docs/api/#deep-security-event
Args:
symbol (string); Ticker to reque... |
def addDeprecatedIndividual(self, old_id, new_ids=None):
"""
Will mark the oldid as a deprecated individual.
if one newid is supplied, it will mark it as replaced by.
if >1 newid is supplied, it will mark it with consider properties
:param g:
:param oldid: the individual ... | Will mark the oldid as a deprecated individual.
if one newid is supplied, it will mark it as replaced by.
if >1 newid is supplied, it will mark it with consider properties
:param g:
:param oldid: the individual id to deprecate
:param newids: the individual idlist that is the repl... | Below is the the instruction that describes the task:
### Input:
Will mark the oldid as a deprecated individual.
if one newid is supplied, it will mark it as replaced by.
if >1 newid is supplied, it will mark it with consider properties
:param g:
:param oldid: the individual id to de... |
def attach_tracker(self, stanza, tracker=None, token=None):
"""
Configure tracking for a stanza without sending it.
:param stanza: Message stanza to send.
:type stanza: :class:`aioxmpp.Message`
:param tracker: Message tracker to use.
:type tracker: :class:`~.MessageTrack... | Configure tracking for a stanza without sending it.
:param stanza: Message stanza to send.
:type stanza: :class:`aioxmpp.Message`
:param tracker: Message tracker to use.
:type tracker: :class:`~.MessageTracker` or :data:`None`
:param token: Optional stanza token for more fine-gr... | Below is the the instruction that describes the task:
### Input:
Configure tracking for a stanza without sending it.
:param stanza: Message stanza to send.
:type stanza: :class:`aioxmpp.Message`
:param tracker: Message tracker to use.
:type tracker: :class:`~.MessageTracker` or :dat... |
def alterar(self, id_script, id_script_type, script, description, model=None):
"""Change Script from by the identifier.
:param id_script: Identifier of the Script. Integer value and greater than zero.
:param id_script_type: Identifier of the Script Type. Integer value and greater than zero.
... | Change Script from by the identifier.
:param id_script: Identifier of the Script. Integer value and greater than zero.
:param id_script_type: Identifier of the Script Type. Integer value and greater than zero.
:param script: Script name. String with a minimum 3 and maximum of 40 characters
... | Below is the the instruction that describes the task:
### Input:
Change Script from by the identifier.
:param id_script: Identifier of the Script. Integer value and greater than zero.
:param id_script_type: Identifier of the Script Type. Integer value and greater than zero.
:param script: S... |
def start_notify(self, on_change):
"""Enable notification of changes for this characteristic on the
specified on_change callback. on_change should be a function that takes
one parameter which is the value (as a string of bytes) of the changed
characteristic value.
"""
# ... | Enable notification of changes for this characteristic on the
specified on_change callback. on_change should be a function that takes
one parameter which is the value (as a string of bytes) of the changed
characteristic value. | Below is the the instruction that describes the task:
### Input:
Enable notification of changes for this characteristic on the
specified on_change callback. on_change should be a function that takes
one parameter which is the value (as a string of bytes) of the changed
characteristic value.... |
def stream(self, status=values.unset, iccid=values.unset,
rate_plan=values.unset, e_id=values.unset,
sim_registration_code=values.unset, limit=None, page_size=None):
"""
Streams SimInstance records from the API as a generator stream.
This operation lazily loads reco... | Streams SimInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param unicode status: The status
:param uni... | Below is the the instruction that describes the task:
### Input:
Streams SimInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory eff... |
def add_linear_obj(model):
"""Add a linear version of a minimal medium to the model solver.
Changes the optimization objective to finding the growth medium requiring
the smallest total import flux::
minimize sum |r_i| for r_i in import_reactions
Arguments
---------
model : cobra.Model... | Add a linear version of a minimal medium to the model solver.
Changes the optimization objective to finding the growth medium requiring
the smallest total import flux::
minimize sum |r_i| for r_i in import_reactions
Arguments
---------
model : cobra.Model
The model to modify. | Below is the the instruction that describes the task:
### Input:
Add a linear version of a minimal medium to the model solver.
Changes the optimization objective to finding the growth medium requiring
the smallest total import flux::
minimize sum |r_i| for r_i in import_reactions
Arguments
... |
def S(self):
"""Allow for the projection (and update) of nested values contained within the single match of an array.
Projection operator: https://docs.mongodb.com/manual/reference/operator/projection/positional/#proj._S_
Array update operator: https://docs.mongodb.com/manual/reference/operator/update/position... | Allow for the projection (and update) of nested values contained within the single match of an array.
Projection operator: https://docs.mongodb.com/manual/reference/operator/projection/positional/#proj._S_
Array update operator: https://docs.mongodb.com/manual/reference/operator/update/positional/ | Below is the the instruction that describes the task:
### Input:
Allow for the projection (and update) of nested values contained within the single match of an array.
Projection operator: https://docs.mongodb.com/manual/reference/operator/projection/positional/#proj._S_
Array update operator: https://docs.mo... |
def register(id, url=None):
"""Register a UUID key in the global S3 bucket."""
bucket = registration_s3_bucket()
key = registration_key(id)
obj = bucket.Object(key)
obj.put(Body=url or "missing")
return _generate_s3_url(bucket, key) | Register a UUID key in the global S3 bucket. | Below is the the instruction that describes the task:
### Input:
Register a UUID key in the global S3 bucket.
### Response:
def register(id, url=None):
"""Register a UUID key in the global S3 bucket."""
bucket = registration_s3_bucket()
key = registration_key(id)
obj = bucket.Object(key)
obj.pu... |
def render_head(self, ctx, data):
"""
This renderer calculates content for the <head> tag by concatenating the
values from L{getHeadContent} and the overridden L{head} method.
"""
req = inevow.IRequest(ctx)
more = getattr(self.fragment, 'head', None)
if more is no... | This renderer calculates content for the <head> tag by concatenating the
values from L{getHeadContent} and the overridden L{head} method. | Below is the the instruction that describes the task:
### Input:
This renderer calculates content for the <head> tag by concatenating the
values from L{getHeadContent} and the overridden L{head} method.
### Response:
def render_head(self, ctx, data):
"""
This renderer calculates content for... |
def generate_message(contract: Contract, condition_kwargs: Mapping[str, Any]) -> str:
"""Generate the message upon contract violation."""
# pylint: disable=protected-access
parts = [] # type: List[str]
if contract.location is not None:
parts.append("{}:\n".format(contract.location))
if co... | Generate the message upon contract violation. | Below is the the instruction that describes the task:
### Input:
Generate the message upon contract violation.
### Response:
def generate_message(contract: Contract, condition_kwargs: Mapping[str, Any]) -> str:
"""Generate the message upon contract violation."""
# pylint: disable=protected-access
parts... |
def iter_cast(inputs, dst_type, return_type=None):
"""Cast elements of an iterable object into some type.
Args:
inputs (Iterable): The input object.
dst_type (type): Destination type.
return_type (type, optional): If specified, the output object will be
converted to this typ... | Cast elements of an iterable object into some type.
Args:
inputs (Iterable): The input object.
dst_type (type): Destination type.
return_type (type, optional): If specified, the output object will be
converted to this type, otherwise an iterator.
Returns:
iterator o... | Below is the the instruction that describes the task:
### Input:
Cast elements of an iterable object into some type.
Args:
inputs (Iterable): The input object.
dst_type (type): Destination type.
return_type (type, optional): If specified, the output object will be
converted ... |
def build_gui(self, container):
"""Build GUI such that image list area is maximized."""
vbox, sw, orientation = Widgets.get_oriented_box(container)
captions = (('Channel:', 'label', 'Channel Name', 'combobox',
'Modified only', 'checkbutton'), )
w, b = Widgets.build... | Build GUI such that image list area is maximized. | Below is the the instruction that describes the task:
### Input:
Build GUI such that image list area is maximized.
### Response:
def build_gui(self, container):
"""Build GUI such that image list area is maximized."""
vbox, sw, orientation = Widgets.get_oriented_box(container)
captions = (... |
def add_spot(self, component=None, feature=None, **kwargs):
"""
Shortcut to :meth:`add_feature` but with kind='spot'
"""
if component is None:
if len(self.hierarchy.get_stars())==1:
component = self.hierarchy.get_stars()[0]
else:
ra... | Shortcut to :meth:`add_feature` but with kind='spot' | Below is the the instruction that describes the task:
### Input:
Shortcut to :meth:`add_feature` but with kind='spot'
### Response:
def add_spot(self, component=None, feature=None, **kwargs):
"""
Shortcut to :meth:`add_feature` but with kind='spot'
"""
if component is None:
... |
def parse_params(self, params):
"""
Parsing params, params is a dict
and the dict value can be a string
or an iterable, namely a list, we
need to process those iterables
"""
for (key, value) in params.items():
if not isinstance(value, str):
... | Parsing params, params is a dict
and the dict value can be a string
or an iterable, namely a list, we
need to process those iterables | Below is the the instruction that describes the task:
### Input:
Parsing params, params is a dict
and the dict value can be a string
or an iterable, namely a list, we
need to process those iterables
### Response:
def parse_params(self, params):
"""
Parsing params, params is ... |
def find_obfuscatables(tokens, obfunc, ignore_length=False):
"""
Iterates over *tokens*, which must be an equivalent output to what
tokenize.generate_tokens() produces, calling *obfunc* on each with the
following parameters:
- **tokens:** The current list of tokens.
- **index:** ... | Iterates over *tokens*, which must be an equivalent output to what
tokenize.generate_tokens() produces, calling *obfunc* on each with the
following parameters:
- **tokens:** The current list of tokens.
- **index:** The current position in the list.
*obfunc* is expected to return t... | Below is the the instruction that describes the task:
### Input:
Iterates over *tokens*, which must be an equivalent output to what
tokenize.generate_tokens() produces, calling *obfunc* on each with the
following parameters:
- **tokens:** The current list of tokens.
- **index:** Th... |
def _ring_2d(m, n):
"""Ring-order of a mxn mesh.
Args:
m: an integer
n: an integer
Returns:
a list of mxn pairs
"""
if m == 1:
return [(0, i) for i in range(n)]
if n == 1:
return [(i, 0) for i in range(m)]
if m % 2 != 0:
tf.logging.warning("Odd dimension")
return [(i % m, i //... | Ring-order of a mxn mesh.
Args:
m: an integer
n: an integer
Returns:
a list of mxn pairs | Below is the the instruction that describes the task:
### Input:
Ring-order of a mxn mesh.
Args:
m: an integer
n: an integer
Returns:
a list of mxn pairs
### Response:
def _ring_2d(m, n):
"""Ring-order of a mxn mesh.
Args:
m: an integer
n: an integer
Returns:
a list of mxn pairs... |
def add_transition(self, from_state_id, from_outcome, to_state_id, to_outcome, transition_id=None):
"""Adds a transition to the container state
Note: Either the toState or the toOutcome needs to be "None"
:param from_state_id: The source state of the transition
:param from_outcome: The... | Adds a transition to the container state
Note: Either the toState or the toOutcome needs to be "None"
:param from_state_id: The source state of the transition
:param from_outcome: The outcome id of the source state to connect the transition to
:param to_state_id: The target state of th... | Below is the the instruction that describes the task:
### Input:
Adds a transition to the container state
Note: Either the toState or the toOutcome needs to be "None"
:param from_state_id: The source state of the transition
:param from_outcome: The outcome id of the source state to connect... |
def _default_http_header(self, empty_session_only: bool = False) -> Dict[str, str]:
"""Returns default HTTP header we use for requests."""
header = {'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'en-US,en;q=0.8',
'Connection': 'keep-alive',
... | Returns default HTTP header we use for requests. | Below is the the instruction that describes the task:
### Input:
Returns default HTTP header we use for requests.
### Response:
def _default_http_header(self, empty_session_only: bool = False) -> Dict[str, str]:
"""Returns default HTTP header we use for requests."""
header = {'Accept-Encoding': 'gz... |
def from_unit_cube(self, x):
"""
Used by multinest
:param x: 0 < x < 1
:param lower_bound:
:param upper_bound:
:return:
"""
lower_bound = self.lower_bound.value
upper_bound = self.upper_bound.value
low = lower_bound
spread = floa... | Used by multinest
:param x: 0 < x < 1
:param lower_bound:
:param upper_bound:
:return: | Below is the the instruction that describes the task:
### Input:
Used by multinest
:param x: 0 < x < 1
:param lower_bound:
:param upper_bound:
:return:
### Response:
def from_unit_cube(self, x):
"""
Used by multinest
:param x: 0 < x < 1
:param lower... |
def load(self, name):
"""Loads and returns foreign library."""
name = ctypes.util.find_library(name)
return ctypes.cdll.LoadLibrary(name) | Loads and returns foreign library. | Below is the the instruction that describes the task:
### Input:
Loads and returns foreign library.
### Response:
def load(self, name):
"""Loads and returns foreign library."""
name = ctypes.util.find_library(name)
return ctypes.cdll.LoadLibrary(name) |
def _get_page_data(self, pno, zoom=0):
"""
Return a PNG image for a document page number. If zoom is other than 0, one of
the 4 page quadrants are zoomed-in instead and the corresponding clip returned.
"""
dlist = self.dlist_tab[pno] # get display list
if not dlist: # c... | Return a PNG image for a document page number. If zoom is other than 0, one of
the 4 page quadrants are zoomed-in instead and the corresponding clip returned. | Below is the the instruction that describes the task:
### Input:
Return a PNG image for a document page number. If zoom is other than 0, one of
the 4 page quadrants are zoomed-in instead and the corresponding clip returned.
### Response:
def _get_page_data(self, pno, zoom=0):
"""
Return a P... |
def get_lock(self, lockname, locktime=60, auto_renewal=False):
''' Gets a lock and returns if it can be stablished. Returns false otherwise '''
pid = os.getpid()
caller = inspect.stack()[0][3]
try:
# rl = redlock.Redlock([{"host": settings.REDIS_SERVERS['std_redis']['hos... | Gets a lock and returns if it can be stablished. Returns false otherwise | Below is the the instruction that describes the task:
### Input:
Gets a lock and returns if it can be stablished. Returns false otherwise
### Response:
def get_lock(self, lockname, locktime=60, auto_renewal=False):
''' Gets a lock and returns if it can be stablished. Returns false otherwise '''
p... |
def team_districts(self, team):
"""
Get districts a team has competed in.
:param team: Team to get data on.
:return: List of District objects.
"""
return [District(raw) for raw in self._get('team/%s/districts' % self.team_key(team))] | Get districts a team has competed in.
:param team: Team to get data on.
:return: List of District objects. | Below is the the instruction that describes the task:
### Input:
Get districts a team has competed in.
:param team: Team to get data on.
:return: List of District objects.
### Response:
def team_districts(self, team):
"""
Get districts a team has competed in.
:param team: ... |
def count(self):
"""
Returns the number of rows matched by this query.
*Note: This function executes a SELECT COUNT() and has a performance cost on large datasets*
"""
if self._batch:
raise CQLEngineException("Only inserts, updates, and deletes are available in batch... | Returns the number of rows matched by this query.
*Note: This function executes a SELECT COUNT() and has a performance cost on large datasets* | Below is the the instruction that describes the task:
### Input:
Returns the number of rows matched by this query.
*Note: This function executes a SELECT COUNT() and has a performance cost on large datasets*
### Response:
def count(self):
"""
Returns the number of rows matched by this quer... |
async def get_poll(poll_id):
""" Get a strawpoll.
Example:
poll = strawpy.get_poll('11682852')
:param poll_id:
:return: strawpy.Strawpoll object
"""
async with aiohttp.get('{api_url}/{poll_id}'.format(api_url=api_url, poll_id=poll_id)) as r:
return await StrawPoll(r) | Get a strawpoll.
Example:
poll = strawpy.get_poll('11682852')
:param poll_id:
:return: strawpy.Strawpoll object | Below is the the instruction that describes the task:
### Input:
Get a strawpoll.
Example:
poll = strawpy.get_poll('11682852')
:param poll_id:
:return: strawpy.Strawpoll object
### Response:
async def get_poll(poll_id):
""" Get a strawpoll.
Example:
poll = strawpy.get_poll(... |
def pertibate(self, pertibate_columns=None, filter_func=None,
max_size=1000):
"""
:param pertibate_columns: list of str fo columns to pertibate see DOE
:param filter_func: func that takes a SeabornRow and return
True if this row should be exist
... | :param pertibate_columns: list of str fo columns to pertibate see DOE
:param filter_func: func that takes a SeabornRow and return
True if this row should be exist
:param max_size: int of the max number of rows to try
but some may be filtered out
... | Below is the the instruction that describes the task:
### Input:
:param pertibate_columns: list of str fo columns to pertibate see DOE
:param filter_func: func that takes a SeabornRow and return
True if this row should be exist
:param max_size: int of the max number of ro... |
def add_projection(self, A, alpha = 1.0, beta = 1.0, reordered=False):
"""
Add projection of a dense matrix :math:`A` to :py:class:`cspmatrix`.
X := alpha*proj(A) + beta*X
"""
assert self.is_factor is False, "cannot project matrix onto a cspmatrix factor"
assert isin... | Add projection of a dense matrix :math:`A` to :py:class:`cspmatrix`.
X := alpha*proj(A) + beta*X | Below is the the instruction that describes the task:
### Input:
Add projection of a dense matrix :math:`A` to :py:class:`cspmatrix`.
X := alpha*proj(A) + beta*X
### Response:
def add_projection(self, A, alpha = 1.0, beta = 1.0, reordered=False):
"""
Add projection of a dense matrix :m... |
def move_to(self, target_datetime):
"""Moves frozen date to the given ``target_datetime``"""
target_datetime = _parse_time_to_freeze(target_datetime)
delta = target_datetime - self.time_to_freeze
self.tick(delta=delta) | Moves frozen date to the given ``target_datetime`` | Below is the the instruction that describes the task:
### Input:
Moves frozen date to the given ``target_datetime``
### Response:
def move_to(self, target_datetime):
"""Moves frozen date to the given ``target_datetime``"""
target_datetime = _parse_time_to_freeze(target_datetime)
delta = tar... |
def users_setPhoto(self, *, image: Union[str, IOBase], **kwargs) -> SlackResponse:
"""Set the user profile photo
Args:
image (str): Supply the path of the image you'd like to upload.
e.g. 'myimage.png'
"""
self._validate_xoxp_token()
return self.api_c... | Set the user profile photo
Args:
image (str): Supply the path of the image you'd like to upload.
e.g. 'myimage.png' | Below is the the instruction that describes the task:
### Input:
Set the user profile photo
Args:
image (str): Supply the path of the image you'd like to upload.
e.g. 'myimage.png'
### Response:
def users_setPhoto(self, *, image: Union[str, IOBase], **kwargs) -> SlackResponse:
... |
def focus_next(self, count=1):
" Focus the next pane. "
panes = self.panes
if panes:
self.active_pane = panes[(panes.index(self.active_pane) + count) % len(panes)]
else:
self.active_pane = None | Focus the next pane. | Below is the the instruction that describes the task:
### Input:
Focus the next pane.
### Response:
def focus_next(self, count=1):
" Focus the next pane. "
panes = self.panes
if panes:
self.active_pane = panes[(panes.index(self.active_pane) + count) % len(panes)]
else:
... |
def selectImports(pth, xtrapath=None):
"""
Return the dependencies of a binary that should be included.
Return a list of pairs (name, fullpath)
"""
rv = []
if xtrapath is None:
xtrapath = [os.path.dirname(pth)]
else:
assert isinstance(xtrapath, list)
xtrapath = [os.p... | Return the dependencies of a binary that should be included.
Return a list of pairs (name, fullpath) | Below is the the instruction that describes the task:
### Input:
Return the dependencies of a binary that should be included.
Return a list of pairs (name, fullpath)
### Response:
def selectImports(pth, xtrapath=None):
"""
Return the dependencies of a binary that should be included.
Return a list... |
def schedule_window(report_type, start_at, stop_at, resolution):
"""
Find all active schedules and schedule celery tasks for
each of them with a specific ETA (determined by parsing
the cron schedule for the schedule)
"""
model_cls = get_scheduler_model(report_type)
dbsession = db.create_scop... | Find all active schedules and schedule celery tasks for
each of them with a specific ETA (determined by parsing
the cron schedule for the schedule) | Below is the the instruction that describes the task:
### Input:
Find all active schedules and schedule celery tasks for
each of them with a specific ETA (determined by parsing
the cron schedule for the schedule)
### Response:
def schedule_window(report_type, start_at, stop_at, resolution):
"""
Fin... |
def _get_ordering_field_lookup(self, field_name):
"""
get real model field to order by
"""
field = field_name
get_field = getattr(self, "get_%s_ordering_field" % field_name, None)
if get_field:
field = get_field()
return field | get real model field to order by | Below is the the instruction that describes the task:
### Input:
get real model field to order by
### Response:
def _get_ordering_field_lookup(self, field_name):
"""
get real model field to order by
"""
field = field_name
get_field = getattr(self, "get_%s_ordering_field" % f... |
def get_random_integer(N, randfunc=None):
"""getRandomInteger(N:int, randfunc:callable):long
Return a random number with at most N bits.
If randfunc is omitted, then Random.new().read is used.
This function is for internal use only and may be renamed or removed in
the future.
"""
if randfu... | getRandomInteger(N:int, randfunc:callable):long
Return a random number with at most N bits.
If randfunc is omitted, then Random.new().read is used.
This function is for internal use only and may be renamed or removed in
the future. | Below is the the instruction that describes the task:
### Input:
getRandomInteger(N:int, randfunc:callable):long
Return a random number with at most N bits.
If randfunc is omitted, then Random.new().read is used.
This function is for internal use only and may be renamed or removed in
the future.
#... |
def to_numpy(nd4j_array):
""" Convert an ND4J array to a numpy array
:param nd4j_array:
:return:
"""
buff = nd4j_array.data()
address = buff.pointer().address()
type_name = java_classes.DataTypeUtil.getDtypeFromContext()
data_type = java_classes.DataTypeUtil.getDTypeForName(type_name)
... | Convert an ND4J array to a numpy array
:param nd4j_array:
:return: | Below is the the instruction that describes the task:
### Input:
Convert an ND4J array to a numpy array
:param nd4j_array:
:return:
### Response:
def to_numpy(nd4j_array):
""" Convert an ND4J array to a numpy array
:param nd4j_array:
:return:
"""
buff = nd4j_array.data()
address = b... |
def unsign(self, value, max_age=None):
"""
Retrieve original value and check it wasn't signed more
than max_age seconds ago.
"""
result = super(TimestampSigner, self).unsign(value)
value, timestamp = result.rsplit(self.sep, 1)
timestamp = baseconv.base62.decode(ti... | Retrieve original value and check it wasn't signed more
than max_age seconds ago. | Below is the the instruction that describes the task:
### Input:
Retrieve original value and check it wasn't signed more
than max_age seconds ago.
### Response:
def unsign(self, value, max_age=None):
"""
Retrieve original value and check it wasn't signed more
than max_age seconds ag... |
def updateMigrationBlockStatus(self, migration_status=0, migration_block=None, migration_request=None):
"""
migration_status:
0=PENDING
1=IN PROGRESS
2=COMPLETED
3=FAILED (will be retried)
9=Terminally FAILED
status change:
0 -> 1
1 -> 2
... | migration_status:
0=PENDING
1=IN PROGRESS
2=COMPLETED
3=FAILED (will be retried)
9=Terminally FAILED
status change:
0 -> 1
1 -> 2
1 -> 3
1 -> 9
are only allowed changes for working through migration.
3 -> 1 allowed for retry... | Below is the the instruction that describes the task:
### Input:
migration_status:
0=PENDING
1=IN PROGRESS
2=COMPLETED
3=FAILED (will be retried)
9=Terminally FAILED
status change:
0 -> 1
1 -> 2
1 -> 3
1 -> 9
are only allowed ch... |
def srp1flood(x, promisc=None, filter=None, iface=None, nofilter=0, *args, **kargs): # noqa: E501
"""Flood and receive packets at layer 2 and return only the first answer
prn: function applied to packets received
verbose: set verbosity level
nofilter: put 1 to avoid use of BPF filters
filter: provide a BPF... | Flood and receive packets at layer 2 and return only the first answer
prn: function applied to packets received
verbose: set verbosity level
nofilter: put 1 to avoid use of BPF filters
filter: provide a BPF filter
iface: listen answers only on the given interface | Below is the the instruction that describes the task:
### Input:
Flood and receive packets at layer 2 and return only the first answer
prn: function applied to packets received
verbose: set verbosity level
nofilter: put 1 to avoid use of BPF filters
filter: provide a BPF filter
iface: listen answers only... |
def _loadUi(uifile, baseinstance=None):
"""Dynamically load a user interface from the given `uifile`
This function calls `uic.loadUi` if using PyQt bindings,
else it implements a comparable binding for PySide.
Documentation:
http://pyqt.sourceforge.net/Docs/PyQt5/designer.html#PyQt5.uic.loadUi... | Dynamically load a user interface from the given `uifile`
This function calls `uic.loadUi` if using PyQt bindings,
else it implements a comparable binding for PySide.
Documentation:
http://pyqt.sourceforge.net/Docs/PyQt5/designer.html#PyQt5.uic.loadUi
Arguments:
uifile (str): Absolute... | Below is the the instruction that describes the task:
### Input:
Dynamically load a user interface from the given `uifile`
This function calls `uic.loadUi` if using PyQt bindings,
else it implements a comparable binding for PySide.
Documentation:
http://pyqt.sourceforge.net/Docs/PyQt5/designer... |
def with_write_hdf5(func):
"""Decorate an HDF5-writing function to open a filepath if needed
``func`` should be written to take the object to be written as the
first argument, and then presume an `h5py.Group` as the second.
This method uses keywords ``append`` and ``overwrite`` as follows if
the o... | Decorate an HDF5-writing function to open a filepath if needed
``func`` should be written to take the object to be written as the
first argument, and then presume an `h5py.Group` as the second.
This method uses keywords ``append`` and ``overwrite`` as follows if
the output file already exists:
- ... | Below is the the instruction that describes the task:
### Input:
Decorate an HDF5-writing function to open a filepath if needed
``func`` should be written to take the object to be written as the
first argument, and then presume an `h5py.Group` as the second.
This method uses keywords ``append`` and ``... |
def is_cptp(self, atol=None, rtol=None):
"""Return True if completely-positive trace-preserving."""
if self._data[1] is not None:
return False
if atol is None:
atol = self._atol
if rtol is None:
rtol = self._rtol
accum = 0j
for op in se... | Return True if completely-positive trace-preserving. | Below is the the instruction that describes the task:
### Input:
Return True if completely-positive trace-preserving.
### Response:
def is_cptp(self, atol=None, rtol=None):
"""Return True if completely-positive trace-preserving."""
if self._data[1] is not None:
return False
if a... |
def dict_to_etree(source, root_tag=None):
""" Recursively load dict/list representation of an XML tree into an etree representation.
Args:
source -- A dictionary representing an XML document where identical children tags are
countained in a list.
Keyword args:
... | Recursively load dict/list representation of an XML tree into an etree representation.
Args:
source -- A dictionary representing an XML document where identical children tags are
countained in a list.
Keyword args:
root_tag -- A parent tag in which to wrap t... | Below is the the instruction that describes the task:
### Input:
Recursively load dict/list representation of an XML tree into an etree representation.
Args:
source -- A dictionary representing an XML document where identical children tags are
countained in a list.
... |
def cat_file(path):
"""Cat file and return content"""
cmd = ["cat", path]
status, stdout, _ = cij.ssh.command(cmd, shell=True, echo=True)
if status:
raise RuntimeError("cij.nvme.env: cat %s failed" % path)
return stdout.strip() | Cat file and return content | Below is the the instruction that describes the task:
### Input:
Cat file and return content
### Response:
def cat_file(path):
"""Cat file and return content"""
cmd = ["cat", path]
status, stdout, _ = cij.ssh.command(cmd, shell=True, echo=True)
if status:
raise RuntimeError("cij.nvme.env: ... |
def _get_query_params(self):
"""Getter for query parameters for the next request.
Returns:
dict: A dictionary of query parameters.
"""
result = {}
if self.next_page_token is not None:
result[self._PAGE_TOKEN] = self.next_page_token
if self.max_res... | Getter for query parameters for the next request.
Returns:
dict: A dictionary of query parameters. | Below is the the instruction that describes the task:
### Input:
Getter for query parameters for the next request.
Returns:
dict: A dictionary of query parameters.
### Response:
def _get_query_params(self):
"""Getter for query parameters for the next request.
Returns:
... |
def _encode_observations(self, observations):
"""Encodes observations as PNG."""
return [
Observation(
self._session.obj.run(
self._encoded_image_t.obj,
feed_dict={self._decoded_image_p.obj: observation}
),
self._decode_png
)
... | Encodes observations as PNG. | Below is the the instruction that describes the task:
### Input:
Encodes observations as PNG.
### Response:
def _encode_observations(self, observations):
"""Encodes observations as PNG."""
return [
Observation(
self._session.obj.run(
self._encoded_image_t.obj,
... |
def get_name_value_hash_txid( self, name, value_hash ):
"""
Given a name and a value hash (i.e. the zone file hash), return the txid for the value hash.
Return None if the name doesn't exist, or is revoked, or did not
receive a NAME_UPDATE since it was last preordered.
"""
... | Given a name and a value hash (i.e. the zone file hash), return the txid for the value hash.
Return None if the name doesn't exist, or is revoked, or did not
receive a NAME_UPDATE since it was last preordered. | Below is the the instruction that describes the task:
### Input:
Given a name and a value hash (i.e. the zone file hash), return the txid for the value hash.
Return None if the name doesn't exist, or is revoked, or did not
receive a NAME_UPDATE since it was last preordered.
### Response:
def get_na... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.