text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def random_str(length=16, only_digits=False):
"""
生成随机字符串
:return:
"""
choices = string.digits
if not only_digits:
choices += string.ascii_uppercase
return ''.join(random.SystemRandom().choice(choices)
for _ in range(length)) | 0.003546 |
def autoscale_y(ax,margin=0.1):
"""This function rescales the y-axis based on the data that is visible given the current xlim of the axis.
ax -- a matplotlib axes object
margin -- the fraction of the total height of the y-data to pad the upper and lower ylims"""
# Thanks to http://stackoverflow.com/ques... | 0.020188 |
def log_local_message(message_format, *args):
"""
Log a request so that it matches our local log format.
"""
prefix = '{} {}'.format(color('INFO', fg=248), color('request', fg=5))
message = message_format % args
sys.stderr.write('{} {}\n'.format(prefix, message)) | 0.003472 |
def tempo_account_add_customer(self, data=None):
"""
Gets all or some Attribute whose key or name contain a specific substring.
Attributes can be a Category or Customer.
:param data:
:return: if error will show in error log, like validation unsuccessful. If success will good.
... | 0.006859 |
def field(ctx, text, index, delimiter=' '):
"""
Reference a field in string separated by a delimiter
"""
splits = text.split(delimiter)
# remove our delimiters and whitespace
splits = [f for f in splits if f != delimiter and len(f.strip()) > 0]
index = conversions.to_integer(index, ctx)
... | 0.002058 |
def save_translations(self, instances):
"""
Saves cached translations (cached in model instances as dictionaries).
"""
if not isinstance(instances, (list, tuple)):
instances = [instances]
for instance in instances:
translations = []
for obj ... | 0.002887 |
def _datalog(self, parameter, run, maxrun, det_id):
"Extract data from database"
values = {
'parameter_name': parameter,
'minrun': run,
'maxrun': maxrun,
'detid': det_id,
}
data = urlencode(values)
content = self._get_content('strea... | 0.002012 |
def _do_prioritize(items):
"""Determine if we should perform prioritization.
Currently done on tumor-only input samples and feeding into PureCN
which needs the germline annotations.
"""
if not any("tumoronly-prioritization" in dd.get_tools_off(d) for d in items):
if vcfutils.get_paired_phen... | 0.002857 |
def parse(args):
"""Parse command-line arguments. Arguments may consist of any
combination of directories, files, and options."""
import argparse
parser = argparse.ArgumentParser(
add_help=False,
description="Remove spam and advertising from subtitle files.",
usage="%(prog)s [O... | 0.000547 |
def appendGraph(self, graph_name, graph):
"""Utility method to associate Graph Object to Plugin.
This utility method is for use in constructor of child classes for
associating a MuninGraph instances to the plugin.
@param graph_name: Graph Name
@param graph: ... | 0.010033 |
def reset(self):
"""Clear ConfigObj instance and restore to 'freshly created' state."""
self.clear()
self._initialise()
# FIXME: Should be done by '_initialise', but ConfigObj constructor (and reload)
# requires an empty dictionary
self.configspec = None
# ... | 0.007895 |
def _plugin_get(self, plugin_name):
"""
Find plugins in controller
:param plugin_name: Name of the plugin to find
:type plugin_name: str | None
:return: Plugin or None and error message
:rtype: (settable_plugin.SettablePlugin | None, str)
"""
if not plugi... | 0.003058 |
def bsrchi(value, ndim, array):
"""
Do a binary search for a key value within an integer array,
assumed to be in increasing order. Return the index of the
matching array entry, or -1 if the key value is not found.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bsrchi_c.html
:param val... | 0.001453 |
def print_version(ctx, value):
"""Print the current version of sandman and exit."""
if not value:
return
import pkg_resources
version = None
try:
version = pkg_resources.get_distribution('sandman').version
finally:
del pkg_resources
click.echo(version)
ctx.exit() | 0.003135 |
def returner(ret):
'''
Write the return data to a file on the minion.
'''
opts = _get_options(ret)
try:
with salt.utils.files.flopen(opts['filename'], 'a') as logfile:
salt.utils.json.dump(ret, logfile)
logfile.write(str('\n')) # future lint: disable=blacklisted-func... | 0.004556 |
def write(self, *args, **kwargs):
"""Deprecated, use :meth:`~chemcoord.Zmat.to_zmat`
"""
message = 'Will be removed in the future. Please use to_zmat().'
with warnings.catch_warnings():
warnings.simplefilter("always")
warnings.warn(message, DeprecationWarning)
... | 0.00554 |
def _derive(self, record, hist=None):
"""
Derivation filters like 'deriveValue' to replace given input values
from one or more fields. In case 'copyValue' copy value to the target
field from given an input value from one field. 'deriveRegex' replace
given an input value from one ... | 0.000854 |
def locally(self):
"""
Will execute the current queryset and pass it to the python backend
so user can run query on the local dataset (instead of contacting the store)
"""
from .backends import python
from . import models
store = python.IterableStore(values=self... | 0.008021 |
def load_ply(fileobj):
"""Same as load_ply, but takes a file-like object"""
def nextline():
"""Read next line, skip comments"""
while True:
line = fileobj.readline()
assert line != '' # eof
if not line.startswith('comment'):
return line.strip(... | 0.000544 |
def isFile(self):
""" Check if the given object is a file
"""
try:
filetype = file
except NameError:
filetype = io.IOBase
return self._wrap(type(self.obj) is filetype) | 0.008621 |
def volume_correlation(results, references):
r"""
Volume correlation.
Computes the linear correlation in binary object volume between the
contents of the successive binary images supplied. Measured through
the Pearson product-moment correlation coefficient.
Parameters
----------
... | 0.006314 |
def superpose(ras, rbs, weights=None):
"""Compute the transformation that minimizes the RMSD between the points ras and rbs
Arguments:
| ``ras`` -- a ``np.array`` with 3D coordinates of geometry A,
shape=(N,3)
| ``rbs`` -- a ``np.array`` with 3D coordinates of geom... | 0.002554 |
def timed_loop(name=None,
rgstr_stamps=None,
save_itrs=SET['SI'],
loop_end_stamp=None,
end_stamp_unique=SET['UN'],
keep_prev_subdivisions=SET['KS'],
keep_end_subdivisions=SET['KS'],
quick_print=SET['QP']):
"""
... | 0.002021 |
def desaturate(c, k=0):
"""
Utility function to desaturate a color c by an amount k.
"""
from matplotlib.colors import ColorConverter
c = ColorConverter().to_rgb(c)
intensity = 0.299 * c[0] + 0.587 * c[1] + 0.114 * c[2]
return [intensity * k + i * (1 - k) for i in c] | 0.00339 |
def body(self, features):
"""Body of the model.
Args:
features: a dictionary with the tensors.
Returns:
A pair (predictions, losses) where predictions is the generated image
and losses is a dictionary of losses (that get added for the final loss).
"""
features["targets"] = featur... | 0.001667 |
def get_func(fullFuncName):
"""Retrieve a function object from a full dotted-package name."""
# Parse out the path, module, and function
lastDot = fullFuncName.rfind(u".")
funcName = fullFuncName[lastDot + 1:]
modPath = fullFuncName[:lastDot]
aMod = get_mod(modPath)
aFunc = getattr(aMod, f... | 0.001789 |
def put_pipeline_definition(pipeline_id, pipeline_objects, parameter_objects=None,
parameter_values=None, region=None, key=None, keyid=None, profile=None):
'''
Add tasks, schedules, and preconditions to the specified pipeline. This function is
idempotent and will replace an exist... | 0.005155 |
def schedule(self, schedule_time):
"""Add a specific enqueue time to the message.
:param schedule_time: The scheduled time to enqueue the message.
:type schedule_time: ~datetime.datetime
"""
if not self.properties.message_id:
self.properties.message_id = str(uuid.uui... | 0.005871 |
def network_protocol(self, layer: Optional[Layer] = None) -> str:
"""Get a random network protocol form OSI model.
:param layer: Enum object Layer.
:return: Protocol name.
:Example:
AMQP
"""
key = self._validate_enum(item=layer, enum=Layer)
protocols... | 0.005128 |
def list_directory2(self, mdir, limit=None, marker=None):
"""A lower-level version of `list_directory` that returns the
response object (which includes the headers).
...
@returns (res, dirents) {2-tuple}
"""
log.debug('ListDirectory %r', mdir)
query = {}
... | 0.002128 |
def copyPage(self, pno, to=-1):
"""Copy a page to before some other page of the document. Specify 'to = -1' to copy after last page.
"""
pl = list(range(len(self)))
if pno < 0 or pno > pl[-1]:
raise ValueError("'from' page number out of range")
if to < -1 or to > pl[-... | 0.005894 |
def connected_subgraphs(self, directed=True, ordered=False):
'''Generates connected components as subgraphs.
When ordered=True, subgraphs are ordered by number of vertices.
'''
num_ccs, labels = self.connected_components(directed=directed)
# check the trivial case first
if num_ccs == 1:
yi... | 0.013369 |
def train_by_stream(self, stream: StreamWrapper) -> None:
"""
Train the model with the given stream.
:param stream: stream to train with
"""
self._run_epoch(stream=stream, train=True) | 0.008929 |
def ensure_flat_galactic(f):
"""
A decorator for class methods of the form
.. code-block:: python
Class.method(self, coords, **kwargs)
where ``coords`` is an :obj:`astropy.coordinates.SkyCoord` object.
The decorator ensures that the ``coords`` that gets passed to
``Class.method`` is ... | 0.002137 |
def update_object_with_data(content, record):
"""Update the content with the record data
:param content: A single folderish catalog brain or content object
:type content: ATContentType/DexterityContentType/CatalogBrain
:param record: The data to update
:type record: dict
:returns: The updated c... | 0.001267 |
def invites(self):
"""
Access the invites
:returns: twilio.rest.chat.v1.service.channel.invite.InviteList
:rtype: twilio.rest.chat.v1.service.channel.invite.InviteList
"""
if self._invites is None:
self._invites = InviteList(
self._version,
... | 0.004255 |
def get_text(self, locator, params=None, timeout=None, visible=True):
"""
Get text or value from element based on locator with optional parameters.
:param locator: element identifier
:param params: (optional) locator parameters
:param timeout: (optional) time to wait for text (d... | 0.005841 |
def to_dict(self, column_names=None, selection=None, strings=True, virtual=False):
"""Return a dict containing the ndarray corresponding to the evaluated data
:param column_names: list of column names, to export, when None DataFrame.get_column_names(strings=strings, virtual=virtual) is used
:pa... | 0.011611 |
def init_from_wave_file(wavpath):
"""Init a sonic visualiser environment structure based the analysis
of the main audio file. The audio file have to be encoded in wave
Args:
wavpath(str): the full path to the wavfile
"""
try:
samplerate, data = SW.read(... | 0.009103 |
def show_channel(self, channel, owner):
'''List the channels for owner
If owner is none, the currently logged in user is used
'''
url = '%s/channels/%s/%s' % (self.domain, owner, channel)
res = self.session.get(url)
self._check_response(res, [200])
return res.jso... | 0.006192 |
def mBank_set_iph_id(transactions, tag, tag_dict, *args):
"""
mBank Collect uses ID IPH to distinguish between virtual accounts,
adding iph_id may be helpful in further processing
"""
matches = iph_id_re.search(tag_dict[tag.slug])
if matches: # pragma no branch
tag_dict['iph_id'] = mat... | 0.002725 |
def draw_polygon(
self,
*pts,
close_path=True,
stroke=None,
stroke_width=1,
stroke_dash=None,
fill=None
) -> None:
"""Draws the given polygon."""
c = self.c
c.saveState()
if stroke is not Non... | 0.003807 |
def index(self, elem):
"""Find the index of elem in the reversed iterator."""
return _coconut.len(self._iter) - self._iter.index(elem) - 1 | 0.012987 |
def addScalarBar3D(
self,
obj=None,
at=0,
pos=(0, 0, 0),
normal=(0, 0, 1),
sx=0.1,
sy=2,
nlabels=9,
ncols=256,
cmap=None,
c=None,
alpha=1,
):
"""Draw a 3D scalar bar.
``obj`` input can be:
- ... | 0.006803 |
def SUSSelection(self, mating_pool_size):
'''
Make Selection of the mating pool with the
stochastic universal sampling algorithm
'''
A = numpy.zeros(self.length)
mating_pool = numpy.zeros(mating_pool_size)
r = numpy.random.random()/float(mating_pool_size)
[F,S,P] = self.rankingEval()
P_Sorted = num... | 0.049612 |
def bounds(self):
"""
Return the axis aligned bounding box of the current path.
Returns
----------
bounds: (2, dimension) float, (min, max) coordinates
"""
# get the exact bounds of each entity
# some entities (aka 3- point Arc) have bounds that can't
... | 0.00237 |
def _request_activity_list(self, athlete):
"""Actually do the request for activity list
This call is slow and therefore this method is memory cached.
Keyword arguments:
athlete -- Full name of athlete
"""
response = self._get_request(self._athlete_endpoint(athlete))
... | 0.002613 |
def position_target_global_int_encode(self, time_boot_ms, coordinate_frame, type_mask, lat_int, lon_int, alt, vx, vy, vz, afx, afy, afz, yaw, yaw_rate):
'''
Reports the current commanded vehicle position, velocity, and
acceleration as specified by the autopilot. This
... | 0.00566 |
def disconnect(self, instance, another_instance):
'''
Disconnect an *instance* from *another_instance*.
'''
if instance not in self:
return False
if another_instance not in self[instance]:
return False
self[instance].remove(another_insta... | 0.011628 |
def get(self, name="", owner=None, app=None, sharing=None, **query):
"""Performs a GET request to the server on the collection.
If *owner*, *app*, and *sharing* are omitted, this method takes a
default namespace from the :class:`Service` object for this :class:`Endpoint`.
All other keyw... | 0.00256 |
def _update_capacity(self, data):
""" Update the consumed capacity metrics """
if 'ConsumedCapacity' in data:
# This is all for backwards compatibility
consumed = data['ConsumedCapacity']
if not isinstance(consumed, list):
consumed = [consumed]
... | 0.001953 |
def outline(self, face_ids=None, **kwargs):
"""
Given a list of face indexes find the outline of those
faces and return it as a Path3D.
The outline is defined here as every edge which is only
included by a single triangle.
Note that this implies a non-watertight mesh as... | 0.00202 |
def __get_start_stop_iterations(sync_output_dynamic, start_iteration, stop_iteration):
"""!
@brief Apply rule of preparation for start iteration and stop iteration values.
@param[in] sync_output_dynamic (sync_dynamic): Output dynamic of the Sync network.
@param[in] start_it... | 0.018428 |
def make_transformer(self, umap_kwargs={}):
"""
Creates an internal transformer pipeline to project the data set into
2D space using UMAP. This method will reset the transformer on the
class.
Parameters
----------
Returns
-------
transformer : Pi... | 0.003044 |
def decode(self, name, as_map_key=False):
"""Always returns the name"""
if is_cache_key(name) and (name in self.key_to_value):
return self.key_to_value[name]
return self.encache(name) if is_cacheable(name, as_map_key) else name | 0.007605 |
def is_subscribed(user, obj):
"""
Returns ``True`` if the user is subscribed to the given object.
:param user: A ``User`` instance.
:param obj: Any object.
"""
if not user.is_authenticated():
return False
ctype = ContentType.objects.get_for_model(obj)
try:
Subscriptio... | 0.002123 |
def RegisterPathSpec(cls, path_spec_type):
"""Registers a path specification type.
Args:
path_spec_type (type): path specification type.
Raises:
KeyError: if path specification is already registered.
"""
type_indicator = path_spec_type.TYPE_INDICATOR
if type_indicator in cls._path_... | 0.004688 |
def pairwise_tukey(dv=None, between=None, data=None, alpha=.05,
tail='two-sided', effsize='hedges'):
'''Pairwise Tukey-HSD post-hoc test.
Parameters
----------
dv : string
Name of column containing the dependant variable.
between: string
Name of column containing ... | 0.000184 |
def cmd(admin_only=False, acl='*', aliases=None, while_ignored=False, *args, **kwargs):
"""
Decorator to mark plugin functions as commands in the form of !<cmd_name>
* admin_only - indicates only users in bot_admin are allowed to execute (only used if AuthManager is loaded)
* acl - indicates which ACL ... | 0.006601 |
def cleanup_defenses(self):
"""Cleans up all data about defense work in current round."""
print_header('CLEANING UP DEFENSES DATA')
work_ancestor_key = self.datastore_client.key('WorkType', 'AllDefenses')
keys_to_delete = [
e.key
for e in self.datastore_client.query_fetch(kind=u'Classifi... | 0.001773 |
def add_bundle(self, *args):
"""
Add some bundle to build group
:type bundle: static_bundle.bundles.AbstractBundle
@rtype: BuildGroup
"""
for bundle in args:
if not self.multitype and self.has_bundles():
first_bundle = self.get_first_bundle()
... | 0.004082 |
def get_data(self, start=None, length=None):
"""Get data chunk from a section.
Allows to query data from the section by passing the
addresses where the PE file would be loaded by default.
It is then possible to retrieve code and data by their real
addresses as they would be if l... | 0.010901 |
def loader(filepath, logger=None, **kwargs):
"""
Load an object from an ASDF file.
See :func:`ginga.util.loader` for more info.
TODO: kwargs may contain info about what part of the file to load
"""
# see ginga.util.loader module
# TODO: return an AstroTable if loading a table, etc.
# ... | 0.003527 |
def _FloatingPointEncoder(wire_type, format):
"""Return a constructor for an encoder for float fields.
This is like StructPackEncoder, but catches errors that may be due to
passing non-finite floating-point values to struct.pack, and makes a
second attempt to encode those values.
Args:
wire_type: The... | 0.014301 |
def dumpf(obj, path):
"""
Write an nginx configuration to file.
:param obj obj: nginx object (Conf, Server, Container)
:param str path: path to nginx configuration on disk
:returns: path the configuration was written to
"""
with open(path, 'w') as f:
dump(obj, f)
return path | 0.003165 |
def show(self, func_name, values, labels=None):
"""Prints out nice representations of the given values."""
s = self.Stanza(self.indent)
if func_name == '<module>' and self.in_console:
func_name = '<console>'
s.add([func_name + ': '])
reprs = map(self.safe_repr, values... | 0.002861 |
def get_objective_bank_query_session(self, proxy):
"""Gets the OsidSession associated with the objective bank query service.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: an ``ObjectiveBankQuerySession``
:rtype: ``osid.learning.ObjectiveBankQuerySession``
... | 0.00552 |
def check_package(self, package, package_dir):
"""Check namespace packages' __init__ for declare_namespace"""
try:
return self.packages_checked[package]
except KeyError:
pass
init_py = orig.build_py.check_package(self, package, package_dir)
self.packages_... | 0.001779 |
def _spawn(self, command, args=[], preexec_fn=None, dimensions=None):
'''This starts the given command in a child process. This does all the
fork/exec type of stuff for a pty. This is called by __init__. If args
is empty then command will be parsed (split on spaces) and args will be
set ... | 0.002517 |
async def finalize_request(
self,
result: ResponseReturnValue,
request_context: Optional[RequestContext]=None,
from_error_handler: bool=False,
) -> Response:
"""Turns the view response return value into a response.
Arguments:
result: The result of the req... | 0.008206 |
def append(self, item):
"""add item to the end of the item list
"""
if not self.items: # was list empty ?
self.items = item # then this is the new head
item.insert(self.items) | 0.008696 |
def packet_is_for_me(self, m):
'''returns true if this packet is appropriately addressed'''
if m.target_system != self.master.mav.srcSystem:
return False
if m.target_component != self.master.mav.srcComponent:
return False
# if have a sender we can also check the s... | 0.004065 |
def clean(self):
'''Check to make sure password fields match.'''
data = super(SignupForm, self).clean()
# basic check for now
if 'username' in data:
if User.objects.filter(
username=data['username'],
email=data['email']).exists():
... | 0.002882 |
def bar(self, serie, rescale=False):
"""Draw a bar graph for a serie"""
serie_node = self.svg.serie(serie)
bars = self.svg.node(serie_node['plot'], class_="bars")
if rescale and self.secondary_series:
points = self._rescale(serie.points)
else:
points = ser... | 0.001845 |
def shape(self):
"""Copy the shape from TCMPS as a new numpy ndarray."""
# Create C variables that will serve as out parameters for TCMPS.
shape_ptr = _ctypes.POINTER(_ctypes.c_size_t)() # size_t* shape_ptr
dim = _ctypes.c_size_t() # size_t dim
# Obtain... | 0.00315 |
def _win32_junction(path, link, verbose=0):
"""
On older (pre 10) versions of windows we need admin privledges to make
symlinks, however junctions seem to work.
For paths we do a junction (softlink) and for files we use a hard link
CommandLine:
python -m ubelt._win32_links _win32_junction
... | 0.000407 |
def get_secret(secret_name, default=None):
"""
Gets contents of secret file
:param secret_name: The name of the secret present in BANANAS_SECRETS_DIR
:param default: Default value to return if no secret was found
:return: The secret or default if not found
"""
secrets_dir = get_secrets_dir(... | 0.001923 |
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 ... | 0.001403 |
def post(self, request, *args, **kwargs):
"""
Do the login and password protection.
"""
self.object = self.get_object()
self.login()
if self.object.password:
entry_password = self.request.POST.get('entry_password')
if entry_password:
... | 0.002813 |
def query(self, *args):
""" Send a query to the watchman service and return the response
This call will block until the response is returned.
If any unilateral responses are sent by the service in between
the request-response they will be buffered up in the client object
and NOT... | 0.001918 |
def update(self, *args, **kwargs):
"""Calls update on each of the systems self.systems."""
for system in self.systems:
system.update(self, *args, **kwargs) | 0.010929 |
def parseFragment(doc, container="div", treebuilder="etree", namespaceHTMLElements=True, **kwargs):
"""Parse an HTML fragment as a string or file-like object into a tree
:arg doc: the fragment to parse as a string or file-like object
:arg container: the container context to parse the fragment in
:arg... | 0.002387 |
def _re_establish_use_watch(self):
"""Call after a close/re-connect.
Automatically re-establishes the USE and WATCH configs previously setup.
"""
if self.current_tube != self.desired_tube:
self.use(self.desired_tube)
if self._watchlist != self.desired_watchlist:
... | 0.008174 |
def get_enthalpy(self, temperature, electronic_energy = 'Default'):
"""Returns the internal energy of an adsorbed molecule.
Parameters
----------
temperature : numeric
temperature in K
electronic_energy : numeric
energy in eV
Returns
-------
... | 0.008615 |
def breadth_first_search(graph, root_node=None):
"""Searches through the tree in a breadth-first fashion.
If root_node is None, an arbitrary node will be used as the root.
If root_node is not None, it will be used as the root for the search tree.
Returns a list of nodes, in the order that th... | 0.002045 |
def qs_from_dict(qsdict, prefix=""):
''' Same as dict_from_qs, but in reverse
i.e. {"period": {"di": {}, "fhr": {}}} => "period.di,period.fhr"
'''
prefix = prefix + '.' if prefix else ""
def descend(qsd):
for key, val in sorted(qsd.items()):
if val:
yield qs_... | 0.002283 |
def _get_converter_type(identifier):
"""Return the converter type for `identifier`."""
if isinstance(identifier, str):
return ConverterType[identifier]
if isinstance(identifier, ConverterType):
return identifier
return ConverterType(identifier) | 0.003623 |
def postinit(self, test=None, fail=None):
"""Do some setup after initialisation.
:param test: The test that passes or fails the assertion.
:type test: NodeNG or None
:param fail: The message shown when the assertion fails.
:type fail: NodeNG or None
"""
self.fai... | 0.005666 |
def get_subhash(hash):
"""Get a second hash based on napiprojekt's hash.
:param str hash: napiprojekt's hash.
:return: the subhash.
:rtype: str
"""
idx = [0xe, 0x3, 0x6, 0x8, 0x2]
mul = [2, 2, 5, 4, 3]
add = [0, 0xd, 0x10, 0xb, 0x5]
b = []
for i in range(len(idx)):
a =... | 0.00202 |
def visitFunctionCall(self, ctx):
"""
expression : fnname LPAREN parameters? RPAREN
"""
func_name = ctx.fnname().getText()
if ctx.parameters() is not None:
parameters = self.visit(ctx.parameters())
else:
parameters = []
return self._funct... | 0.007833 |
def info(self):
"""
Show expiration dates, equity price, quote time.
Returns
-------
self : :class:`~pynance.opt.core.Options`
Returns a reference to the calling object to allow
chaining.
expiries : :class:`pandas.tseries.index.DatetimeIndex`
... | 0.004405 |
def string_to_double_precision_float(s: str) -> float:
"""
Double precision float in Fortran file will have form 'x.ydz' or 'x.yDz', this cannot be convert directly to float
by Python ``float`` function, so I wrote this function to help conversion. For example,
:param s: a string denoting a double prec... | 0.008255 |
def yield_figs(self, **kwargs): # pragma: no cover
"""
This function *generates* a predefined list of matplotlib figures with minimal input from the user.
"""
yield self.plot_densities(title="PAW densities", show=False)
yield self.plot_waves(title="PAW waves", show=False)
... | 0.007813 |
def SetProperties(has_props_cls, input_dict, include_immutable=True):
"""A helper method to set an ``HasProperties`` object's properties from a dictionary"""
props = has_props_cls()
if not isinstance(input_dict, (dict, collections.OrderedDict)):
raise RuntimeError('input_dict invalid: ', input_dict)... | 0.00407 |
def phase_by(val: Any, phase_turns: float, qubit_index: int,
default: TDefault = RaiseTypeErrorIfNotProvided):
"""Returns a phased version of the effect.
For example, an X gate phased by 90 degrees would be a Y gate.
This works by calling `val`'s _phase_by_ method and returning
the result.... | 0.000518 |
def check_composite_tokens(self, name, tokens):
"""
Return the key and contents of a KEY..END block
for PATTERN, POINTS, and PROJECTION
"""
assert len(tokens) >= 2
key = tokens[0]
assert key.value.lower() == name
assert tokens[-1].value.lower() == "end"
... | 0.002999 |
def SensorShare(self, sensor_id, parameters):
"""
Share a sensor with a user
@param sensor_id (int) - Id of sensor to be shared
@param parameters (dictionary) - Additional parameters for the call
@return (bool) - Boolean indicating whether the ShareSensor... | 0.009056 |
def batch_query_state_changes(
self,
batch_size: int,
filters: List[Tuple[str, Any]] = None,
logical_and: bool = True,
) -> Iterator[List[StateChangeRecord]]:
"""Batch query state change records with a given batch size and an optional filter
This is a... | 0.006234 |
def split_name(name):
"""Splits a (possibly versioned) name into unversioned name and version.
Returns a tuple ``(unversioned_name, version)``, where ``version`` may
be ``None``.
"""
s = name.rsplit('@', 1)
if len(s) == 1:
return s[0], None
else:
try:
retur... | 0.002016 |
def _estimate_label_shape(self):
"""Helper function to estimate label shape"""
max_count = 0
self.reset()
try:
while True:
label, _ = self.next_sample()
label = self._parse_label(label)
max_count = max(max_count, label.shape[0])... | 0.00464 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.