code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _parse_description(html_chunk):
"""
Parse description of the book.
Args:
html_chunk (obj): HTMLElement containing slice of the page with details.
Returns:
str/None: Description as string or None if not found.
"""
description_tag = html_chunk.match(
["div", {"class":... | Parse description of the book.
Args:
html_chunk (obj): HTMLElement containing slice of the page with details.
Returns:
str/None: Description as string or None if not found. | Below is the the instruction that describes the task:
### Input:
Parse description of the book.
Args:
html_chunk (obj): HTMLElement containing slice of the page with details.
Returns:
str/None: Description as string or None if not found.
### Response:
def _parse_description(html_chunk):
... |
def context_value(name):
"""
Returns an effect that drops the current value, and replaces it with
the value from the context with the given name.
"""
def context_value(_value, context, **_params):
return defer.succeed(context[name])
return context_value | Returns an effect that drops the current value, and replaces it with
the value from the context with the given name. | Below is the the instruction that describes the task:
### Input:
Returns an effect that drops the current value, and replaces it with
the value from the context with the given name.
### Response:
def context_value(name):
"""
Returns an effect that drops the current value, and replaces it with
the v... |
def any_slug_field(field, **kwargs):
"""
Return random value for SlugField
>>> result = any_field(models.SlugField())
>>> type(result)
<type 'str'>
>>> from django.core.validators import slug_re
>>> re.match(slug_re, result) is not None
True
"""
letters = ascii_letters ... | Return random value for SlugField
>>> result = any_field(models.SlugField())
>>> type(result)
<type 'str'>
>>> from django.core.validators import slug_re
>>> re.match(slug_re, result) is not None
True | Below is the the instruction that describes the task:
### Input:
Return random value for SlugField
>>> result = any_field(models.SlugField())
>>> type(result)
<type 'str'>
>>> from django.core.validators import slug_re
>>> re.match(slug_re, result) is not None
True
### Response:
def a... |
def close(self):
"""Cleanly shutdown the connection to RabbitMQ
:raises: sprockets.mixins.amqp.ConnectionStateError
"""
if not self.closable:
LOGGER.warning('Closed called while %s', self.state_description)
raise ConnectionStateError(self.state_description)
... | Cleanly shutdown the connection to RabbitMQ
:raises: sprockets.mixins.amqp.ConnectionStateError | Below is the the instruction that describes the task:
### Input:
Cleanly shutdown the connection to RabbitMQ
:raises: sprockets.mixins.amqp.ConnectionStateError
### Response:
def close(self):
"""Cleanly shutdown the connection to RabbitMQ
:raises: sprockets.mixins.amqp.ConnectionStateErro... |
def _backup_pb_tqdm(self, dirs):
"""Create a backup with a tqdm progress bar."""
with ZipFile(self.zip_filename, 'w') as backup_zip:
for path in tqdm(dirs, desc='Writing Zip Files', total=len(dirs)):
backup_zip.write(path, path[len(self.source):len(path)]) | Create a backup with a tqdm progress bar. | Below is the the instruction that describes the task:
### Input:
Create a backup with a tqdm progress bar.
### Response:
def _backup_pb_tqdm(self, dirs):
"""Create a backup with a tqdm progress bar."""
with ZipFile(self.zip_filename, 'w') as backup_zip:
for path in tqdm(dirs, desc='Writ... |
def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(NetstatCollector, self).get_default_config()
config.update({
'path': 'netstat',
})
return config | Returns the default collector settings | Below is the the instruction that describes the task:
### Input:
Returns the default collector settings
### Response:
def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(NetstatCollector, self).get_default_config()
config.update({
... |
def discover(scope, loglevel, capture):
"Discover systems using WS-Discovery"
if loglevel:
level = getattr(logging, loglevel, None)
if not level:
print("Invalid log level '%s'" % loglevel)
return
logger.setLevel(level)
run(scope=scope, capture=capture) | Discover systems using WS-Discovery | Below is the the instruction that describes the task:
### Input:
Discover systems using WS-Discovery
### Response:
def discover(scope, loglevel, capture):
"Discover systems using WS-Discovery"
if loglevel:
level = getattr(logging, loglevel, None)
if not level:
print("Invalid log... |
def _ReadStreamDataTypeDefinition(
self, definitions_registry, definition_values, definition_name,
is_member=False):
"""Reads a stream data type definition.
Args:
definitions_registry (DataTypeDefinitionsRegistry): data type definitions
registry.
definition_values (dict[str, o... | Reads a stream data type definition.
Args:
definitions_registry (DataTypeDefinitionsRegistry): data type definitions
registry.
definition_values (dict[str, object]): definition values.
definition_name (str): name of the definition.
is_member (Optional[bool]): True if the data type... | Below is the the instruction that describes the task:
### Input:
Reads a stream data type definition.
Args:
definitions_registry (DataTypeDefinitionsRegistry): data type definitions
registry.
definition_values (dict[str, object]): definition values.
definition_name (str): name of th... |
def setParent(self,parent):
"""
Sets the parent of this bone for all entities.
Note that this method must be called before many other methods to ensure internal state has been initialized.
This method also registers this bone as a child of its parent.
"""
... | Sets the parent of this bone for all entities.
Note that this method must be called before many other methods to ensure internal state has been initialized.
This method also registers this bone as a child of its parent. | Below is the the instruction that describes the task:
### Input:
Sets the parent of this bone for all entities.
Note that this method must be called before many other methods to ensure internal state has been initialized.
This method also registers this bone as a child of its paren... |
async def open(self, wait_for_completion=True):
"""Open window.
Parameters:
* wait_for_completion: If set, function will return
after device has reached target position.
"""
await self.set_position(
position=Position(position_percent=0),
... | Open window.
Parameters:
* wait_for_completion: If set, function will return
after device has reached target position. | Below is the the instruction that describes the task:
### Input:
Open window.
Parameters:
* wait_for_completion: If set, function will return
after device has reached target position.
### Response:
async def open(self, wait_for_completion=True):
"""Open window.
... |
def add(self, cell, overwrite_duplicate=False):
"""
Add one or more cells to the library.
Parameters
----------
cell : ``Cell`` of list of ``Cell``
Cells to be included in the library.
overwrite_duplicate : bool
If True an existing cell with the s... | Add one or more cells to the library.
Parameters
----------
cell : ``Cell`` of list of ``Cell``
Cells to be included in the library.
overwrite_duplicate : bool
If True an existing cell with the same name in the library
will be overwritten.
Re... | Below is the the instruction that describes the task:
### Input:
Add one or more cells to the library.
Parameters
----------
cell : ``Cell`` of list of ``Cell``
Cells to be included in the library.
overwrite_duplicate : bool
If True an existing cell with the ... |
def GetEntries(self, parser_mediator, match=None, **unused_kwargs):
"""Extracts relevant Airport entries.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
match (Optional[dict[str: object]]): keys extracted from... | Extracts relevant Airport entries.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
match (Optional[dict[str: object]]): keys extracted from PLIST_KEYS. | Below is the the instruction that describes the task:
### Input:
Extracts relevant Airport entries.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
match (Optional[dict[str: object]]): keys extracted from PLIST... |
def in_collision_other(self, other_manager,
return_names=False, return_data=False):
"""
Check if any object from this manager collides with any object
from another manager.
Parameters
-------------------
other_manager : CollisionManager
... | Check if any object from this manager collides with any object
from another manager.
Parameters
-------------------
other_manager : CollisionManager
Another collision manager object
return_names : bool
If true, a set is returned containing the names
... | Below is the the instruction that describes the task:
### Input:
Check if any object from this manager collides with any object
from another manager.
Parameters
-------------------
other_manager : CollisionManager
Another collision manager object
return_names : boo... |
async def close_room(self, room, namespace=None):
"""Close a room.
The only difference with the :func:`socketio.Server.close_room` method
is that when the ``namespace`` argument is not given the namespace
associated with the class is used.
Note: this method is a coroutine.
... | Close a room.
The only difference with the :func:`socketio.Server.close_room` method
is that when the ``namespace`` argument is not given the namespace
associated with the class is used.
Note: this method is a coroutine. | Below is the the instruction that describes the task:
### Input:
Close a room.
The only difference with the :func:`socketio.Server.close_room` method
is that when the ``namespace`` argument is not given the namespace
associated with the class is used.
Note: this method is a corouti... |
def detect(self, volume_system, vstype='detect'):
"""Finds and mounts all volumes based on mmls."""
try:
cmd = ['mmls']
if volume_system.parent.offset:
cmd.extend(['-o', str(volume_system.parent.offset // volume_system.disk.block_size)])
if vstype in ... | Finds and mounts all volumes based on mmls. | Below is the the instruction that describes the task:
### Input:
Finds and mounts all volumes based on mmls.
### Response:
def detect(self, volume_system, vstype='detect'):
"""Finds and mounts all volumes based on mmls."""
try:
cmd = ['mmls']
if volume_system.parent.offset:... |
def past_active(self):
"""
Weak verbs
I
>>> verb = WeakOldNorseVerb()
>>> verb.set_canonic_forms(["kalla", "kallaði", "kallaðinn"])
>>> verb.past_active()
['kallaða', 'kallaðir', 'kallaði', 'kölluðum', 'kölluðuð', 'kölluðu']
II
>>> verb = WeakOldN... | Weak verbs
I
>>> verb = WeakOldNorseVerb()
>>> verb.set_canonic_forms(["kalla", "kallaði", "kallaðinn"])
>>> verb.past_active()
['kallaða', 'kallaðir', 'kallaði', 'kölluðum', 'kölluðuð', 'kölluðu']
II
>>> verb = WeakOldNorseVerb()
>>> verb.set_canonic_for... | Below is the the instruction that describes the task:
### Input:
Weak verbs
I
>>> verb = WeakOldNorseVerb()
>>> verb.set_canonic_forms(["kalla", "kallaði", "kallaðinn"])
>>> verb.past_active()
['kallaða', 'kallaðir', 'kallaði', 'kölluðum', 'kölluðuð', 'kölluðu']
II
... |
def connect(self):
"""
Starts up an authentication session for the client using cookie
authentication if necessary.
"""
if self.r_session:
self.session_logout()
if self.admin_party:
self._use_iam = False
self.r_session = ClientSession(... | Starts up an authentication session for the client using cookie
authentication if necessary. | Below is the the instruction that describes the task:
### Input:
Starts up an authentication session for the client using cookie
authentication if necessary.
### Response:
def connect(self):
"""
Starts up an authentication session for the client using cookie
authentication if necess... |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'limit') and self.limit is not None:
_dict['limit'] = self.limit
if hasattr(self, 'model') and self.model is not None:
_dict['model'] = self.model
retur... | Return a json dictionary representing this model. | Below is the the instruction that describes the task:
### Input:
Return a json dictionary representing this model.
### Response:
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'limit') and self.limit is not None:
_dict['li... |
def add_member(self, member):
"""
Add a single member to the scope.
You may only edit the list of members if the pykechain credentials allow this.
:param member: single username to be added to the scope list of members
:type member: basestring
:raises APIError: when una... | Add a single member to the scope.
You may only edit the list of members if the pykechain credentials allow this.
:param member: single username to be added to the scope list of members
:type member: basestring
:raises APIError: when unable to update the scope member | Below is the the instruction that describes the task:
### Input:
Add a single member to the scope.
You may only edit the list of members if the pykechain credentials allow this.
:param member: single username to be added to the scope list of members
:type member: basestring
:raises... |
def get_ways(self, way_id=None, **kwargs):
"""
Alias for get_elements() but filter the result by Way
:param way_id: The Id of the way
:type way_id: Integer
:return: List of elements
"""
return self.get_elements(Way, elem_id=way_id, **kwargs) | Alias for get_elements() but filter the result by Way
:param way_id: The Id of the way
:type way_id: Integer
:return: List of elements | Below is the the instruction that describes the task:
### Input:
Alias for get_elements() but filter the result by Way
:param way_id: The Id of the way
:type way_id: Integer
:return: List of elements
### Response:
def get_ways(self, way_id=None, **kwargs):
"""
Alias for get... |
def set_mouse_handler_for_range(self, x_min, x_max, y_min, y_max, handler=None):
"""
Set mouse handler for a region.
"""
for x, y in product(range(x_min, x_max), range(y_min, y_max)):
self.mouse_handlers[x,y] = handler | Set mouse handler for a region. | Below is the the instruction that describes the task:
### Input:
Set mouse handler for a region.
### Response:
def set_mouse_handler_for_range(self, x_min, x_max, y_min, y_max, handler=None):
"""
Set mouse handler for a region.
"""
for x, y in product(range(x_min, x_max), range(y_mi... |
def hydrate_struct(address_mapper, address):
"""Given an AddressMapper and an Address, resolve a Struct from a BUILD file.
Recursively collects any embedded addressables within the Struct, but will not walk into a
dependencies field, since those should be requested explicitly by rules.
"""
address_family = ... | Given an AddressMapper and an Address, resolve a Struct from a BUILD file.
Recursively collects any embedded addressables within the Struct, but will not walk into a
dependencies field, since those should be requested explicitly by rules. | Below is the the instruction that describes the task:
### Input:
Given an AddressMapper and an Address, resolve a Struct from a BUILD file.
Recursively collects any embedded addressables within the Struct, but will not walk into a
dependencies field, since those should be requested explicitly by rules.
### Res... |
def print_value(value: Any, type_: GraphQLInputType) -> str:
"""Convenience function for printing a Python value"""
return print_ast(ast_from_value(value, type_)) | Convenience function for printing a Python value | Below is the the instruction that describes the task:
### Input:
Convenience function for printing a Python value
### Response:
def print_value(value: Any, type_: GraphQLInputType) -> str:
"""Convenience function for printing a Python value"""
return print_ast(ast_from_value(value, type_)) |
def shiftx_image2d_flux(image2d_orig, xoffset):
"""Resample 2D image using a shift in the x direction (flux is preserved).
Parameters
----------
image2d_orig : numpy array
2D image to be resampled.
xoffset : float
Offset to be applied.
Returns
-------
image2d_resampled ... | Resample 2D image using a shift in the x direction (flux is preserved).
Parameters
----------
image2d_orig : numpy array
2D image to be resampled.
xoffset : float
Offset to be applied.
Returns
-------
image2d_resampled : numpy array
Resampled 2D image. | Below is the the instruction that describes the task:
### Input:
Resample 2D image using a shift in the x direction (flux is preserved).
Parameters
----------
image2d_orig : numpy array
2D image to be resampled.
xoffset : float
Offset to be applied.
Returns
-------
imag... |
def import_lsdinst(self, struct_data):
"""import from an lsdinst struct"""
self.name = struct_data['name']
self.automate = struct_data['data']['automate']
self.pan = struct_data['data']['pan']
if self.table is not None:
self.table.import_lsdinst(struct_data) | import from an lsdinst struct | Below is the the instruction that describes the task:
### Input:
import from an lsdinst struct
### Response:
def import_lsdinst(self, struct_data):
"""import from an lsdinst struct"""
self.name = struct_data['name']
self.automate = struct_data['data']['automate']
self.pan = struct_d... |
def has_neigh(tag_name, params=None, content=None, left=True):
"""
This function generates functions, which matches all tags with neighbours
defined by parameters.
Args:
tag_name (str): Tag has to have neighbour with this tagname.
params (dict): Tag has to have neighbour with this param... | This function generates functions, which matches all tags with neighbours
defined by parameters.
Args:
tag_name (str): Tag has to have neighbour with this tagname.
params (dict): Tag has to have neighbour with this parameters.
params (str): Tag has to have neighbour with this content.
... | Below is the the instruction that describes the task:
### Input:
This function generates functions, which matches all tags with neighbours
defined by parameters.
Args:
tag_name (str): Tag has to have neighbour with this tagname.
params (dict): Tag has to have neighbour with this parameters.... |
def groupByKey(self, numPartitions=None):
"""
Return a new DStream by applying groupByKey on each RDD.
"""
if numPartitions is None:
numPartitions = self._sc.defaultParallelism
return self.transform(lambda rdd: rdd.groupByKey(numPartitions)) | Return a new DStream by applying groupByKey on each RDD. | Below is the the instruction that describes the task:
### Input:
Return a new DStream by applying groupByKey on each RDD.
### Response:
def groupByKey(self, numPartitions=None):
"""
Return a new DStream by applying groupByKey on each RDD.
"""
if numPartitions is None:
nu... |
def update(self, columns=(), by=(), where=(), **kwds):
"""update from self
>>> t = q('([]a:1 2 3; b:10 20 30)')
>>> t.update('a*2',
... where='b > 20').show() # doctest: +NORMALIZE_WHITESPACE
a b
----
1 10
2 20
6 30
"""
r... | update from self
>>> t = q('([]a:1 2 3; b:10 20 30)')
>>> t.update('a*2',
... where='b > 20').show() # doctest: +NORMALIZE_WHITESPACE
a b
----
1 10
2 20
6 30 | Below is the the instruction that describes the task:
### Input:
update from self
>>> t = q('([]a:1 2 3; b:10 20 30)')
>>> t.update('a*2',
... where='b > 20').show() # doctest: +NORMALIZE_WHITESPACE
a b
----
1 10
2 20
6 30
### Response:
def... |
def _utc_year(self):
"""Return a fractional UTC year, for convenience when plotting.
An experiment, probably superseded by the ``J`` attribute below.
"""
d = self._utc_float() - 1721059.5
#d += offset
C = 365 * 100 + 24
d -= 365
d += d // C - d // (4 * C... | Return a fractional UTC year, for convenience when plotting.
An experiment, probably superseded by the ``J`` attribute below. | Below is the the instruction that describes the task:
### Input:
Return a fractional UTC year, for convenience when plotting.
An experiment, probably superseded by the ``J`` attribute below.
### Response:
def _utc_year(self):
"""Return a fractional UTC year, for convenience when plotting.
... |
def fetch_open_orders(self, limit: int) -> List[Order]:
"""Fetch latest open orders, must provide a limit."""
return self._fetch_orders_limit(self._open_orders, limit) | Fetch latest open orders, must provide a limit. | Below is the the instruction that describes the task:
### Input:
Fetch latest open orders, must provide a limit.
### Response:
def fetch_open_orders(self, limit: int) -> List[Order]:
"""Fetch latest open orders, must provide a limit."""
return self._fetch_orders_limit(self._open_orders, limit) |
def _verified_version_from_id(version_id):
# type: (int) -> SerializationVersion
"""Load a message :class:`SerializationVersion` for the specified version ID.
:param int version_id: Message format version ID
:return: Message format version
:rtype: SerializationVersion
:raises NotSupportedError:... | Load a message :class:`SerializationVersion` for the specified version ID.
:param int version_id: Message format version ID
:return: Message format version
:rtype: SerializationVersion
:raises NotSupportedError: if unsupported version ID is received | Below is the the instruction that describes the task:
### Input:
Load a message :class:`SerializationVersion` for the specified version ID.
:param int version_id: Message format version ID
:return: Message format version
:rtype: SerializationVersion
:raises NotSupportedError: if unsupported version... |
def configure_stream(level='WARNING'):
"""Configure root logger using a standard stream handler.
Args:
level (string, optional): lowest level to log to the console
Returns:
logging.RootLogger: root logger instance with attached handler
"""
# get the root logger
root_logger = lo... | Configure root logger using a standard stream handler.
Args:
level (string, optional): lowest level to log to the console
Returns:
logging.RootLogger: root logger instance with attached handler | Below is the the instruction that describes the task:
### Input:
Configure root logger using a standard stream handler.
Args:
level (string, optional): lowest level to log to the console
Returns:
logging.RootLogger: root logger instance with attached handler
### Response:
def configure_st... |
def commit_withdrawal(self, account_id, withdrawal_id, **params):
"""https://developers.coinbase.com/api/v2#commit-a-withdrawal"""
response = self._post(
'v2', 'accounts', account_id, 'withdrawals', withdrawal_id, 'commit',
data=params)
return self._make_api_object(respon... | https://developers.coinbase.com/api/v2#commit-a-withdrawal | Below is the the instruction that describes the task:
### Input:
https://developers.coinbase.com/api/v2#commit-a-withdrawal
### Response:
def commit_withdrawal(self, account_id, withdrawal_id, **params):
"""https://developers.coinbase.com/api/v2#commit-a-withdrawal"""
response = self._post(
... |
def lattice(prng, n_features, alpha, random_sign=False, low=0.3, high=0.7):
"""Returns the adjacency matrix for a lattice network.
The resulting network is a Toeplitz matrix with random values summing
between -1 and 1 and zeros along the diagonal.
The range of the values can be controlled via the para... | Returns the adjacency matrix for a lattice network.
The resulting network is a Toeplitz matrix with random values summing
between -1 and 1 and zeros along the diagonal.
The range of the values can be controlled via the parameters low and high.
If random_sign is false, all entries will be negative, oth... | Below is the the instruction that describes the task:
### Input:
Returns the adjacency matrix for a lattice network.
The resulting network is a Toeplitz matrix with random values summing
between -1 and 1 and zeros along the diagonal.
The range of the values can be controlled via the parameters low and... |
def unit_overlap(evaluated_model, reference_model):
"""
Computes unit overlap of two text documents. Documents
has to be represented as TF models of non-empty document.
:returns float:
0 <= overlap <= 1, where 0 means no match and 1 means
exactly the same.
"""
if not (isinstance... | Computes unit overlap of two text documents. Documents
has to be represented as TF models of non-empty document.
:returns float:
0 <= overlap <= 1, where 0 means no match and 1 means
exactly the same. | Below is the the instruction that describes the task:
### Input:
Computes unit overlap of two text documents. Documents
has to be represented as TF models of non-empty document.
:returns float:
0 <= overlap <= 1, where 0 means no match and 1 means
exactly the same.
### Response:
def unit_o... |
async def get_data(self, url):
"""Get data from the TMDb API via :py:func:`aiohttp.get`.
Notes:
Updates configuration (if required) on successful requests.
Arguments:
url (:py:class:`str`): The endpoint URL and params.
Returns:
:py:class:`dict`: The parse... | Get data from the TMDb API via :py:func:`aiohttp.get`.
Notes:
Updates configuration (if required) on successful requests.
Arguments:
url (:py:class:`str`): The endpoint URL and params.
Returns:
:py:class:`dict`: The parsed JSON result. | Below is the the instruction that describes the task:
### Input:
Get data from the TMDb API via :py:func:`aiohttp.get`.
Notes:
Updates configuration (if required) on successful requests.
Arguments:
url (:py:class:`str`): The endpoint URL and params.
Returns:
... |
def _RunCommand(self, command):
"""Runs the command."""
arguments = shlex.split(command)
process = subprocess.Popen(
arguments, stderr=subprocess.PIPE, stdout=subprocess.PIPE,
universal_newlines=True)
if not process:
raise RuntimeError("Running: {0:s} failed.".format(command))
... | Runs the command. | Below is the the instruction that describes the task:
### Input:
Runs the command.
### Response:
def _RunCommand(self, command):
"""Runs the command."""
arguments = shlex.split(command)
process = subprocess.Popen(
arguments, stderr=subprocess.PIPE, stdout=subprocess.PIPE,
universal_newl... |
def main(sample_id, assembly_file, minsize):
"""Main executor of the process_mapping template.
Parameters
----------
sample_id : str
Sample Identification string.
assembly: str
Path to the fatsa file generated by the assembler.
minsize: str
Min contig size to be consider... | Main executor of the process_mapping template.
Parameters
----------
sample_id : str
Sample Identification string.
assembly: str
Path to the fatsa file generated by the assembler.
minsize: str
Min contig size to be considered a complete ORF | Below is the the instruction that describes the task:
### Input:
Main executor of the process_mapping template.
Parameters
----------
sample_id : str
Sample Identification string.
assembly: str
Path to the fatsa file generated by the assembler.
minsize: str
Min contig si... |
def get_mutator(self, obj, obj_type):
"""
Get a random mutator for the given type
"""
if obj_type == unicode:
obj_type = str
obj = str(obj)
return self._get_random(obj_type)(obj) | Get a random mutator for the given type | Below is the the instruction that describes the task:
### Input:
Get a random mutator for the given type
### Response:
def get_mutator(self, obj, obj_type):
"""
Get a random mutator for the given type
"""
if obj_type == unicode:
obj_type = str
obj = str(obj)
... |
def find_lb_by_name(self, name):
"""
Look up a LBaaS instance by name (rather than id)
:attr string name: The LBaaS name assigned at creation time
:rtype :class:`dict`
"""
log.debug("Finding load balancers matching name '%s'" % name)
matching = filter(lambda l:... | Look up a LBaaS instance by name (rather than id)
:attr string name: The LBaaS name assigned at creation time
:rtype :class:`dict` | Below is the the instruction that describes the task:
### Input:
Look up a LBaaS instance by name (rather than id)
:attr string name: The LBaaS name assigned at creation time
:rtype :class:`dict`
### Response:
def find_lb_by_name(self, name):
"""
Look up a LBaaS instance by name ... |
def dnld_annotation(assc_file, prt=sys.stdout):
"""Download gaf, gpad, or gpi from http://current.geneontology.org/annotations/"""
if not os.path.isfile(assc_file):
# assc_http = "http://geneontology.org/gene-associations/"
assc_http = "http://current.geneontology.org/annotations/"
_, as... | Download gaf, gpad, or gpi from http://current.geneontology.org/annotations/ | Below is the the instruction that describes the task:
### Input:
Download gaf, gpad, or gpi from http://current.geneontology.org/annotations/
### Response:
def dnld_annotation(assc_file, prt=sys.stdout):
"""Download gaf, gpad, or gpi from http://current.geneontology.org/annotations/"""
if not os.path.isfil... |
def delete(self,pool_or_cursor):
".. warning:: pgmock doesn't support delete yet, so this isn't tested"
vals=self.pkey_vals()
whereclause=' and '.join('%s=%%s'%k for k in self.PKEY.split(','))
q='delete from %s where %s'%(self.TABLE,whereclause)
commit_or_execute(pool_or_cursor,q,vals) | .. warning:: pgmock doesn't support delete yet, so this isn't tested | Below is the the instruction that describes the task:
### Input:
.. warning:: pgmock doesn't support delete yet, so this isn't tested
### Response:
def delete(self,pool_or_cursor):
".. warning:: pgmock doesn't support delete yet, so this isn't tested"
vals=self.pkey_vals()
whereclause=' and '.join('... |
def model(self, inputs, mode='train'):
"""Build a simple convnet (BN before ReLU).
Args:
inputs: a tensor of size [batch_size, height, width, channels]
mode: string in ['train', 'test']
Returns:
the last op containing the predictions
Note:
... | Build a simple convnet (BN before ReLU).
Args:
inputs: a tensor of size [batch_size, height, width, channels]
mode: string in ['train', 'test']
Returns:
the last op containing the predictions
Note:
Best score
Step: 7015 - Epoch: 18/20 ... | Below is the the instruction that describes the task:
### Input:
Build a simple convnet (BN before ReLU).
Args:
inputs: a tensor of size [batch_size, height, width, channels]
mode: string in ['train', 'test']
Returns:
the last op containing the predictions
... |
def check_new_version_available(this_version):
"""
Checks if a newer version of Zappa is available.
Returns True is updateable, else False.
"""
import requests
pypi_url = 'https://pypi.python.org/pypi/Zappa/json'
resp = requests.get(pypi_url, timeout=1.5)
top_version = resp.json()['in... | Checks if a newer version of Zappa is available.
Returns True is updateable, else False. | Below is the the instruction that describes the task:
### Input:
Checks if a newer version of Zappa is available.
Returns True is updateable, else False.
### Response:
def check_new_version_available(this_version):
"""
Checks if a newer version of Zappa is available.
Returns True is updateable, e... |
def tomindec(origin):
"""
Convert [+/-]DDD.DDDDD to a tuple (degrees, minutes)
"""
origin = float(origin)
degrees = int(origin)
minutes = (origin % 1) * 60
return degrees, minutes | Convert [+/-]DDD.DDDDD to a tuple (degrees, minutes) | Below is the the instruction that describes the task:
### Input:
Convert [+/-]DDD.DDDDD to a tuple (degrees, minutes)
### Response:
def tomindec(origin):
"""
Convert [+/-]DDD.DDDDD to a tuple (degrees, minutes)
"""
origin = float(origin)
degrees = int(origin)
minutes = (origin % 1) * 60
... |
def get_active_entry(user, select_for_update=False):
"""Returns the user's currently-active entry, or None."""
entries = apps.get_model('entries', 'Entry').no_join
if select_for_update:
entries = entries.select_for_update()
entries = entries.filter(user=user, end_time__isnull=True)
if not e... | Returns the user's currently-active entry, or None. | Below is the the instruction that describes the task:
### Input:
Returns the user's currently-active entry, or None.
### Response:
def get_active_entry(user, select_for_update=False):
"""Returns the user's currently-active entry, or None."""
entries = apps.get_model('entries', 'Entry').no_join
if selec... |
def get_str(self, key, default=None):
"""
Args:
key (str | unicode | None): Key to lookup
default (str | unicode | None): Default to use if key is not configured
Returns:
(str | None): Value of key, if defined
"""
if key:
for provi... | Args:
key (str | unicode | None): Key to lookup
default (str | unicode | None): Default to use if key is not configured
Returns:
(str | None): Value of key, if defined | Below is the the instruction that describes the task:
### Input:
Args:
key (str | unicode | None): Key to lookup
default (str | unicode | None): Default to use if key is not configured
Returns:
(str | None): Value of key, if defined
### Response:
def get_str(self, key, ... |
def pmt_angles(self):
"""A list of PMT directions sorted by PMT channel, on DU-1, floor-1"""
if self._pmt_angles == []:
mask = (self.pmts.du == 1) & (self.pmts.floor == 1)
self._pmt_angles = self.pmts.dir[mask]
return self._pmt_angles | A list of PMT directions sorted by PMT channel, on DU-1, floor-1 | Below is the the instruction that describes the task:
### Input:
A list of PMT directions sorted by PMT channel, on DU-1, floor-1
### Response:
def pmt_angles(self):
"""A list of PMT directions sorted by PMT channel, on DU-1, floor-1"""
if self._pmt_angles == []:
mask = (self.pmts.du ==... |
def get_error(self, block=False, timeout=None):
"""Removes and returns an error from self._errors
Args:
block(bool): if True block until a RTMMessage is available,
else it will return None when self._inbox is empty
timeout(int): it blocks at most timeout... | Removes and returns an error from self._errors
Args:
block(bool): if True block until a RTMMessage is available,
else it will return None when self._inbox is empty
timeout(int): it blocks at most timeout seconds
Returns:
error if inbox is no... | Below is the the instruction that describes the task:
### Input:
Removes and returns an error from self._errors
Args:
block(bool): if True block until a RTMMessage is available,
else it will return None when self._inbox is empty
timeout(int): it blocks at mo... |
def is_published(self):
"""Check fields 980 and 773 to see if the record has already been published.
:return: True is published, else False
"""
field980 = record_get_field_instances(self.record, '980')
field773 = record_get_field_instances(self.record, '773')
for f980 in... | Check fields 980 and 773 to see if the record has already been published.
:return: True is published, else False | Below is the the instruction that describes the task:
### Input:
Check fields 980 and 773 to see if the record has already been published.
:return: True is published, else False
### Response:
def is_published(self):
"""Check fields 980 and 773 to see if the record has already been published.
... |
def detect_number_of_cores():
"""
Detects the number of cores on a system. Cribbed from pp.
"""
# Linux, Unix and MacOS:
if hasattr(os, "sysconf"):
if "SC_NPROCESSORS_ONLN" in os.sysconf_names:
# Linux & Unix:
ncpus = os.sysconf("SC_NPROCESSORS_ONLN")
if i... | Detects the number of cores on a system. Cribbed from pp. | Below is the the instruction that describes the task:
### Input:
Detects the number of cores on a system. Cribbed from pp.
### Response:
def detect_number_of_cores():
"""
Detects the number of cores on a system. Cribbed from pp.
"""
# Linux, Unix and MacOS:
if hasattr(os, "sysconf"):
if... |
def gen_primes():
""" Generate an infinite sequence of prime numbers.
"""
D = {}
q = 2
while True:
if q not in D:
yield q
D[q * q] = [q]
else:
for p in D[q]:
D.setdefault(p + q, []).append(p)
del D[q]
q += 1 | Generate an infinite sequence of prime numbers. | Below is the the instruction that describes the task:
### Input:
Generate an infinite sequence of prime numbers.
### Response:
def gen_primes():
""" Generate an infinite sequence of prime numbers.
"""
D = {}
q = 2
while True:
if q not in D:
yield q
D[q * q] = [q]... |
def p_labelled_statement(self, p):
"""labelled_statement : identifier COLON statement"""
p[0] = ast.Label(identifier=p[1], statement=p[3]) | labelled_statement : identifier COLON statement | Below is the the instruction that describes the task:
### Input:
labelled_statement : identifier COLON statement
### Response:
def p_labelled_statement(self, p):
"""labelled_statement : identifier COLON statement"""
p[0] = ast.Label(identifier=p[1], statement=p[3]) |
def padding(s, bs=AES.block_size):
"""Fills a bytes-like object with arbitrary symbols to make its length divisible by `bs`.
"""
s = to_bytes(s)
if len(s) % bs == 0:
res = s + b''.join(map(to_bytes, [random.SystemRandom().choice(string.ascii_lowercase + string.digits) for _ in range(bs - 1... | Fills a bytes-like object with arbitrary symbols to make its length divisible by `bs`. | Below is the the instruction that describes the task:
### Input:
Fills a bytes-like object with arbitrary symbols to make its length divisible by `bs`.
### Response:
def padding(s, bs=AES.block_size):
"""Fills a bytes-like object with arbitrary symbols to make its length divisible by `bs`.
"""
s =... |
def describe_parameter_group(name, Filters=None, MaxRecords=None, Marker=None,
region=None, key=None, keyid=None, profile=None):
'''
Returns a list of `DBParameterGroup` descriptions.
CLI example to description of parameter group::
salt myminion boto_rds.describe_parame... | Returns a list of `DBParameterGroup` descriptions.
CLI example to description of parameter group::
salt myminion boto_rds.describe_parameter_group parametergroupname\
region=us-east-1 | Below is the the instruction that describes the task:
### Input:
Returns a list of `DBParameterGroup` descriptions.
CLI example to description of parameter group::
salt myminion boto_rds.describe_parameter_group parametergroupname\
region=us-east-1
### Response:
def describe_parameter_grou... |
def get_upload_path(self, filename):
''' Override this in proxy subclass to customize upload path.
Default upload path is
:file:`/media/images/<user.id>/<filename>.<ext>`
or :file:`/media/images/common/<filename>.<ext>` if user is not set.
``<filename>`` is retur... | Override this in proxy subclass to customize upload path.
Default upload path is
:file:`/media/images/<user.id>/<filename>.<ext>`
or :file:`/media/images/common/<filename>.<ext>` if user is not set.
``<filename>`` is returned by
:meth:`~generic_images.models.... | Below is the the instruction that describes the task:
### Input:
Override this in proxy subclass to customize upload path.
Default upload path is
:file:`/media/images/<user.id>/<filename>.<ext>`
or :file:`/media/images/common/<filename>.<ext>` if user is not set.
``<... |
def _check_link_completion(self, link, fail_pending=False, fail_running=False):
"""Internal function to check the completion of all the dispatched jobs
Returns
-------
status_vect : `JobStatusVector`
Vector that summarize the number of jobs in various states.
"""
... | Internal function to check the completion of all the dispatched jobs
Returns
-------
status_vect : `JobStatusVector`
Vector that summarize the number of jobs in various states. | Below is the the instruction that describes the task:
### Input:
Internal function to check the completion of all the dispatched jobs
Returns
-------
status_vect : `JobStatusVector`
Vector that summarize the number of jobs in various states.
### Response:
def _check_link_compl... |
def normalize_file(file, separators=None):
"""
Normalizes the file path to use the POSIX path separator (i.e., ``'/'``).
*file* (:class:`str`) is the file path.
*separators* (:class:`~collections.abc.Collection` of :class:`str`; or
:data:`None`) optionally contains the path separators to normalize.
This does no... | Normalizes the file path to use the POSIX path separator (i.e., ``'/'``).
*file* (:class:`str`) is the file path.
*separators* (:class:`~collections.abc.Collection` of :class:`str`; or
:data:`None`) optionally contains the path separators to normalize.
This does not need to include the POSIX path separator (``'/'... | Below is the the instruction that describes the task:
### Input:
Normalizes the file path to use the POSIX path separator (i.e., ``'/'``).
*file* (:class:`str`) is the file path.
*separators* (:class:`~collections.abc.Collection` of :class:`str`; or
:data:`None`) optionally contains the path separators to norm... |
def set_weights(self, weights_values: dict, ignore_missing=False):
"""
Sets the weights values of the network.
:param weights_values: dictionary with weights for each layer
"""
network_name = self.__class__.__name__.lower()
with tf.variable_scope(network_name):
... | Sets the weights values of the network.
:param weights_values: dictionary with weights for each layer | Below is the the instruction that describes the task:
### Input:
Sets the weights values of the network.
:param weights_values: dictionary with weights for each layer
### Response:
def set_weights(self, weights_values: dict, ignore_missing=False):
"""
Sets the weights values of the network.... |
def get_table_acl(self, table_name, timeout=None):
'''
Returns details about any stored access policies specified on the
table that may be used with Shared Access Signatures.
:param str table_name:
The name of an existing table.
:param int timeout:
The se... | Returns details about any stored access policies specified on the
table that may be used with Shared Access Signatures.
:param str table_name:
The name of an existing table.
:param int timeout:
The server timeout, expressed in seconds.
:return: A dictionary of ac... | Below is the the instruction that describes the task:
### Input:
Returns details about any stored access policies specified on the
table that may be used with Shared Access Signatures.
:param str table_name:
The name of an existing table.
:param int timeout:
The serv... |
def begin(self):
"""Called once before using the session to check global step."""
self._global_step_tensor = tf.train.get_global_step()
if self._global_step_tensor is None:
raise RuntimeError(
'Global step should be created to use StepCounterHook.') | Called once before using the session to check global step. | Below is the the instruction that describes the task:
### Input:
Called once before using the session to check global step.
### Response:
def begin(self):
"""Called once before using the session to check global step."""
self._global_step_tensor = tf.train.get_global_step()
if self._global_step_tensor i... |
def _create_put_request(self, resource, billomat_id, command=None, send_data=None):
"""
Creates a put request and return the response data
"""
assert (isinstance(resource, str))
if isinstance(billomat_id, int):
billomat_id = str(billomat_id)
if not command:
... | Creates a put request and return the response data | Below is the the instruction that describes the task:
### Input:
Creates a put request and return the response data
### Response:
def _create_put_request(self, resource, billomat_id, command=None, send_data=None):
"""
Creates a put request and return the response data
"""
assert (is... |
def filter_jobs(sacct_jobs, failed=True):
"""Filter jobs that have a FAILED etc. status."""
categories = FAILED_CATEGORIES if failed else NORMAL_CATEGORIES
filtered_jobs = [job for job in sacct_jobs if job['state'] in categories]
return filtered_jobs | Filter jobs that have a FAILED etc. status. | Below is the the instruction that describes the task:
### Input:
Filter jobs that have a FAILED etc. status.
### Response:
def filter_jobs(sacct_jobs, failed=True):
"""Filter jobs that have a FAILED etc. status."""
categories = FAILED_CATEGORIES if failed else NORMAL_CATEGORIES
filtered_jobs = [job for... |
def get_config_map(self, name):
"""
Get a ConfigMap object from the server
Raises exception on error
:param name: str, name of configMap to get from the server
:returns: ConfigMapResponse containing the ConfigMap with the requested name
"""
response = self.os.ge... | Get a ConfigMap object from the server
Raises exception on error
:param name: str, name of configMap to get from the server
:returns: ConfigMapResponse containing the ConfigMap with the requested name | Below is the the instruction that describes the task:
### Input:
Get a ConfigMap object from the server
Raises exception on error
:param name: str, name of configMap to get from the server
:returns: ConfigMapResponse containing the ConfigMap with the requested name
### Response:
def get_c... |
def timezone_at(self, *, lng, lat):
"""
this function looks up in which polygons the point could be included in
to speed things up there are shortcuts being used (stored in a binary file)
especially for large polygons it is expensive to check if a point is really included,
so cer... | this function looks up in which polygons the point could be included in
to speed things up there are shortcuts being used (stored in a binary file)
especially for large polygons it is expensive to check if a point is really included,
so certain simplifications are made and even when you get a hi... | Below is the the instruction that describes the task:
### Input:
this function looks up in which polygons the point could be included in
to speed things up there are shortcuts being used (stored in a binary file)
especially for large polygons it is expensive to check if a point is really included,
... |
def set_filters(self, filters):
"""
set and validate filters dict
"""
if not isinstance(filters, dict):
raise Exception("filters must be a dict")
self.filters = {}
for key in filters.keys():
value = filters[key]
self.add_filter(key,valu... | set and validate filters dict | Below is the the instruction that describes the task:
### Input:
set and validate filters dict
### Response:
def set_filters(self, filters):
"""
set and validate filters dict
"""
if not isinstance(filters, dict):
raise Exception("filters must be a dict")
self.fil... |
def set_value(self, value):
"""Set the value associated with the keyword"""
if not isinstance(value, str):
raise TypeError("A value must be a string, got %s." % value)
self.__value = value | Set the value associated with the keyword | Below is the the instruction that describes the task:
### Input:
Set the value associated with the keyword
### Response:
def set_value(self, value):
"""Set the value associated with the keyword"""
if not isinstance(value, str):
raise TypeError("A value must be a string, got %s." % value... |
def get_stats(self, stat_name):
"""
:param stat_name: requested statistics name.
:returns: all values of the requested statistic for all objects.
"""
return [self.get_stat(r, stat_name) for r in self.statistics.keys()] | :param stat_name: requested statistics name.
:returns: all values of the requested statistic for all objects. | Below is the the instruction that describes the task:
### Input:
:param stat_name: requested statistics name.
:returns: all values of the requested statistic for all objects.
### Response:
def get_stats(self, stat_name):
"""
:param stat_name: requested statistics name.
:returns: all... |
def view(self):
"""View slpkg config file
"""
print("") # new line at start
conf_args = [
"RELEASE",
"SLACKWARE_VERSION",
"COMP_ARCH",
"BUILD_PATH",
"PACKAGES",
"PATCHES",
"CHECKMD5",
"DEL_A... | View slpkg config file | Below is the the instruction that describes the task:
### Input:
View slpkg config file
### Response:
def view(self):
"""View slpkg config file
"""
print("") # new line at start
conf_args = [
"RELEASE",
"SLACKWARE_VERSION",
"COMP_ARCH",
... |
def clean_promoted_guids(raw_promoted_guids):
""" Verify that the promoted GUIDs are formatted correctly,
otherwise strip it down into an empty list.
"""
valid = True
for row in raw_promoted_guids:
if len(row) != 2:
valid = False
break
if not (
(... | Verify that the promoted GUIDs are formatted correctly,
otherwise strip it down into an empty list. | Below is the the instruction that describes the task:
### Input:
Verify that the promoted GUIDs are formatted correctly,
otherwise strip it down into an empty list.
### Response:
def clean_promoted_guids(raw_promoted_guids):
""" Verify that the promoted GUIDs are formatted correctly,
otherwise strip it... |
def delete_activity(self, id_num):
"""Delete an activity (run).
:param id_num: The activity ID to delete
"""
url = self._build_url('my', 'activities', id_num)
r = self.session.delete(url)
r.raise_for_status()
return r | Delete an activity (run).
:param id_num: The activity ID to delete | Below is the the instruction that describes the task:
### Input:
Delete an activity (run).
:param id_num: The activity ID to delete
### Response:
def delete_activity(self, id_num):
"""Delete an activity (run).
:param id_num: The activity ID to delete
"""
url = self._buil... |
def _fill_queue(self, loglstar):
"""Sequentially add new live point proposals to the queue."""
# Add/zip arguments to submit to the queue.
point_queue = []
axes_queue = []
while self.nqueue < self.queue_size:
if self._beyond_unit_bound(loglstar):
# Pr... | Sequentially add new live point proposals to the queue. | Below is the the instruction that describes the task:
### Input:
Sequentially add new live point proposals to the queue.
### Response:
def _fill_queue(self, loglstar):
"""Sequentially add new live point proposals to the queue."""
# Add/zip arguments to submit to the queue.
point_queue = []... |
def new(self, array):
"""
Convert an array of compatible length into a DictArray:
>>> d = DictArray({'PGA': [0.01, 0.02, 0.04], 'PGV': [0.1, 0.2]})
>>> d.new(numpy.arange(0, 5, 1)) # array of lenght 5 = 3 + 2
<DictArray
PGA: [0 1 2]
PGV: [3 4]>
"""
... | Convert an array of compatible length into a DictArray:
>>> d = DictArray({'PGA': [0.01, 0.02, 0.04], 'PGV': [0.1, 0.2]})
>>> d.new(numpy.arange(0, 5, 1)) # array of lenght 5 = 3 + 2
<DictArray
PGA: [0 1 2]
PGV: [3 4]> | Below is the the instruction that describes the task:
### Input:
Convert an array of compatible length into a DictArray:
>>> d = DictArray({'PGA': [0.01, 0.02, 0.04], 'PGV': [0.1, 0.2]})
>>> d.new(numpy.arange(0, 5, 1)) # array of lenght 5 = 3 + 2
<DictArray
PGA: [0 1 2]
PG... |
def to_csv(self, filename, stimuli=None, inhibitors=None, prepend=""):
"""
Writes the list of clampings to a CSV file
Parameters
----------
filename : str
Absolute path where to write the CSV file
stimuli : Optional[list[str]]
List of stimuli nam... | Writes the list of clampings to a CSV file
Parameters
----------
filename : str
Absolute path where to write the CSV file
stimuli : Optional[list[str]]
List of stimuli names. If given, stimuli are converted to {0,1} instead of {-1,1}.
inhibitors : Optio... | Below is the the instruction that describes the task:
### Input:
Writes the list of clampings to a CSV file
Parameters
----------
filename : str
Absolute path where to write the CSV file
stimuli : Optional[list[str]]
List of stimuli names. If given, stimuli ... |
def extract_full(rec, sites, flank, fw):
"""
Full extraction of seq flanking the sites.
"""
for s in sites:
newid = "{0}:{1}".format(rec.name, s)
left = max(s - flank, 0)
right = min(s + flank, len(rec))
frag = rec.seq[left:right].strip("Nn")
newrec = SeqRecord(fr... | Full extraction of seq flanking the sites. | Below is the the instruction that describes the task:
### Input:
Full extraction of seq flanking the sites.
### Response:
def extract_full(rec, sites, flank, fw):
"""
Full extraction of seq flanking the sites.
"""
for s in sites:
newid = "{0}:{1}".format(rec.name, s)
left = max(s - ... |
def has_perm(self, service, perm_name, obj, call_name):
"""
Raise PermissionDenied if user has no permission in object
"""
user = service.user
if not (perm_name is False):
if not user.has_perm(perm_name, obj=obj):
LOG_PERM.warn(
u'U... | Raise PermissionDenied if user has no permission in object | Below is the the instruction that describes the task:
### Input:
Raise PermissionDenied if user has no permission in object
### Response:
def has_perm(self, service, perm_name, obj, call_name):
"""
Raise PermissionDenied if user has no permission in object
"""
user = service.user
... |
def mask(self):
'''
The array of indices to be masked. This is the union of the sets of
outliers, bad (flagged) cadences, transit cadences, and :py:obj:`NaN`
cadences.
'''
return np.array(list(set(np.concatenate([self.outmask, self.badmask,
self.... | The array of indices to be masked. This is the union of the sets of
outliers, bad (flagged) cadences, transit cadences, and :py:obj:`NaN`
cadences. | Below is the the instruction that describes the task:
### Input:
The array of indices to be masked. This is the union of the sets of
outliers, bad (flagged) cadences, transit cadences, and :py:obj:`NaN`
cadences.
### Response:
def mask(self):
'''
The array of indices to be masked. T... |
def irregular_sampling(T, N, rseed=None):
"""
Generates an irregularly sampled time vector by perturbating a
linearly spaced vector and latter deleting a certain number of
points
Parameters
----------
T: float
Time span of the vector, i.e. how long it is in time
N: positiv... | Generates an irregularly sampled time vector by perturbating a
linearly spaced vector and latter deleting a certain number of
points
Parameters
----------
T: float
Time span of the vector, i.e. how long it is in time
N: positive integer
Number of samples of the resulting t... | Below is the the instruction that describes the task:
### Input:
Generates an irregularly sampled time vector by perturbating a
linearly spaced vector and latter deleting a certain number of
points
Parameters
----------
T: float
Time span of the vector, i.e. how long it is in time... |
def step1_get_authorize_url(self, redirect_uri=None, state=None):
"""Returns a URI to redirect to the provider.
Args:
redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob'
for a non-web-based application, or a URI that
handle... | Returns a URI to redirect to the provider.
Args:
redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob'
for a non-web-based application, or a URI that
handles the callback from the authorization server.
This ... | Below is the the instruction that describes the task:
### Input:
Returns a URI to redirect to the provider.
Args:
redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob'
for a non-web-based application, or a URI that
handles the ca... |
def check_bam(bam, samtype="bam"):
"""Check if bam file is valid.
Bam file should:
- exists
- has an index (create if necessary)
- is sorted by coordinate
- has at least one mapped read
"""
ut.check_existance(bam)
samfile = pysam.AlignmentFile(bam, "rb")
if not samfile.has_index... | Check if bam file is valid.
Bam file should:
- exists
- has an index (create if necessary)
- is sorted by coordinate
- has at least one mapped read | Below is the the instruction that describes the task:
### Input:
Check if bam file is valid.
Bam file should:
- exists
- has an index (create if necessary)
- is sorted by coordinate
- has at least one mapped read
### Response:
def check_bam(bam, samtype="bam"):
"""Check if bam file is vali... |
def get_logins(self, user_id, start_date=None):
"""Gets the login history for a user, default start_date is 30 days ago
:param int id: User id to get
:param string start_date: "%m/%d/%Y %H:%M:%s" formatted string.
:returns: list https://softlayer.github.io/reference/datatypes/SoftLayer_... | Gets the login history for a user, default start_date is 30 days ago
:param int id: User id to get
:param string start_date: "%m/%d/%Y %H:%M:%s" formatted string.
:returns: list https://softlayer.github.io/reference/datatypes/SoftLayer_User_Customer_Access_Authentication/
Example::
... | Below is the the instruction that describes the task:
### Input:
Gets the login history for a user, default start_date is 30 days ago
:param int id: User id to get
:param string start_date: "%m/%d/%Y %H:%M:%s" formatted string.
:returns: list https://softlayer.github.io/reference/datatypes/... |
def animate(self,*args,**kwargs): #pragma: no cover
"""
NAME:
animate
PURPOSE:
animate an Orbit
INPUT:
d1= first dimension to plot ('x', 'y', 'R', 'vR', 'vT', 'z', 'vz', ...); can be list with up to three entries for three subplots
d2= second d... | NAME:
animate
PURPOSE:
animate an Orbit
INPUT:
d1= first dimension to plot ('x', 'y', 'R', 'vR', 'vT', 'z', 'vz', ...); can be list with up to three entries for three subplots
d2= second dimension to plot; can be list with up to three entries for three subplot... | Below is the the instruction that describes the task:
### Input:
NAME:
animate
PURPOSE:
animate an Orbit
INPUT:
d1= first dimension to plot ('x', 'y', 'R', 'vR', 'vT', 'z', 'vz', ...); can be list with up to three entries for three subplots
d2= second dime... |
def read_object(ctx, pin, object_id):
"""
Read arbitrary PIV object.
Read PIV object by providing the object id.
\b
OBJECT-ID Id of PIV object in HEX.
"""
controller = ctx.obj['controller']
def do_read_object(retry=True):
try:
click.echo(controller.get_data(... | Read arbitrary PIV object.
Read PIV object by providing the object id.
\b
OBJECT-ID Id of PIV object in HEX. | Below is the the instruction that describes the task:
### Input:
Read arbitrary PIV object.
Read PIV object by providing the object id.
\b
OBJECT-ID Id of PIV object in HEX.
### Response:
def read_object(ctx, pin, object_id):
"""
Read arbitrary PIV object.
Read PIV object by provid... |
def sub_dfs_by_size(df, size):
"""Get a generator yielding consecutive sub-dataframes of the given size.
Arguments
---------
df : pandas.DataFrame
The dataframe for which to get sub-dataframes.
size : int
The size of each sub-dataframe.
Returns
-------
generator
... | Get a generator yielding consecutive sub-dataframes of the given size.
Arguments
---------
df : pandas.DataFrame
The dataframe for which to get sub-dataframes.
size : int
The size of each sub-dataframe.
Returns
-------
generator
A generator yielding consecutive sub-... | Below is the the instruction that describes the task:
### Input:
Get a generator yielding consecutive sub-dataframes of the given size.
Arguments
---------
df : pandas.DataFrame
The dataframe for which to get sub-dataframes.
size : int
The size of each sub-dataframe.
Returns
... |
def get_hangul_syllable_type_property(value, is_bytes=False):
"""Get `HANGUL SYLLABLE TYPE` property."""
obj = unidata.ascii_hangul_syllable_type if is_bytes else unidata.unicode_hangul_syllable_type
if value.startswith('^'):
negated = value[1:]
value = '^' + unidata.unicode_alias['hanguls... | Get `HANGUL SYLLABLE TYPE` property. | Below is the the instruction that describes the task:
### Input:
Get `HANGUL SYLLABLE TYPE` property.
### Response:
def get_hangul_syllable_type_property(value, is_bytes=False):
"""Get `HANGUL SYLLABLE TYPE` property."""
obj = unidata.ascii_hangul_syllable_type if is_bytes else unidata.unicode_hangul_syll... |
def post_request(profile, resource, payload):
"""Do a POST request to Github's API.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.... | Do a POST request to Github's API.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
resource
The part of a Github A... | Below is the the instruction that describes the task:
### Input:
Do a POST request to Github's API.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` ... |
def _on_items_changed(self, change):
""" Observe container events on the items list and update the
adapter appropriately.
"""
if change['type'] != 'container':
return
op = change['operation']
if op == 'append':
i = len(change['value'])-1
... | Observe container events on the items list and update the
adapter appropriately. | Below is the the instruction that describes the task:
### Input:
Observe container events on the items list and update the
adapter appropriately.
### Response:
def _on_items_changed(self, change):
""" Observe container events on the items list and update the
adapter appropriately.
... |
def update_multi_precision(self, index, weight, grad, state):
"""Updates the given parameter using the corresponding gradient and state.
Mixed precision version.
Parameters
----------
index : int
The unique index of the parameter into the individual learning
... | Updates the given parameter using the corresponding gradient and state.
Mixed precision version.
Parameters
----------
index : int
The unique index of the parameter into the individual learning
rates and weight decays. Learning rates and weight decay
... | Below is the the instruction that describes the task:
### Input:
Updates the given parameter using the corresponding gradient and state.
Mixed precision version.
Parameters
----------
index : int
The unique index of the parameter into the individual learning
... |
def reset_new_request(self):
"""Remove the non-sense args from the self.ignore, return self.new_request"""
raw_url = self.new_request['url']
parsed_url = urlparse(raw_url)
qsl = parse_qsl(parsed_url.query)
new_url = self._join_url(
parsed_url, [i for i in qsl if i not... | Remove the non-sense args from the self.ignore, return self.new_request | Below is the the instruction that describes the task:
### Input:
Remove the non-sense args from the self.ignore, return self.new_request
### Response:
def reset_new_request(self):
"""Remove the non-sense args from the self.ignore, return self.new_request"""
raw_url = self.new_request['url']
... |
def _parse_args():
"""
Parse the command line for options
"""
parser = optparse.OptionParser()
parser.add_option(
'--user', dest='user_install', action='store_true', default=False,
help='install in user site package (requires Python 2.6 or later)')
parser.add_option(
'--d... | Parse the command line for options | Below is the the instruction that describes the task:
### Input:
Parse the command line for options
### Response:
def _parse_args():
"""
Parse the command line for options
"""
parser = optparse.OptionParser()
parser.add_option(
'--user', dest='user_install', action='store_true', default... |
def actions(acts, done):
'''
Prepare actions pipeline.
:param tuple acts: called functions
:param function done: get result from actions
:returns function: function that starts executio
'''
def _intermediate(acc, action):
result = action(acc['state'])
values = concatv(acc['... | Prepare actions pipeline.
:param tuple acts: called functions
:param function done: get result from actions
:returns function: function that starts executio | Below is the the instruction that describes the task:
### Input:
Prepare actions pipeline.
:param tuple acts: called functions
:param function done: get result from actions
:returns function: function that starts executio
### Response:
def actions(acts, done):
'''
Prepare actions pipeline.
... |
def hashkey(*args, **kwargs):
"""Return a cache key for the specified hashable arguments."""
if kwargs:
return _HashedTuple(args + sum(sorted(kwargs.items()), _kwmark))
else:
return _HashedTuple(args) | Return a cache key for the specified hashable arguments. | Below is the the instruction that describes the task:
### Input:
Return a cache key for the specified hashable arguments.
### Response:
def hashkey(*args, **kwargs):
"""Return a cache key for the specified hashable arguments."""
if kwargs:
return _HashedTuple(args + sum(sorted(kwargs.items()), _kw... |
def get_taints(arg, taint=None):
"""
Helper to list an object taints.
:param arg: a value or Expression
:param taint: a regular expression matching a taint value (eg. 'IMPORTANT.*'). If None, this function checks for any taint value.
"""
if not issymbolic(arg):
return
for arg_taint ... | Helper to list an object taints.
:param arg: a value or Expression
:param taint: a regular expression matching a taint value (eg. 'IMPORTANT.*'). If None, this function checks for any taint value. | Below is the the instruction that describes the task:
### Input:
Helper to list an object taints.
:param arg: a value or Expression
:param taint: a regular expression matching a taint value (eg. 'IMPORTANT.*'). If None, this function checks for any taint value.
### Response:
def get_taints(arg, taint=None)... |
def _readlines(fname, fpointer1=open, fpointer2=open): # pragma: no cover
"""Read all lines from file."""
# fpointer1, fpointer2 arguments to ease testing
try:
with fpointer1(fname, "r") as fobj:
return fobj.readlines()
except UnicodeDecodeError: # pragma: no cover
with fpo... | Read all lines from file. | Below is the the instruction that describes the task:
### Input:
Read all lines from file.
### Response:
def _readlines(fname, fpointer1=open, fpointer2=open): # pragma: no cover
"""Read all lines from file."""
# fpointer1, fpointer2 arguments to ease testing
try:
with fpointer1(fname, "r") as... |
def triple_reference_of(label: ShExJ.tripleExprLabel, cntxt: Context) -> Optional[ShExJ.tripleExpr]:
""" Search for the label in a Schema """
te: Optional[ShExJ.tripleExpr] = None
if cntxt.schema.start is not None:
te = triple_in_shape(cntxt.schema.start, label, cntxt)
if te is None:
for... | Search for the label in a Schema | Below is the the instruction that describes the task:
### Input:
Search for the label in a Schema
### Response:
def triple_reference_of(label: ShExJ.tripleExprLabel, cntxt: Context) -> Optional[ShExJ.tripleExpr]:
""" Search for the label in a Schema """
te: Optional[ShExJ.tripleExpr] = None
if cntxt.sc... |
def _virt_call(domain, function, section, comment,
connection=None, username=None, password=None, **kwargs):
'''
Helper to call the virt functions. Wildcards supported.
:param domain:
:param function:
:param section:
:param comment:
:return:
'''
ret = {'name': domain,... | Helper to call the virt functions. Wildcards supported.
:param domain:
:param function:
:param section:
:param comment:
:return: | Below is the the instruction that describes the task:
### Input:
Helper to call the virt functions. Wildcards supported.
:param domain:
:param function:
:param section:
:param comment:
:return:
### Response:
def _virt_call(domain, function, section, comment,
connection=None, use... |
def create_rrset(self, zone_name, rtype, owner_name, ttl, rdata):
"""Creates a new RRSet in the specified zone.
Arguments:
zone_name -- The zone that will contain the new RRSet. The trailing dot is optional.
rtype -- The type of the RRSet. This can be numeric (1) or
i... | Creates a new RRSet in the specified zone.
Arguments:
zone_name -- The zone that will contain the new RRSet. The trailing dot is optional.
rtype -- The type of the RRSet. This can be numeric (1) or
if a well-known name is defined for the type (A), you can use it instead.
... | Below is the the instruction that describes the task:
### Input:
Creates a new RRSet in the specified zone.
Arguments:
zone_name -- The zone that will contain the new RRSet. The trailing dot is optional.
rtype -- The type of the RRSet. This can be numeric (1) or
if a well... |
def submit_populator_batch(self, column_name, batch):
"""Submit a populator batch
Submit a populator batch as a series of HTTP requests in small chunks,
returning the batch GUID, or raising exception on error."""
if not set(column_name).issubset(_allowedCustomDimensionChars):
... | Submit a populator batch
Submit a populator batch as a series of HTTP requests in small chunks,
returning the batch GUID, or raising exception on error. | Below is the the instruction that describes the task:
### Input:
Submit a populator batch
Submit a populator batch as a series of HTTP requests in small chunks,
returning the batch GUID, or raising exception on error.
### Response:
def submit_populator_batch(self, column_name, batch):
"""S... |
def _get_texture(arr, default, n_items, from_bounds):
"""Prepare data to be uploaded as a texture.
The from_bounds must be specified.
"""
if not hasattr(default, '__len__'): # pragma: no cover
default = [default]
n_cols = len(default)
if arr is None: # pragma: no cover
arr = ... | Prepare data to be uploaded as a texture.
The from_bounds must be specified. | Below is the the instruction that describes the task:
### Input:
Prepare data to be uploaded as a texture.
The from_bounds must be specified.
### Response:
def _get_texture(arr, default, n_items, from_bounds):
"""Prepare data to be uploaded as a texture.
The from_bounds must be specified.
"""
... |
def _ordered_node_addrs(self, function_address):
"""
For a given function, return all nodes in an optimal traversal order. If the function does not exist, return an
empty list.
:param int function_address: Address of the function.
:return: A ordered list of the nodes.
:r... | For a given function, return all nodes in an optimal traversal order. If the function does not exist, return an
empty list.
:param int function_address: Address of the function.
:return: A ordered list of the nodes.
:rtype: list | Below is the the instruction that describes the task:
### Input:
For a given function, return all nodes in an optimal traversal order. If the function does not exist, return an
empty list.
:param int function_address: Address of the function.
:return: A ordered list of the nodes.
:r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.