code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def agent(cls, version=None):
"""
Returns:
a connection object to make REST calls to QDS
optionally override the `version` of the REST endpoint for advanced
features available only in the newer version of the API available
for certain resource end points eg: ... | Returns:
a connection object to make REST calls to QDS
optionally override the `version` of the REST endpoint for advanced
features available only in the newer version of the API available
for certain resource end points eg: /v1.3/cluster. When version is
None we ... | Below is the the instruction that describes the task:
### Input:
Returns:
a connection object to make REST calls to QDS
optionally override the `version` of the REST endpoint for advanced
features available only in the newer version of the API available
for certain resou... |
def writeNumber(self, n):
"""
Writes a float to the stream.
@type n: C{float}
"""
self.stream.write(TYPE_NUMBER)
self.stream.write_double(n) | Writes a float to the stream.
@type n: C{float} | Below is the the instruction that describes the task:
### Input:
Writes a float to the stream.
@type n: C{float}
### Response:
def writeNumber(self, n):
"""
Writes a float to the stream.
@type n: C{float}
"""
self.stream.write(TYPE_NUMBER)
self.stream.write... |
def run(self):
"""
Starts the server.
"""
server_logger = logging.getLogger('aiohttp.server')
# In debug mode we don't use the standard request log but a more complete in response.py
if log.getEffectiveLevel() == logging.DEBUG:
server_logger.setLevel(logging.... | Starts the server. | Below is the the instruction that describes the task:
### Input:
Starts the server.
### Response:
def run(self):
"""
Starts the server.
"""
server_logger = logging.getLogger('aiohttp.server')
# In debug mode we don't use the standard request log but a more complete in respo... |
def create_throttle():
""" Create a THROTTLE statement """
throttle_amount = "*" | Combine(number + "%") | number
return Group(
function("throttle", throttle_amount, throttle_amount, caseless=True)
).setResultsName("throttle") | Create a THROTTLE statement | Below is the the instruction that describes the task:
### Input:
Create a THROTTLE statement
### Response:
def create_throttle():
""" Create a THROTTLE statement """
throttle_amount = "*" | Combine(number + "%") | number
return Group(
function("throttle", throttle_amount, throttle_amount, casel... |
def _make_model(self, data, key=None):
"""
Creates a model instance with the given data.
Args:
data: Model data returned from DB.
key: Object key
Returns:
pyoko.Model object.
"""
if data['deleted'] and not self.adapter.want_deleted:
... | Creates a model instance with the given data.
Args:
data: Model data returned from DB.
key: Object key
Returns:
pyoko.Model object. | Below is the the instruction that describes the task:
### Input:
Creates a model instance with the given data.
Args:
data: Model data returned from DB.
key: Object key
Returns:
pyoko.Model object.
### Response:
def _make_model(self, data, key=None):
"""
... |
def transfer_and_wait(
self,
registry_address: PaymentNetworkID,
token_address: TokenAddress,
amount: TokenAmount,
target: Address,
identifier: PaymentID = None,
transfer_timeout: int = None,
secret: Secret = None,
... | Do a transfer with `target` with the given `amount` of `token_address`. | Below is the the instruction that describes the task:
### Input:
Do a transfer with `target` with the given `amount` of `token_address`.
### Response:
def transfer_and_wait(
self,
registry_address: PaymentNetworkID,
token_address: TokenAddress,
amount: TokenAmount,
... |
def equal_args(*args, **kwargs):
"""A memoized key factory that compares the equality (`==`) of a stable sort of the parameters."""
key = args
if kwargs:
key += _kwargs_separator + tuple(sorted(kwargs.items()))
return key | A memoized key factory that compares the equality (`==`) of a stable sort of the parameters. | Below is the the instruction that describes the task:
### Input:
A memoized key factory that compares the equality (`==`) of a stable sort of the parameters.
### Response:
def equal_args(*args, **kwargs):
"""A memoized key factory that compares the equality (`==`) of a stable sort of the parameters."""
key = a... |
def _check_r(self, r):
"""the columns must orthogonal"""
if abs(np.dot(r[:, 0], r[:, 0]) - 1) > eps or \
abs(np.dot(r[:, 0], r[:, 0]) - 1) > eps or \
abs(np.dot(r[:, 0], r[:, 0]) - 1) > eps or \
np.dot(r[:, 0], r[:, 1]) > eps or \
np.dot(r[:, 1], r[:, 2]) ... | the columns must orthogonal | Below is the the instruction that describes the task:
### Input:
the columns must orthogonal
### Response:
def _check_r(self, r):
"""the columns must orthogonal"""
if abs(np.dot(r[:, 0], r[:, 0]) - 1) > eps or \
abs(np.dot(r[:, 0], r[:, 0]) - 1) > eps or \
abs(np.dot(r[:, 0]... |
def _handle_special_yaml_cases(v):
"""Handle values that pass integer, boolean, list or dictionary values.
"""
if "::" in v:
out = {}
for part in v.split("::"):
k_part, v_part = part.split(":")
out[k_part] = v_part.split(";")
v = out
elif ";" in v:
... | Handle values that pass integer, boolean, list or dictionary values. | Below is the the instruction that describes the task:
### Input:
Handle values that pass integer, boolean, list or dictionary values.
### Response:
def _handle_special_yaml_cases(v):
"""Handle values that pass integer, boolean, list or dictionary values.
"""
if "::" in v:
out = {}
for p... |
def main():
'''Main function.'''
usage = ('\n\n %prog [options] XML_PATH\n\nArguments:\n\n '
'XML_PATH the directory containing the '
'GermaNet .xml files')
parser = optparse.OptionParser(usage=usage)
parser.add_option('--host', default=None,
... | Main function. | Below is the the instruction that describes the task:
### Input:
Main function.
### Response:
def main():
'''Main function.'''
usage = ('\n\n %prog [options] XML_PATH\n\nArguments:\n\n '
'XML_PATH the directory containing the '
'GermaNet .xml files')
parser = o... |
def update(self, data, decayFactor, timeUnit):
"""Update the centroids, according to data
:param data:
RDD with new data for the model update.
:param decayFactor:
Forgetfulness of the previous centroids.
:param timeUnit:
Can be "batches" or "points". If poi... | Update the centroids, according to data
:param data:
RDD with new data for the model update.
:param decayFactor:
Forgetfulness of the previous centroids.
:param timeUnit:
Can be "batches" or "points". If points, then the decay factor
is raised to the powe... | Below is the the instruction that describes the task:
### Input:
Update the centroids, according to data
:param data:
RDD with new data for the model update.
:param decayFactor:
Forgetfulness of the previous centroids.
:param timeUnit:
Can be "batches" or "poin... |
def install_package(package,
wheels_path,
venv=None,
requirement_files=None,
upgrade=False,
install_args=None):
"""Install a Python package.
Can specify a specific version.
Can specify a prerelease.
Can ... | Install a Python package.
Can specify a specific version.
Can specify a prerelease.
Can specify a venv to install in.
Can specify a list of paths or urls to requirement txt files.
Can specify a local wheels_path to use for offline installation.
Can request an upgrade. | Below is the the instruction that describes the task:
### Input:
Install a Python package.
Can specify a specific version.
Can specify a prerelease.
Can specify a venv to install in.
Can specify a list of paths or urls to requirement txt files.
Can specify a local wheels_path to use for offline... |
def day_of_year(self):
"""
Returns the day of the year (1-366).
:rtype: int
"""
k = 1 if self.is_leap_year() else 2
return (275 * self.month) // 9 - k * ((self.month + 9) // 12) + self.day - 30 | Returns the day of the year (1-366).
:rtype: int | Below is the the instruction that describes the task:
### Input:
Returns the day of the year (1-366).
:rtype: int
### Response:
def day_of_year(self):
"""
Returns the day of the year (1-366).
:rtype: int
"""
k = 1 if self.is_leap_year() else 2
return (275 ... |
def post_process(self, paths, dry_run=False, **options):
"""
Overridden to allow some files to be excluded (using
``postprocess_exclusions``)
"""
if self.postprocess_exclusions:
paths = dict((k, v) for k, v in paths.items() if not
self.exclude_fil... | Overridden to allow some files to be excluded (using
``postprocess_exclusions``) | Below is the the instruction that describes the task:
### Input:
Overridden to allow some files to be excluded (using
``postprocess_exclusions``)
### Response:
def post_process(self, paths, dry_run=False, **options):
"""
Overridden to allow some files to be excluded (using
``postpro... |
def balance(self):
"""Returns a tuple of (total amount deposited, total amount
withdrawn)."""
sin = Decimal("0.00")
sout = Decimal("0.00")
for t in self.trans:
if t.amount < Decimal("0.00"):
sout += t.amount
else:
sin += t.... | Returns a tuple of (total amount deposited, total amount
withdrawn). | Below is the the instruction that describes the task:
### Input:
Returns a tuple of (total amount deposited, total amount
withdrawn).
### Response:
def balance(self):
"""Returns a tuple of (total amount deposited, total amount
withdrawn)."""
sin = Decimal("0.00")
sout = Deci... |
def write(self, filename):
"""
Write detector to a file - uses HDF5 file format.
Meta-data are stored alongside numpy data arrays. See h5py.org for \
details of the methods.
:type filename: str
:param filename: Filename to save the detector to.
"""
f = h... | Write detector to a file - uses HDF5 file format.
Meta-data are stored alongside numpy data arrays. See h5py.org for \
details of the methods.
:type filename: str
:param filename: Filename to save the detector to. | Below is the the instruction that describes the task:
### Input:
Write detector to a file - uses HDF5 file format.
Meta-data are stored alongside numpy data arrays. See h5py.org for \
details of the methods.
:type filename: str
:param filename: Filename to save the detector to.
###... |
def __unify_unique_identities(self, uidentities, matcher,
fast_matching, interactive):
"""Unify unique identities looking for similar identities."""
self.total = len(uidentities)
self.matched = 0
if self.recovery and self.recovery_file.exists():
... | Unify unique identities looking for similar identities. | Below is the the instruction that describes the task:
### Input:
Unify unique identities looking for similar identities.
### Response:
def __unify_unique_identities(self, uidentities, matcher,
fast_matching, interactive):
"""Unify unique identities looking for similar iden... |
def _is_descendant_of(self, parent):
"""
Returns True if parent is in the list of ancestors, returns False
otherwise.
:type parent: Task
:param parent: The parent that is searched in the ancestors.
:rtype: bool
:returns: Whether the parent was found.
""... | Returns True if parent is in the list of ancestors, returns False
otherwise.
:type parent: Task
:param parent: The parent that is searched in the ancestors.
:rtype: bool
:returns: Whether the parent was found. | Below is the the instruction that describes the task:
### Input:
Returns True if parent is in the list of ancestors, returns False
otherwise.
:type parent: Task
:param parent: The parent that is searched in the ancestors.
:rtype: bool
:returns: Whether the parent was found... |
def _printHeadline(self, kind, test, is_failure=True):
"""Output a 1-line error summary to the stream if appropriate.
The line contains the kind of error and the pathname of the test.
:arg kind: The (string) type of incident the precipitated this call
:arg test: The test that precipita... | Output a 1-line error summary to the stream if appropriate.
The line contains the kind of error and the pathname of the test.
:arg kind: The (string) type of incident the precipitated this call
:arg test: The test that precipitated this call | Below is the the instruction that describes the task:
### Input:
Output a 1-line error summary to the stream if appropriate.
The line contains the kind of error and the pathname of the test.
:arg kind: The (string) type of incident the precipitated this call
:arg test: The test that precip... |
def detailed_tokens(tokenizer, text):
"""Format Mecab output into a nice data structure, based on Janome."""
node = tokenizer.parseToNode(text)
node = node.next # first node is beginning of sentence and empty, skip it
words = []
while node.posid != 0:
surface = node.surface
base = s... | Format Mecab output into a nice data structure, based on Janome. | Below is the the instruction that describes the task:
### Input:
Format Mecab output into a nice data structure, based on Janome.
### Response:
def detailed_tokens(tokenizer, text):
"""Format Mecab output into a nice data structure, based on Janome."""
node = tokenizer.parseToNode(text)
node = node.nex... |
def block_code(self):
inputs = self._get_all_input_values()
outputs = {}
"""
self.f = self.user_function(**inputs)
try:
outputs = self.f.send(inputs)
except StopIteration:
self.terminate()
"""
if self.first_time:
self.f ... | self.f = self.user_function(**inputs)
try:
outputs = self.f.send(inputs)
except StopIteration:
self.terminate() | Below is the the instruction that describes the task:
### Input:
self.f = self.user_function(**inputs)
try:
outputs = self.f.send(inputs)
except StopIteration:
self.terminate()
### Response:
def block_code(self):
inputs = self._get_all_input_values()
outputs ... |
def _get_label(self):
'''Find the label for the output files
for this calculation
'''
if self._label is None:
foundfiles = False
for f in self._files:
if ".files" in f:
foundfiles = True
self._label = f.sp... | Find the label for the output files
for this calculation | Below is the the instruction that describes the task:
### Input:
Find the label for the output files
for this calculation
### Response:
def _get_label(self):
'''Find the label for the output files
for this calculation
'''
if self._label is None:
foundfiles = ... |
def show_term_protect(name=None, instance_id=None, call=None, quiet=False):
'''
Show the details from EC2 concerning an instance's termination protection state
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_term_protect action must be called with -a or --action.'
... | Show the details from EC2 concerning an instance's termination protection state | Below is the the instruction that describes the task:
### Input:
Show the details from EC2 concerning an instance's termination protection state
### Response:
def show_term_protect(name=None, instance_id=None, call=None, quiet=False):
'''
Show the details from EC2 concerning an instance's termination prote... |
def discover(timeout=1, retries=1):
"""Discover Raumfeld devices in the network
:param timeout: The timeout in seconds
:param retries: How often the search should be retried
:returns: A list of raumfeld devices, sorted by name
"""
locations = []
group = ('239.255.255.250', 1900)
... | Discover Raumfeld devices in the network
:param timeout: The timeout in seconds
:param retries: How often the search should be retried
:returns: A list of raumfeld devices, sorted by name | Below is the the instruction that describes the task:
### Input:
Discover Raumfeld devices in the network
:param timeout: The timeout in seconds
:param retries: How often the search should be retried
:returns: A list of raumfeld devices, sorted by name
### Response:
def discover(timeout=1, retri... |
def unzip_file_to_dir(path_to_zip, output_directory):
"""
Extract a ZIP archive to a directory
"""
z = ZipFile(path_to_zip, 'r')
z.extractall(output_directory)
z.close() | Extract a ZIP archive to a directory | Below is the the instruction that describes the task:
### Input:
Extract a ZIP archive to a directory
### Response:
def unzip_file_to_dir(path_to_zip, output_directory):
"""
Extract a ZIP archive to a directory
"""
z = ZipFile(path_to_zip, 'r')
z.extractall(output_directory)
z.close() |
def get_roles(client):
"""Returns a list of all the roles for an account. Returns a list containing all the roles for the account.
Args:
client (:obj:`boto3.session.Session`): A boto3 Session object
Returns:
:obj:`list` of `dict`
"""
done = False
... | Returns a list of all the roles for an account. Returns a list containing all the roles for the account.
Args:
client (:obj:`boto3.session.Session`): A boto3 Session object
Returns:
:obj:`list` of `dict` | Below is the the instruction that describes the task:
### Input:
Returns a list of all the roles for an account. Returns a list containing all the roles for the account.
Args:
client (:obj:`boto3.session.Session`): A boto3 Session object
Returns:
:obj:`list` of `dict`
### R... |
def _read_range(self, start, end=0):
"""
Read a range of bytes in stream.
Args:
start (int): Start stream position.
end (int): End stream position.
0 To not specify end.
Returns:
bytes: number of bytes read
"""
stream ... | Read a range of bytes in stream.
Args:
start (int): Start stream position.
end (int): End stream position.
0 To not specify end.
Returns:
bytes: number of bytes read | Below is the the instruction that describes the task:
### Input:
Read a range of bytes in stream.
Args:
start (int): Start stream position.
end (int): End stream position.
0 To not specify end.
Returns:
bytes: number of bytes read
### Response:
... |
def download(self, path=None, file_obj=None, progressbar=False):
"""Downloads files from One Codex.
Parameters
----------
path : `string`, optional
Full path to save the file to. If omitted, defaults to the original filename
in the current working directory.
... | Downloads files from One Codex.
Parameters
----------
path : `string`, optional
Full path to save the file to. If omitted, defaults to the original filename
in the current working directory.
file_obj : file-like object, optional
Rather than save the f... | Below is the the instruction that describes the task:
### Input:
Downloads files from One Codex.
Parameters
----------
path : `string`, optional
Full path to save the file to. If omitted, defaults to the original filename
in the current working directory.
fil... |
def configure(self, options=None, attribute_options=None): # pylint: disable=W0221
"""
Configures the options and attribute options of the mapping associated
with this representer with the given dictionaries.
:param dict options: configuration options for the mapping associated
... | Configures the options and attribute options of the mapping associated
with this representer with the given dictionaries.
:param dict options: configuration options for the mapping associated
with this representer.
:param dict attribute_options: attribute options for the mapping
... | Below is the the instruction that describes the task:
### Input:
Configures the options and attribute options of the mapping associated
with this representer with the given dictionaries.
:param dict options: configuration options for the mapping associated
with this representer.
:... |
def scanString( self, instring, maxMatches=_MAX_INT, overlap=False ):
"""
Scan the input string for expression matches. Each match will return the
matching tokens, start location, and end location. May be called with optional
C{maxMatches} argument, to clip scanning after 'n' match... | Scan the input string for expression matches. Each match will return the
matching tokens, start location, and end location. May be called with optional
C{maxMatches} argument, to clip scanning after 'n' matches are found. If
C{overlap} is specified, then overlapping matches will be reporte... | Below is the the instruction that describes the task:
### Input:
Scan the input string for expression matches. Each match will return the
matching tokens, start location, and end location. May be called with optional
C{maxMatches} argument, to clip scanning after 'n' matches are found. If
... |
def parse_clubs(self, clubs_page):
"""Parses the DOM and returns user clubs attributes.
:type clubs_page: :class:`bs4.BeautifulSoup`
:param clubs_page: MAL user clubs page's DOM
:rtype: dict
:return: User clubs attributes.
"""
user_info = self.parse_sidebar(clubs_page)
second_col = cl... | Parses the DOM and returns user clubs attributes.
:type clubs_page: :class:`bs4.BeautifulSoup`
:param clubs_page: MAL user clubs page's DOM
:rtype: dict
:return: User clubs attributes. | Below is the the instruction that describes the task:
### Input:
Parses the DOM and returns user clubs attributes.
:type clubs_page: :class:`bs4.BeautifulSoup`
:param clubs_page: MAL user clubs page's DOM
:rtype: dict
:return: User clubs attributes.
### Response:
def parse_clubs(self, clubs_page)... |
def visitExactRange(self, ctx: ShExDocParser.ExactRangeContext):
""" repeatRange: '{' INTEGER '}' #exactRange """
self.expression.min = int(ctx.INTEGER().getText())
self.expression.max = self.expression.min | repeatRange: '{' INTEGER '}' #exactRange | Below is the the instruction that describes the task:
### Input:
repeatRange: '{' INTEGER '}' #exactRange
### Response:
def visitExactRange(self, ctx: ShExDocParser.ExactRangeContext):
""" repeatRange: '{' INTEGER '}' #exactRange """
self.expression.min = int(ctx.INTEGER().getText())
self.e... |
def _disable_socket_timeout(self, socket):
""" Depending on the combination of python version and whether we're
connecting over http or https, we might need to access _sock, which
may or may not exist; or we may need to just settimeout on socket
itself, which also may or may not have set... | Depending on the combination of python version and whether we're
connecting over http or https, we might need to access _sock, which
may or may not exist; or we may need to just settimeout on socket
itself, which also may or may not have settimeout on it. To avoid
missing the correct one... | Below is the the instruction that describes the task:
### Input:
Depending on the combination of python version and whether we're
connecting over http or https, we might need to access _sock, which
may or may not exist; or we may need to just settimeout on socket
itself, which also may or ma... |
def _validate_classpath_tuples(self, classpath, target):
"""Validates that all files are located within the working directory, to simplify relativization.
:param classpath: The list of classpath tuples. Each tuple is a 2-tuple of ivy_conf and
ClasspathEntry.
:param target: The target ... | Validates that all files are located within the working directory, to simplify relativization.
:param classpath: The list of classpath tuples. Each tuple is a 2-tuple of ivy_conf and
ClasspathEntry.
:param target: The target that the classpath tuple is being registered for.
:raises: `... | Below is the the instruction that describes the task:
### Input:
Validates that all files are located within the working directory, to simplify relativization.
:param classpath: The list of classpath tuples. Each tuple is a 2-tuple of ivy_conf and
ClasspathEntry.
:param target: The ta... |
def set_elevation(self, elevation_grid_path, mask_shapefile):
"""
Adds elevation file to project
"""
# ADD ELEVATION FILE
ele_file = ElevationGridFile(project_file=self.project_manager,
session=self.db_session)
ele_file.generateFromRas... | Adds elevation file to project | Below is the the instruction that describes the task:
### Input:
Adds elevation file to project
### Response:
def set_elevation(self, elevation_grid_path, mask_shapefile):
"""
Adds elevation file to project
"""
# ADD ELEVATION FILE
ele_file = ElevationGridFile(project_file=s... |
def _get_preprocessed(self, data):
"""
Returns:
(DeveloperPackage, new_data) 2-tuple IFF the preprocess function
changed the package; otherwise None.
"""
from rez.serialise import process_python_objects
from rez.utils.data_utils import get_dict_diff_str
... | Returns:
(DeveloperPackage, new_data) 2-tuple IFF the preprocess function
changed the package; otherwise None. | Below is the the instruction that describes the task:
### Input:
Returns:
(DeveloperPackage, new_data) 2-tuple IFF the preprocess function
changed the package; otherwise None.
### Response:
def _get_preprocessed(self, data):
"""
Returns:
(DeveloperPackage, new_da... |
def refitPrefixes(self):
"""
Refit namespace qualification by replacing prefixes
with explicit namespaces. Also purges prefix mapping table.
@return: self
@rtype: L{Element}
"""
for c in self.children:
c.refitPrefixes()
if self.prefix is not No... | Refit namespace qualification by replacing prefixes
with explicit namespaces. Also purges prefix mapping table.
@return: self
@rtype: L{Element} | Below is the the instruction that describes the task:
### Input:
Refit namespace qualification by replacing prefixes
with explicit namespaces. Also purges prefix mapping table.
@return: self
@rtype: L{Element}
### Response:
def refitPrefixes(self):
"""
Refit namespace qualif... |
def is_closed_chunk(self, chk):
"""Check the chunk is free or not"""
cs = self.get_chunk_status(chk)
if cs & 0x2 != 0:
return True
return False | Check the chunk is free or not | Below is the the instruction that describes the task:
### Input:
Check the chunk is free or not
### Response:
def is_closed_chunk(self, chk):
"""Check the chunk is free or not"""
cs = self.get_chunk_status(chk)
if cs & 0x2 != 0:
return True
return False |
def resizeColumnsToContents(self):
"""Resize the columns to its contents."""
self._autosized_cols = set()
self._resizeColumnsToContents(self.table_level,
self.table_index, self._max_autosize_ms)
self._update_layout() | Resize the columns to its contents. | Below is the the instruction that describes the task:
### Input:
Resize the columns to its contents.
### Response:
def resizeColumnsToContents(self):
"""Resize the columns to its contents."""
self._autosized_cols = set()
self._resizeColumnsToContents(self.table_level,
... |
def get_article(doi, output_format='txt'):
"""Get the full body of an article from Elsevier.
Parameters
----------
doi : str
The doi for the desired article.
output_format : 'txt' or 'xml'
The desired format for the output. Selecting 'txt' (default) strips all
xml tags and j... | Get the full body of an article from Elsevier.
Parameters
----------
doi : str
The doi for the desired article.
output_format : 'txt' or 'xml'
The desired format for the output. Selecting 'txt' (default) strips all
xml tags and joins the pieces of text in the main text, while 'x... | Below is the the instruction that describes the task:
### Input:
Get the full body of an article from Elsevier.
Parameters
----------
doi : str
The doi for the desired article.
output_format : 'txt' or 'xml'
The desired format for the output. Selecting 'txt' (default) strips all
... |
def _setMetadata(self, text):
"""_setMetadata(self, text) -> PyObject *"""
if self.isClosed or self.isEncrypted:
raise ValueError("operation illegal for closed / encrypted doc")
return _fitz.Document__setMetadata(self, text) | _setMetadata(self, text) -> PyObject * | Below is the the instruction that describes the task:
### Input:
_setMetadata(self, text) -> PyObject *
### Response:
def _setMetadata(self, text):
"""_setMetadata(self, text) -> PyObject *"""
if self.isClosed or self.isEncrypted:
raise ValueError("operation illegal for closed / encrypt... |
def save_model(self, file_name='model.cx'):
"""Save the assembled CX network in a file.
Parameters
----------
file_name : Optional[str]
The name of the file to save the CX network to. Default: model.cx
"""
with open(file_name, 'wt') as fh:
cx_str ... | Save the assembled CX network in a file.
Parameters
----------
file_name : Optional[str]
The name of the file to save the CX network to. Default: model.cx | Below is the the instruction that describes the task:
### Input:
Save the assembled CX network in a file.
Parameters
----------
file_name : Optional[str]
The name of the file to save the CX network to. Default: model.cx
### Response:
def save_model(self, file_name='model.cx'):
... |
def updateScreenshotProgress(self, screenshotHandle, flProgress):
"""
Call this if the application is taking the screen shot
will take more than a few ms processing. This will result
in an overlay being presented that shows a completion
bar.
"""
fn = self.func... | Call this if the application is taking the screen shot
will take more than a few ms processing. This will result
in an overlay being presented that shows a completion
bar. | Below is the the instruction that describes the task:
### Input:
Call this if the application is taking the screen shot
will take more than a few ms processing. This will result
in an overlay being presented that shows a completion
bar.
### Response:
def updateScreenshotProgress(self, sc... |
def makeelement(tagname, tagtext=None, nsprefix='w', attributes=None,
attrnsprefix=None):
'''Create an element & return it'''
# Deal with list of nsprefix by making namespacemap
namespacemap = None
if isinstance(nsprefix, list):
namespacemap = {}
for prefix in nsprefix:
... | Create an element & return it | Below is the the instruction that describes the task:
### Input:
Create an element & return it
### Response:
def makeelement(tagname, tagtext=None, nsprefix='w', attributes=None,
attrnsprefix=None):
'''Create an element & return it'''
# Deal with list of nsprefix by making namespacemap
... |
def putCallback(self,url,headers=""):
'''
Set the callback URL. To be used in place of LongPolling when deploying a webapp.
**note**: make sure you set up a callback URL in your web app
:param str url: complete url, including port, where the callback url is located
:param str headers: Optional - Headers... | Set the callback URL. To be used in place of LongPolling when deploying a webapp.
**note**: make sure you set up a callback URL in your web app
:param str url: complete url, including port, where the callback url is located
:param str headers: Optional - Headers to have Connector send back with all calls
... | Below is the the instruction that describes the task:
### Input:
Set the callback URL. To be used in place of LongPolling when deploying a webapp.
**note**: make sure you set up a callback URL in your web app
:param str url: complete url, including port, where the callback url is located
:param str head... |
def output_after_run_set(self, runSet, cputime=None, walltime=None, energy={}):
"""
The method output_after_run_set() stores the times of a run set in XML.
@params cputime, walltime: accumulated times of the run set
"""
self.add_values_to_run_set_xml(runSet, cputime, walltime, e... | The method output_after_run_set() stores the times of a run set in XML.
@params cputime, walltime: accumulated times of the run set | Below is the the instruction that describes the task:
### Input:
The method output_after_run_set() stores the times of a run set in XML.
@params cputime, walltime: accumulated times of the run set
### Response:
def output_after_run_set(self, runSet, cputime=None, walltime=None, energy={}):
"""
... |
def switch_delete_record_for_userid(self, userid):
"""Remove userid switch record from switch table."""
with get_network_conn() as conn:
conn.execute("DELETE FROM switch WHERE userid=?",
(userid,))
LOG.debug("Switch record for user %s is removed from "
... | Remove userid switch record from switch table. | Below is the the instruction that describes the task:
### Input:
Remove userid switch record from switch table.
### Response:
def switch_delete_record_for_userid(self, userid):
"""Remove userid switch record from switch table."""
with get_network_conn() as conn:
conn.execute("DELETE FRO... |
async def main():
"""
Main code (synchronous requests)
"""
# Create Client from endpoint string in Duniter format
client = Client(BMAS_ENDPOINT)
# Get the node summary infos by dedicated method (with json schema validation)
print("\nCall bma.node.summary:")
response = await client(bma.n... | Main code (synchronous requests) | Below is the the instruction that describes the task:
### Input:
Main code (synchronous requests)
### Response:
async def main():
"""
Main code (synchronous requests)
"""
# Create Client from endpoint string in Duniter format
client = Client(BMAS_ENDPOINT)
# Get the node summary infos by d... |
def term_count_buckets(self):
"""
Returns:
dict: A dictionary that maps occurrence counts to the terms that
appear that many times in the text.
"""
buckets = {}
for term, count in self.term_counts().items():
if count in buckets: buckets[count... | Returns:
dict: A dictionary that maps occurrence counts to the terms that
appear that many times in the text. | Below is the the instruction that describes the task:
### Input:
Returns:
dict: A dictionary that maps occurrence counts to the terms that
appear that many times in the text.
### Response:
def term_count_buckets(self):
"""
Returns:
dict: A dictionary that maps o... |
def main() -> None:
"""
Command-line handler for the ``find_recovered_openxml`` tool.
Use the ``--help`` option for help.
"""
parser = ArgumentParser(
formatter_class=RawDescriptionHelpFormatter,
description="""
Tool to recognize and rescue Microsoft Office OpenXML files, even if the... | Command-line handler for the ``find_recovered_openxml`` tool.
Use the ``--help`` option for help. | Below is the the instruction that describes the task:
### Input:
Command-line handler for the ``find_recovered_openxml`` tool.
Use the ``--help`` option for help.
### Response:
def main() -> None:
"""
Command-line handler for the ``find_recovered_openxml`` tool.
Use the ``--help`` option for help.
... |
def as_sql(self, *args, **kwargs):
"""
Overrides the :class:`SQLUpdateCompiler` method in order to remove any
CTE-related WHERE clauses, which are not necessary for UPDATE queries,
yet may have been added if this query was cloned from a CTEQuery.
:return:
:rtype:
... | Overrides the :class:`SQLUpdateCompiler` method in order to remove any
CTE-related WHERE clauses, which are not necessary for UPDATE queries,
yet may have been added if this query was cloned from a CTEQuery.
:return:
:rtype: | Below is the the instruction that describes the task:
### Input:
Overrides the :class:`SQLUpdateCompiler` method in order to remove any
CTE-related WHERE clauses, which are not necessary for UPDATE queries,
yet may have been added if this query was cloned from a CTEQuery.
:return:
:... |
def _inherited_dashboard(dashboard, base_dashboards_from_pillar, ret):
'''Return a dashboard with properties from parents.'''
base_dashboards = []
for base_dashboard_from_pillar in base_dashboards_from_pillar:
base_dashboard = __salt__['pillar.get'](base_dashboard_from_pillar)
if base_dashbo... | Return a dashboard with properties from parents. | Below is the the instruction that describes the task:
### Input:
Return a dashboard with properties from parents.
### Response:
def _inherited_dashboard(dashboard, base_dashboards_from_pillar, ret):
'''Return a dashboard with properties from parents.'''
base_dashboards = []
for base_dashboard_from_pill... |
def numlistbetween(num1, num2, option='list', listoption='string'):
"""
List Or Count The Numbers Between Two Numbers
"""
if option == 'list':
if listoption == 'string':
output = ''
output += str(num1)
for currentnum in range(num1 + 1, num2 + 1):
... | List Or Count The Numbers Between Two Numbers | Below is the the instruction that describes the task:
### Input:
List Or Count The Numbers Between Two Numbers
### Response:
def numlistbetween(num1, num2, option='list', listoption='string'):
"""
List Or Count The Numbers Between Two Numbers
"""
if option == 'list':
if listoption == 'strin... |
def configuration_get_default_folder():
"""
Return the default folder where user-specific data is stored.
This depends of the system on which Python is running,
:return: path to the user-specific configuration data folder
"""
system = platform.system()
if system == 'Linux':
# https:/... | Return the default folder where user-specific data is stored.
This depends of the system on which Python is running,
:return: path to the user-specific configuration data folder | Below is the the instruction that describes the task:
### Input:
Return the default folder where user-specific data is stored.
This depends of the system on which Python is running,
:return: path to the user-specific configuration data folder
### Response:
def configuration_get_default_folder():
"""
... |
def default_capability(self):
"""Set capability name in md.
Every ResourceSync document should have the top-level
capability attributes.
"""
if ('capability' not in self.md and self.capability_name is not None):
self.md['capability'] = self.capability_name | Set capability name in md.
Every ResourceSync document should have the top-level
capability attributes. | Below is the the instruction that describes the task:
### Input:
Set capability name in md.
Every ResourceSync document should have the top-level
capability attributes.
### Response:
def default_capability(self):
"""Set capability name in md.
Every ResourceSync document should hav... |
def parse_get_list_response(content):
"""Parses of response content XML from WebDAV server and extract file and directory names.
:param content: the XML content of HTTP response from WebDAV server for getting list of files by remote path.
:return: list of extracted file or directory names.
... | Parses of response content XML from WebDAV server and extract file and directory names.
:param content: the XML content of HTTP response from WebDAV server for getting list of files by remote path.
:return: list of extracted file or directory names. | Below is the the instruction that describes the task:
### Input:
Parses of response content XML from WebDAV server and extract file and directory names.
:param content: the XML content of HTTP response from WebDAV server for getting list of files by remote path.
:return: list of extracted file or d... |
def bar(self, x=None, y=None, **kwds):
"""
Vertical bar plot.
A bar plot is a plot that presents categorical data with
rectangular bars with lengths proportional to the values that they
represent. A bar plot shows comparisons among discrete categories. One
axis of the pl... | Vertical bar plot.
A bar plot is a plot that presents categorical data with
rectangular bars with lengths proportional to the values that they
represent. A bar plot shows comparisons among discrete categories. One
axis of the plot shows the specific categories being compared, and the
... | Below is the the instruction that describes the task:
### Input:
Vertical bar plot.
A bar plot is a plot that presents categorical data with
rectangular bars with lengths proportional to the values that they
represent. A bar plot shows comparisons among discrete categories. One
axis... |
def remove_straddlers(events, time, s_freq, toler=0.1):
"""Reject an event if it straddles a stitch, by comparing its
duration to its timespan.
Parameters
----------
events : ndarray (dtype='int')
N x M matrix with start, ..., end samples
time : ndarray (dtype='float')
vector w... | Reject an event if it straddles a stitch, by comparing its
duration to its timespan.
Parameters
----------
events : ndarray (dtype='int')
N x M matrix with start, ..., end samples
time : ndarray (dtype='float')
vector with time points
s_freq : float
sampling frequency
... | Below is the the instruction that describes the task:
### Input:
Reject an event if it straddles a stitch, by comparing its
duration to its timespan.
Parameters
----------
events : ndarray (dtype='int')
N x M matrix with start, ..., end samples
time : ndarray (dtype='float')
ve... |
def _build_dictionary(self, models):
"""
Build a dictionary with the models.
:param models: The models
:type models: Collection
"""
for model in models:
key = getattr(model, self._morph_type, None)
if key:
foreign = getattr(model, ... | Build a dictionary with the models.
:param models: The models
:type models: Collection | Below is the the instruction that describes the task:
### Input:
Build a dictionary with the models.
:param models: The models
:type models: Collection
### Response:
def _build_dictionary(self, models):
"""
Build a dictionary with the models.
:param models: The models
... |
def environ(self):
"""
Add path_info to the request's META dictionary.
"""
environ = dict(self._request.META)
environ['PATH_INFO'] = self._request.path_info
return environ | Add path_info to the request's META dictionary. | Below is the the instruction that describes the task:
### Input:
Add path_info to the request's META dictionary.
### Response:
def environ(self):
"""
Add path_info to the request's META dictionary.
"""
environ = dict(self._request.META)
environ['PATH_INFO'] = self._request.... |
def inversefunc(func,
y_values=None,
domain=None,
image=None,
open_domain=None,
args=(),
accuracy=2):
r"""Obtain the inverse of a function.
Returns the numerical inverse of the function `f`. It may return a callable... | r"""Obtain the inverse of a function.
Returns the numerical inverse of the function `f`. It may return a callable
that can be used to calculate the inverse, or the inverse of certain points
depending on the `y_values` argument.
In order for the numerical inverse to exist in its domain, the
input fu... | Below is the the instruction that describes the task:
### Input:
r"""Obtain the inverse of a function.
Returns the numerical inverse of the function `f`. It may return a callable
that can be used to calculate the inverse, or the inverse of certain points
depending on the `y_values` argument.
In ord... |
def get_field_mapping(self):
"""Obtain metadata from current state of the widget.
Null or empty list will be removed.
:returns: Dictionary of values by type in this format:
{'fields': {}, 'values': {}}.
:rtype: dict
"""
field_mapping = self.field_mapping_wid... | Obtain metadata from current state of the widget.
Null or empty list will be removed.
:returns: Dictionary of values by type in this format:
{'fields': {}, 'values': {}}.
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Obtain metadata from current state of the widget.
Null or empty list will be removed.
:returns: Dictionary of values by type in this format:
{'fields': {}, 'values': {}}.
:rtype: dict
### Response:
def get_field_... |
def burn(self):
"""
Process the template with the data and
config which has been set and return the resulting SVG.
Raises ValueError when no data set has
been added to the graph object.
"""
if not self.data:
raise ValueError("No data available")
if hasattr(self, 'calculations'):
self.calculation... | Process the template with the data and
config which has been set and return the resulting SVG.
Raises ValueError when no data set has
been added to the graph object. | Below is the the instruction that describes the task:
### Input:
Process the template with the data and
config which has been set and return the resulting SVG.
Raises ValueError when no data set has
been added to the graph object.
### Response:
def burn(self):
"""
Process the template with the data and
... |
def finalize_env(env):
"""
Produce a platform specific env for passing into subprocess.Popen
family of external process calling methods, and the supplied env
will be updated on top of it. Returns a new env.
"""
keys = _PLATFORM_ENV_KEYS.get(sys.platform, [])
if 'PATH' not in keys:
... | Produce a platform specific env for passing into subprocess.Popen
family of external process calling methods, and the supplied env
will be updated on top of it. Returns a new env. | Below is the the instruction that describes the task:
### Input:
Produce a platform specific env for passing into subprocess.Popen
family of external process calling methods, and the supplied env
will be updated on top of it. Returns a new env.
### Response:
def finalize_env(env):
"""
Produce a pl... |
def audio_samples(self):
"""
The audio audio_samples, that is, an array of ``float64`` values,
each representing an audio sample in ``[-1.0, 1.0]``.
Note that this function returns a view into the
first ``self.__samples_length`` elements of ``self.__samples``.
If you wan... | The audio audio_samples, that is, an array of ``float64`` values,
each representing an audio sample in ``[-1.0, 1.0]``.
Note that this function returns a view into the
first ``self.__samples_length`` elements of ``self.__samples``.
If you want to clone the values,
you must use e... | Below is the the instruction that describes the task:
### Input:
The audio audio_samples, that is, an array of ``float64`` values,
each representing an audio sample in ``[-1.0, 1.0]``.
Note that this function returns a view into the
first ``self.__samples_length`` elements of ``self.__sampl... |
def _appendComponent(self, baseGlyph, transformation=None, identifier=None, **kwargs):
"""
baseGlyph will be a valid glyph name.
The baseGlyph may or may not be in the layer.
offset will be a valid offset (x, y).
scale will be a valid scale (x, y).
identifier will be a v... | baseGlyph will be a valid glyph name.
The baseGlyph may or may not be in the layer.
offset will be a valid offset (x, y).
scale will be a valid scale (x, y).
identifier will be a valid, nonconflicting identifier.
This must return the new component.
Subclasses may overr... | Below is the the instruction that describes the task:
### Input:
baseGlyph will be a valid glyph name.
The baseGlyph may or may not be in the layer.
offset will be a valid offset (x, y).
scale will be a valid scale (x, y).
identifier will be a valid, nonconflicting identifier.
... |
def add_policy_statements(self, statements):
"""Adds statements to the policy.
Args:
statements (:class:`awacs.aws.Statement` or list): Either a single
Statment, or a list of statements.
"""
if isinstance(statements, Statement):
statements = [stat... | Adds statements to the policy.
Args:
statements (:class:`awacs.aws.Statement` or list): Either a single
Statment, or a list of statements. | Below is the the instruction that describes the task:
### Input:
Adds statements to the policy.
Args:
statements (:class:`awacs.aws.Statement` or list): Either a single
Statment, or a list of statements.
### Response:
def add_policy_statements(self, statements):
"""Adds... |
def make_embedded_push(value):
"""Returns a closure that pushed the given value onto a Machine's stack.
We use this to embed stack pushes in the VM code, so that the interpreter
can assume that all instructions are callable Python functions. This makes
dispatching much faster than checking if an instru... | Returns a closure that pushed the given value onto a Machine's stack.
We use this to embed stack pushes in the VM code, so that the interpreter
can assume that all instructions are callable Python functions. This makes
dispatching much faster than checking if an instruction is a constant
(number, strin... | Below is the the instruction that describes the task:
### Input:
Returns a closure that pushed the given value onto a Machine's stack.
We use this to embed stack pushes in the VM code, so that the interpreter
can assume that all instructions are callable Python functions. This makes
dispatching much fa... |
def update(name=None,
pkgs=None,
refresh=True,
skip_verify=False,
normalize=True,
minimal=False,
obsoletes=False,
**kwargs):
'''
.. versionadded:: 2019.2.0
Calls :py:func:`pkg.upgrade <salt.modules.yumpkg.upgrade>` with
``obso... | .. versionadded:: 2019.2.0
Calls :py:func:`pkg.upgrade <salt.modules.yumpkg.upgrade>` with
``obsoletes=False``. Mirrors the CLI behavior of ``yum update``.
See :py:func:`pkg.upgrade <salt.modules.yumpkg.upgrade>` for
further documentation.
.. code-block:: bash
salt '*' pkg.update | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 2019.2.0
Calls :py:func:`pkg.upgrade <salt.modules.yumpkg.upgrade>` with
``obsoletes=False``. Mirrors the CLI behavior of ``yum update``.
See :py:func:`pkg.upgrade <salt.modules.yumpkg.upgrade>` for
further documenta... |
def updateResults(self, forward=None):
"""
Reload search results or load another "page".
Parameters
----------
forward : bool or None, optional
Whether move forwards or backwards (``True`` or ``False``). If ``None``, then first page is loaded.
"""
#... | Reload search results or load another "page".
Parameters
----------
forward : bool or None, optional
Whether move forwards or backwards (``True`` or ``False``). If ``None``, then first page is loaded. | Below is the the instruction that describes the task:
### Input:
Reload search results or load another "page".
Parameters
----------
forward : bool or None, optional
Whether move forwards or backwards (``True`` or ``False``). If ``None``, then first page is loaded.
### Response:... |
def get_go_server(settings=None):
"""Returns a `gocd.Server` configured by the `settings`
object.
Args:
settings: a `gocd_cli.settings.Settings` object.
Default: if falsey calls `get_settings`.
Returns:
gocd.Server: a configured gocd.Server instance
"""
if not settings:
... | Returns a `gocd.Server` configured by the `settings`
object.
Args:
settings: a `gocd_cli.settings.Settings` object.
Default: if falsey calls `get_settings`.
Returns:
gocd.Server: a configured gocd.Server instance | Below is the the instruction that describes the task:
### Input:
Returns a `gocd.Server` configured by the `settings`
object.
Args:
settings: a `gocd_cli.settings.Settings` object.
Default: if falsey calls `get_settings`.
Returns:
gocd.Server: a configured gocd.Server instance
### ... |
def demo(delay=1, interactive=True):
"""
Play a demo script showing most of the oct2py api features.
Parameters
==========
delay : float
Time between each command in seconds.
"""
script = """
#########################
# Oct2Py demo
#########################... | Play a demo script showing most of the oct2py api features.
Parameters
==========
delay : float
Time between each command in seconds. | Below is the the instruction that describes the task:
### Input:
Play a demo script showing most of the oct2py api features.
Parameters
==========
delay : float
Time between each command in seconds.
### Response:
def demo(delay=1, interactive=True):
"""
Play a demo script showin... |
def dependencies(self, deps_dict):
"""Generate graph file with depenndencies map tree
"""
try:
import pygraphviz as pgv
except ImportError:
graph_easy, comma = "", ""
if (self.image == "ascii" and
not os.path.isfile("/usr/bin/graph-... | Generate graph file with depenndencies map tree | Below is the the instruction that describes the task:
### Input:
Generate graph file with depenndencies map tree
### Response:
def dependencies(self, deps_dict):
"""Generate graph file with depenndencies map tree
"""
try:
import pygraphviz as pgv
except ImportError:
... |
def reset(self):
"""
Empties all internal storage containers
"""
super(MorseComplex, self).reset()
self.base_partitions = {}
self.merge_sequence = {}
self.persistences = []
self.max_indices = []
# State properties
self.persistence = ... | Empties all internal storage containers | Below is the the instruction that describes the task:
### Input:
Empties all internal storage containers
### Response:
def reset(self):
"""
Empties all internal storage containers
"""
super(MorseComplex, self).reset()
self.base_partitions = {}
self.merge_sequenc... |
def get_instance(self, payload):
"""
Build an instance of AuthTypesInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.sip.domain.auth_types.AuthTypesInstance
:rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.AuthTypesIn... | Build an instance of AuthTypesInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.sip.domain.auth_types.AuthTypesInstance
:rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.AuthTypesInstance | Below is the the instruction that describes the task:
### Input:
Build an instance of AuthTypesInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.sip.domain.auth_types.AuthTypesInstance
:rtype: twilio.rest.api.v2010.account.sip.domain.auth_t... |
def boundary_maximum_power(graph, xxx_todo_changeme7):
"""
Boundary term processing adjacent voxels maximum value using a power relationship.
An implementation of a boundary term, suitable to be used with the
`~medpy.graphcut.generate.graph_from_voxels` function.
The same as `boundary_dif... | Boundary term processing adjacent voxels maximum value using a power relationship.
An implementation of a boundary term, suitable to be used with the
`~medpy.graphcut.generate.graph_from_voxels` function.
The same as `boundary_difference_power`, but working on the gradient image instead
of th... | Below is the the instruction that describes the task:
### Input:
Boundary term processing adjacent voxels maximum value using a power relationship.
An implementation of a boundary term, suitable to be used with the
`~medpy.graphcut.generate.graph_from_voxels` function.
The same as `boundary_d... |
def _load_w2v(model_file=_f_model, binary=True):
'''
load word2vec model
'''
if not os.path.exists(model_file):
print("os.path : ", os.path)
raise Exception("Model file [%s] does not exist." % model_file)
return KeyedVectors.load_word2vec_format(
model_file, binary=binary, un... | load word2vec model | Below is the the instruction that describes the task:
### Input:
load word2vec model
### Response:
def _load_w2v(model_file=_f_model, binary=True):
'''
load word2vec model
'''
if not os.path.exists(model_file):
print("os.path : ", os.path)
raise Exception("Model file [%s] does not e... |
def set_threshold_overrides(self, override_dict):
"""
Set manual overrides on the threshold (used for determining
warning/critical status) a dict of limits. See
:py:class:`~.AwsLimitChecker` for information on Warning and
Critical thresholds.
Dict is composed of service ... | Set manual overrides on the threshold (used for determining
warning/critical status) a dict of limits. See
:py:class:`~.AwsLimitChecker` for information on Warning and
Critical thresholds.
Dict is composed of service name keys (string) to dict of
limit names (string), to dict of... | Below is the the instruction that describes the task:
### Input:
Set manual overrides on the threshold (used for determining
warning/critical status) a dict of limits. See
:py:class:`~.AwsLimitChecker` for information on Warning and
Critical thresholds.
Dict is composed of service n... |
def commit_account_debit(self, opcode, account_payment_info, current_block_number, current_vtxindex, current_txid):
"""
Given the account info set by a state-create or state-transition or a token-operation,
debit the relevant account.
Do not call this directly.
Return T... | Given the account info set by a state-create or state-transition or a token-operation,
debit the relevant account.
Do not call this directly.
Return True on success
Abort on error | Below is the the instruction that describes the task:
### Input:
Given the account info set by a state-create or state-transition or a token-operation,
debit the relevant account.
Do not call this directly.
Return True on success
Abort on error
### Response:
def commit_acc... |
def __cache_covered_data(self):
"""!
@brief Cache covered data.
"""
self.__cache_points = True
self.__points = []
for index_point in range(len(self.__data)):
if self.__data[index_point] in self.__spatial_block:
self.__cache_point(in... | !
@brief Cache covered data. | Below is the the instruction that describes the task:
### Input:
!
@brief Cache covered data.
### Response:
def __cache_covered_data(self):
"""!
@brief Cache covered data.
"""
self.__cache_points = True
self.__points = []
for index_point in range(l... |
def _update_pypi_version(self):
"""Get the latest PyPI version (as a string) via the RESTful JSON API"""
logger.debug("Get latest Glances version from the PyPI RESTful API ({})".format(PYPI_API_URL))
# Update the current time
self.data[u'refresh_date'] = datetime.now()
try:
... | Get the latest PyPI version (as a string) via the RESTful JSON API | Below is the the instruction that describes the task:
### Input:
Get the latest PyPI version (as a string) via the RESTful JSON API
### Response:
def _update_pypi_version(self):
"""Get the latest PyPI version (as a string) via the RESTful JSON API"""
logger.debug("Get latest Glances version from th... |
def features_extraction(windowed_signal, functions):
"""
-----
Brief
-----
Function to extract features given in functions, that returns an array with the set of features
for each time window.
-----------
Description
-----------
Machine learning pipelines usually use features to... | -----
Brief
-----
Function to extract features given in functions, that returns an array with the set of features
for each time window.
-----------
Description
-----------
Machine learning pipelines usually use features to represent each sample of the input signals.
Those features s... | Below is the the instruction that describes the task:
### Input:
-----
Brief
-----
Function to extract features given in functions, that returns an array with the set of features
for each time window.
-----------
Description
-----------
Machine learning pipelines usually use feature... |
def import_image_tags(self, name, stream_import, tags, repository, insecure):
"""
Import image tags from a Docker registry into an ImageStream
:return: bool, whether tags were imported
"""
# Get the JSON for the ImageStream
imagestream_json = self.get_image_stream(name)... | Import image tags from a Docker registry into an ImageStream
:return: bool, whether tags were imported | Below is the the instruction that describes the task:
### Input:
Import image tags from a Docker registry into an ImageStream
:return: bool, whether tags were imported
### Response:
def import_image_tags(self, name, stream_import, tags, repository, insecure):
"""
Import image tags from a D... |
def from_ad_date(cls, date):
""" Gets a NepDate object from gregorian calendar date """
functions.check_valid_ad_range(date)
days = values.START_EN_DATE - date
# Add the required number of days to the start nepali date
start_date = NepDate(values.START_NP_YEAR, 1, 1)
# N... | Gets a NepDate object from gregorian calendar date | Below is the the instruction that describes the task:
### Input:
Gets a NepDate object from gregorian calendar date
### Response:
def from_ad_date(cls, date):
""" Gets a NepDate object from gregorian calendar date """
functions.check_valid_ad_range(date)
days = values.START_EN_DATE - date
... |
def _load_tmp_fact(filepath):
"""
Load an 'ongoing fact' from a given location.
Args:
filepath: Full path to the tmpfile location.
Returns:
hamster_lib.Fact: ``Fact`` representing the 'ongoing fact'. Returns ``False``
if no file was found.
Raises:
TypeError: If... | Load an 'ongoing fact' from a given location.
Args:
filepath: Full path to the tmpfile location.
Returns:
hamster_lib.Fact: ``Fact`` representing the 'ongoing fact'. Returns ``False``
if no file was found.
Raises:
TypeError: If for some reason our stored instance is no... | Below is the the instruction that describes the task:
### Input:
Load an 'ongoing fact' from a given location.
Args:
filepath: Full path to the tmpfile location.
Returns:
hamster_lib.Fact: ``Fact`` representing the 'ongoing fact'. Returns ``False``
if no file was found.
Ra... |
def _to_zipfile(self, file_generator):
"""Convert files to zip archive.
:return: None
:rtype: :py:obj:`None`
"""
with zipfile.ZipFile(file_generator.to_path, mode="w", compression=zipfile.ZIP_DEFLATED) as outfile:
for f in file_generator:
outpath = sel... | Convert files to zip archive.
:return: None
:rtype: :py:obj:`None` | Below is the the instruction that describes the task:
### Input:
Convert files to zip archive.
:return: None
:rtype: :py:obj:`None`
### Response:
def _to_zipfile(self, file_generator):
"""Convert files to zip archive.
:return: None
:rtype: :py:obj:`None`
"""
... |
def subset(args):
"""
%prog subset pairsfile ksfile1 ksfile2 ... -o pairs.ks
Subset some pre-calculated ks ka values (in ksfile) according to pairs
in tab delimited pairsfile/anchorfile.
"""
p = OptionParser(subset.__doc__)
p.add_option("--noheader", action="store_true",
he... | %prog subset pairsfile ksfile1 ksfile2 ... -o pairs.ks
Subset some pre-calculated ks ka values (in ksfile) according to pairs
in tab delimited pairsfile/anchorfile. | Below is the the instruction that describes the task:
### Input:
%prog subset pairsfile ksfile1 ksfile2 ... -o pairs.ks
Subset some pre-calculated ks ka values (in ksfile) according to pairs
in tab delimited pairsfile/anchorfile.
### Response:
def subset(args):
"""
%prog subset pairsfile ksfile1 k... |
def copy(self):
"""Return a copy"""
mapping = OrderedDict(self.mapping.items())
return self.__class__(self.key, self.value, mapping) | Return a copy | Below is the the instruction that describes the task:
### Input:
Return a copy
### Response:
def copy(self):
"""Return a copy"""
mapping = OrderedDict(self.mapping.items())
return self.__class__(self.key, self.value, mapping) |
def rename(self, old_key, new_key):
"""Rename a file.
:param old_key: Old key that holds the object.
:param new_key: New key that will hold the object.
:returns: The object that has been renamed.
"""
assert new_key not in self
assert old_key != new_key
f... | Rename a file.
:param old_key: Old key that holds the object.
:param new_key: New key that will hold the object.
:returns: The object that has been renamed. | Below is the the instruction that describes the task:
### Input:
Rename a file.
:param old_key: Old key that holds the object.
:param new_key: New key that will hold the object.
:returns: The object that has been renamed.
### Response:
def rename(self, old_key, new_key):
"""Rename ... |
def ows_security_tween_factory(handler, registry):
"""A tween factory which produces a tween which raises an exception
if access to OWS service is not allowed."""
security = owssecurity_factory(registry)
def ows_security_tween(request):
try:
security.check_request(request)
... | A tween factory which produces a tween which raises an exception
if access to OWS service is not allowed. | Below is the the instruction that describes the task:
### Input:
A tween factory which produces a tween which raises an exception
if access to OWS service is not allowed.
### Response:
def ows_security_tween_factory(handler, registry):
"""A tween factory which produces a tween which raises an exception
... |
def __potential_connection_failure(self, e):
""" OperationalError's are emitted by the _mysql library for
almost every error code emitted by MySQL. Because of this we
verify that the error is actually a connection error before
terminating the connection and firing off a PoolConnectionEx... | OperationalError's are emitted by the _mysql library for
almost every error code emitted by MySQL. Because of this we
verify that the error is actually a connection error before
terminating the connection and firing off a PoolConnectionException | Below is the the instruction that describes the task:
### Input:
OperationalError's are emitted by the _mysql library for
almost every error code emitted by MySQL. Because of this we
verify that the error is actually a connection error before
terminating the connection and firing off a Pool... |
def current(config, **kwargs):
"""
Display the current revision for a database.
"""
with alembic_lock(
config.registry["sqlalchemy.engine"], config.alembic_config()
) as alembic_config:
alembic.command.current(alembic_config, **kwargs) | Display the current revision for a database. | Below is the the instruction that describes the task:
### Input:
Display the current revision for a database.
### Response:
def current(config, **kwargs):
"""
Display the current revision for a database.
"""
with alembic_lock(
config.registry["sqlalchemy.engine"], config.alembic_config()
... |
def get_encoded_url_to_dict(string):
"""
Converts an encoded URL to a dict.
Example: given string = 'a=1&b=2' it returns {'a': 1, 'b': 2}
"""
data = urllib.parse.parse_qsl(string, keep_blank_values=True)
data = dict(data)
return data | Converts an encoded URL to a dict.
Example: given string = 'a=1&b=2' it returns {'a': 1, 'b': 2} | Below is the the instruction that describes the task:
### Input:
Converts an encoded URL to a dict.
Example: given string = 'a=1&b=2' it returns {'a': 1, 'b': 2}
### Response:
def get_encoded_url_to_dict(string):
"""
Converts an encoded URL to a dict.
Example: given string = 'a=1&b=2' it returns {'... |
def ccx(self, ctl1, ctl2, tgt):
"""Apply Toffoli to from ctl1 and ctl2 to tgt."""
return self.append(ToffoliGate(), [ctl1, ctl2, tgt], []) | Apply Toffoli to from ctl1 and ctl2 to tgt. | Below is the the instruction that describes the task:
### Input:
Apply Toffoli to from ctl1 and ctl2 to tgt.
### Response:
def ccx(self, ctl1, ctl2, tgt):
"""Apply Toffoli to from ctl1 and ctl2 to tgt."""
return self.append(ToffoliGate(), [ctl1, ctl2, tgt], []) |
def handle_combo(self,combo,symbol,modifiers,release=False,mod=True):
"""
Handles a key combination and dispatches associated events.
First, all keybind handlers registered via :py:meth:`add` will be handled,
then the pyglet event :peng3d:pgevent:`on_key_combo` with params ``(co... | Handles a key combination and dispatches associated events.
First, all keybind handlers registered via :py:meth:`add` will be handled,
then the pyglet event :peng3d:pgevent:`on_key_combo` with params ``(combo,symbol,modifiers,release,mod)`` is sent to the :py:class:`Peng()` instance.
... | Below is the the instruction that describes the task:
### Input:
Handles a key combination and dispatches associated events.
First, all keybind handlers registered via :py:meth:`add` will be handled,
then the pyglet event :peng3d:pgevent:`on_key_combo` with params ``(combo,symbol,modifiers,... |
def main():
"""
This is the main body of the process that does the work.
Summary:
- load the raw data
- read in rules list
- create log events for AIKIF according to rules [map]
- create new facts / reports based on rules [report]
OUTPUT =
AIKIF mapping : Date_of_... | This is the main body of the process that does the work.
Summary:
- load the raw data
- read in rules list
- create log events for AIKIF according to rules [map]
- create new facts / reports based on rules [report]
OUTPUT =
AIKIF mapping : Date_of_transaction => event
... | Below is the the instruction that describes the task:
### Input:
This is the main body of the process that does the work.
Summary:
- load the raw data
- read in rules list
- create log events for AIKIF according to rules [map]
- create new facts / reports based on rules [report]
OUTPUT... |
def get_datetime_now():
"""
Returns datetime object with current point in time.
In Django 1.4+ it uses Django's django.utils.timezone.now() which returns
an aware or naive datetime that represents the current point in time
when ``USE_TZ`` in project's settings is True or False respectively.
In ... | Returns datetime object with current point in time.
In Django 1.4+ it uses Django's django.utils.timezone.now() which returns
an aware or naive datetime that represents the current point in time
when ``USE_TZ`` in project's settings is True or False respectively.
In older versions of Django it uses dat... | Below is the the instruction that describes the task:
### Input:
Returns datetime object with current point in time.
In Django 1.4+ it uses Django's django.utils.timezone.now() which returns
an aware or naive datetime that represents the current point in time
when ``USE_TZ`` in project's settings is Tr... |
def triangle_areas(p1,p2,p3):
"""Compute an array of triangle areas given three arrays of triangle pts
p1,p2,p3 - three Nx2 arrays of points
"""
v1 = (p2 - p1).astype(np.float)
v2 = (p3 - p1).astype(np.float)
# Original:
# cross1 = v1[:,1] * v2[:,0]
# cross2 = v2[:,1] * v1[:,0]
... | Compute an array of triangle areas given three arrays of triangle pts
p1,p2,p3 - three Nx2 arrays of points | Below is the the instruction that describes the task:
### Input:
Compute an array of triangle areas given three arrays of triangle pts
p1,p2,p3 - three Nx2 arrays of points
### Response:
def triangle_areas(p1,p2,p3):
"""Compute an array of triangle areas given three arrays of triangle pts
p1,... |
def when_i_send_the_request(context, method):
"""
:type method: str
:type context: behave.runner.Context
"""
data = context.apiRequestData
context.apiRequest = context.apiClient.generic(
method,
data['url'],
data=json.dumps(data['params']),
content_type=... | :type method: str
:type context: behave.runner.Context | Below is the the instruction that describes the task:
### Input:
:type method: str
:type context: behave.runner.Context
### Response:
def when_i_send_the_request(context, method):
"""
:type method: str
:type context: behave.runner.Context
"""
data = context.apiRequestData
context... |
def sanitize_word(word):
"""
sanitize a word by removing its accents, special characters, etc
"""
# use an unicode string for `unidecode`
if type(word) == str:
try:
word = word.decode()
except AttributeError:
pass # Python3
# remove trailing spaces
w... | sanitize a word by removing its accents, special characters, etc | Below is the the instruction that describes the task:
### Input:
sanitize a word by removing its accents, special characters, etc
### Response:
def sanitize_word(word):
"""
sanitize a word by removing its accents, special characters, etc
"""
# use an unicode string for `unidecode`
if type(word)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.