text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def _specialize_curve(nodes, start, end):
"""Specialize a curve to a re-parameterization
.. note::
This assumes the curve is degree 1 or greater but doesn't check.
.. note::
There is also a Fortran implementation of this function, which
will be used if it can be built.
Args:
... | 0.000565 |
def add(self, item):
"""Add an item in the history."""
self._check_index()
# Possibly truncate the history up to the current point.
self._history = self._history[:self._index + 1]
# Append the item
self._history.append(item)
# Increment the index.
self._in... | 0.004132 |
def _imm_getattribute(self, name):
'''
An immutable's getattribute calculates lazy values when not yet cached in the object then adds
them as attributes.
'''
if _imm_is_init(self):
return _imm_init_getattribute(self, name)
else:
dd = object.__getattribute__(self, '__dict__')
... | 0.0057 |
def surrogate(self, u_sparse, q_sparse):
'''Combines the train and predict methods to create a surrogate
model function fitted to the input/output combinations given in
u_sparse and q_sparse.
:param numpy.ndarray u_sparse: input values at which the output
values are obtained... | 0.00295 |
def fix_display(self):
"""If this is being run on a headless system the Matplotlib
backend must be changed to one that doesn't need a display.
"""
try:
tkinter.Tk()
except (tkinter.TclError, NameError): # If there is no display.
try:
impor... | 0.006 |
def RegisterDecoder(cls, decoder):
"""Registers a decoder for a specific encoding method.
Args:
decoder (type): decoder class.
Raises:
KeyError: if the corresponding decoder is already set.
"""
encoding_method = decoder.ENCODING_METHOD.lower()
if encoding_method in cls._decoders:
... | 0.004049 |
def _pending_of(self, workload):
"""Return the number of pending tests in a workload."""
pending = sum(list(scope.values()).count(False) for scope in workload.values())
return pending | 0.014493 |
def char_span_to_token_span(token_offsets: List[Tuple[int, int]],
character_span: Tuple[int, int]) -> Tuple[Tuple[int, int], bool]:
"""
Converts a character span from a passage into the corresponding token span in the tokenized
version of the passage. If you pass in a character ... | 0.007699 |
def _get_run_results(self, run_id, request_type="plan", timeout_count=120):
"""
Wait for plan/apply results, else timeout
:param run_id: ID for the run
:return: Returns object of the results.
"""
if request_type is not "plan" and request_type is not "apply":
... | 0.005767 |
def get_span_datas(self, span):
"""Extracts a list of SpanData tuples from a span
:rtype: list of opencensus.trace.span_data.SpanData
:return list of SpanData tuples
"""
span_datas = [
span_data_module.SpanData(
name=ss.name,
context=s... | 0.002016 |
def make_symmetric(dict):
"""Makes the given dictionary symmetric. Values are assumed to be unique."""
for key, value in list(dict.items()):
dict[value] = key
return dict | 0.010526 |
def nonzero_pixels(self):
""" Return an array of the nonzero pixels.
Returns
-------
:obj:`numpy.ndarray`
Nx2 array of the nonzero pixels
"""
nonzero_px = np.where(np.sum(self.raw_data, axis=2) > 0)
nonzero_px = np.c_[nonzero_px[0], nonzero_px[1]]
... | 0.005831 |
def to_intermediate(self):
"""
Converts the NetJSON configuration dictionary (self.config)
to the intermediate data structure (self.intermediate_data) that will
be then used by the renderer class to generate the router configuration
"""
self.validate()
self.interm... | 0.00253 |
def p_lpartselect(self, p):
'lpartselect : identifier LBRACKET expression COLON expression RBRACKET'
p[0] = Partselect(p[1], p[3], p[5], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | 0.014354 |
def vms(message, level=1):
"""Writes the specified message *only* if verbose output is enabled."""
if verbose is not None and verbose != False:
if isinstance(verbose, bool) or (isinstance(verbose, int) and level <= verbose):
std(message) | 0.011321 |
def _center_transform(self, transform):
''''
Works like setupTransform of a version of java nodebox
http://dev.nodebox.net/browser/nodebox-java/branches/rewrite/src/java/net/nodebox/graphics/Grob.java
'''
dx, dy = self._get_center()
t = cairo.Matrix()
t.translate(... | 0.005 |
def ndiff(a, b, linejunk=None, charjunk=IS_CHARACTER_JUNK):
r"""
Compare `a` and `b` (lists of strings); return a `Differ`-style delta.
Optional keyword parameters `linejunk` and `charjunk` are for filter
functions (or None):
- linejunk: A function that should accept a single string argument, and
... | 0.000882 |
def enabled(self):
""" True if coloring is currently enabled """
# In auto-detection mode color enabled when terminal attached
if self._mode == COLOR_AUTO:
return sys.stdout.isatty()
return self._mode == COLOR_ON | 0.007813 |
def kill_all_processes(self, check_alive=True, allow_graceful=False):
"""Kill all of the processes.
Note that This is slower than necessary because it calls kill, wait,
kill, wait, ... instead of kill, kill, ..., wait, wait, ...
Args:
check_alive (bool): Raise an exception ... | 0.001489 |
def ex_best_offers_overrides(best_prices_depth=None, rollup_model=None, rollup_limit=None,
rollup_liability_threshold=None, rollup_liability_factor=None):
"""
Create filter to specify whether to accumulate market volume info, how deep a book to return and rollup methods if
accum... | 0.007199 |
def i_from_v(resistance_shunt, resistance_series, nNsVth, voltage,
saturation_current, photocurrent, method='lambertw'):
'''
Device current at the given device voltage for the single diode model.
Uses the single diode model (SDM) as described in, e.g.,
Jain and Kapoor 2004 [1].
The so... | 0.001421 |
def geq_multiple(self, other):
"""
Return the next multiple of this time value,
greater than or equal to ``other``.
If ``other`` is zero, return this time value.
:rtype: :class:`~aeneas.exacttiming.TimeValue`
"""
if other == TimeValue("0.000"):
return... | 0.005319 |
def query(sql, format='df'):
'''
Submit an `sql` query (string) to treasury.io and return a pandas DataFrame.
For example::
print('Operating cash balances for May 22, 2013')
print(treasuryio.query('SELECT * FROM "t1" WHERE "date" = \'2013-05-22\';'))
Return a dict::
treasuryi... | 0.005903 |
def signature(self, name=None):
"""Return our function signature as a string.
By default this function uses the annotated name of the function
however if you need to override that with a custom name you can
pass name=<custom name>
Args:
name (str): Optional name to ... | 0.002888 |
def _append_expectation(self, expectation_config):
"""Appends an expectation to `DataAsset._expectations_config` and drops existing expectations of the same type.
If `expectation_config` is a column expectation, this drops existing expectations that are specific to \
that column and only ... | 0.006019 |
def wait_until(name, state, timeout=300):
'''
Wait until a specific state has been reached on a node
'''
start_time = time.time()
node = show_instance(name, call='action')
while True:
if node['state'] == state:
return True
time.sleep(1)
if time.time() - start... | 0.002433 |
def request(self, *args, **kwargs):
"""
Makes an API request based on arguments.
:Parameters:
- `args`: Non-keyword arguments
- `kwargs`: Keyword arguments
"""
return self.session.request(*args, **self.get_kwargs(**kwargs)) | 0.006993 |
def is_valid_ipv4 (ip):
"""
Return True if given ip is a valid IPv4 address.
"""
if not _ipv4_re.match(ip):
return False
a, b, c, d = [int(i) for i in ip.split(".")]
return a <= 255 and b <= 255 and c <= 255 and d <= 255 | 0.007937 |
def _planck_spi(self, lam, Teff):
"""
Computes the spectral index of the monochromatic blackbody intensity
using the Planck function. The spectral index is defined as:
B(lambda) = 5 + d(log I)/d(log lambda),
where I is the Planck function.
@lam: wavelength in m
... | 0.003534 |
def new_tag(self, label, cfrom=None, cto=None, tagtype=None, **kwargs):
''' Create a new tag on this token '''
if cfrom is None:
cfrom = self.cfrom
if cto is None:
cto = self.cto
tag = Tag(label=label, cfrom=cfrom, cto=cto, tagtype=tagtype, **kwargs)
retur... | 0.0059 |
def run_op(self, op, sched):
"""
Handle the operation:
* if coro is in STATE_RUNNING, send or throw the given op
* if coro is in STATE_NEED_INIT, call the init function and if it
doesn't return a generator, set STATE_COMPLETED and set the result
to whatever t... | 0.006787 |
def onecons_qcqp(z, f, tol=1e-6):
""" Solves a nonconvex problem
minimize ||x-z||_2^2
subject to f(x) = x^T P x + q^T x + r ~ 0
where the relation ~ is given by f.relop (either <= or ==)
"""
# if constraint is ineq and z is feasible: z is the solution
if f.relop == '<=' and f.eval(z) ... | 0.007386 |
def before_render(self):
"""Before template render hook
"""
super(PricelistsView, self).before_render()
# Render the Add button if the user has the AddPricelist permission
if check_permission(AddPricelist, self.context):
self.context_actions[_("Add")] = {
... | 0.003617 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'name') and self.name is not None:
_dict['name'] = self.name
if hasattr(self,
'dbpedia_resource') and self.dbpedia_resource is not None:
_dic... | 0.004032 |
def eval(self, code, mode="single"):
"""Evaluate code in the context of the frame."""
if isinstance(code, string_types):
if PY2 and isinstance(code, text_type): # noqa
code = UTF8_COOKIE + code.encode("utf-8")
code = compile(code, "<interactive>", mode)
r... | 0.00551 |
def get_all_names( self, offset=None, count=None, include_expired=False ):
"""
Get the set of all registered names, with optional pagination
Returns the list of names.
"""
if offset is not None and offset < 0:
offset = None
if count is not None and count < 0:... | 0.015385 |
def derive_value(self, value):
"""Derives a new event from this one setting the ``value`` attribute.
Args:
value: (any):
The value associated with the derived event.
Returns:
IonEvent: The newly generated non-thunk event.
"""
return IonEv... | 0.004073 |
async def error(self, status=500, allowredirect = True, close = True, showerror = None, headers = []):
"""
Show default error response
"""
if showerror is None:
showerror = self.showerrorinfo
if self._sendHeaders:
if showerror:
typ, exc, tb... | 0.016173 |
def prepare_intervals(data, region_file, work_dir):
"""Prepare interval regions for targeted and gene based regions.
"""
target_file = os.path.join(work_dir, "%s-target.interval_list" % dd.get_sample_name(data))
if not utils.file_uptodate(target_file, region_file):
with file_transaction(data, ta... | 0.003505 |
def batch_means(x, f=lambda y: y, theta=.5, q=.95, burn=0):
"""
TODO: Use Bayesian CI.
Returns the half-width of the frequentist confidence interval
(q'th quantile) of the Monte Carlo estimate of E[f(x)].
:Parameters:
x : sequence
Sampled series. Must be a one-dimensional array... | 0.000764 |
def capture_on_device_name(device_name, callback):
"""
:param device_name: the name (guid) of a device as provided by WinPcapDevices.list_devices()
:param callback: a function to call with each intercepted packet
"""
with WinPcap(device_name) as capture:
capture.run(c... | 0.008902 |
def load_log(args):
"""Load a `logging.Logger` object.
Arguments
---------
args : `argparse.Namespace` object
Namespace containing required settings:
{`args.debug`, `args.verbose`, and `args.log_filename`}.
Returns
-------
log : `logging.Logger` object
"""
from ast... | 0.001344 |
def _init_impl(self, data, ctx_list):
"""Sets data and grad."""
self._ctx_list = list(ctx_list)
self._ctx_map = [[], []]
for i, ctx in enumerate(self._ctx_list):
dev_list = self._ctx_map[ctx.device_typeid&1]
while len(dev_list) <= ctx.device_id:
de... | 0.006356 |
def generate_defect_structure(self, supercell=(1, 1, 1)):
"""
Returns Defective Vacancy structure, decorated with charge
Args:
supercell (int, [3x1], or [[]] (3x3)): supercell integer, vector, or scaling matrix
"""
defect_structure = self.bulk_structure.copy()
... | 0.007745 |
def snip_line(line, max_width, split_at):
"""Shorten a line to a maximum length."""
if len(line) < max_width:
return line
return line[:split_at] + " … " \
+ line[-(max_width - split_at - 3):] | 0.004566 |
def locate_range(self, chrom, start=None, stop=None):
"""Locate slice of index containing all entries within the range
`key`:`start`-`stop` **inclusive**.
Parameters
----------
chrom : object
Chromosome or contig.
start : int, optional
Position st... | 0.001269 |
def save(self):
"""Saves this order to Holvi, returns a tuple with the order itself and checkout_uri"""
if self.code:
raise HolviError("Orders cannot be updated")
send_json = self.to_holvi_dict()
send_json.update({
'pool': self.api.connection.pool
})
... | 0.006211 |
def Clift(Re):
r'''Calculates drag coefficient of a smooth sphere using the method in
[1]_ as described in [2]_.
.. math::
C_D = \left\{ \begin{array}{ll}
\frac{24}{Re} + \frac{3}{16} & \mbox{if $Re < 0.01$}\\
\frac{24}{Re}(1 + 0.1315Re^{0.82 - 0.05\log Re}) & \mbox{if $0.01 < Re < ... | 0.003271 |
def hash(hash_type, input_text):
'''Hash input_text with the algorithm choice'''
hash_funcs = {'MD5' : hashlib.md5,
'SHA1' : hashlib.sha1,
'SHA224' : hashlib.sha224,
'SHA256' : hashlib.sha256,
'SHA384' : hashlib.sha384,
'S... | 0.015025 |
def closing_plugin(self, cancelable=False):
"""Perform actions before parent main window is closed"""
state = self.splitter.saveState()
self.set_option('splitter_state', qbytearray_to_str(state))
filenames = []
editorstack = self.editorstacks[0]
active_project_pat... | 0.003539 |
def serve(application, host='127.0.0.1', port=8080, **options):
"""Tornado's HTTPServer.
This is a high quality asynchronous server with many options. For details, please visit:
http://www.tornadoweb.org/en/stable/httpserver.html#http-server
"""
# Wrap our our WSGI application (potentially stack) in a Torn... | 0.036335 |
def orthologize(self, ortho_species_id, belast):
"""Decanonical ortholog name used"""
if (
self.orthologs
and ortho_species_id in self.orthologs
and ortho_species_id != self.species_id
):
self.orthology_species = ortho_species_id
self.... | 0.002743 |
def reset(rh):
"""
Reset a virtual machine.
Input:
Request Handle with the following properties:
function - 'POWERVM'
subfunction - 'RESET'
userid - userid of the virtual machine
parms['maxQueries'] - Maximum number of queries to issue.
... | 0.001088 |
def neighbor(args):
"""
%prog neighbor agpfile componentID
Check overlaps of a particular component in agpfile.
"""
p = OptionParser(neighbor.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
agpfile, componentID = args
fastadir = "fa... | 0.003717 |
def delete_global_cache(appname='default'):
""" Reads cache files to a safe place in each operating system """
#close_global_shelf(appname)
shelf_fpath = get_global_shelf_fpath(appname)
util_path.remove_file(shelf_fpath, verbose=True, dryrun=False) | 0.007576 |
def lockToColumn(self, index):
"""
Sets the column that the tree view will lock to. If None is supplied,
then locking will be removed.
:param index | <int> || None
"""
self._lockColumn = index
if index is None:
self.__... | 0.005616 |
def relatedItems(self):
'''
If this item is associated with a registration, then return all other items associated with
the same registration.
'''
if self.registration:
return self.registration.revenueitem_set.exclude(pk=self.pk) | 0.010676 |
def parse_value(self, value):
"""Parse string into instance of `datetime`."""
if isinstance(value, datetime.datetime):
return value
if value:
return parse(value)
else:
return None | 0.008097 |
def to_markdown(self):
"""Converts to markdown
:return: item in markdown format
"""
if self.type == "text":
return self.text
elif self.type == "url" or self.type == "image":
return "[" + self.text + "](" + self.attributes["ref"] + ")"
elif self.typ... | 0.004695 |
def e():
"""This is a hypothetical reference radiator. All wavelengths in CIE
illuminant E are weighted equally with a relative spectral power of 100.0.
"""
lmbda = 1.0e-9 * numpy.arange(300, 831)
data = numpy.full(lmbda.shape, 100.0)
return lmbda, data | 0.00361 |
def FileHashIndexQuery(self, subject, target_prefix, limit=100):
"""Search the index for matches starting with target_prefix.
Args:
subject: The index to use. Should be a urn that points to the sha256
namespace.
target_prefix: The prefix to match against the index.
limit: Either a... | 0.008359 |
def populate_keys_tree(self):
"""Reads the HOTKEYS global variable and insert all data in
the TreeStore used by the preferences window treeview.
"""
for group in HOTKEYS:
parent = self.store.append(None, [None, group['label'], None, None])
for item in group['keys'... | 0.006601 |
def change_frozen_attr(self):
"""Changes frozen state of cell if there is no selection"""
# Selections are not supported
if self.grid.selection:
statustext = _("Freezing selections is not supported.")
post_command_event(self.main_window, self.StatusBarMsg,
... | 0.001878 |
def dump_selected_keys_or_addrs(wallet_obj, used=None, zero_balance=None):
'''
Works for both public key only or private key access
'''
if wallet_obj.private_key:
content_str = 'private keys'
else:
content_str = 'addresses'
if not USER_ONLINE:
puts(colored.red('\nInterne... | 0.001792 |
def buckets(bucket=None, account=None, matched=False, kdenied=False,
errors=False, dbpath=None, size=None, denied=False,
format=None, incomplete=False, oversize=False, region=(),
not_region=(), inventory=None, output=None, config=None, sort=None,
tagprefix=None, not_bucke... | 0.000471 |
def read_names(rows, source_id=1):
"""Return an iterator of rows ready to insert into table
"names". Adds columns "is_primary" (identifying the primary name
for each tax_id with a vaule of 1) and "is_classified" (always None).
* rows - iterator of lists (eg, output from read_archive or read_dmp)
* ... | 0.000617 |
def get_config_status():
'''
Get the status of the current DSC Configuration
Returns:
dict: A dictionary representing the status of the current DSC
Configuration on the machine
CLI Example:
.. code-block:: bash
salt '*' dsc.get_config_status
'''
cmd = 'Get-Dsc... | 0.002522 |
def register(self, method, uri, call_back):
"""Register a class instance function to handle a request.
:param method: string - HTTP Verb
:param uri: string - URI for the request
:param call_back: class instance function that handles the request
:returns: n/a
"""
... | 0.004016 |
def render(gpg_data, saltenv='base', sls='', argline='', **kwargs):
'''
Create a gpg object given a gpg_keydir, and then use it to try to decrypt
the data to be rendered.
'''
if not _get_gpg_exec():
raise SaltRenderError('GPG unavailable')
log.debug('Reading GPG keys from: %s', _get_key_... | 0.002137 |
def protected(self, *tests, **kwargs):
"""Factory of decorators for limit the access to views.
:tests: *function, optional
One or more functions that takes the args and kwargs of the
view and returns either `True` or `False`.
All test must return True to show the vie... | 0.002691 |
def unreduce_tensor(tensor, shape, axis, keepdims):
"""Reverse summing over a dimension.
See utils.py.
Args:
tensor: The tensor that was reduced.
shape: A list, the original shape of the tensor before reduction.
axis: The axis or axes that were summed.
keepdims: Whether these axes were kept as s... | 0.01108 |
def setInstitutionLogo(self, pathList: tuple):
"""
takes one or more [logo].svg paths
if logo should be clickable, set
pathList = (
(my_path1.svg,www.something1.html),
(my_path2.svg,www.something2.html),
...)
"""... | 0.002522 |
def _apply_section_children(self, section, hosts):
"""
Add the variables for each entry in a 'children' section to the hosts
belonging to that entry.
"""
for entry in section['entries']:
for hostname in self._group_get_hostnames(entry['name']):
host = ... | 0.004367 |
def equals(self, data):
"""Adds new `IN` or `=` condition depending on if a list or string was provided
:param data: string or list of values
:raise:
- QueryTypeError: if `data` is of an unexpected type
"""
if isinstance(data, six.string_types):
return s... | 0.008606 |
def error(bot, update, error):
"""Log Errors caused by Updates."""
logger.error('Update {} caused error {}'.format(update, error), extra={"tag": "err"}) | 0.0125 |
def parse(text, encoding='utf8'):
"""Parse the querystring into a normalized form."""
# Decode the text if we got bytes.
if isinstance(text, six.binary_type):
text = text.decode(encoding)
return Query(text, split_segments(text)) | 0.003937 |
def main(command_line=True, **kwargs):
"""
NAME
sio_magic.py
DESCRIPTION
converts SIO .mag format files to magic_measurements format files
SYNTAX
sio_magic.py [command line options]
OPTIONS
-h: prints the help message and quits.
-usr USER: identify user, ... | 0.023407 |
def enqueue(self, item, queue=None):
"""
Enqueue items.
If you define "self.filter" (sequence),
this method put the item to queue after filtering.
"self.filter" operates as blacklist.
This method expects that
"item" argument has dict type "data" attribute.
... | 0.001682 |
def decrement_display_ref_count(self, amount: int=1):
"""Decrement display reference count to indicate this library item is no longer displayed."""
assert not self._closed
self.__display_ref_count -= amount
if self.__display_ref_count == 0:
self.__is_master = False
if... | 0.011521 |
def order_search(self, article_code, **kwargs):
'''taobao.vas.order.search 订单记录导出
用于ISV查询自己名下的应用及收费项目的订单记录。目前所有应用调用此接口的频率限制为200次/分钟,即每分钟内,所有应用调用此接口的次数加起来最多为200次。'''
request = TOPRequest('taobao.vas.order.search')
request['article_code'] = article_code
for k, v in kwargs.... | 0.017266 |
def delete(self, force=False, client=None):
"""Delete this bucket.
The bucket **must** be empty in order to submit a delete request. If
``force=True`` is passed, this will first attempt to delete all the
objects / blobs in the bucket (i.e. try to empty the bucket).
If the bucke... | 0.001124 |
def shuffle(self):
"""
Shuffle the deque
Deques themselves do not support this, so this will make all items into
a list, shuffle that list, clear the deque, and then re-init the deque.
"""
args = list(self)
random.shuffle(args)
self.clear()
sup... | 0.00565 |
def imagetransformer_b10l_4h_big_uncond_dr03_lr025_tpu():
"""TPU related small model."""
hparams = imagetransformer_bas8l_8h_big_uncond_dr03_imgnet()
update_hparams_for_tpu(hparams)
hparams.batch_size = 4
hparams.num_heads = 4 # heads are expensive on tpu
hparams.num_decoder_layers = 10
hparams.learning... | 0.025194 |
def to_ascii_bytes(self, filter_func=None):
""" Attempt to encode the headers block as ascii
If encoding fails, call percent_encode_non_ascii_headers()
to encode any headers per RFCs
"""
try:
string = self.to_str(filter_func)
string = string.encode... | 0.003565 |
def transform(data, channels, transform_fxn, def_channels = None):
"""
Apply some transformation function to flow cytometry data.
This function is a template transformation function, intended to be
used by other specific transformation functions. It performs basic
checks on `channels` and `data`. I... | 0.002872 |
def _relay(self, **kwargs):
"""Send the request through the server and return the HTTP response."""
retval = None
delay_time = 2 # For connection retries
read_attempts = 0 # For reading from socket
while retval is None: # Evict can return False
sock = socket.socket... | 0.001542 |
async def substr(self, name, start, end=-1):
"""
Return a substring of the string at key ``name``. ``start`` and ``end``
are 0-based integers specifying the portion of the string to return.
"""
return await self.execute_command('SUBSTR', name, start, end) | 0.00678 |
def change_last_focused_widget(self, old, now):
"""To keep track of to the last focused widget"""
if (now is None and QApplication.activeWindow() is not None):
QApplication.activeWindow().setFocus()
self.last_focused_widget = QApplication.focusWidget()
elif now is no... | 0.007177 |
def duration(self):
"""Get duration of composition
"""
return max([x.comp_location + x.duration
for x in self.segments]) | 0.012195 |
def correct(self, image, keepSize=False, borderValue=0):
'''
remove lens distortion from given image
'''
image = imread(image)
(h, w) = image.shape[:2]
mapx, mapy = self.getUndistortRectifyMap(w, h)
self.img = cv2.remap(image, mapx, mapy, cv2.INTER_LINEAR,
... | 0.003247 |
def idle_task(self):
'''called rapidly by mavproxy'''
now = time.time()
if now-self.last_sent > self.system_time_settings.interval:
self.last_sent = now
time_us = time.time() * 1000000
if self.system_time_settings.verbose:
print("ST: Sending s... | 0.003254 |
def value(self, dcode, dextra):
"""Decode value of symbol together with the extra bits.
>>> d = DistanceAlphabet('D', NPOSTFIX=2, NDIRECT=10)
>>> d[34].value(2)
(0, 35)
"""
if dcode<16:
return [(1,0),(2,0),(3,0),(4,0),
(1,-1),(1,+1),(1,-2),... | 0.038974 |
def add_empty_fields(untl_dict):
"""Add empty values if UNTL fields don't have values."""
# Iterate the ordered UNTL XML element list to determine
# which elements are missing from the untl_dict.
for element in UNTL_XML_ORDER:
if element not in untl_dict:
# Try to create an element w... | 0.002077 |
def gauge(self, key, gauge=None, default=float("nan"), **dims):
"""Adds gauge with dimensions to the registry"""
return super(RegexRegistry, self).gauge(
self._get_key(key), gauge=gauge, default=default, **dims) | 0.008368 |
def pages(self):
"""A generator of all pages in the stream.
Returns:
types.GeneratorType[google.cloud.bigquery_storage_v1beta1.ReadRowsPage]:
A generator of pages.
"""
# Each page is an iterator of rows. But also has num_items, remaining,
# and to_dat... | 0.003731 |
def fromtimestamp(cls, t, tz=None):
"""Construct a datetime from a POSIX timestamp (like time.time()).
A timezone info object may be passed in as well.
"""
_check_tzinfo_arg(tz)
converter = _time.localtime if tz is None else _time.gmtime
t, frac = divmod(t, 1.0)
... | 0.002174 |
def _legacy_add_user(self, name, password, read_only, **kwargs):
"""Uses v1 system to add users, i.e. saving to system.users.
"""
# Use a Collection with the default codec_options.
system_users = self._collection_default_options('system.users')
user = system_users.find_one({"user... | 0.00161 |
def subkey_for_path(self, path):
"""
path: a path of subkeys denoted by numbers and slashes. Use H or p
for private key derivation. End with .pub to force the key
public.
Examples: 1H/5/2/1 would call subkey(i=1, is_hardened=True)
.subkey(i=5).subkey(i=2).sub... | 0.00256 |
def get_fields(self, db_name, table_name):
"""
Parameters:
- db_name
- table_name
"""
self.send_get_fields(db_name, table_name)
return self.recv_get_fields() | 0.005348 |
def proxy(self, signal_source, *signal_names, weak_ref=False):
""" :meth:`.WSignalProxyProto.proxy` implementation
"""
callback = self.__callback if weak_ref is False else self.__weak_ref_callback
for signal_name in signal_names:
signal_source.callback(signal_name, callback) | 0.024476 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.