code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def update(self, docs=None, split=0, parallelism=None, progress_bar=True):
"""Update the features of the specified candidates.
:param docs: If provided, apply features to all the candidates in these
documents.
:param split: If docs is None, apply features to the candidates in this
... | Update the features of the specified candidates.
:param docs: If provided, apply features to all the candidates in these
documents.
:param split: If docs is None, apply features to the candidates in this
particular split.
:type split: int
:param parallelism: How ... | Below is the the instruction that describes the task:
### Input:
Update the features of the specified candidates.
:param docs: If provided, apply features to all the candidates in these
documents.
:param split: If docs is None, apply features to the candidates in this
partic... |
def _get_stats_table(self, table_id, kind='R', summary=False):
"""Gets a stats table from the player page; helper function that does
the work for per-game, per-100-poss, etc. stats.
:table_id: the ID of the HTML table.
:kind: specifies regular season, playoffs, or both. One of 'R', 'P',... | Gets a stats table from the player page; helper function that does
the work for per-game, per-100-poss, etc. stats.
:table_id: the ID of the HTML table.
:kind: specifies regular season, playoffs, or both. One of 'R', 'P',
'B'. Defaults to 'R'.
:returns: A DataFrame of stats. | Below is the the instruction that describes the task:
### Input:
Gets a stats table from the player page; helper function that does
the work for per-game, per-100-poss, etc. stats.
:table_id: the ID of the HTML table.
:kind: specifies regular season, playoffs, or both. One of 'R', 'P',
... |
def cast(func, value):
""" Cast the specified value to the specified type (returned by func). Currently this
only support int, float, bool. Should be extended if needed.
Parameters:
func (func): Calback function to used cast to type (int, bool, float).
value (any): value to ... | Cast the specified value to the specified type (returned by func). Currently this
only support int, float, bool. Should be extended if needed.
Parameters:
func (func): Calback function to used cast to type (int, bool, float).
value (any): value to be cast and returned. | Below is the the instruction that describes the task:
### Input:
Cast the specified value to the specified type (returned by func). Currently this
only support int, float, bool. Should be extended if needed.
Parameters:
func (func): Calback function to used cast to type (int, bool, floa... |
def save(self):
""" Exports all user attributes to the user's configuration and writes configuration
Saves the values for each attribute stored in User.configVars
into the user's configuration. The password is automatically
encoded and salted to prevent saving it as plaintext. T... | Exports all user attributes to the user's configuration and writes configuration
Saves the values for each attribute stored in User.configVars
into the user's configuration. The password is automatically
encoded and salted to prevent saving it as plaintext. The
session is pickl... | Below is the the instruction that describes the task:
### Input:
Exports all user attributes to the user's configuration and writes configuration
Saves the values for each attribute stored in User.configVars
into the user's configuration. The password is automatically
encoded and sa... |
def parse_config(file_path):
"""
Convert the CISM configuration file to a python dictionary
Args:
file_path: absolute path to the configuration file
Returns:
A dictionary representation of the given file
"""
if not os.path.isfile(file_path):
return {}
parser = Confi... | Convert the CISM configuration file to a python dictionary
Args:
file_path: absolute path to the configuration file
Returns:
A dictionary representation of the given file | Below is the the instruction that describes the task:
### Input:
Convert the CISM configuration file to a python dictionary
Args:
file_path: absolute path to the configuration file
Returns:
A dictionary representation of the given file
### Response:
def parse_config(file_path):
"""
... |
def advance(self, blocksize, timeout=10):
"""Advanced buffer blocksize seconds.
Add blocksize seconds more to the buffer, push blocksize seconds
from the beginning.
Parameters
----------
blocksize: int
The number of seconds to attempt to read from the channe... | Advanced buffer blocksize seconds.
Add blocksize seconds more to the buffer, push blocksize seconds
from the beginning.
Parameters
----------
blocksize: int
The number of seconds to attempt to read from the channel
Returns
-------
status: bo... | Below is the the instruction that describes the task:
### Input:
Advanced buffer blocksize seconds.
Add blocksize seconds more to the buffer, push blocksize seconds
from the beginning.
Parameters
----------
blocksize: int
The number of seconds to attempt to read... |
def gameloop(self):
"""
A game loop that circles through the methods.
"""
try:
while True:
self.handle_events()
self.update()
self.render()
except KeyboardInterrupt:
pass | A game loop that circles through the methods. | Below is the the instruction that describes the task:
### Input:
A game loop that circles through the methods.
### Response:
def gameloop(self):
"""
A game loop that circles through the methods.
"""
try:
while True:
self.handle_events()
se... |
def _format_dict(dict_, **kwargs):
"""
Makes a pretty printable / human-readable string representation of a
dictionary. In most cases this string could be evaled.
Args:
dict_ (dict): a dictionary
**kwargs: si, stritems, strkeys, strvals, sk, sv, nl, newlines, nobr,
no... | Makes a pretty printable / human-readable string representation of a
dictionary. In most cases this string could be evaled.
Args:
dict_ (dict): a dictionary
**kwargs: si, stritems, strkeys, strvals, sk, sv, nl, newlines, nobr,
nobraces, cbr, compact_brace, trailing_sep,
... | Below is the the instruction that describes the task:
### Input:
Makes a pretty printable / human-readable string representation of a
dictionary. In most cases this string could be evaled.
Args:
dict_ (dict): a dictionary
**kwargs: si, stritems, strkeys, strvals, sk, sv, nl, newlines, nobr... |
def apply_units_to_cache(self, data):
"""
Applies units to data when a proxy reader is used. For example if the
data is cached as JSON and retrieved using the
:class:`~simkit.core.data_readers.JSONReader`, then units can be
applied from the original parameter schema.
:pa... | Applies units to data when a proxy reader is used. For example if the
data is cached as JSON and retrieved using the
:class:`~simkit.core.data_readers.JSONReader`, then units can be
applied from the original parameter schema.
:param data: Data read by proxy reader.
:return: data... | Below is the the instruction that describes the task:
### Input:
Applies units to data when a proxy reader is used. For example if the
data is cached as JSON and retrieved using the
:class:`~simkit.core.data_readers.JSONReader`, then units can be
applied from the original parameter schema.
... |
def labels(self):
""" Returns symbol instances corresponding to labels
in the current scope.
"""
return [x for x in self[self.current_scope].values() if x.class_ == CLASS.label] | Returns symbol instances corresponding to labels
in the current scope. | Below is the the instruction that describes the task:
### Input:
Returns symbol instances corresponding to labels
in the current scope.
### Response:
def labels(self):
""" Returns symbol instances corresponding to labels
in the current scope.
"""
return [x for x in self[self... |
def merge_metrics(self):
"""
Merge metrics in the internal _metrics dict to metrics list
and delete the internal _metrics
"""
self.metrics.extend(self._metrics.values())
del self._metrics | Merge metrics in the internal _metrics dict to metrics list
and delete the internal _metrics | Below is the the instruction that describes the task:
### Input:
Merge metrics in the internal _metrics dict to metrics list
and delete the internal _metrics
### Response:
def merge_metrics(self):
"""
Merge metrics in the internal _metrics dict to metrics list
and delete the interna... |
def save_ical(self, ical_location): # type: (str) -> None
""" Save the calendar instance to a file """
data = self.cal.to_ical()
with open(ical_location, 'w') as ical_file:
ical_file.write(data.decode('utf-8')) | Save the calendar instance to a file | Below is the the instruction that describes the task:
### Input:
Save the calendar instance to a file
### Response:
def save_ical(self, ical_location): # type: (str) -> None
""" Save the calendar instance to a file """
data = self.cal.to_ical()
with open(ical_location, 'w') as ical_file:
... |
def place2thing(self, name, location):
"""Turn a Place into a Thing with the given location.
It will keep all its attached Portals.
"""
self.engine._set_thing_loc(
self.name, name, location
)
if (self.name, name) in self.engine._node_objs:
... | Turn a Place into a Thing with the given location.
It will keep all its attached Portals. | Below is the the instruction that describes the task:
### Input:
Turn a Place into a Thing with the given location.
It will keep all its attached Portals.
### Response:
def place2thing(self, name, location):
"""Turn a Place into a Thing with the given location.
It will kee... |
def exists(self):
"""
Test, if this task has been run.
"""
try:
self.es.get(index=self.marker_index, doc_type=self.marker_doc_type, id=self.marker_index_document_id())
return True
except elasticsearch.NotFoundError:
logger.debug('Marker documen... | Test, if this task has been run. | Below is the the instruction that describes the task:
### Input:
Test, if this task has been run.
### Response:
def exists(self):
"""
Test, if this task has been run.
"""
try:
self.es.get(index=self.marker_index, doc_type=self.marker_doc_type, id=self.marker_index_docume... |
def atlasdb_get_zonefiles_by_name(name, max_index=None, con=None, path=None):
"""
Look up the sequence of zone file records by name, optionally up to a specific zonefile index
Returns [{'zonefile_hash': ..., 'txid': ..., 'inv_index': ..., 'block_height': ..., 'present': ..., 'tried_storage': ...}], in block... | Look up the sequence of zone file records by name, optionally up to a specific zonefile index
Returns [{'zonefile_hash': ..., 'txid': ..., 'inv_index': ..., 'block_height': ..., 'present': ..., 'tried_storage': ...}], in blockchain order | Below is the the instruction that describes the task:
### Input:
Look up the sequence of zone file records by name, optionally up to a specific zonefile index
Returns [{'zonefile_hash': ..., 'txid': ..., 'inv_index': ..., 'block_height': ..., 'present': ..., 'tried_storage': ...}], in blockchain order
### Respo... |
def MakeProto():
"""Make sure our protos have been compiled to python libraries."""
# Start running from one directory above the grr directory which is found by
# this scripts's location as __file__.
cwd = os.path.dirname(os.path.abspath(__file__))
# Find all the .proto files.
protos_to_compile = []
for ... | Make sure our protos have been compiled to python libraries. | Below is the the instruction that describes the task:
### Input:
Make sure our protos have been compiled to python libraries.
### Response:
def MakeProto():
"""Make sure our protos have been compiled to python libraries."""
# Start running from one directory above the grr directory which is found by
# this s... |
def recursive_copy(source, destination):
"""A wrapper around distutils.dir_util.copy_tree but won't throw any exception when the source
directory does not exist.
Args:
source (str): source path
destination (str): destination path
"""
if os.path.isdir(source):
copy_tree(sourc... | A wrapper around distutils.dir_util.copy_tree but won't throw any exception when the source
directory does not exist.
Args:
source (str): source path
destination (str): destination path | Below is the the instruction that describes the task:
### Input:
A wrapper around distutils.dir_util.copy_tree but won't throw any exception when the source
directory does not exist.
Args:
source (str): source path
destination (str): destination path
### Response:
def recursive_copy(source... |
def connect(db_url=None,
pooling=hgvs.global_config.uta.pooling,
application_name=None,
mode=None,
cache=None):
"""Connect to a UTA database instance and return a UTA interface instance.
:param db_url: URL for database connection
:type db_url: string
:par... | Connect to a UTA database instance and return a UTA interface instance.
:param db_url: URL for database connection
:type db_url: string
:param pooling: whether to use connection pooling (postgresql only)
:type pooling: bool
:param application_name: log application name in connection (useful for deb... | Below is the the instruction that describes the task:
### Input:
Connect to a UTA database instance and return a UTA interface instance.
:param db_url: URL for database connection
:type db_url: string
:param pooling: whether to use connection pooling (postgresql only)
:type pooling: bool
:param... |
def fetch(self, card_id, data={}, **kwargs):
""""
Fetch Card for given Id
Args:
card_id : Id for which card object has to be retrieved
Returns:
Card dict for given card Id
"""
return super(Card, self).fetch(card_id, data, **kwargs) | Fetch Card for given Id
Args:
card_id : Id for which card object has to be retrieved
Returns:
Card dict for given card Id | Below is the the instruction that describes the task:
### Input:
Fetch Card for given Id
Args:
card_id : Id for which card object has to be retrieved
Returns:
Card dict for given card Id
### Response:
def fetch(self, card_id, data={}, **kwargs):
""""
Fetch ... |
def create_package(name, data, package_cls=None):
"""Create a package given package data.
Args:
name (str): Package name.
data (dict): Package data. Must conform to `package_maker.package_schema`.
Returns:
`Package` object.
"""
from rez.package_maker__ import PackageMaker
... | Create a package given package data.
Args:
name (str): Package name.
data (dict): Package data. Must conform to `package_maker.package_schema`.
Returns:
`Package` object. | Below is the the instruction that describes the task:
### Input:
Create a package given package data.
Args:
name (str): Package name.
data (dict): Package data. Must conform to `package_maker.package_schema`.
Returns:
`Package` object.
### Response:
def create_package(name, data, ... |
def get_version(path="src/devpy/__init__.py"):
""" Return the version of by with regex intead of importing it"""
init_content = open(path, "rt").read()
pattern = r"^__version__ = ['\"]([^'\"]*)['\"]"
return re.search(pattern, init_content, re.M).group(1) | Return the version of by with regex intead of importing it | Below is the the instruction that describes the task:
### Input:
Return the version of by with regex intead of importing it
### Response:
def get_version(path="src/devpy/__init__.py"):
""" Return the version of by with regex intead of importing it"""
init_content = open(path, "rt").read()
pattern = r"^... |
def in_scope(self, *args, **kw):
"""
Scope this object to a parent environment (like bind but reversed.)
"""
new_self = self.copy()
new_scopes = Object.translate_to_scopes(*args, **kw)
new_self._scopes = new_self._scopes + new_scopes
return new_self | Scope this object to a parent environment (like bind but reversed.) | Below is the the instruction that describes the task:
### Input:
Scope this object to a parent environment (like bind but reversed.)
### Response:
def in_scope(self, *args, **kw):
"""
Scope this object to a parent environment (like bind but reversed.)
"""
new_self = self.copy()
new_scopes = O... |
def iter_fields(self, schema: Schema) -> Iterable[Tuple[str, Field]]:
"""
Iterate through marshmallow schema fields.
Generates: name, field pairs
"""
for name in sorted(schema.fields.keys()):
field = schema.fields[name]
yield field.dump_to or name, field | Iterate through marshmallow schema fields.
Generates: name, field pairs | Below is the the instruction that describes the task:
### Input:
Iterate through marshmallow schema fields.
Generates: name, field pairs
### Response:
def iter_fields(self, schema: Schema) -> Iterable[Tuple[str, Field]]:
"""
Iterate through marshmallow schema fields.
Generates: na... |
def get_resource(self, uri, resource_type=None, response_format=None):
'''
Retrieve resource:
- Issues an initial GET request
- If 200, continues, 404, returns False, otherwise raises Exception
- Parse resource type
- If custom resource type parser provided, this fires
- Else, or if custom parser ... | Retrieve resource:
- Issues an initial GET request
- If 200, continues, 404, returns False, otherwise raises Exception
- Parse resource type
- If custom resource type parser provided, this fires
- Else, or if custom parser misses, fire HEAD request and parse LDP resource type from Link header
- Retu... | Below is the the instruction that describes the task:
### Input:
Retrieve resource:
- Issues an initial GET request
- If 200, continues, 404, returns False, otherwise raises Exception
- Parse resource type
- If custom resource type parser provided, this fires
- Else, or if custom parser misses, fir... |
def get_cherry_pick_for_ref_name(self, project, repository_id, ref_name):
"""GetCherryPickForRefName.
[Preview API] Retrieve information about a cherry pick for a specific branch.
:param str project: Project ID or project name
:param str repository_id: ID of the repository.
:para... | GetCherryPickForRefName.
[Preview API] Retrieve information about a cherry pick for a specific branch.
:param str project: Project ID or project name
:param str repository_id: ID of the repository.
:param str ref_name: The GitAsyncRefOperationParameters generatedRefName used for the cher... | Below is the the instruction that describes the task:
### Input:
GetCherryPickForRefName.
[Preview API] Retrieve information about a cherry pick for a specific branch.
:param str project: Project ID or project name
:param str repository_id: ID of the repository.
:param str ref_name: ... |
def upload_to_mugshot(instance, filename):
"""
Uploads a mugshot for a user to the ``USERENA_MUGSHOT_PATH`` and saving it
under unique hash for the image. This is for privacy reasons so others
can't just browse through the mugshot directory.
"""
extension = filename.split('.')[-1].lower()
s... | Uploads a mugshot for a user to the ``USERENA_MUGSHOT_PATH`` and saving it
under unique hash for the image. This is for privacy reasons so others
can't just browse through the mugshot directory. | Below is the the instruction that describes the task:
### Input:
Uploads a mugshot for a user to the ``USERENA_MUGSHOT_PATH`` and saving it
under unique hash for the image. This is for privacy reasons so others
can't just browse through the mugshot directory.
### Response:
def upload_to_mugshot(instance, f... |
def _expand_des_key(key):
"""
Expand the key from a 7-byte password key into a 8-byte DES key
"""
key = key[:7] + b'\0' * (7 - len(key))
byte = struct.unpack_from('BBBBBBB', key)
s = struct.pack('B', ((byte[0] >> 1) & 0x7f) << 1)
s += struct.pack("B", ((byte[0] &... | Expand the key from a 7-byte password key into a 8-byte DES key | Below is the the instruction that describes the task:
### Input:
Expand the key from a 7-byte password key into a 8-byte DES key
### Response:
def _expand_des_key(key):
"""
Expand the key from a 7-byte password key into a 8-byte DES key
"""
key = key[:7] + b'\0' * (7 - len(key))
... |
def _run_job(self):
"""
Build a bsub argument that will run lsf_runner.py on the directory we've specified.
"""
args = []
if isinstance(self.output(), list):
log_output = os.path.split(self.output()[0].path)
else:
log_output = os.path.split(self.... | Build a bsub argument that will run lsf_runner.py on the directory we've specified. | Below is the the instruction that describes the task:
### Input:
Build a bsub argument that will run lsf_runner.py on the directory we've specified.
### Response:
def _run_job(self):
"""
Build a bsub argument that will run lsf_runner.py on the directory we've specified.
"""
args = ... |
def get_bag_info(bag_file):
'''Get uamle dict of the bag information
by calling the subprocess -- used to create correct sized
arrays'''
# Get the info on the bag
bag_info = yaml.load(subprocess.Popen(
['rosbag', 'info', '--yaml', bag_file],
stdout=subprocess.PIPE).communicate()[0])
... | Get uamle dict of the bag information
by calling the subprocess -- used to create correct sized
arrays | Below is the the instruction that describes the task:
### Input:
Get uamle dict of the bag information
by calling the subprocess -- used to create correct sized
arrays
### Response:
def get_bag_info(bag_file):
'''Get uamle dict of the bag information
by calling the subprocess -- used to create corr... |
def update_widget(self, idx=None):
"""Forces the widget at given index to be updated from the
property value. If index is not given, all controlled
widgets will be updated. This method should be called
directly by the user when the property is not observable, or
in very unusual c... | Forces the widget at given index to be updated from the
property value. If index is not given, all controlled
widgets will be updated. This method should be called
directly by the user when the property is not observable, or
in very unusual conditions. | Below is the the instruction that describes the task:
### Input:
Forces the widget at given index to be updated from the
property value. If index is not given, all controlled
widgets will be updated. This method should be called
directly by the user when the property is not observable, or
... |
def word2array(ft_names, word):
"""Converts `word` [[(value, feature),...],...] to a NumPy array
Given a word consisting of lists of lists/sets of (value, feature) tuples,
return a NumPy array where each row is a segment and each column is a
feature.
Args:
ft_names (list): list of feature ... | Converts `word` [[(value, feature),...],...] to a NumPy array
Given a word consisting of lists of lists/sets of (value, feature) tuples,
return a NumPy array where each row is a segment and each column is a
feature.
Args:
ft_names (list): list of feature names (as strings) in order; this
... | Below is the the instruction that describes the task:
### Input:
Converts `word` [[(value, feature),...],...] to a NumPy array
Given a word consisting of lists of lists/sets of (value, feature) tuples,
return a NumPy array where each row is a segment and each column is a
feature.
Args:
ft_... |
def getLogs(self, CorpNum, MgtKeyType, MgtKey):
""" 세금계산서 문서이력 목록 확인
args
CorpNum : 회원 사업자 번호
MgtKeyType : 관리번호 유형 one of ['SELL','BUY','TRUSTEE']
MgtKey : 파트너 관리번호
return
문서이력 정보 목록 as List
raise
... | 세금계산서 문서이력 목록 확인
args
CorpNum : 회원 사업자 번호
MgtKeyType : 관리번호 유형 one of ['SELL','BUY','TRUSTEE']
MgtKey : 파트너 관리번호
return
문서이력 정보 목록 as List
raise
PopbillException | Below is the the instruction that describes the task:
### Input:
세금계산서 문서이력 목록 확인
args
CorpNum : 회원 사업자 번호
MgtKeyType : 관리번호 유형 one of ['SELL','BUY','TRUSTEE']
MgtKey : 파트너 관리번호
return
문서이력 정보 목록 as List
raise
... |
def unweave(target, *advices):
"""Unweave advices from input target."""
advices = (
advice if isinstance(advice, Advice) else Advice(advice)
for advice in advices
)
unweave(target=target, *advices) | Unweave advices from input target. | Below is the the instruction that describes the task:
### Input:
Unweave advices from input target.
### Response:
def unweave(target, *advices):
"""Unweave advices from input target."""
advices = (
advice if isinstance(advice, Advice) else Advice(advice)
for advice in advic... |
def _check_cols(df, col_names):
""" Raise an AttributeError if `df` does not have a column named as an item of
the list of strings `col_names`.
"""
for col in col_names:
if not hasattr(df, col):
raise AttributeError("DataFrame does not have a '{}' column, got {}.".format(col,
... | Raise an AttributeError if `df` does not have a column named as an item of
the list of strings `col_names`. | Below is the the instruction that describes the task:
### Input:
Raise an AttributeError if `df` does not have a column named as an item of
the list of strings `col_names`.
### Response:
def _check_cols(df, col_names):
""" Raise an AttributeError if `df` does not have a column named as an item of
the l... |
def points_close(a,b):
'''
points_close(a,b) yields True if points a and b are close to each other and False otherwise.
'''
(a,b) = [np.asarray(u) for u in (a,b)]
if len(a.shape) == 2 or len(b.shape) == 2: (a,b) = [np.reshape(u,(len(u),-1)) for u in (a,b)]
return np.isclose(np.sqrt(np.sum((a - b... | points_close(a,b) yields True if points a and b are close to each other and False otherwise. | Below is the the instruction that describes the task:
### Input:
points_close(a,b) yields True if points a and b are close to each other and False otherwise.
### Response:
def points_close(a,b):
'''
points_close(a,b) yields True if points a and b are close to each other and False otherwise.
'''
(a,... |
def gen_output_fmt_1(self, fmt):
"""given a single format specifier, get_output_fmt_1() constructs and returns
a list of tuples for matching against that specifier.
Each element of this list is a tuple
(gen_fmt, cvt_fmt, sz)
where:
gen_fmt is the Python forma... | given a single format specifier, get_output_fmt_1() constructs and returns
a list of tuples for matching against that specifier.
Each element of this list is a tuple
(gen_fmt, cvt_fmt, sz)
where:
gen_fmt is the Python format specifier for assembling this value into
... | Below is the the instruction that describes the task:
### Input:
given a single format specifier, get_output_fmt_1() constructs and returns
a list of tuples for matching against that specifier.
Each element of this list is a tuple
(gen_fmt, cvt_fmt, sz)
where:
ge... |
def WSGIHandler(self):
"""Returns GRR's WSGI handler."""
sdm = werkzeug_wsgi.SharedDataMiddleware(self, {
"/": config.CONFIG["AdminUI.document_root"],
})
# Use DispatcherMiddleware to make sure that SharedDataMiddleware is not
# used at all if the URL path doesn't start with "/static". This ... | Returns GRR's WSGI handler. | Below is the the instruction that describes the task:
### Input:
Returns GRR's WSGI handler.
### Response:
def WSGIHandler(self):
"""Returns GRR's WSGI handler."""
sdm = werkzeug_wsgi.SharedDataMiddleware(self, {
"/": config.CONFIG["AdminUI.document_root"],
})
# Use DispatcherMiddleware to ... |
def absolute_distance(cls, q0, q1):
"""Quaternion absolute distance.
Find the distance between two quaternions accounting for the sign ambiguity.
Params:
q0: the first quaternion
q1: the second quaternion
Returns:
A positive scalar corresponding to t... | Quaternion absolute distance.
Find the distance between two quaternions accounting for the sign ambiguity.
Params:
q0: the first quaternion
q1: the second quaternion
Returns:
A positive scalar corresponding to the chord of the shortest path/arc that
... | Below is the the instruction that describes the task:
### Input:
Quaternion absolute distance.
Find the distance between two quaternions accounting for the sign ambiguity.
Params:
q0: the first quaternion
q1: the second quaternion
Returns:
A positive sca... |
def reshape_fortran(tensor, shape):
"""The missing Fortran reshape for mx.NDArray
Parameters
----------
tensor : NDArray
source tensor
shape : NDArray
desired shape
Returns
-------
output : NDArray
reordered result
"""
return tensor.T.reshape(tuple(rever... | The missing Fortran reshape for mx.NDArray
Parameters
----------
tensor : NDArray
source tensor
shape : NDArray
desired shape
Returns
-------
output : NDArray
reordered result | Below is the the instruction that describes the task:
### Input:
The missing Fortran reshape for mx.NDArray
Parameters
----------
tensor : NDArray
source tensor
shape : NDArray
desired shape
Returns
-------
output : NDArray
reordered result
### Response:
def re... |
def fit(self, X, y=None):
"""
Build a trainer and run main_loop.
Parameters
----------
X : array_like
Training examples.
y : array_like, optional
Labels.
"""
from pylearn2.config import yaml_parse
from pylearn2.train import... | Build a trainer and run main_loop.
Parameters
----------
X : array_like
Training examples.
y : array_like, optional
Labels. | Below is the the instruction that describes the task:
### Input:
Build a trainer and run main_loop.
Parameters
----------
X : array_like
Training examples.
y : array_like, optional
Labels.
### Response:
def fit(self, X, y=None):
"""
Build a t... |
def associate(base_dir: str, rr_id: str, tails_hash: str) -> None:
"""
Create symbolic link to tails file named tails_hash for rev reg id rr_id.
:param rr_id: rev reg id
:param tails_hash: hash of tails file, serving as file name
"""
cd_id = rev_reg_id2cred_def_id(rr_id... | Create symbolic link to tails file named tails_hash for rev reg id rr_id.
:param rr_id: rev reg id
:param tails_hash: hash of tails file, serving as file name | Below is the the instruction that describes the task:
### Input:
Create symbolic link to tails file named tails_hash for rev reg id rr_id.
:param rr_id: rev reg id
:param tails_hash: hash of tails file, serving as file name
### Response:
def associate(base_dir: str, rr_id: str, tails_hash: str) ->... |
def sample(self, N=1):
"""Sample N trajectories from the posterior.
Note
----
Performs the forward step in case it has not been performed.
"""
if not self.filt:
self.forward()
paths = np.empty((len(self.filt), N), np.int)
paths[-1, ... | Sample N trajectories from the posterior.
Note
----
Performs the forward step in case it has not been performed. | Below is the the instruction that describes the task:
### Input:
Sample N trajectories from the posterior.
Note
----
Performs the forward step in case it has not been performed.
### Response:
def sample(self, N=1):
"""Sample N trajectories from the posterior.
... |
def model_functions(vk, model):
"""Fill the model with functions"""
def get_vk_extension_functions():
names = set()
for extension in get_extensions_filtered(vk):
for req in extension['require']:
if 'command' not in req:
continue
fo... | Fill the model with functions | Below is the the instruction that describes the task:
### Input:
Fill the model with functions
### Response:
def model_functions(vk, model):
"""Fill the model with functions"""
def get_vk_extension_functions():
names = set()
for extension in get_extensions_filtered(vk):
for req... |
def maybe_sendraw(self, host_port: Tuple[int, int], messagedata: bytes):
""" Send message to recipient if the transport is running. """
# Don't sleep if timeout is zero, otherwise a context-switch is done
# and the message is delayed, increasing its latency
sleep_timeout = self.throttle... | Send message to recipient if the transport is running. | Below is the the instruction that describes the task:
### Input:
Send message to recipient if the transport is running.
### Response:
def maybe_sendraw(self, host_port: Tuple[int, int], messagedata: bytes):
""" Send message to recipient if the transport is running. """
# Don't sleep if timeout is ... |
def D_s(self, H_0, Om0, Ode0=None):
"""
angular diameter to source
:param H_0: Hubble parameter [km/s/Mpc]
:param Om0: normalized matter density at present time
:return: float [Mpc]
"""
lensCosmo = self._get_cosom(H_0, Om0, Ode0)
return lensCosmo.D_s | angular diameter to source
:param H_0: Hubble parameter [km/s/Mpc]
:param Om0: normalized matter density at present time
:return: float [Mpc] | Below is the the instruction that describes the task:
### Input:
angular diameter to source
:param H_0: Hubble parameter [km/s/Mpc]
:param Om0: normalized matter density at present time
:return: float [Mpc]
### Response:
def D_s(self, H_0, Om0, Ode0=None):
"""
angular diamet... |
def _default_poll_callback(self, poll_resp):
"""
Checks the condition in poll response to determine if it is complete
and no subsequent poll requests should be done.
"""
if poll_resp.parsed is None:
return False
success_list = ['UpdatesComplete', True, 'COMPLE... | Checks the condition in poll response to determine if it is complete
and no subsequent poll requests should be done. | Below is the the instruction that describes the task:
### Input:
Checks the condition in poll response to determine if it is complete
and no subsequent poll requests should be done.
### Response:
def _default_poll_callback(self, poll_resp):
"""
Checks the condition in poll response to deter... |
def sc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Correlation (SC).
.. image:: /pictures/SC.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral correlation metric measures the ang... | Compute the Spectral Correlation (SC).
.. image:: /pictures/SC.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral correlation metric measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Para... | Below is the the instruction that describes the task:
### Input:
Compute the Spectral Correlation (SC).
.. image:: /pictures/SC.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral correlation metric measures the angle between the two vectors in
hyperspace. It indicates ... |
def tokenize(self, string):
"""Used to parce a string into tokens
This function is to take in a string and return a list of tokens
Args:
string(str): This is a string of words or a sentance to be parsed into tokens
Returns:
list: a list of tokens from the strin... | Used to parce a string into tokens
This function is to take in a string and return a list of tokens
Args:
string(str): This is a string of words or a sentance to be parsed into tokens
Returns:
list: a list of tokens from the string passed in.
Notes:
... | Below is the the instruction that describes the task:
### Input:
Used to parce a string into tokens
This function is to take in a string and return a list of tokens
Args:
string(str): This is a string of words or a sentance to be parsed into tokens
Returns:
list: a... |
def delete(self, config_object, purge=None, recurse=False):
"""
send a delete request
XXX [more here]
"""
rest_url = config_object.href
params = []
# purge deletes the SLD from disk when a style is deleted
if purge:
params.append("purge=" + st... | send a delete request
XXX [more here] | Below is the the instruction that describes the task:
### Input:
send a delete request
XXX [more here]
### Response:
def delete(self, config_object, purge=None, recurse=False):
"""
send a delete request
XXX [more here]
"""
rest_url = config_object.href
params... |
def filter_search(self, search):
"""Filter given search by the filter parameter given in request.
:param search: ElasticSearch query object
"""
builder = QueryBuilder(
self.filtering_fields,
self.filtering_map,
self
)
search, unmatche... | Filter given search by the filter parameter given in request.
:param search: ElasticSearch query object | Below is the the instruction that describes the task:
### Input:
Filter given search by the filter parameter given in request.
:param search: ElasticSearch query object
### Response:
def filter_search(self, search):
"""Filter given search by the filter parameter given in request.
:param s... |
def has_public(self):
"""Whether this JWK has an asymmetric Public key."""
if self.is_symmetric:
return False
reg = JWKValuesRegistry[self._params['kty']]
for value in reg:
if reg[value].public and value in self._key:
return True | Whether this JWK has an asymmetric Public key. | Below is the the instruction that describes the task:
### Input:
Whether this JWK has an asymmetric Public key.
### Response:
def has_public(self):
"""Whether this JWK has an asymmetric Public key."""
if self.is_symmetric:
return False
reg = JWKValuesRegistry[self._params['kty']... |
def FindByName(cls, name):
"""Find an installed VirtualTile by name.
This function searches for installed virtual tiles
using the pkg_resources entry_point `iotile.virtual_tile`.
If name is a path ending in .py, it is assumed to point to
a module on disk and loaded directly rat... | Find an installed VirtualTile by name.
This function searches for installed virtual tiles
using the pkg_resources entry_point `iotile.virtual_tile`.
If name is a path ending in .py, it is assumed to point to
a module on disk and loaded directly rather than using
pkg_resources.
... | Below is the the instruction that describes the task:
### Input:
Find an installed VirtualTile by name.
This function searches for installed virtual tiles
using the pkg_resources entry_point `iotile.virtual_tile`.
If name is a path ending in .py, it is assumed to point to
a module ... |
def proc_line_coordinate(self, line):
"""Extracts data from columns in ATOM/HETATM record."""
pdb_atom_col_dict = global_settings['ampal']['pdb_atom_col_dict']
at_type = line[0:6].strip() # 0
at_ser = int(line[6:11].strip()) # 1
at_name = line[12:16].strip() # 2
alt_lo... | Extracts data from columns in ATOM/HETATM record. | Below is the the instruction that describes the task:
### Input:
Extracts data from columns in ATOM/HETATM record.
### Response:
def proc_line_coordinate(self, line):
"""Extracts data from columns in ATOM/HETATM record."""
pdb_atom_col_dict = global_settings['ampal']['pdb_atom_col_dict']
at... |
def write(self,
fout=None,
fmt=SPARSE,
schema_only=False,
data_only=False):
"""
Write an arff structure to a string.
"""
assert not (schema_only and data_only), 'Make up your mind.'
assert fmt in FORMATS, 'Invalid format "%s". Should be one of: %s'... | Write an arff structure to a string. | Below is the the instruction that describes the task:
### Input:
Write an arff structure to a string.
### Response:
def write(self,
fout=None,
fmt=SPARSE,
schema_only=False,
data_only=False):
"""
Write an arff structure to a string.
"""
assert not (sc... |
def create_hit(
self,
title,
description,
keywords,
reward,
duration_hours,
lifetime_days,
ad_url,
notification_url,
approve_requirement,
max_assignments,
us_only,
blacklist=None,
annotation=None,
):
... | Create the actual HIT and return a dict with its useful properties. | Below is the the instruction that describes the task:
### Input:
Create the actual HIT and return a dict with its useful properties.
### Response:
def create_hit(
self,
title,
description,
keywords,
reward,
duration_hours,
lifetime_days,
ad_url,
... |
def send_request(self, method, url, headers=None,
json_data=None, retry=True):
"""Send requests to Skybell."""
if not self.cache(CONST.ACCESS_TOKEN) and url != CONST.LOGIN_URL:
self.login()
if not headers:
headers = {}
if self.cache(CONST.AC... | Send requests to Skybell. | Below is the the instruction that describes the task:
### Input:
Send requests to Skybell.
### Response:
def send_request(self, method, url, headers=None,
json_data=None, retry=True):
"""Send requests to Skybell."""
if not self.cache(CONST.ACCESS_TOKEN) and url != CONST.LOGIN_U... |
def add_warning(self, key, *args, **kwargs):
"""Add a warning to be triggered when the specified key is read
Parameters
----------
key : any hashable object
The key
"""
self._deprecations[key] = (args, kwargs) | Add a warning to be triggered when the specified key is read
Parameters
----------
key : any hashable object
The key | Below is the the instruction that describes the task:
### Input:
Add a warning to be triggered when the specified key is read
Parameters
----------
key : any hashable object
The key
### Response:
def add_warning(self, key, *args, **kwargs):
"""Add a warning to be trigge... |
def get_columns(self, *, top=None, skip=None):
"""
Return the columns of this table
:param int top: specify n columns to retrieve
:param int skip: specify n columns to skip
"""
url = self.build_url(self._endpoints.get('get_columns'))
params = {}
if top is... | Return the columns of this table
:param int top: specify n columns to retrieve
:param int skip: specify n columns to skip | Below is the the instruction that describes the task:
### Input:
Return the columns of this table
:param int top: specify n columns to retrieve
:param int skip: specify n columns to skip
### Response:
def get_columns(self, *, top=None, skip=None):
"""
Return the columns of this tabl... |
def sp_to_rshares(self, sp, voting_power=10000, vote_pct=10000):
""" Obtain the r-shares
:param number sp: Steem Power
:param int voting_power: voting power (100% = 10000)
:param int vote_pct: voting participation (100% = 10000)
"""
vesting_shares = int(self.s... | Obtain the r-shares
:param number sp: Steem Power
:param int voting_power: voting power (100% = 10000)
:param int vote_pct: voting participation (100% = 10000) | Below is the the instruction that describes the task:
### Input:
Obtain the r-shares
:param number sp: Steem Power
:param int voting_power: voting power (100% = 10000)
:param int vote_pct: voting participation (100% = 10000)
### Response:
def sp_to_rshares(self, sp, voting_power... |
def nan_circstd(samples, high=2.0*np.pi, low=0.0, axis=None):
"""NaN insensitive version of scipy's circular standard deviation routine
Parameters
-----------
samples : array_like
Input array
low : float or int
Lower boundary for circular standard deviation range (default=0)
hig... | NaN insensitive version of scipy's circular standard deviation routine
Parameters
-----------
samples : array_like
Input array
low : float or int
Lower boundary for circular standard deviation range (default=0)
high: float or int
Upper boundary for circular standard deviatio... | Below is the the instruction that describes the task:
### Input:
NaN insensitive version of scipy's circular standard deviation routine
Parameters
-----------
samples : array_like
Input array
low : float or int
Lower boundary for circular standard deviation range (default=0)
hig... |
def update_external_account(resource_root, account):
"""
Update an external account
@param resource_root: The root Resource object.
@param account: Account to update, account name must be specified.
@return: An ApiExternalAccount object, representing the updated external account
"""
return call(resource_r... | Update an external account
@param resource_root: The root Resource object.
@param account: Account to update, account name must be specified.
@return: An ApiExternalAccount object, representing the updated external account | Below is the the instruction that describes the task:
### Input:
Update an external account
@param resource_root: The root Resource object.
@param account: Account to update, account name must be specified.
@return: An ApiExternalAccount object, representing the updated external account
### Response:
def upd... |
def _service_by_name(name):
'''
Return the service info for a service by label, filename or path
'''
services = _available_services()
name = name.lower()
if name in services:
# Match on label
return services[name]
for service in six.itervalues(services):
if service[... | Return the service info for a service by label, filename or path | Below is the the instruction that describes the task:
### Input:
Return the service info for a service by label, filename or path
### Response:
def _service_by_name(name):
'''
Return the service info for a service by label, filename or path
'''
services = _available_services()
name = name.lower... |
def day_counts(index):
"""Days between DatetimeIndex values as a :any:`pandas.Series`.
Parameters
----------
index : :any:`pandas.DatetimeIndex`
The index for which to get day counts.
Returns
-------
day_counts : :any:`pandas.Series`
A :any:`pandas.Series` with counts of da... | Days between DatetimeIndex values as a :any:`pandas.Series`.
Parameters
----------
index : :any:`pandas.DatetimeIndex`
The index for which to get day counts.
Returns
-------
day_counts : :any:`pandas.Series`
A :any:`pandas.Series` with counts of days between periods. Counts are... | Below is the the instruction that describes the task:
### Input:
Days between DatetimeIndex values as a :any:`pandas.Series`.
Parameters
----------
index : :any:`pandas.DatetimeIndex`
The index for which to get day counts.
Returns
-------
day_counts : :any:`pandas.Series`
A... |
def RZToplanarPotential(RZPot):
"""
NAME:
RZToplanarPotential
PURPOSE:
convert an RZPotential to a planarPotential in the mid-plane (z=0)
INPUT:
RZPot - RZPotential instance or list of such instances (existing planarPotential instances are just copied to the output)
OUTPUT... | NAME:
RZToplanarPotential
PURPOSE:
convert an RZPotential to a planarPotential in the mid-plane (z=0)
INPUT:
RZPot - RZPotential instance or list of such instances (existing planarPotential instances are just copied to the output)
OUTPUT:
planarPotential instance(s)
H... | Below is the the instruction that describes the task:
### Input:
NAME:
RZToplanarPotential
PURPOSE:
convert an RZPotential to a planarPotential in the mid-plane (z=0)
INPUT:
RZPot - RZPotential instance or list of such instances (existing planarPotential instances are just copied t... |
def _get_block_transactions(
self,
transaction_root: Hash32,
transaction_class: Type['BaseTransaction']) -> Iterable['BaseTransaction']:
"""
Memoizable version of `get_block_transactions`
"""
for encoded_transaction in self._get_block_transaction_data(... | Memoizable version of `get_block_transactions` | Below is the the instruction that describes the task:
### Input:
Memoizable version of `get_block_transactions`
### Response:
def _get_block_transactions(
self,
transaction_root: Hash32,
transaction_class: Type['BaseTransaction']) -> Iterable['BaseTransaction']:
"""
... |
def decode(name, byts, **opts):
'''
Decode the given byts with the named decoder.
If name is a comma separated list of decoders,
loop through and do them all.
Example:
byts = s_encoding.decode('base64',byts)
Note: Decoder names may also be prefixed with +
to *encode* for tha... | Decode the given byts with the named decoder.
If name is a comma separated list of decoders,
loop through and do them all.
Example:
byts = s_encoding.decode('base64',byts)
Note: Decoder names may also be prefixed with +
to *encode* for that name/layer. | Below is the the instruction that describes the task:
### Input:
Decode the given byts with the named decoder.
If name is a comma separated list of decoders,
loop through and do them all.
Example:
byts = s_encoding.decode('base64',byts)
Note: Decoder names may also be prefixed with +
... |
def get_qrcode_url(self, ticket, data=None):
"""
通过 ticket 换取二维码地址
详情请参考
https://iot.weixin.qq.com/wiki/new/index.html?page=3-4-4
:param ticket: 二维码 ticket
:param data: 额外数据
:return: 二维码地址
"""
url = 'https://we.qq.com/d/{ticket}'.format(ticket=tic... | 通过 ticket 换取二维码地址
详情请参考
https://iot.weixin.qq.com/wiki/new/index.html?page=3-4-4
:param ticket: 二维码 ticket
:param data: 额外数据
:return: 二维码地址 | Below is the the instruction that describes the task:
### Input:
通过 ticket 换取二维码地址
详情请参考
https://iot.weixin.qq.com/wiki/new/index.html?page=3-4-4
:param ticket: 二维码 ticket
:param data: 额外数据
:return: 二维码地址
### Response:
def get_qrcode_url(self, ticket, data=None):
""... |
def do_classdesc(self, parent=None, ident=0):
"""
Handles a TC_CLASSDESC opcode
:param parent:
:param ident: Log indentation level
:return: A JavaClass object
"""
# TC_CLASSDESC className serialVersionUID newHandle classDescInfo
# classDescInfo:
#... | Handles a TC_CLASSDESC opcode
:param parent:
:param ident: Log indentation level
:return: A JavaClass object | Below is the the instruction that describes the task:
### Input:
Handles a TC_CLASSDESC opcode
:param parent:
:param ident: Log indentation level
:return: A JavaClass object
### Response:
def do_classdesc(self, parent=None, ident=0):
"""
Handles a TC_CLASSDESC opcode
... |
def f_get_default(self, name, default=None, fast_access=True, with_links=True,
shortcuts=True, max_depth=None, auto_load=False):
""" Similar to `f_get`, but returns the default value if `name` is not found in the
trajectory.
This function uses the `f_get` method and will return th... | Similar to `f_get`, but returns the default value if `name` is not found in the
trajectory.
This function uses the `f_get` method and will return the default value
in case `f_get` raises an AttributeError or a DataNotInStorageError.
Other errors are not handled.
In contrast to ... | Below is the the instruction that describes the task:
### Input:
Similar to `f_get`, but returns the default value if `name` is not found in the
trajectory.
This function uses the `f_get` method and will return the default value
in case `f_get` raises an AttributeError or a DataNotInStorage... |
def unquote(str):
"""Remove quotes from a string."""
if len(str) > 1:
if str.startswith('"') and str.endswith('"'):
return str[1:-1].replace('\\\\', '\\').replace('\\"', '"')
if str.startswith('<') and str.endswith('>'):
return str[1:-1]
return str | Remove quotes from a string. | Below is the the instruction that describes the task:
### Input:
Remove quotes from a string.
### Response:
def unquote(str):
"""Remove quotes from a string."""
if len(str) > 1:
if str.startswith('"') and str.endswith('"'):
return str[1:-1].replace('\\\\', '\\').replace('\\"', '"')
... |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: SyncListPermissionContext for this SyncListPermissionInstance
:rtype: twilio.rest.sync.v1.service... | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: SyncListPermissionContext for this SyncListPermissionInstance
:rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncLi... | Below is the the instruction that describes the task:
### Input:
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: SyncListPermissionContext for this SyncListPermissionInstance
:rty... |
def optimize_var(self):
""" Optimize the VAR model's hyperparameters (such as regularization).
Returns
-------
self : Workspace
The Workspace object.
Raises
------
RuntimeError
If the :class:`Workspace` instance does not contain source ac... | Optimize the VAR model's hyperparameters (such as regularization).
Returns
-------
self : Workspace
The Workspace object.
Raises
------
RuntimeError
If the :class:`Workspace` instance does not contain source activations. | Below is the the instruction that describes the task:
### Input:
Optimize the VAR model's hyperparameters (such as regularization).
Returns
-------
self : Workspace
The Workspace object.
Raises
------
RuntimeError
If the :class:`Workspace` in... |
def get_jids():
'''
Return all job data from all returners
'''
ret = {}
for returner_ in __opts__[CONFIG_KEY]:
ret.update(_mminion().returners['{0}.get_jids'.format(returner_)]())
return ret | Return all job data from all returners | Below is the the instruction that describes the task:
### Input:
Return all job data from all returners
### Response:
def get_jids():
'''
Return all job data from all returners
'''
ret = {}
for returner_ in __opts__[CONFIG_KEY]:
ret.update(_mminion().returners['{0}.get_jids'.format(retu... |
def _trim_external_pores(self, shape):
r'''
'''
# Find all pores within the domain
Ps = topotools.isoutside(coords=self['pore.coords'], shape=shape)
self['pore.external'] = False
self['pore.external'][Ps] = True
# Find which internal pores are delaunay
Ps... | r''' | Below is the the instruction that describes the task:
### Input:
r'''
### Response:
def _trim_external_pores(self, shape):
r'''
'''
# Find all pores within the domain
Ps = topotools.isoutside(coords=self['pore.coords'], shape=shape)
self['pore.external'] = False
self... |
def dft_optsize_same(im0, im1):
"""Resize 2 image same size for optimal DFT and computes it
Parameters
----------
im0: 2d array
First image
im1: 2d array
Second image
Returns
-------
dft0: 2d array
The dft of the first image
dft1: 2d array
The dft of... | Resize 2 image same size for optimal DFT and computes it
Parameters
----------
im0: 2d array
First image
im1: 2d array
Second image
Returns
-------
dft0: 2d array
The dft of the first image
dft1: 2d array
The dft of the second image
Notes
-----
... | Below is the the instruction that describes the task:
### Input:
Resize 2 image same size for optimal DFT and computes it
Parameters
----------
im0: 2d array
First image
im1: 2d array
Second image
Returns
-------
dft0: 2d array
The dft of the first image
dft... |
def verify_reg(self, obj, object_type):
"""Verify a register."""
# How to verify:
# types must match
# indexes must be checked
if obj.name not in self.global_symtab:
raise QasmError('Cannot find definition for', object_type, "'"
+ obj... | Verify a register. | Below is the the instruction that describes the task:
### Input:
Verify a register.
### Response:
def verify_reg(self, obj, object_type):
"""Verify a register."""
# How to verify:
# types must match
# indexes must be checked
if obj.name not in self.global_symtab:
... |
def get_segment_leaderboard(self, segment_id, gender=None, age_group=None, weight_class=None,
following=None, club_id=None, timeframe=None, top_results_limit=None,
page=None, context_entries = None):
"""
Gets the leaderboard for a segment.
... | Gets the leaderboard for a segment.
http://strava.github.io/api/v3/segments/#leaderboard
Note that by default Strava will return the top 10 results, and if the current user has ridden
that segment, the current user's result along with the two results above in rank and the two
results b... | Below is the the instruction that describes the task:
### Input:
Gets the leaderboard for a segment.
http://strava.github.io/api/v3/segments/#leaderboard
Note that by default Strava will return the top 10 results, and if the current user has ridden
that segment, the current user's result a... |
def iterate_schema(fields, schema, path=None):
"""Recursively iterate over all schema sub-fields.
:param fields: Field instance (e.g. input)
:type fields: dict
:param schema: Schema instance (e.g. input_schema)
:type schema: dict
:path schema: Field path
:path schema: string
"""
fo... | Recursively iterate over all schema sub-fields.
:param fields: Field instance (e.g. input)
:type fields: dict
:param schema: Schema instance (e.g. input_schema)
:type schema: dict
:path schema: Field path
:path schema: string | Below is the the instruction that describes the task:
### Input:
Recursively iterate over all schema sub-fields.
:param fields: Field instance (e.g. input)
:type fields: dict
:param schema: Schema instance (e.g. input_schema)
:type schema: dict
:path schema: Field path
:path schema: string
... |
def check_partial(func, *args, **kwargs):
"""Create a partial to be used by goodtables."""
new_func = partial(func, *args, **kwargs)
new_func.check = func.check
return new_func | Create a partial to be used by goodtables. | Below is the the instruction that describes the task:
### Input:
Create a partial to be used by goodtables.
### Response:
def check_partial(func, *args, **kwargs):
"""Create a partial to be used by goodtables."""
new_func = partial(func, *args, **kwargs)
new_func.check = func.check
return new_func |
def _replace(self, data, replacements):
"""
Given a list of 2-tuples (find, repl) this function performs all
replacements on the input and returns the result.
"""
for find, repl in replacements:
data = data.replace(find, repl)
return data | Given a list of 2-tuples (find, repl) this function performs all
replacements on the input and returns the result. | Below is the the instruction that describes the task:
### Input:
Given a list of 2-tuples (find, repl) this function performs all
replacements on the input and returns the result.
### Response:
def _replace(self, data, replacements):
"""
Given a list of 2-tuples (find, repl) this function p... |
def aggregate(self, dataset_ids=None, boundary='exact', side='left', func='mean', **dim_kwargs):
"""Create an aggregated version of the Scene.
Args:
dataset_ids (iterable): DatasetIDs to include in the returned
`Scene`. Defaults to all datasets.
... | Create an aggregated version of the Scene.
Args:
dataset_ids (iterable): DatasetIDs to include in the returned
`Scene`. Defaults to all datasets.
func (string): Function to apply on each aggregation window. One of
'mean', 's... | Below is the the instruction that describes the task:
### Input:
Create an aggregated version of the Scene.
Args:
dataset_ids (iterable): DatasetIDs to include in the returned
`Scene`. Defaults to all datasets.
func (string): Function to apply on ... |
def drop_all(self):
"""Drops all tables in the database"""
log.info('dropping tables in %s', self.engine.url)
self.session.commit()
models.Base.metadata.drop_all(self.engine)
self.session.commit() | Drops all tables in the database | Below is the the instruction that describes the task:
### Input:
Drops all tables in the database
### Response:
def drop_all(self):
"""Drops all tables in the database"""
log.info('dropping tables in %s', self.engine.url)
self.session.commit()
models.Base.metadata.drop_all(self.engi... |
def logvol_prefactor(n, p=2.):
"""
Returns the ln(volume constant) for an `n`-dimensional sphere with an
:math:`L^p` norm. The constant is defined as::
lnf = n * ln(2.) + n * LogGamma(1./p + 1) - LogGamma(n/p + 1.)
By default the `p=2.` norm is used (i.e. the standard Euclidean norm).
"""... | Returns the ln(volume constant) for an `n`-dimensional sphere with an
:math:`L^p` norm. The constant is defined as::
lnf = n * ln(2.) + n * LogGamma(1./p + 1) - LogGamma(n/p + 1.)
By default the `p=2.` norm is used (i.e. the standard Euclidean norm). | Below is the the instruction that describes the task:
### Input:
Returns the ln(volume constant) for an `n`-dimensional sphere with an
:math:`L^p` norm. The constant is defined as::
lnf = n * ln(2.) + n * LogGamma(1./p + 1) - LogGamma(n/p + 1.)
By default the `p=2.` norm is used (i.e. the standard... |
def list_boards(self):
"""Return a list with all the supported boards"""
# Print table
click.echo('\nSupported boards:\n')
BOARDLIST_TPL = ('{board:25} {fpga:20} {type:<5} {size:<5} {pack:<10}')
terminal_width, _ = click.get_terminal_size()
click.echo('-' * terminal_wi... | Return a list with all the supported boards | Below is the the instruction that describes the task:
### Input:
Return a list with all the supported boards
### Response:
def list_boards(self):
"""Return a list with all the supported boards"""
# Print table
click.echo('\nSupported boards:\n')
BOARDLIST_TPL = ('{board:25} {fpga:... |
def transform_sequence(f):
"""
A decorator to take a function operating on a point and
turn it into a function returning a callable operating on a sequence.
The functions passed to this decorator must define a kwarg called "point",
or have point be the last positional argument
"""
@wraps(f)
... | A decorator to take a function operating on a point and
turn it into a function returning a callable operating on a sequence.
The functions passed to this decorator must define a kwarg called "point",
or have point be the last positional argument | Below is the the instruction that describes the task:
### Input:
A decorator to take a function operating on a point and
turn it into a function returning a callable operating on a sequence.
The functions passed to this decorator must define a kwarg called "point",
or have point be the last positional a... |
def save_form(self, form):
"""
Save a valid form. If there is a parent attribute,
this will make sure that the parent object is added
to the saved object. Either as a relationship before
saving or in the case of many to many relations after
saving. Any forced instance val... | Save a valid form. If there is a parent attribute,
this will make sure that the parent object is added
to the saved object. Either as a relationship before
saving or in the case of many to many relations after
saving. Any forced instance values are set as well.
Returns the saved... | Below is the the instruction that describes the task:
### Input:
Save a valid form. If there is a parent attribute,
this will make sure that the parent object is added
to the saved object. Either as a relationship before
saving or in the case of many to many relations after
saving. A... |
def real_value(value, digit):
"""
function to calculate the real value
we need to devide the value by the digit
e.g.
value = 100
digit = 2
return: "1.0"
"""
return str(float(value) / math.pow(10, float(digit))) | function to calculate the real value
we need to devide the value by the digit
e.g.
value = 100
digit = 2
return: "1.0" | Below is the the instruction that describes the task:
### Input:
function to calculate the real value
we need to devide the value by the digit
e.g.
value = 100
digit = 2
return: "1.0"
### Response:
def real_value(value, digit):
"""
function to calcula... |
def yeardoy2datetime(yeardate: int,
utsec: Union[float, int] = None) -> datetime.datetime:
"""
Inputs:
yd: yyyyddd four digit year, 3 digit day of year (INTEGER 7 digits)
outputs:
t: datetime
http://stackoverflow.com/questions/2427555/python-question-year-and-day-of-year-t... | Inputs:
yd: yyyyddd four digit year, 3 digit day of year (INTEGER 7 digits)
outputs:
t: datetime
http://stackoverflow.com/questions/2427555/python-question-year-and-day-of-year-to-date | Below is the the instruction that describes the task:
### Input:
Inputs:
yd: yyyyddd four digit year, 3 digit day of year (INTEGER 7 digits)
outputs:
t: datetime
http://stackoverflow.com/questions/2427555/python-question-year-and-day-of-year-to-date
### Response:
def yeardoy2datetime(yeardate: in... |
def apply_config(self, config):
"""
Constructs HAProxyConfig and HAProxyControl instances based on the
contents of the config.
This is mostly a matter of constructing the configuration stanzas.
"""
self.haproxy_config_path = config["config_file"]
global_stanza =... | Constructs HAProxyConfig and HAProxyControl instances based on the
contents of the config.
This is mostly a matter of constructing the configuration stanzas. | Below is the the instruction that describes the task:
### Input:
Constructs HAProxyConfig and HAProxyControl instances based on the
contents of the config.
This is mostly a matter of constructing the configuration stanzas.
### Response:
def apply_config(self, config):
"""
Construct... |
def make_named_stemmer(stem=None, min_len=3):
"""Construct a callable object and a string sufficient to reconstruct it later (unpickling)
>>> make_named_stemmer('str_lower')
('str_lower', <function str_lower at ...>)
>>> make_named_stemmer('Lancaster')
('lancaster', <Stemmer object at ...>)
"""... | Construct a callable object and a string sufficient to reconstruct it later (unpickling)
>>> make_named_stemmer('str_lower')
('str_lower', <function str_lower at ...>)
>>> make_named_stemmer('Lancaster')
('lancaster', <Stemmer object at ...>) | Below is the the instruction that describes the task:
### Input:
Construct a callable object and a string sufficient to reconstruct it later (unpickling)
>>> make_named_stemmer('str_lower')
('str_lower', <function str_lower at ...>)
>>> make_named_stemmer('Lancaster')
('lancaster', <Stemmer object ... |
def AddMemberDefinition(self, member_definition):
"""Adds a member definition.
Args:
member_definition (DataTypeDefinition): member data type definition.
"""
self._byte_size = None
self.members.append(member_definition)
if self.sections:
section_definition = self.sections[-1]
... | Adds a member definition.
Args:
member_definition (DataTypeDefinition): member data type definition. | Below is the the instruction that describes the task:
### Input:
Adds a member definition.
Args:
member_definition (DataTypeDefinition): member data type definition.
### Response:
def AddMemberDefinition(self, member_definition):
"""Adds a member definition.
Args:
member_definition (DataT... |
def dir2fn(ofn, ifn, suffix) -> Union[None, Path]:
"""
ofn = filename or output directory, to create filename based on ifn
ifn = input filename (don't overwrite!)
suffix = desired file extension e.g. .h5
"""
if not ofn: # no output file desired
return None
ofn = Path(ofn).expanduse... | ofn = filename or output directory, to create filename based on ifn
ifn = input filename (don't overwrite!)
suffix = desired file extension e.g. .h5 | Below is the the instruction that describes the task:
### Input:
ofn = filename or output directory, to create filename based on ifn
ifn = input filename (don't overwrite!)
suffix = desired file extension e.g. .h5
### Response:
def dir2fn(ofn, ifn, suffix) -> Union[None, Path]:
"""
ofn = filename o... |
def transition(self, state, message=""):
"""Change to a new state if the transition is allowed
Args:
state (str): State to transition to
message (str): Message if the transition is to a fault state
"""
with self.changes_squashed:
initial_state = self.... | Change to a new state if the transition is allowed
Args:
state (str): State to transition to
message (str): Message if the transition is to a fault state | Below is the the instruction that describes the task:
### Input:
Change to a new state if the transition is allowed
Args:
state (str): State to transition to
message (str): Message if the transition is to a fault state
### Response:
def transition(self, state, message=""):
... |
def index():
"""Show the index with all posts.
:param int all: Whether or not should show all posts
"""
context = {'postform': NewPostForm(),
'pageform': NewPageForm(),
'delform': DeleteForm()}
n = request.args.get('all')
if n is None:
wants_now = None
... | Show the index with all posts.
:param int all: Whether or not should show all posts | Below is the the instruction that describes the task:
### Input:
Show the index with all posts.
:param int all: Whether or not should show all posts
### Response:
def index():
"""Show the index with all posts.
:param int all: Whether or not should show all posts
"""
context = {'postform': New... |
def get_method_by_idx(self, idx):
"""
Return a specific method by using an index
:param idx: the index of the method
:type idx: int
:rtype: None or an :class:`EncodedMethod` object
"""
if self.__cached_methods_idx == None:
self.__cached_method... | Return a specific method by using an index
:param idx: the index of the method
:type idx: int
:rtype: None or an :class:`EncodedMethod` object | Below is the the instruction that describes the task:
### Input:
Return a specific method by using an index
:param idx: the index of the method
:type idx: int
:rtype: None or an :class:`EncodedMethod` object
### Response:
def get_method_by_idx(self, idx):
"""
Return... |
def alts_columns_used(self):
"""
Columns from the alternatives table that are used for filtering.
"""
return list(tz.unique(tz.concat(
m.alts_columns_used() for m in self.models.values()))) | Columns from the alternatives table that are used for filtering. | Below is the the instruction that describes the task:
### Input:
Columns from the alternatives table that are used for filtering.
### Response:
def alts_columns_used(self):
"""
Columns from the alternatives table that are used for filtering.
"""
return list(tz.unique(tz.concat(
... |
def _inhibitColumns(self, overlaps):
"""
Performs inhibition. This method calculates the necessary values needed to
actually perform inhibition and then delegates the task of picking the
active columns to helper functions.
Parameters:
----------------------------
:param overlaps: an array c... | Performs inhibition. This method calculates the necessary values needed to
actually perform inhibition and then delegates the task of picking the
active columns to helper functions.
Parameters:
----------------------------
:param overlaps: an array containing the overlap score for each column.
... | Below is the the instruction that describes the task:
### Input:
Performs inhibition. This method calculates the necessary values needed to
actually perform inhibition and then delegates the task of picking the
active columns to helper functions.
Parameters:
----------------------------
:param ... |
def create_event(self, actors=None, ignore_duplicates=False, **kwargs):
"""
Create events with actors.
This method can be used in place of ``Event.objects.create``
to create events, and the appropriate actors. It takes all the
same keywords as ``Event.objects.create`` for the ev... | Create events with actors.
This method can be used in place of ``Event.objects.create``
to create events, and the appropriate actors. It takes all the
same keywords as ``Event.objects.create`` for the event
creation, but additionally takes a list of actors, and can be
told to no... | Below is the the instruction that describes the task:
### Input:
Create events with actors.
This method can be used in place of ``Event.objects.create``
to create events, and the appropriate actors. It takes all the
same keywords as ``Event.objects.create`` for the event
creation, b... |
def _remove_debug_handlers(self):
"""Remove any handlers with an attribute of debug_only that is True and
remove the references to said handlers from any loggers that are
referencing them.
"""
remove = list()
for handler in self.config[self.HANDLERS]:
if self... | Remove any handlers with an attribute of debug_only that is True and
remove the references to said handlers from any loggers that are
referencing them. | Below is the the instruction that describes the task:
### Input:
Remove any handlers with an attribute of debug_only that is True and
remove the references to said handlers from any loggers that are
referencing them.
### Response:
def _remove_debug_handlers(self):
"""Remove any handlers wit... |
def tabbar_toggled(self, settings, key, user_data):
"""If the gconf var use_tabbar be changed, this method will be
called and will show/hide the tabbar.
"""
if settings.get_boolean(key):
for n in self.guake.notebook_manager.iter_notebooks():
n.set_property("sh... | If the gconf var use_tabbar be changed, this method will be
called and will show/hide the tabbar. | Below is the the instruction that describes the task:
### Input:
If the gconf var use_tabbar be changed, this method will be
called and will show/hide the tabbar.
### Response:
def tabbar_toggled(self, settings, key, user_data):
"""If the gconf var use_tabbar be changed, this method will be
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.