code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def default(restart_cb=None, restart_func=None, close_fds=True):
'''Sets up lazarus in default mode.
See the :py:func:`custom` function for a more powerful mode of use.
The default mode of lazarus is to watch all modules rooted at
``PYTHONPATH`` for changes and restart when they take place.
Keywo... | Sets up lazarus in default mode.
See the :py:func:`custom` function for a more powerful mode of use.
The default mode of lazarus is to watch all modules rooted at
``PYTHONPATH`` for changes and restart when they take place.
Keyword arguments:
restart_cb -- Callback invoked prior to restartin... | Below is the the instruction that describes the task:
### Input:
Sets up lazarus in default mode.
See the :py:func:`custom` function for a more powerful mode of use.
The default mode of lazarus is to watch all modules rooted at
``PYTHONPATH`` for changes and restart when they take place.
Keyword ... |
def introspect_table(table):
"""Given a SQLAlchemy Table object, return a Shelf description suitable
for passing to Shelf.from_config.
"""
d = {}
for c in table.columns:
if isinstance(c.type, String):
d[c.name] = {'kind': 'Dimension', 'field': c.name}
if isinstance(c.type... | Given a SQLAlchemy Table object, return a Shelf description suitable
for passing to Shelf.from_config. | Below is the the instruction that describes the task:
### Input:
Given a SQLAlchemy Table object, return a Shelf description suitable
for passing to Shelf.from_config.
### Response:
def introspect_table(table):
"""Given a SQLAlchemy Table object, return a Shelf description suitable
for passing to Shelf... |
def _check_parameter_dependencies(self, parameters):
"""Find out in what order parameters should be called."""
# Warning: parameters only provide reverse dependencies; we reverse them into standard dependencies.
# deep_revdeps: set of fields a field depend indirectly upon
deep_revdeps = ... | Find out in what order parameters should be called. | Below is the the instruction that describes the task:
### Input:
Find out in what order parameters should be called.
### Response:
def _check_parameter_dependencies(self, parameters):
"""Find out in what order parameters should be called."""
# Warning: parameters only provide reverse dependencies; ... |
def _decompress_dicom(dicom_file, output_file):
"""
This function can be used to convert a jpeg compressed image to an uncompressed one for further conversion
:param input_file: single dicom file to decompress
"""
gdcmconv_executable = _get_gdcmconv()
subprocess.check_output([gdcmconv_executab... | This function can be used to convert a jpeg compressed image to an uncompressed one for further conversion
:param input_file: single dicom file to decompress | Below is the the instruction that describes the task:
### Input:
This function can be used to convert a jpeg compressed image to an uncompressed one for further conversion
:param input_file: single dicom file to decompress
### Response:
def _decompress_dicom(dicom_file, output_file):
"""
This function... |
def iter(self, start=0, stop=-1, withscores=False, reverse=None):
""" Return a range of values from sorted set name between
@start and @end sorted in ascending order unless @reverse or
:prop:reversed.
@start and @end: #int, can be negative, indicating the end of
... | Return a range of values from sorted set name between
@start and @end sorted in ascending order unless @reverse or
:prop:reversed.
@start and @end: #int, can be negative, indicating the end of
the range.
@withscores: #bool indicates to return the scores a... | Below is the the instruction that describes the task:
### Input:
Return a range of values from sorted set name between
@start and @end sorted in ascending order unless @reverse or
:prop:reversed.
@start and @end: #int, can be negative, indicating the end of
the r... |
def process():
"""Get process overview."""
pmi = ProcessMemoryInfo()
threads = get_current_threads()
return dict(info=pmi, threads=threads) | Get process overview. | Below is the the instruction that describes the task:
### Input:
Get process overview.
### Response:
def process():
"""Get process overview."""
pmi = ProcessMemoryInfo()
threads = get_current_threads()
return dict(info=pmi, threads=threads) |
def set(self, name, value, **kwargs):
"""Dict-like set() that also supports optional domain and path args in
order to resolve naming collisions from using one cookie jar over
multiple domains.
"""
# support client code that unsets cookies by assignment of a None value:
if... | Dict-like set() that also supports optional domain and path args in
order to resolve naming collisions from using one cookie jar over
multiple domains. | Below is the the instruction that describes the task:
### Input:
Dict-like set() that also supports optional domain and path args in
order to resolve naming collisions from using one cookie jar over
multiple domains.
### Response:
def set(self, name, value, **kwargs):
"""Dict-like set() tha... |
def select_as_dict(self, table_name, columns=None, where=None, extra=None):
"""
Get data in the database and return fetched data as a
|OrderedDict| list.
:param str table_name: |arg_select_table_name|
:param list columns: |arg_select_as_xx_columns|
:param where: |arg_sel... | Get data in the database and return fetched data as a
|OrderedDict| list.
:param str table_name: |arg_select_table_name|
:param list columns: |arg_select_as_xx_columns|
:param where: |arg_select_where|
:type where: |arg_where_type|
:param str extra: |arg_select_extra|
... | Below is the the instruction that describes the task:
### Input:
Get data in the database and return fetched data as a
|OrderedDict| list.
:param str table_name: |arg_select_table_name|
:param list columns: |arg_select_as_xx_columns|
:param where: |arg_select_where|
:type wh... |
def __run_pre_all(self):
"""Execute the pre-all.py and pre-all.sql files if they exist"""
# if the list of delta dirs is [delta1, delta2] the pre scripts of delta2 are
# executed before the pre scripts of delta1
for d in reversed(self.dirs):
pre_all_py_path = os.path.join(d... | Execute the pre-all.py and pre-all.sql files if they exist | Below is the the instruction that describes the task:
### Input:
Execute the pre-all.py and pre-all.sql files if they exist
### Response:
def __run_pre_all(self):
"""Execute the pre-all.py and pre-all.sql files if they exist"""
# if the list of delta dirs is [delta1, delta2] the pre scripts of del... |
def _get_error(self, code, errors, indentation=0):
"""Get error and show the faulty line + some context
Other GLIR implementations may omit this.
"""
# Init
results = []
lines = None
if code is not None:
lines = [line.strip() for line in code.split('\n... | Get error and show the faulty line + some context
Other GLIR implementations may omit this. | Below is the the instruction that describes the task:
### Input:
Get error and show the faulty line + some context
Other GLIR implementations may omit this.
### Response:
def _get_error(self, code, errors, indentation=0):
"""Get error and show the faulty line + some context
Other GLIR imple... |
def do_archive(self, line):
"""archive <identifier> [identifier ...] Mark one or more existing Science
Objects as archived."""
pids = self._split_args(line, 1, -1)
self._command_processor.science_object_archive(pids)
self._print_info_if_verbose(
"Added archive operati... | archive <identifier> [identifier ...] Mark one or more existing Science
Objects as archived. | Below is the the instruction that describes the task:
### Input:
archive <identifier> [identifier ...] Mark one or more existing Science
Objects as archived.
### Response:
def do_archive(self, line):
"""archive <identifier> [identifier ...] Mark one or more existing Science
Objects as archi... |
def lexical_parent(self):
"""Return the lexical parent for this cursor."""
if not hasattr(self, '_lexical_parent'):
self._lexical_parent = conf.lib.clang_getCursorLexicalParent(self)
return self._lexical_parent | Return the lexical parent for this cursor. | Below is the the instruction that describes the task:
### Input:
Return the lexical parent for this cursor.
### Response:
def lexical_parent(self):
"""Return the lexical parent for this cursor."""
if not hasattr(self, '_lexical_parent'):
self._lexical_parent = conf.lib.clang_getCursorLe... |
def action_approve(self):
"""Set a change request as approved."""
for rec in self:
if rec.state not in ['draft', 'to approve']:
raise UserError(
_("Can't approve page in '%s' state.") % rec.state)
if not rec.am_i_approver:
raise... | Set a change request as approved. | Below is the the instruction that describes the task:
### Input:
Set a change request as approved.
### Response:
def action_approve(self):
"""Set a change request as approved."""
for rec in self:
if rec.state not in ['draft', 'to approve']:
raise UserError(
... |
def _update_message_request(self, message):
"""Add row keys and row range to given request message
:type message: class:`data_messages_v2_pb2.ReadRowsRequest`
:param message: The ``ReadRowsRequest`` protobuf
"""
for each in self.row_keys:
message.rows.row_keys.append... | Add row keys and row range to given request message
:type message: class:`data_messages_v2_pb2.ReadRowsRequest`
:param message: The ``ReadRowsRequest`` protobuf | Below is the the instruction that describes the task:
### Input:
Add row keys and row range to given request message
:type message: class:`data_messages_v2_pb2.ReadRowsRequest`
:param message: The ``ReadRowsRequest`` protobuf
### Response:
def _update_message_request(self, message):
"""Add... |
def itertrain(self, train, valid=None, **kwargs):
'''Train a model using a training and validation set.
This method yields a series of monitor values to the caller. After every
iteration, a pair of monitor dictionaries is generated: one evaluated on
the training dataset, and another eva... | Train a model using a training and validation set.
This method yields a series of monitor values to the caller. After every
iteration, a pair of monitor dictionaries is generated: one evaluated on
the training dataset, and another evaluated on the validation dataset.
The validation moni... | Below is the the instruction that describes the task:
### Input:
Train a model using a training and validation set.
This method yields a series of monitor values to the caller. After every
iteration, a pair of monitor dictionaries is generated: one evaluated on
the training dataset, and ano... |
def set_window_option(self, option, value):
"""
Wrapper for ``$ tmux set-window-option <option> <value>``.
Parameters
----------
option : str
option to set, e.g. 'aggressive-resize'
value : str
window option value. True/False will turn in 'on' and... | Wrapper for ``$ tmux set-window-option <option> <value>``.
Parameters
----------
option : str
option to set, e.g. 'aggressive-resize'
value : str
window option value. True/False will turn in 'on' and 'off',
also accepts string of 'on' or 'off' directl... | Below is the the instruction that describes the task:
### Input:
Wrapper for ``$ tmux set-window-option <option> <value>``.
Parameters
----------
option : str
option to set, e.g. 'aggressive-resize'
value : str
window option value. True/False will turn in 'on... |
def previousExon(self) :
"""Returns the previous exon of the transcript, or None if there is none"""
if self.number == 0 :
return None
try :
return self.transcript.exons[self.number-1]
except IndexError :
return None | Returns the previous exon of the transcript, or None if there is none | Below is the the instruction that describes the task:
### Input:
Returns the previous exon of the transcript, or None if there is none
### Response:
def previousExon(self) :
"""Returns the previous exon of the transcript, or None if there is none"""
if self.number == 0 :
return None
try :
return ... |
def _should_ignore(self, path):
"""
Return True iff path should be ignored.
"""
for ignore in self.options.ignores:
if fnmatch.fnmatch(path, ignore):
return True
return False | Return True iff path should be ignored. | Below is the the instruction that describes the task:
### Input:
Return True iff path should be ignored.
### Response:
def _should_ignore(self, path):
"""
Return True iff path should be ignored.
"""
for ignore in self.options.ignores:
if fnmatch.fnmatch(path, ignore):
... |
def priority(self, item):
"""
The priority of the item depends of the number of entries published
in the cache divided by the maximum of entries.
"""
return '%.1f' % max(self.cache[item.pk][0] / self.max_entries, 0.1) | The priority of the item depends of the number of entries published
in the cache divided by the maximum of entries. | Below is the the instruction that describes the task:
### Input:
The priority of the item depends of the number of entries published
in the cache divided by the maximum of entries.
### Response:
def priority(self, item):
"""
The priority of the item depends of the number of entries publishe... |
async def read(self, count=-1):
"""
:py:func:`asyncio.coroutine`
:py:meth:`aioftp.StreamIO.read` proxy
"""
await self.wait("read")
start = _now()
data = await super().read(count)
self.append("read", data, start)
return data | :py:func:`asyncio.coroutine`
:py:meth:`aioftp.StreamIO.read` proxy | Below is the the instruction that describes the task:
### Input:
:py:func:`asyncio.coroutine`
:py:meth:`aioftp.StreamIO.read` proxy
### Response:
async def read(self, count=-1):
"""
:py:func:`asyncio.coroutine`
:py:meth:`aioftp.StreamIO.read` proxy
"""
await self.w... |
def vendorize(vendor_requirements):
"""
This is the main entry point for vendorizing requirements. It expects
a list of tuples that should contain the name of the library and the
version.
For example, a library ``foo`` with version ``0.0.1`` would look like::
vendor_requirements = [
... | This is the main entry point for vendorizing requirements. It expects
a list of tuples that should contain the name of the library and the
version.
For example, a library ``foo`` with version ``0.0.1`` would look like::
vendor_requirements = [
('foo', '0.0.1'),
] | Below is the the instruction that describes the task:
### Input:
This is the main entry point for vendorizing requirements. It expects
a list of tuples that should contain the name of the library and the
version.
For example, a library ``foo`` with version ``0.0.1`` would look like::
vendor_re... |
def _search_show_id(self, series, year=None):
"""Search the show id from the `series` and `year`.
:param str series: series of the episode.
:param year: year of the series, if any.
:type year: int
:return: the show id, if found.
:rtype: int
"""
# addic7e... | Search the show id from the `series` and `year`.
:param str series: series of the episode.
:param year: year of the series, if any.
:type year: int
:return: the show id, if found.
:rtype: int | Below is the the instruction that describes the task:
### Input:
Search the show id from the `series` and `year`.
:param str series: series of the episode.
:param year: year of the series, if any.
:type year: int
:return: the show id, if found.
:rtype: int
### Response:
def... |
def update_xml_element(self):
"""
Updates the xml element contents to matches the instance contents.
:returns: Updated XML element.
:rtype: lxml.etree._Element
"""
super(Description, self).update_xml_element()
if hasattr(self, 'lang'):
self.xml_elem... | Updates the xml element contents to matches the instance contents.
:returns: Updated XML element.
:rtype: lxml.etree._Element | Below is the the instruction that describes the task:
### Input:
Updates the xml element contents to matches the instance contents.
:returns: Updated XML element.
:rtype: lxml.etree._Element
### Response:
def update_xml_element(self):
"""
Updates the xml element contents to matches... |
def _translate_nd(self,
source: mx.nd.NDArray,
source_length: int,
restrict_lexicon: Optional[lexicon.TopKLexicon],
raw_constraints: List[Optional[constrained.RawConstraintList]],
raw_avoid_list: List[Optional[... | Translates source of source_length, given a bucket_key.
:param source: Source ids. Shape: (batch_size, bucket_key, num_factors).
:param source_length: Bucket key.
:param restrict_lexicon: Lexicon to use for vocabulary restriction.
:param raw_constraints: A list of optional constraint li... | Below is the the instruction that describes the task:
### Input:
Translates source of source_length, given a bucket_key.
:param source: Source ids. Shape: (batch_size, bucket_key, num_factors).
:param source_length: Bucket key.
:param restrict_lexicon: Lexicon to use for vocabulary restrict... |
def show_fabric_trunk_info_input_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_fabric_trunk_info = ET.Element("show_fabric_trunk_info")
config = show_fabric_trunk_info
input = ET.SubElement(show_fabric_trunk_info, "input")
... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def show_fabric_trunk_info_input_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_fabric_trunk_info = ET.Element("show_fabric_trunk_info")
... |
def addScalarBar3D(
obj=None,
at=0,
pos=(0, 0, 0),
normal=(0, 0, 1),
sx=0.1,
sy=2,
nlabels=9,
ncols=256,
cmap=None,
c=None,
alpha=1,
):
"""Draw a 3D scalar bar.
``obj`` input can be:
- a list of numbers,
- a list of two numbers in the form `(min, max)... | Draw a 3D scalar bar.
``obj`` input can be:
- a list of numbers,
- a list of two numbers in the form `(min, max)`,
- a ``vtkActor`` already containing a set of scalars associated to vertices or cells,
- if ``None`` the last actor in the list of actors will be used.
.. hint:: |s... | Below is the the instruction that describes the task:
### Input:
Draw a 3D scalar bar.
``obj`` input can be:
- a list of numbers,
- a list of two numbers in the form `(min, max)`,
- a ``vtkActor`` already containing a set of scalars associated to vertices or cells,
- if ``None``... |
def registry_storage(cls):
""" Get registry storage
:return: WTaskDependencyRegistryStorage
"""
if cls.__registry_storage__ is None:
raise ValueError('__registry_storage__ must be defined')
if isinstance(cls.__registry_storage__, WTaskDependencyRegistryStorage) is False:
raise TypeError(
"Property ... | Get registry storage
:return: WTaskDependencyRegistryStorage | Below is the the instruction that describes the task:
### Input:
Get registry storage
:return: WTaskDependencyRegistryStorage
### Response:
def registry_storage(cls):
""" Get registry storage
:return: WTaskDependencyRegistryStorage
"""
if cls.__registry_storage__ is None:
raise ValueError('__registr... |
def receive_message(self, message, data): # noqa: E501 pylint: disable=too-many-return-statements
""" Called when a multizone message is received. """
if data[MESSAGE_TYPE] == TYPE_DEVICE_ADDED:
uuid = data['device']['deviceId']
name = data['device']['name']
self._ad... | Called when a multizone message is received. | Below is the the instruction that describes the task:
### Input:
Called when a multizone message is received.
### Response:
def receive_message(self, message, data): # noqa: E501 pylint: disable=too-many-return-statements
""" Called when a multizone message is received. """
if data[MESSAGE_TYPE] =... |
def error(self, message, *args, **kwargs):
"""Log error with stack trace and locals information.
By default, enables stack trace information in logging messages, so that stacktrace and locals appear in Sentry.
"""
kwargs.setdefault('extra', {}).setdefault('stack', True)
return s... | Log error with stack trace and locals information.
By default, enables stack trace information in logging messages, so that stacktrace and locals appear in Sentry. | Below is the the instruction that describes the task:
### Input:
Log error with stack trace and locals information.
By default, enables stack trace information in logging messages, so that stacktrace and locals appear in Sentry.
### Response:
def error(self, message, *args, **kwargs):
"""Log error... |
def resize(self):
"""
Get target size for a cropped image and do the resizing if we got
anything usable.
"""
resized_size = self.get_resized_size()
if not resized_size:
return
self.image = self.image.resize(resized_size, Image.ANTIALIAS) | Get target size for a cropped image and do the resizing if we got
anything usable. | Below is the the instruction that describes the task:
### Input:
Get target size for a cropped image and do the resizing if we got
anything usable.
### Response:
def resize(self):
"""
Get target size for a cropped image and do the resizing if we got
anything usable.
"""
... |
def strip_wsgi(request):
"""Strip WSGI data out of the request META data."""
meta = copy(request.META)
for key in meta:
if key[:4] == 'wsgi':
meta[key] = None
return meta | Strip WSGI data out of the request META data. | Below is the the instruction that describes the task:
### Input:
Strip WSGI data out of the request META data.
### Response:
def strip_wsgi(request):
"""Strip WSGI data out of the request META data."""
meta = copy(request.META)
for key in meta:
if key[:4] == 'wsgi':
meta[key] = Non... |
def _handle_location(self, location):
"""Return an element located at location with flexible args.
Args:
location: String xpath to use in an Element.find search OR
an Element (which is simply returned).
Returns:
The found Element.
Raises:
... | Return an element located at location with flexible args.
Args:
location: String xpath to use in an Element.find search OR
an Element (which is simply returned).
Returns:
The found Element.
Raises:
ValueError if the location is a string that... | Below is the the instruction that describes the task:
### Input:
Return an element located at location with flexible args.
Args:
location: String xpath to use in an Element.find search OR
an Element (which is simply returned).
Returns:
The found Element.
... |
def log_request_fail(self, method, full_url, body, duration, status_code=None, exception=None):
"""
Log an unsuccessful API call.
"""
logger.warning(
'%s %s [status:%s request:%.3fs]', method, full_url,
status_code or 'N/A', duration, exc_info=exception is not Non... | Log an unsuccessful API call. | Below is the the instruction that describes the task:
### Input:
Log an unsuccessful API call.
### Response:
def log_request_fail(self, method, full_url, body, duration, status_code=None, exception=None):
"""
Log an unsuccessful API call.
"""
logger.warning(
'%s %s [stat... |
def re_flags_str(flags, custom_flags):
"""Convert regexp flags to string.
Parameters
----------
flags : `int`
Flags.
custom_flags : `int`
Custom flags.
Returns
-------
`str`
Flag string.
"""
res = ''
for flag in RE_FLAGS:
if flags & getattr(r... | Convert regexp flags to string.
Parameters
----------
flags : `int`
Flags.
custom_flags : `int`
Custom flags.
Returns
-------
`str`
Flag string. | Below is the the instruction that describes the task:
### Input:
Convert regexp flags to string.
Parameters
----------
flags : `int`
Flags.
custom_flags : `int`
Custom flags.
Returns
-------
`str`
Flag string.
### Response:
def re_flags_str(flags, custom_flags)... |
def _collect_data(directory, input_ext, transcription_ext):
"""Traverses directory collecting input and target files."""
# Directory from string to tuple pair of strings
# key: the filepath to a datafile including the datafile's basename. Example,
# if the datafile was "/path/to/datafile.wav" then the key wou... | Traverses directory collecting input and target files. | Below is the the instruction that describes the task:
### Input:
Traverses directory collecting input and target files.
### Response:
def _collect_data(directory, input_ext, transcription_ext):
"""Traverses directory collecting input and target files."""
# Directory from string to tuple pair of strings
# key... |
def add_compound(self, compound):
"""Add the information of a compound variant
This adds a compound dict to variant['compounds']
Args:
compound (dict): A compound dictionary
"""
logger.debug("Adding compound {0} to variant {1}".format(
compo... | Add the information of a compound variant
This adds a compound dict to variant['compounds']
Args:
compound (dict): A compound dictionary | Below is the the instruction that describes the task:
### Input:
Add the information of a compound variant
This adds a compound dict to variant['compounds']
Args:
compound (dict): A compound dictionary
### Response:
def add_compound(self, compound):
"""Add the info... |
def service_table(format='simple', authenticated=False):
"""
Returns a string depicting all services currently installed.
"""
if authenticated:
all_services = ExchangeUniverse.get_authenticated_services()
else:
all_services = ALL_SERVICES
if format == 'html':
linkify = l... | Returns a string depicting all services currently installed. | Below is the the instruction that describes the task:
### Input:
Returns a string depicting all services currently installed.
### Response:
def service_table(format='simple', authenticated=False):
"""
Returns a string depicting all services currently installed.
"""
if authenticated:
all_ser... |
def POST(self, courseid): # pylint: disable=arguments-differ
""" POST request """
course = self.get_course(courseid)
user_input = web.input()
if "unregister" in user_input and course.allow_unregister():
self.user_manager.course_unregister_user(course, self.user_manager.sess... | POST request | Below is the the instruction that describes the task:
### Input:
POST request
### Response:
def POST(self, courseid): # pylint: disable=arguments-differ
""" POST request """
course = self.get_course(courseid)
user_input = web.input()
if "unregister" in user_input and course.allow_... |
def is_list_of_dict_like(obj, attr=('keys', 'items')):
"""test if object is a list only containing dict like items """
try:
if len(obj) == 0:
return False
return all([is_dict_like(i, attr) for i in obj])
except Exception:
return False | test if object is a list only containing dict like items | Below is the the instruction that describes the task:
### Input:
test if object is a list only containing dict like items
### Response:
def is_list_of_dict_like(obj, attr=('keys', 'items')):
"""test if object is a list only containing dict like items """
try:
if len(obj) == 0:
return Fa... |
def rotate(obj, axis, angle, origin=None):
'''
Rotation around unit vector following the right hand rule
Parameters:
obj : obj to be rotated (e.g. neurite, neuron).
Must implement a transform method.
axis : unit vector for the axis of rotation
angle : rotation angle in r... | Rotation around unit vector following the right hand rule
Parameters:
obj : obj to be rotated (e.g. neurite, neuron).
Must implement a transform method.
axis : unit vector for the axis of rotation
angle : rotation angle in rads
Returns:
A copy of the object with the... | Below is the the instruction that describes the task:
### Input:
Rotation around unit vector following the right hand rule
Parameters:
obj : obj to be rotated (e.g. neurite, neuron).
Must implement a transform method.
axis : unit vector for the axis of rotation
angle : rotat... |
def get(self, key_use, key_type="", owner="", kid=None, **kwargs):
"""
Get all keys that matches a set of search criteria
:param key_use: A key useful for this usage (enc, dec, sig, ver)
:param key_type: Type of key (rsa, ec, oct, ..)
:param owner: Who is the owner of the keys, ... | Get all keys that matches a set of search criteria
:param key_use: A key useful for this usage (enc, dec, sig, ver)
:param key_type: Type of key (rsa, ec, oct, ..)
:param owner: Who is the owner of the keys, "" == me (default)
:param kid: A Key Identifier
:return: A possibly emp... | Below is the the instruction that describes the task:
### Input:
Get all keys that matches a set of search criteria
:param key_use: A key useful for this usage (enc, dec, sig, ver)
:param key_type: Type of key (rsa, ec, oct, ..)
:param owner: Who is the owner of the keys, "" == me (default)... |
def _to_relative_path(self, path):
""":return: Version of path relative to our git directory or raise ValueError
if it is not within our git direcotory"""
if not osp.isabs(path):
return path
if self.repo.bare:
raise InvalidGitRepositoryError("require non-bare repo... | :return: Version of path relative to our git directory or raise ValueError
if it is not within our git direcotory | Below is the the instruction that describes the task:
### Input:
:return: Version of path relative to our git directory or raise ValueError
if it is not within our git direcotory
### Response:
def _to_relative_path(self, path):
""":return: Version of path relative to our git directory or raise Valu... |
def _hardware_count(self):
"""
Amount of hardware resources.
:return: integer
"""
return self._counts.get("hardware") + self._counts.get("serial") + self._counts.get("mbed") | Amount of hardware resources.
:return: integer | Below is the the instruction that describes the task:
### Input:
Amount of hardware resources.
:return: integer
### Response:
def _hardware_count(self):
"""
Amount of hardware resources.
:return: integer
"""
return self._counts.get("hardware") + self._counts.get("s... |
def _CreateFeedMapping(client, feed_details):
"""Creates the feed mapping for DSA page feeds.
Args:
client: an AdWordsClient instance.
feed_details: a _DSAFeedDetails instance.
"""
# Get the FeedMappingService.
feed_mapping_service = client.GetService('FeedMappingService',
... | Creates the feed mapping for DSA page feeds.
Args:
client: an AdWordsClient instance.
feed_details: a _DSAFeedDetails instance. | Below is the the instruction that describes the task:
### Input:
Creates the feed mapping for DSA page feeds.
Args:
client: an AdWordsClient instance.
feed_details: a _DSAFeedDetails instance.
### Response:
def _CreateFeedMapping(client, feed_details):
"""Creates the feed mapping for DSA page feeds.
... |
def list_contributors(self, project_id=None, language_code=None):
"""
Returns the list of contributors
"""
data = self._run(
url_path="contributors/list",
id=project_id,
language=language_code
)
return data['result'].get('contributors',... | Returns the list of contributors | Below is the the instruction that describes the task:
### Input:
Returns the list of contributors
### Response:
def list_contributors(self, project_id=None, language_code=None):
"""
Returns the list of contributors
"""
data = self._run(
url_path="contributors/list",
... |
def InitializeDownload(self, http_request, http=None, client=None):
"""Initialize this download by making a request.
Args:
http_request: The HttpRequest to use to initialize this download.
http: The httplib2.Http instance for this request.
client: If provided, let this cli... | Initialize this download by making a request.
Args:
http_request: The HttpRequest to use to initialize this download.
http: The httplib2.Http instance for this request.
client: If provided, let this client process the final URL before
sending any additional requests.... | Below is the the instruction that describes the task:
### Input:
Initialize this download by making a request.
Args:
http_request: The HttpRequest to use to initialize this download.
http: The httplib2.Http instance for this request.
client: If provided, let this client proces... |
def lookup_family_by_name(name):
"""https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/mngt.c#L106.
Positional arguments:
name -- string.
Returns:
genl_ops class instance or None.
"""
for ops in nl_list_for_each_entry(genl_ops(), genl_ops_list, 'o_list'):
if ops.o_name == n... | https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/mngt.c#L106.
Positional arguments:
name -- string.
Returns:
genl_ops class instance or None. | Below is the the instruction that describes the task:
### Input:
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/mngt.c#L106.
Positional arguments:
name -- string.
Returns:
genl_ops class instance or None.
### Response:
def lookup_family_by_name(name):
"""https://github.com/thom311... |
def is_unitless(ds, variable):
'''
Returns true if the variable is unitless
Note units of '1' are considered whole numbers or parts but still represent
physical units and not the absence of units.
:param netCDF4.Dataset ds: An open netCDF dataset
:param str variable: Name of the variable
'... | Returns true if the variable is unitless
Note units of '1' are considered whole numbers or parts but still represent
physical units and not the absence of units.
:param netCDF4.Dataset ds: An open netCDF dataset
:param str variable: Name of the variable | Below is the the instruction that describes the task:
### Input:
Returns true if the variable is unitless
Note units of '1' are considered whole numbers or parts but still represent
physical units and not the absence of units.
:param netCDF4.Dataset ds: An open netCDF dataset
:param str variable: ... |
def __getChannelId(self):
"""
Obtain channel id for channel name, if present in ``self.search_params``.
"""
if not self.search_params.get("channelId"):
return
api_fixed_url = "https://www.googleapis.com/youtube/v3/channels?part=id&maxResults=1&fields=items%2Fid&"
... | Obtain channel id for channel name, if present in ``self.search_params``. | Below is the the instruction that describes the task:
### Input:
Obtain channel id for channel name, if present in ``self.search_params``.
### Response:
def __getChannelId(self):
"""
Obtain channel id for channel name, if present in ``self.search_params``.
"""
if not self.search_p... |
def _add_to_publish_stack(self, exchange, routing_key, message, properties):
"""Temporarily add the message to the stack to publish to RabbitMQ
:param str exchange: The exchange to publish to
:param str routing_key: The routing key to publish with
:param str message: The message body
... | Temporarily add the message to the stack to publish to RabbitMQ
:param str exchange: The exchange to publish to
:param str routing_key: The routing key to publish with
:param str message: The message body
:param pika.BasicProperties: The message properties | Below is the the instruction that describes the task:
### Input:
Temporarily add the message to the stack to publish to RabbitMQ
:param str exchange: The exchange to publish to
:param str routing_key: The routing key to publish with
:param str message: The message body
:param pika.B... |
def plot_embedding(coordinates, partition=None, add_sphere=False, point_size=8,
colours=None, labels=None, legend=True, outfile=False, **kwargs):
""" plot_embedding(coordinates, partition=None, add_sphere=False, point_size=8,
colours=None, labels=None, legend=True, outfile=False, **kwargs):
Plo... | plot_embedding(coordinates, partition=None, add_sphere=False, point_size=8,
colours=None, labels=None, legend=True, outfile=False, **kwargs):
Plot a 2D / 3D scatterplot of coordinates, optionally
coloured by group membership.
Args:
coordinates: numpy array or treeCl.CoordinateMatrix -
... | Below is the the instruction that describes the task:
### Input:
plot_embedding(coordinates, partition=None, add_sphere=False, point_size=8,
colours=None, labels=None, legend=True, outfile=False, **kwargs):
Plot a 2D / 3D scatterplot of coordinates, optionally
coloured by group membership.
Arg... |
def nack(self, delivery_tag, multiple=False, requeue=False):
'''Send a nack to the broker.'''
args = Writer()
args.write_longlong(delivery_tag).\
write_bits(multiple, requeue)
self.send_frame(MethodFrame(self.channel_id, 60, 120, args)) | Send a nack to the broker. | Below is the the instruction that describes the task:
### Input:
Send a nack to the broker.
### Response:
def nack(self, delivery_tag, multiple=False, requeue=False):
'''Send a nack to the broker.'''
args = Writer()
args.write_longlong(delivery_tag).\
write_bits(multiple, requeu... |
def init_app(self, app):
"""Initialize actions with the app or blueprint.
:param app: the Flask application or blueprint object
:type app: :class:`~flask.Flask` or :class:`~flask.Blueprint`
Examples::
api = Api()
api.add_resource(...)
api.init_app(b... | Initialize actions with the app or blueprint.
:param app: the Flask application or blueprint object
:type app: :class:`~flask.Flask` or :class:`~flask.Blueprint`
Examples::
api = Api()
api.add_resource(...)
api.init_app(blueprint) | Below is the the instruction that describes the task:
### Input:
Initialize actions with the app or blueprint.
:param app: the Flask application or blueprint object
:type app: :class:`~flask.Flask` or :class:`~flask.Blueprint`
Examples::
api = Api()
api.add_resourc... |
def retweeted_tweet(self):
"""
The retweeted Tweet as a Tweet object
If the Tweet is not a Retweet, return None
If the Retweet payload cannot be loaded as a Tweet, this will
raise a `NotATweetError`
Returns:
Tweet: A Tweet representing the retweeted status (o... | The retweeted Tweet as a Tweet object
If the Tweet is not a Retweet, return None
If the Retweet payload cannot be loaded as a Tweet, this will
raise a `NotATweetError`
Returns:
Tweet: A Tweet representing the retweeted status (or None)
(see tweet_embeds.get_retwe... | Below is the the instruction that describes the task:
### Input:
The retweeted Tweet as a Tweet object
If the Tweet is not a Retweet, return None
If the Retweet payload cannot be loaded as a Tweet, this will
raise a `NotATweetError`
Returns:
Tweet: A Tweet representing t... |
def get_healthcheck(value):
"""
Converts input into a :class:`HealthCheck` tuple. Input can be passed as string, tuple, list, or a dictionary. If
set to ``None``, the health check will be set to ``NONE``, i.e. override an existing configuration from the image.
:param value: Health check input.
:typ... | Converts input into a :class:`HealthCheck` tuple. Input can be passed as string, tuple, list, or a dictionary. If
set to ``None``, the health check will be set to ``NONE``, i.e. override an existing configuration from the image.
:param value: Health check input.
:type value: unicode | str | tuple | list | ... | Below is the the instruction that describes the task:
### Input:
Converts input into a :class:`HealthCheck` tuple. Input can be passed as string, tuple, list, or a dictionary. If
set to ``None``, the health check will be set to ``NONE``, i.e. override an existing configuration from the image.
:param value:... |
def create_subscription(
self, topic_name, subscription_name,
lock_duration=30, requires_session=None,
default_message_time_to_live=None,
dead_lettering_on_message_expiration=None,
dead_lettering_on_filter_evaluation_exceptions=None,
enable_batched... | Create a subscription entity.
:param topic_name: The name of the topic under which to create the subscription.
:param subscription_name: The name of the new subscription.
:type subscription_name: str
:param lock_duration: The lock durection in seconds for each message in the subscriptio... | Below is the the instruction that describes the task:
### Input:
Create a subscription entity.
:param topic_name: The name of the topic under which to create the subscription.
:param subscription_name: The name of the new subscription.
:type subscription_name: str
:param lock_durati... |
def nekmin(omega_in,q,x0=0.5,z0=0.5):
'''Computes the position of the neck (minimal radius) in an contact_binary star1'''
def Omega_xz(q,x,z):
return 1./np.sqrt(x**2+z**2)+q/np.sqrt((1-x)**2+z**2)+(q+1)*x**2/2.-q*x
def Omega_xy(q,x,y):
return 1./np.sqrt(x**2+y**2)+q/np.sqrt((1-x)**2+y**2)... | Computes the position of the neck (minimal radius) in an contact_binary star1 | Below is the the instruction that describes the task:
### Input:
Computes the position of the neck (minimal radius) in an contact_binary star1
### Response:
def nekmin(omega_in,q,x0=0.5,z0=0.5):
'''Computes the position of the neck (minimal radius) in an contact_binary star1'''
def Omega_xz(q,x,z):
... |
def install_board_with_programmer(mcu,
programmer,
f_cpu=16000000,
core='arduino',
replace_existing=False,
):
"""install board with programmer."""... | install board with programmer. | Below is the the instruction that describes the task:
### Input:
install board with programmer.
### Response:
def install_board_with_programmer(mcu,
programmer,
f_cpu=16000000,
core='arduino',
... |
def p_annotation_type(self, p):
"""annotation_type : ANNOTATION_TYPE ID NL \
INDENT docsection field_list DEDENT"""
p[0] = AstAnnotationTypeDef(
path=self.path,
lineno=p.lineno(1),
lexpos=p.lexpos(1),
name=p[2],
do... | annotation_type : ANNOTATION_TYPE ID NL \
INDENT docsection field_list DEDENT | Below is the the instruction that describes the task:
### Input:
annotation_type : ANNOTATION_TYPE ID NL \
INDENT docsection field_list DEDENT
### Response:
def p_annotation_type(self, p):
"""annotation_type : ANNOTATION_TYPE ID NL \
INDENT docsec... |
def qn(phi, *n):
"""
Calculate the complex flow vector `Q_n`.
:param array-like phi: Azimuthal angles.
:param int n: One or more harmonics to calculate.
:returns:
A single complex number if only one ``n`` was given or a complex array
for multiple ``n``.
"""
phi = np.ravel... | Calculate the complex flow vector `Q_n`.
:param array-like phi: Azimuthal angles.
:param int n: One or more harmonics to calculate.
:returns:
A single complex number if only one ``n`` was given or a complex array
for multiple ``n``. | Below is the the instruction that describes the task:
### Input:
Calculate the complex flow vector `Q_n`.
:param array-like phi: Azimuthal angles.
:param int n: One or more harmonics to calculate.
:returns:
A single complex number if only one ``n`` was given or a complex array
for mul... |
def element_info(cls_or_slf, node, siblings, level, value_dims):
"""
Return the information summary for an Element. This consists
of the dotted name followed by an value dimension names.
"""
info = cls_or_slf.component_type(node)
if len(node.kdims) >= 1:
info ... | Return the information summary for an Element. This consists
of the dotted name followed by an value dimension names. | Below is the the instruction that describes the task:
### Input:
Return the information summary for an Element. This consists
of the dotted name followed by an value dimension names.
### Response:
def element_info(cls_or_slf, node, siblings, level, value_dims):
"""
Return the information su... |
def wr_data(self, xlsx_data, row_i, worksheet):
"""Write data into xlsx worksheet."""
fld2fmt = self.vars.fld2fmt
# User may specify to skip rows based on values in row
prt_if = self.vars.prt_if
# User may specify a subset of columns to print or
# a column ordering differ... | Write data into xlsx worksheet. | Below is the the instruction that describes the task:
### Input:
Write data into xlsx worksheet.
### Response:
def wr_data(self, xlsx_data, row_i, worksheet):
"""Write data into xlsx worksheet."""
fld2fmt = self.vars.fld2fmt
# User may specify to skip rows based on values in row
prt... |
def stetson_jindex(ftimes, fmags, ferrs, weightbytimediff=False):
'''This calculates the Stetson index for the magseries, based on consecutive
pairs of observations.
Based on Nicole Loncke's work for her Planets and Life certificate at
Princeton in 2014.
Parameters
----------
ftimes,fmags... | This calculates the Stetson index for the magseries, based on consecutive
pairs of observations.
Based on Nicole Loncke's work for her Planets and Life certificate at
Princeton in 2014.
Parameters
----------
ftimes,fmags,ferrs : np.array
The input mag/flux time-series with all non-fin... | Below is the the instruction that describes the task:
### Input:
This calculates the Stetson index for the magseries, based on consecutive
pairs of observations.
Based on Nicole Loncke's work for her Planets and Life certificate at
Princeton in 2014.
Parameters
----------
ftimes,fmags,fer... |
def get_client(self, name):
"""Like :meth:`.get`, but only mechanisms inheriting
:class:`ClientMechanism` will be returned.
Args:
name: The SASL mechanism name.
Returns:
The mechanism object or ``None``
"""
mech = self.get(name)
return m... | Like :meth:`.get`, but only mechanisms inheriting
:class:`ClientMechanism` will be returned.
Args:
name: The SASL mechanism name.
Returns:
The mechanism object or ``None`` | Below is the the instruction that describes the task:
### Input:
Like :meth:`.get`, but only mechanisms inheriting
:class:`ClientMechanism` will be returned.
Args:
name: The SASL mechanism name.
Returns:
The mechanism object or ``None``
### Response:
def get_client... |
def save_b26_file(filename, instruments=None, scripts=None, probes=None, overwrite=False, verbose=False):
"""
save instruments, scripts and probes as a json file
Args:
filename:
instruments:
scripts:
probes: dictionary of the form {instrument_name : probe_1_of_intrument, prob... | save instruments, scripts and probes as a json file
Args:
filename:
instruments:
scripts:
probes: dictionary of the form {instrument_name : probe_1_of_intrument, probe_2_of_intrument, ...}
Returns: | Below is the the instruction that describes the task:
### Input:
save instruments, scripts and probes as a json file
Args:
filename:
instruments:
scripts:
probes: dictionary of the form {instrument_name : probe_1_of_intrument, probe_2_of_intrument, ...}
Returns:
### Response... |
def pw(
ctx,
key_pattern,
user_pattern,
mode,
strict_flag,
user_flag,
file,
edit_subcommand,
gen_subcommand,
):
"""Search for USER and KEY in GPG-encrypted password file."""
# install silent Ctrl-C handler
def handle_sigint(*_):
click.echo()
ctx.exit(1)
... | Search for USER and KEY in GPG-encrypted password file. | Below is the the instruction that describes the task:
### Input:
Search for USER and KEY in GPG-encrypted password file.
### Response:
def pw(
ctx,
key_pattern,
user_pattern,
mode,
strict_flag,
user_flag,
file,
edit_subcommand,
gen_subcommand,
):
"""Search for USER and KEY i... |
def do_ams_post(endpoint, path, body, access_token, rformat="json", ds_min_version="3.0;NetFx"):
'''Do a AMS HTTP POST request and return JSON.
Args:
endpoint (str): Azure Media Services Initial Endpoint.
path (str): Azure Media Services Endpoint Path.
body (str): Azure Media Services C... | Do a AMS HTTP POST request and return JSON.
Args:
endpoint (str): Azure Media Services Initial Endpoint.
path (str): Azure Media Services Endpoint Path.
body (str): Azure Media Services Content Body.
access_token (str): A valid Azure authentication token.
rformat (str): A re... | Below is the the instruction that describes the task:
### Input:
Do a AMS HTTP POST request and return JSON.
Args:
endpoint (str): Azure Media Services Initial Endpoint.
path (str): Azure Media Services Endpoint Path.
body (str): Azure Media Services Content Body.
access_token (... |
def split_bodies(dataset, label=False):
"""Find, label, and split connected bodies/volumes. This splits
different connected bodies into blocks in a MultiBlock dataset.
Parameters
----------
label : bool
A flag on whether to keep the ID arrays given by the
... | Find, label, and split connected bodies/volumes. This splits
different connected bodies into blocks in a MultiBlock dataset.
Parameters
----------
label : bool
A flag on whether to keep the ID arrays given by the
``connectivity`` filter. | Below is the the instruction that describes the task:
### Input:
Find, label, and split connected bodies/volumes. This splits
different connected bodies into blocks in a MultiBlock dataset.
Parameters
----------
label : bool
A flag on whether to keep the ID arrays given ... |
def _raw_aspera_metadata(self, bucket):
''' get the Aspera connection details on Aspera enabled buckets '''
response = self._client.get_bucket_aspera(Bucket=bucket)
# Parse metadata from response
aspera_access_key = response['AccessKey']['Id']
aspera_secret_key = response['Acces... | get the Aspera connection details on Aspera enabled buckets | Below is the the instruction that describes the task:
### Input:
get the Aspera connection details on Aspera enabled buckets
### Response:
def _raw_aspera_metadata(self, bucket):
''' get the Aspera connection details on Aspera enabled buckets '''
response = self._client.get_bucket_aspera(Bucket=buc... |
def positions_to_contigs(positions):
"""Label contigs according to relative positions
Given a list of positions, return an ordered list
of labels reflecting where the positions array started
over (and presumably a new contig began).
Parameters
----------
positions : list or array_like
... | Label contigs according to relative positions
Given a list of positions, return an ordered list
of labels reflecting where the positions array started
over (and presumably a new contig began).
Parameters
----------
positions : list or array_like
A piece-wise ordered list of integers re... | Below is the the instruction that describes the task:
### Input:
Label contigs according to relative positions
Given a list of positions, return an ordered list
of labels reflecting where the positions array started
over (and presumably a new contig began).
Parameters
----------
positions ... |
def write_case_data(self, file):
""" Writes case data to file.
"""
change_code = 0
s_base = self.case.base_mva
timestr = time.strftime("%Y%m%d%H%M", time.gmtime())
file.write("%d, %8.2f, 30 / PSS(tm)E-30 RAW created by Pylon (%s).\n" %
(change_co... | Writes case data to file. | Below is the the instruction that describes the task:
### Input:
Writes case data to file.
### Response:
def write_case_data(self, file):
""" Writes case data to file.
"""
change_code = 0
s_base = self.case.base_mva
timestr = time.strftime("%Y%m%d%H%M", time.gmtime())
... |
def import_dotted_path(path):
"""
Takes a dotted path to a member name in a module, and returns
the member after importing it.
"""
# stolen from Mezzanine (mezzanine.utils.importing.import_dotted_path)
try:
module_path, member_name = path.rsplit(".", 1)
module = import_module(mod... | Takes a dotted path to a member name in a module, and returns
the member after importing it. | Below is the the instruction that describes the task:
### Input:
Takes a dotted path to a member name in a module, and returns
the member after importing it.
### Response:
def import_dotted_path(path):
"""
Takes a dotted path to a member name in a module, and returns
the member after importing it.
... |
def create_from_resource_class(cls, resource_class):
"""
Creates a new representer for the given resource class.
The representer obtains a reference to the (freshly created or looked
up) mapping for the resource class.
"""
mp_reg = get_mapping_registry(cls.content_type)
... | Creates a new representer for the given resource class.
The representer obtains a reference to the (freshly created or looked
up) mapping for the resource class. | Below is the the instruction that describes the task:
### Input:
Creates a new representer for the given resource class.
The representer obtains a reference to the (freshly created or looked
up) mapping for the resource class.
### Response:
def create_from_resource_class(cls, resource_class):
... |
def merge_model_instances(self, primary_object, alias_objects):
"""
Merge several model instances into one, the `primary_object`.
Use this function to merge model objects and migrate all of the related
fields from the alias objects the primary object.
"""
generic_fields =... | Merge several model instances into one, the `primary_object`.
Use this function to merge model objects and migrate all of the related
fields from the alias objects the primary object. | Below is the the instruction that describes the task:
### Input:
Merge several model instances into one, the `primary_object`.
Use this function to merge model objects and migrate all of the related
fields from the alias objects the primary object.
### Response:
def merge_model_instances(self, prim... |
def read_property_to_result_element(obj, propertyIdentifier, propertyArrayIndex=None):
"""Read the specified property of the object, with the optional array index,
and cast the result into an Any object."""
if _debug: read_property_to_result_element._debug("read_property_to_result_element %s %r %r", obj, pr... | Read the specified property of the object, with the optional array index,
and cast the result into an Any object. | Below is the the instruction that describes the task:
### Input:
Read the specified property of the object, with the optional array index,
and cast the result into an Any object.
### Response:
def read_property_to_result_element(obj, propertyIdentifier, propertyArrayIndex=None):
"""Read the specified prope... |
def _truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100):
"""
Truncates a colormap to use.
Code originall from http://stackoverflow.com/questions/18926031/how-to-extract-a-subset-of-a-colormap-as-a-new-colormap-in-matplotlib
"""
new_cmap = LinearSegmentedColormap.from_list(
'trunc({n},{a:... | Truncates a colormap to use.
Code originall from http://stackoverflow.com/questions/18926031/how-to-extract-a-subset-of-a-colormap-as-a-new-colormap-in-matplotlib | Below is the the instruction that describes the task:
### Input:
Truncates a colormap to use.
Code originall from http://stackoverflow.com/questions/18926031/how-to-extract-a-subset-of-a-colormap-as-a-new-colormap-in-matplotlib
### Response:
def _truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100):
"""
... |
def safe_tag(self, tag, errors='strict'):
"""URL Encode and truncate tag to match limit (128 characters) of ThreatConnect API.
Args:
tag (string): The tag to be truncated
Returns:
(string): The truncated tag
"""
if tag is not None:
try:
... | URL Encode and truncate tag to match limit (128 characters) of ThreatConnect API.
Args:
tag (string): The tag to be truncated
Returns:
(string): The truncated tag | Below is the the instruction that describes the task:
### Input:
URL Encode and truncate tag to match limit (128 characters) of ThreatConnect API.
Args:
tag (string): The tag to be truncated
Returns:
(string): The truncated tag
### Response:
def safe_tag(self, tag, errors='... |
def current_consumption(self):
"""Get the current power consumption in Watt."""
res = 'N/A'
if self.use_legacy_protocol:
# Use /my_cgi.cgi to retrieve current consumption
try:
res = self.fetchMyCgi()['Meter Watt']
except:
return... | Get the current power consumption in Watt. | Below is the the instruction that describes the task:
### Input:
Get the current power consumption in Watt.
### Response:
def current_consumption(self):
"""Get the current power consumption in Watt."""
res = 'N/A'
if self.use_legacy_protocol:
# Use /my_cgi.cgi to retrieve curren... |
def make_worker_pool(
processes=None,
initializer=None,
initializer_kwargs_per_process=None,
max_tasks_per_worker=None):
"""
Convenience wrapper to create a multiprocessing.Pool.
This function adds support for per-worker initializer arguments, which are
not natively supp... | Convenience wrapper to create a multiprocessing.Pool.
This function adds support for per-worker initializer arguments, which are
not natively supported by the multiprocessing module. The motivation for
this feature is to support allocating each worker to a (different) GPU.
IMPLEMENTATION NOTE:
... | Below is the the instruction that describes the task:
### Input:
Convenience wrapper to create a multiprocessing.Pool.
This function adds support for per-worker initializer arguments, which are
not natively supported by the multiprocessing module. The motivation for
this feature is to support allocatin... |
def get_words(self):
""" Get words matching the request search terms.
Returns:
A dict in form:
{<search term>: {<matching word>: <number of times this word is found in the Storage>
} // Repeated for every matching word.
... | Get words matching the request search terms.
Returns:
A dict in form:
{<search term>: {<matching word>: <number of times this word is found in the Storage>
} // Repeated for every matching word.
} // Repeated for ev... | Below is the the instruction that describes the task:
### Input:
Get words matching the request search terms.
Returns:
A dict in form:
{<search term>: {<matching word>: <number of times this word is found in the Storage>
} // Repea... |
def send(self, s):
"""
Sends all the given data to the socket.
Aliases: write, put, sendall, send_all
"""
self._print_header('======== Sending ({0}) ========'.format(len(s)))
self._log_send(s)
out = len(s)
while s:
s = s[self._send(s):]
... | Sends all the given data to the socket.
Aliases: write, put, sendall, send_all | Below is the the instruction that describes the task:
### Input:
Sends all the given data to the socket.
Aliases: write, put, sendall, send_all
### Response:
def send(self, s):
"""
Sends all the given data to the socket.
Aliases: write, put, sendall, send_all
"""
s... |
def _harvest_validate(self, userkwargs):
"""Validate and Plant user provided arguments
- Go through and plants the seedlings
for any user arguments provided.
- Validate the arguments, cleaning and adapting (valideer wise)
- Extract negatives "!" arguments
"""
# ... | Validate and Plant user provided arguments
- Go through and plants the seedlings
for any user arguments provided.
- Validate the arguments, cleaning and adapting (valideer wise)
- Extract negatives "!" arguments | Below is the the instruction that describes the task:
### Input:
Validate and Plant user provided arguments
- Go through and plants the seedlings
for any user arguments provided.
- Validate the arguments, cleaning and adapting (valideer wise)
- Extract negatives "!" arguments
### R... |
def get_grad_zmat(self, construction_table, as_function=True):
r"""Return the gradient for the transformation to a Zmatrix.
If ``as_function`` is True, a function is returned that can be directly
applied onto instances of :class:`~Cartesian`, which contain the
applied distortions in car... | r"""Return the gradient for the transformation to a Zmatrix.
If ``as_function`` is True, a function is returned that can be directly
applied onto instances of :class:`~Cartesian`, which contain the
applied distortions in cartesian space.
In this case the user does not have to worry abou... | Below is the the instruction that describes the task:
### Input:
r"""Return the gradient for the transformation to a Zmatrix.
If ``as_function`` is True, a function is returned that can be directly
applied onto instances of :class:`~Cartesian`, which contain the
applied distortions in carte... |
def get_name(key):
"""Given a keyword, try to get the name of it.
.. versionadded:: 4.2
Definition dicts are defined in keywords.py. We try to return
the name if present, otherwise we return none.
keyword = 'layer_purpose'
kio = safe.utilities.keyword_io.Keyword_IO()
name = kio.get_name(k... | Given a keyword, try to get the name of it.
.. versionadded:: 4.2
Definition dicts are defined in keywords.py. We try to return
the name if present, otherwise we return none.
keyword = 'layer_purpose'
kio = safe.utilities.keyword_io.Keyword_IO()
name = kio.get_name(keyword)
print name
... | Below is the the instruction that describes the task:
### Input:
Given a keyword, try to get the name of it.
.. versionadded:: 4.2
Definition dicts are defined in keywords.py. We try to return
the name if present, otherwise we return none.
keyword = 'layer_purpose'
kio = safe.utilities.keywor... |
def _names(lexer):
"""Return a tuple of names."""
first = _expect_token(lexer, {NameToken}).value
rest = _zom_name(lexer)
rnames = (first, ) + rest
return rnames[::-1] | Return a tuple of names. | Below is the the instruction that describes the task:
### Input:
Return a tuple of names.
### Response:
def _names(lexer):
"""Return a tuple of names."""
first = _expect_token(lexer, {NameToken}).value
rest = _zom_name(lexer)
rnames = (first, ) + rest
return rnames[::-1] |
def waveform_image(mediafile, xy_size, outdir=None, center_color=None, outer_color=None, bg_color=None):
""" Create waveform image from audio data.
Return path to created image file.
"""
try:
import waveform
except ImportError, exc:
raise ImportError("%s [get it at https://github... | Create waveform image from audio data.
Return path to created image file. | Below is the the instruction that describes the task:
### Input:
Create waveform image from audio data.
Return path to created image file.
### Response:
def waveform_image(mediafile, xy_size, outdir=None, center_color=None, outer_color=None, bg_color=None):
""" Create waveform image from audio data.
... |
def update_processcount(self, plist):
"""Update the global process count from the current processes list"""
# Update the maximum process ID (pid) number
self.processcount['pid_max'] = self.pid_max
# For each key in the processcount dict
# count the number of processes with the sa... | Update the global process count from the current processes list | Below is the the instruction that describes the task:
### Input:
Update the global process count from the current processes list
### Response:
def update_processcount(self, plist):
"""Update the global process count from the current processes list"""
# Update the maximum process ID (pid) number
... |
def UpdateLease(self, duration):
"""Updates the lease and flushes the object.
The lease is set to expire after the "duration" time from the present
moment.
This method is supposed to be used when operation that requires locking
may run for a time that exceeds the lease time specified in OpenWithLoc... | Updates the lease and flushes the object.
The lease is set to expire after the "duration" time from the present
moment.
This method is supposed to be used when operation that requires locking
may run for a time that exceeds the lease time specified in OpenWithLock().
See flows/hunts locking for an ... | Below is the the instruction that describes the task:
### Input:
Updates the lease and flushes the object.
The lease is set to expire after the "duration" time from the present
moment.
This method is supposed to be used when operation that requires locking
may run for a time that exceeds the lease ... |
def prepare_args(model_matrix,
response,
model_coefficients,
predicted_linear_response,
offset,
name=None):
"""Helper to `fit` which sanitizes input args.
Args:
model_matrix: (Batch of) `float`-like, matrix-shaped `Tensor` whe... | Helper to `fit` which sanitizes input args.
Args:
model_matrix: (Batch of) `float`-like, matrix-shaped `Tensor` where each row
represents a sample's features.
response: (Batch of) vector-shaped `Tensor` where each element represents a
sample's observed response (to the corresponding row of featur... | Below is the the instruction that describes the task:
### Input:
Helper to `fit` which sanitizes input args.
Args:
model_matrix: (Batch of) `float`-like, matrix-shaped `Tensor` where each row
represents a sample's features.
response: (Batch of) vector-shaped `Tensor` where each element represents a... |
def parallel_prep_region(samples, run_parallel):
"""Perform full pre-variant calling BAM prep work on regions.
"""
file_key = "work_bam"
split_fn = _split_by_regions("bamprep", "-prep.bam", file_key)
# identify samples that do not need preparation -- no recalibration or realignment
extras = []
... | Perform full pre-variant calling BAM prep work on regions. | Below is the the instruction that describes the task:
### Input:
Perform full pre-variant calling BAM prep work on regions.
### Response:
def parallel_prep_region(samples, run_parallel):
"""Perform full pre-variant calling BAM prep work on regions.
"""
file_key = "work_bam"
split_fn = _split_by_reg... |
def manage_subscription():
"""Shows how to interact with a parameter subscription."""
subscription = processor.create_parameter_subscription([
'/YSS/SIMULATOR/BatteryVoltage1'
])
sleep(5)
print('Adding extra items to the existing subscription...')
subscription.add([
'/YSS/SIMUL... | Shows how to interact with a parameter subscription. | Below is the the instruction that describes the task:
### Input:
Shows how to interact with a parameter subscription.
### Response:
def manage_subscription():
"""Shows how to interact with a parameter subscription."""
subscription = processor.create_parameter_subscription([
'/YSS/SIMULATOR/BatteryV... |
def kl_divergence(mu, log_var, mu_p=0.0, log_var_p=0.0):
"""KL divergence of diagonal gaussian N(mu,exp(log_var)) and N(0,1).
Args:
mu: mu parameter of the distribution.
log_var: log(var) parameter of the distribution.
mu_p: optional mu from a learned prior distribution
log_var_p: optional log(var)... | KL divergence of diagonal gaussian N(mu,exp(log_var)) and N(0,1).
Args:
mu: mu parameter of the distribution.
log_var: log(var) parameter of the distribution.
mu_p: optional mu from a learned prior distribution
log_var_p: optional log(var) from a learned prior distribution
Returns:
the KL loss. | Below is the the instruction that describes the task:
### Input:
KL divergence of diagonal gaussian N(mu,exp(log_var)) and N(0,1).
Args:
mu: mu parameter of the distribution.
log_var: log(var) parameter of the distribution.
mu_p: optional mu from a learned prior distribution
log_var_p: optional l... |
def get_connected_services(self, project_id, kind=None):
"""GetConnectedServices.
[Preview API]
:param str project_id:
:param str kind:
:rtype: [WebApiConnectedService]
"""
route_values = {}
if project_id is not None:
route_values['projectId'] ... | GetConnectedServices.
[Preview API]
:param str project_id:
:param str kind:
:rtype: [WebApiConnectedService] | Below is the the instruction that describes the task:
### Input:
GetConnectedServices.
[Preview API]
:param str project_id:
:param str kind:
:rtype: [WebApiConnectedService]
### Response:
def get_connected_services(self, project_id, kind=None):
"""GetConnectedServices.
... |
def create_cfg(self, cfg_file, defaults=None, mode='json'):
'''
set mode to json or yaml? probably remove this option..Todo
Creates the config file for your app with default values
The file will only be created if it doesn't exits
also sets up the first_run attribute.
... | set mode to json or yaml? probably remove this option..Todo
Creates the config file for your app with default values
The file will only be created if it doesn't exits
also sets up the first_run attribute.
also sets correct windows permissions
you can add custom stuff to the c... | Below is the the instruction that describes the task:
### Input:
set mode to json or yaml? probably remove this option..Todo
Creates the config file for your app with default values
The file will only be created if it doesn't exits
also sets up the first_run attribute.
also sets c... |
def cookies(self) -> Mapping[str, str]:
"""Return request cookies.
A read-only dictionary-like object.
"""
raw = self.headers.get(hdrs.COOKIE, '')
parsed = SimpleCookie(raw)
return MappingProxyType(
{key: val.value for key, val in parsed.items()}) | Return request cookies.
A read-only dictionary-like object. | Below is the the instruction that describes the task:
### Input:
Return request cookies.
A read-only dictionary-like object.
### Response:
def cookies(self) -> Mapping[str, str]:
"""Return request cookies.
A read-only dictionary-like object.
"""
raw = self.headers.get(hdrs... |
async def receive_bilateral_response(self):
"""Receive the response to a request made to the Watchman service."""
self._check_receive_loop()
resp = await self.bilateral_response_queue.get()
self._check_error(resp)
return resp | Receive the response to a request made to the Watchman service. | Below is the the instruction that describes the task:
### Input:
Receive the response to a request made to the Watchman service.
### Response:
async def receive_bilateral_response(self):
"""Receive the response to a request made to the Watchman service."""
self._check_receive_loop()
resp =... |
def get_inline_func(inline_str, modules=None, **stream_kwargs):
"""returns a function decorated by `cbox.stream` decorator.
:param str inline_str: the inline function to execute,
can use `s` - local variable as the input line/char/raw
(according to `input_type` param).
:param str modules: comma... | returns a function decorated by `cbox.stream` decorator.
:param str inline_str: the inline function to execute,
can use `s` - local variable as the input line/char/raw
(according to `input_type` param).
:param str modules: comma separated list of modules to import before
running the inline fu... | Below is the the instruction that describes the task:
### Input:
returns a function decorated by `cbox.stream` decorator.
:param str inline_str: the inline function to execute,
can use `s` - local variable as the input line/char/raw
(according to `input_type` param).
:param str modules: comma s... |
def add_callback(self, callback, *callback_args, **callback_kwargs):
"""Add a callback without an associated errback."""
return self.add_callbacks(callback, callback_args=callback_args,
callback_kwargs=callback_kwargs) | Add a callback without an associated errback. | Below is the the instruction that describes the task:
### Input:
Add a callback without an associated errback.
### Response:
def add_callback(self, callback, *callback_args, **callback_kwargs):
"""Add a callback without an associated errback."""
return self.add_callbacks(callback, callback_args=cal... |
def load_hdf(cls, filename, path='', name=None):
"""
A class method to load a saved StarModel from an HDF5 file.
File must have been created by a call to :func:`StarModel.save_hdf`.
:param filename:
H5 file to load.
:param path: (optional)
Path within H... | A class method to load a saved StarModel from an HDF5 file.
File must have been created by a call to :func:`StarModel.save_hdf`.
:param filename:
H5 file to load.
:param path: (optional)
Path within HDF file.
:return:
:class:`StarModel` object. | Below is the the instruction that describes the task:
### Input:
A class method to load a saved StarModel from an HDF5 file.
File must have been created by a call to :func:`StarModel.save_hdf`.
:param filename:
H5 file to load.
:param path: (optional)
Path within H... |
def find_playlists_by_ids(self, playlist_ids):
"""doc: http://open.youku.com/docs/doc?id=67
"""
url = 'https://openapi.youku.com/v2/playlists/show_batch.json'
params = {
'client_id': self.client_id,
'playlist_ids': playlist_ids
}
r = requests.get(u... | doc: http://open.youku.com/docs/doc?id=67 | Below is the the instruction that describes the task:
### Input:
doc: http://open.youku.com/docs/doc?id=67
### Response:
def find_playlists_by_ids(self, playlist_ids):
"""doc: http://open.youku.com/docs/doc?id=67
"""
url = 'https://openapi.youku.com/v2/playlists/show_batch.json'
par... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.