text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def __validate(data, classes, labels):
"Validator of inputs."
if not isinstance(data, dict):
raise TypeError(
'data must be a dict! keys: sample ID or any unique identifier')
if not isinstance(labels, dict):
raise TypeError(
'labels must b... | 0.007725 |
def github_repo(github_repo, plugin_name):
"""
Returns a GitRepo from a github repository after either cloning or fetching
(depending on whether it exists)
@param github_repo: the github repository path, e.g. 'drupal/drupal/'
@param plugin_name: the current plugin's name (for namespace purposes).
... | 0.002058 |
def edf_totdev(N, m, alpha):
""" Equivalent degrees of freedom for Total Deviation
FIXME: what is the right behavior for alpha outside 0,-1,-2?
NIST SP1065 page 41, Table 7
"""
alpha = int(alpha)
if alpha in [0, -1, -2]:
# alpha 0 WFM
# alpha -1 FFM
# al... | 0.003683 |
def memoize(func):
"""
Provides memoization for methods on a specific instance.
Results are cached for given parameter list.
See also: http://en.wikipedia.org/wiki/Memoization
N.B. The cache object gets added to the instance instead of the global scope.
Therefore cached results are restricted ... | 0.002962 |
def show_glyphs(self, glyphs):
"""A drawing operator that generates the shape from a list of glyphs,
rendered according to the current
font :meth:`face <set_font_face>`,
font :meth:`size <set_font_size>`
(font :meth:`matrix <set_font_matrix>`),
and font :meth:`options <se... | 0.003226 |
def get_generation(self, *tables, **kwargs):
"""Get the generation key for any number of tables."""
db = kwargs.get('db', 'default')
if len(tables) > 1:
return self.get_multi_generation(tables, db)
return self.get_single_generation(tables[0], db) | 0.006897 |
def _get_area_rates(self, source, mmin, mmax=np.inf):
"""
Adds the rates from the area source by discretising the source
to a set of point sources
:param source:
Area source as instance of :class:
openquake.hazardlib.source.area.AreaSource
"""
poi... | 0.004762 |
def uuid_from_time(time_arg, node=None, clock_seq=None):
"""
Converts a datetime or timestamp to a type 1 :class:`uuid.UUID`.
:param time_arg:
The time to use for the timestamp portion of the UUID.
This can either be a :class:`datetime` object or a timestamp
in seconds (as returned from :... | 0.001112 |
def _remaining_points(hands):
'''
:param list hands: hands for which to compute the remaining points
:return: a list indicating the amount of points
remaining in each of the input hands
'''
points = []
for hand in hands:
points.append(sum(d.first + d.second for d in hand))
... | 0.002967 |
def _drawLine(self, image):
"""Draw morphed line in Image object."""
w, h = image.size
w *= 5
h *= 5
l_image = Image.new('RGBA', (w, h), (0, 0, 0, 0))
l_draw = ImageDraw.Draw(l_image)
x1 = int(w * random.uniform(0, 0.1))
y1 = int(h * random.uniform(0, 1)... | 0.002304 |
def count_ncmonomials(monomials, degree):
"""Given a list of monomials, it counts those that have a certain degree,
or less. The function is useful when certain monomials were eliminated
from the basis.
:param variables: The noncommutative variables making up the monomials
:param monomials: List of... | 0.00159 |
def assignment_action(self, text, loc, assign):
"""Code executed after recognising an assignment statement"""
exshared.setpos(loc, text)
if DEBUG > 0:
print("ASSIGN:",assign)
if DEBUG == 2: self.symtab.display()
if DEBUG > 2: return
var_index = ... | 0.010582 |
def _reload_config(self, reload_original_config):
"""
This command will update the running config from the live device.
Args:
* reload_original_config:
* If ``True`` the original config will be loaded with the running config before reloading the\
orig... | 0.003589 |
def changelog(since, to, write, force):
"""
Generates a markdown file containing the list of checks that changed for a
given Agent release. Agent version numbers are derived inspecting tags on
`integrations-core` so running this tool might provide unexpected results
if the repo is not up to date wit... | 0.002719 |
def migrator(state):
"""Nameless conversations will be lost."""
cleverbot_kwargs, convos_kwargs = state
cb = Cleverbot(**cleverbot_kwargs)
for convo_kwargs in convos_kwargs:
cb.conversation(**convo_kwargs)
return cb | 0.004115 |
def _encode_multipart_formdata(self):
""" Encode POST body.
Return (content_type, body) ready for httplib.HTTP instance
"""
def get_content_type(filename):
"Helper to get MIME type."
return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
... | 0.005279 |
def partial_update(self, index, doc_type, id, doc=None, script=None, params=None,
upsert=None, querystring_args=None):
"""
Partially update a document with a script
"""
if querystring_args is None:
querystring_args = {}
if doc is None and scrip... | 0.006579 |
def plotnoisecum(noisepkl, fluxscale=1, plot_width=450, plot_height=400):
""" Merged noise pkl converted to interactive cumulative histogram
noisepkl is standard noise pickle file.
fluxscale is scaling applied by gain calibrator. telcal solutions have fluxscale=1.
also returns corrected imnoise values... | 0.007322 |
def get_connection(self, command, args=()):
"""Get free connection from pool.
Returns connection.
"""
# TODO: find a better way to determine if connection is free
# and not havily used.
command = command.upper().strip()
is_pubsub = command in _PUBSUB_COMMAN... | 0.00202 |
def handle_stream(self, stream):
'''
Override this to handle the streams as they arrive
:param IOStream stream: An IOStream for processing
See https://tornado.readthedocs.io/en/latest/iostream.html#tornado.iostream.IOStream
for additional details.
'''
@tornado.g... | 0.001825 |
def transform(self, blocks, y=None):
"""
Transform an ordered sequence of blocks into a 2D features matrix with
shape (num blocks, num features).
Args:
blocks (List[Block]): as output by :class:`Blockifier.blockify`
y (None): This isn't used, it's only here for A... | 0.002242 |
def tril(array, k=0):
'''Lower triangle of an array.
Return a copy of an array with elements above the k-th diagonal zeroed.
Need a multi-dimensional version here because numpy.tril does not
broadcast for numpy verison < 1.9.'''
try:
tril_array = np.tril(array, k=k)
except:
# hav... | 0.003604 |
def init_variables(self, verbose=False):
"""Redefine the causes of the graph."""
for j in range(1, self.nodes):
nb_parents = np.random.randint(0, min([self.parents_max, j])+1)
for i in np.random.choice(range(0, j), nb_parents, replace=False):
self.adjacency_matrix... | 0.00528 |
def interval(
value=None,
unit='s',
years=None,
quarters=None,
months=None,
weeks=None,
days=None,
hours=None,
minutes=None,
seconds=None,
milliseconds=None,
microseconds=None,
nanoseconds=None,
):
"""
Returns an interval literal
Parameters
----------... | 0.000575 |
def get_token(access_token=None, refresh_token=None):
"""Load an access token.
Add support for personal access tokens compared to flask-oauthlib.
If the access token is ``None``, it looks for the refresh token.
:param access_token: The access token. (Default: ``None``)
:param refresh_token: The re... | 0.000951 |
def add_moc_from_URL(self, moc_URL, moc_options = {}):
""" load a MOC from a URL and display it in Aladin Lite widget
Arguments:
moc_URL: string url
moc_options: dictionary object"""
self.moc_URL = moc_URL
self.moc_options = moc_options
self.moc_from_U... | 0.011236 |
def accumulate_metric(cls, name, value):
"""
Accumulate a custom metric (name and value) in the metrics cache.
"""
metrics_cache = cls._get_metrics_cache()
metrics_cache.setdefault(name, 0)
metrics_cache.set(name, value) | 0.007463 |
def get_similar(self, example, max_similars=3, similarity_cutoff=None,
term_diff_max_rank=10, filter_list=None,
term_diff_cutoff=None):
"""Devuelve textos similares al ejemplo dentro de los textos entrenados.
Nota:
Usa la distancia de coseno del vecto... | 0.000903 |
def derive_signature(key, qs):
"""Derives the signature from the supplied query string using the key."""
key, qs = (key or "", qs or "")
return hmac.new(key.encode(), qs.encode(), hashlib.sha1).hexdigest() | 0.004608 |
def _initialize_recursion_depth(self):
"""Ensure recursion info is initialized, if not, initialize it."""
from furious.context import get_current_async
recursion_options = self._options.get('_recursion', {})
current_depth = recursion_options.get('current', 0)
max_depth = recurs... | 0.001558 |
def _handle_authn_request(self, context, binding_in, idp):
"""
See doc for handle_authn_request method.
:type context: satosa.context.Context
:type binding_in: str
:type idp: saml.server.Server
:rtype: satosa.response.Response
:param context: The current context... | 0.00296 |
def spherical_angle( ra0, dec0, ra1, dec1, ra2, dec2 ):
"""
Returns the spherical angle distance between two sets of great circles defined by (ra0, dec0), (ra1, dec1) and (ra0, dec0), (ra2, dec2)
:param ra0: array or float, longitude of intersection point(s)
:param dec0: array or float, latitude of int... | 0.020391 |
def _set_clear_mpls_rsvp_statistics_neighbor(self, v, load=False):
"""
Setter method for clear_mpls_rsvp_statistics_neighbor, mapped from YANG variable /brocade_mpls_rpc/clear_mpls_rsvp_statistics_neighbor (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_clear_mpls_... | 0.006076 |
def get_reqd_headers(self, table_name):
"""
Return a list of all required headers for a particular table
"""
df = self.dm[table_name]
cond = df['validations'].map(lambda x: 'required()' in str(x))
return df[cond].index | 0.007519 |
def _analyze(self):
"""
Decide which lines should be filtered out
"""
pids = []
for ip in self.filter['ips']:
if ip in self.ips_to_pids:
for pid in self.ips_to_pids[ip]:
pids.append(pid)
for line in self.parsed_lines:
... | 0.00409 |
def input_sender(self):
"""
This :tl:`InputPeer` is the input version of the user/channel who
sent the message. Similarly to `input_chat`, this doesn't have
things like username or similar, but still useful in some cases.
Note that this might not be available if the library can'... | 0.002933 |
def categories_ref(self):
"""
The Excel worksheet reference to the categories for this chart (not
including the column heading).
"""
categories = self._chart_data.categories
if categories.depth == 0:
raise ValueError('chart data contains no categories')
... | 0.004175 |
def cummax(self, axis=None, skipna=True, *args, **kwargs):
"""Perform a cumulative maximum across the DataFrame.
Args:
axis (int): The axis to take maximum on.
skipna (bool): True to skip NA values, false otherwise.
Returns:
The cumulative maximum of... | 0.003091 |
def verify_face_to_person(
self, face_id, person_id, person_group_id=None, large_person_group_id=None, custom_headers=None, raw=False, **operation_config):
"""Verify whether two faces belong to a same person. Compares a face Id
with a Person Id.
:param face_id: FaceId of the face, c... | 0.001769 |
def _pull_assemble_error_status(logs):
'''
Given input in this form::
u'{"status":"Pulling repository foo/ubuntubox"}:
"image (latest) from foo/ ...
rogress":"complete","id":"2c80228370c9"}'
construct something like that (load JSON data is possible)::
[u'{"status":"Pulli... | 0.001618 |
def run_file(self, path, all_errors_exit=True):
"""Execute a Python file."""
path = fixpath(path)
with self.handling_errors(all_errors_exit):
module_vars = run_file(path)
self.vars.update(module_vars)
self.store("from " + splitname(path)[1] + " import *") | 0.006349 |
def main():
"""Program entry point"""
parser = argparse.ArgumentParser()
parser.add_argument('input',
metavar='INPUT',
help='Input directory with PNG files')
parser.add_argument('output', nargs='?',
metavar='OUTPUT',
... | 0.001742 |
def _sturges_formula(dataset, mult=1):
"""Use Sturges' formula to determine number of bins.
See https://en.wikipedia.org/wiki/Histogram#Sturges'_formula
or https://doi.org/10.1080%2F01621459.1926.10502161
Parameters
----------
dataset: xarray.DataSet
Must have the `draw` dimension
... | 0.00361 |
def get_argument_parser():
"""Function to obtain the argument parser.
Returns
-------
A fully configured `argparse.ArgumentParser` object.
Notes
-----
This function is used by the `sphinx-argparse` extension for sphinx.
"""
file_mv = cli.file_mv
desc = 'Extracts gene-level ex... | 0.000747 |
def _dirint_from_dni_ktprime(dni, kt_prime, solar_zenith, use_delta_kt_prime,
temp_dew):
"""
Calculate DIRINT DNI from supplied DISC DNI and Kt'.
Supports :py:func:`gti_dirint`
"""
times = dni.index
delta_kt_prime = _delta_kt_prime_dirint(kt_prime, use_delta_kt_prim... | 0.001684 |
def configure_settings():
"""
Configures settings for manage.py and for run_tests.py.
"""
if not settings.configured:
# Determine the database settings depending on if a test_db var is set in CI mode or not
test_db = os.environ.get('DB', None)
if test_db is None:
db_c... | 0.00119 |
def compare(self, statement_a, statement_b):
"""
Compare the two input statements.
:return: The percent of similarity between the closest synset distance.
:rtype: float
"""
document_a = self.nlp(statement_a.text)
document_b = self.nlp(statement_b.text)
r... | 0.005571 |
def _get_cmd_output_now(self, exe, suggest_filename=None,
root_symlink=False, timeout=300, stderr=True,
chroot=True, runat=None, env=None,
binary=False, sizelimit=None):
"""Execute a command and save the output to a file for inc... | 0.003369 |
def clean_process_meta(self):
"""Remove all process and build metadata"""
ds = self.dataset
ds.config.build.clean()
ds.config.process.clean()
ds.commit()
self.state = self.STATES.CLEANED | 0.008547 |
def output(self, filename):
"""
Output the inheritance relation
_filename is not used
Args:
_filename(string)
"""
info = 'Inheritance\n'
if not self.contracts:
return
info += blue('Child_Contract -> ') + green('Im... | 0.006443 |
def copy_node(ret, element, msg):
'''copy_node
High-level api: Copy element as a node without its children and put it
as a child of ret.
Parameters
----------
element : `Element`
A node in a model tree.
msg : `str`
Message to be added.
... | 0.00321 |
def enable_api_key(apiKey, region=None, key=None, keyid=None, profile=None):
'''
enable the given apiKey.
CLI Example:
.. code-block:: bash
salt myminion boto_apigateway.enable_api_key api_key
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
... | 0.001859 |
def delete_rule(self, rule_id):
"""Delete the specific Rule from dictionary indexed by rule id. """
if rule_id not in self.rules:
LOG.error("No Rule id present for deleting %s", rule_id)
return
del self.rules[rule_id]
self.rule_cnt -= 1 | 0.006849 |
def _get_new_msg_id(self):
"""
Generates a new unique message ID based on the current
time (in ms) since epoch, applying a known time offset.
"""
now = time.time() + self.time_offset
nanoseconds = int((now - int(now)) * 1e+9)
new_msg_id = (int(now) << 32) | (nanos... | 0.004082 |
def add_data_dir(self, directory):
"""Hack in a data directory"""
dirs = list(self.DATA_DIRS)
dirs.append(directory)
self.DATA_DIRS = dirs | 0.011765 |
def readLine(self):
""" read a line
Maintains its own buffer, callers of the transport should not mix
calls to readBytes and readLine.
"""
if self.buf is None:
self.buf = []
# Buffer may already have a line if we've received unilateral
# response(s) f... | 0.002608 |
def lpc(x, N=None):
"""Linear Predictor Coefficients.
:param x:
:param int N: default is length(X) - 1
:Details:
Finds the coefficients :math:`A=(1, a(2), \dots a(N+1))`, of an Nth order
forward linear predictor that predicts the current value value of the
real-valued time series x based ... | 0.00586 |
def _process_image_files_batch(coder, thread_index, ranges, name, filenames,
texts, labels, num_shards):
"""Processes and saves list of images as TFRecord in 1 thread.
Args:
coder: instance of ImageCoder to provide TensorFlow image coding utils.
thread_index: integer, unique ... | 0.008599 |
def update_lincs_small_molecules():
"""Load the csv of LINCS small molecule metadata into a dict.
Produces a dict keyed by HMS LINCS small molecule ids, with the metadata
contained in a dict of row values keyed by the column headers extracted
from the csv.
"""
url = 'http://lincs.hms.harvard.ed... | 0.001623 |
def del_row(self, row_index):
"""Delete a row to the table
Arguments:
row_index - The index of the row you want to delete. Indexing starts at 0."""
if row_index > len(self._rows)-1:
raise Exception("Cant delete row at index %d, table only has %d rows!" % (row_index, len(... | 0.010899 |
def make_grid_slot(self, n, m):
"""Create a n x m video grid, show it and add it to the list of video containers
"""
def slot_func():
cont = container.VideoContainerNxM(gpu_handler=self.gpu_handler,
filterchain_group=self.filtercha... | 0.016103 |
def setDigitalMinimum(self, edfsignal, digital_minimum):
"""
Sets the minimum digital value of signal edfsignal.
Usually, the value -32768 is used for EDF+ and -8388608 for BDF+. Usually this will be (-(digital_maximum + 1)).
Parameters
----------
edfsignal : int
... | 0.005076 |
def get_value_length(byte):
"""Length of the value, in bytes (value can be 8/16/24/custom bits)
:param byte:
:return:
"""
length_value = byte & length_type_mask
return LengthTypes.to_ints.get(length_value, byte & length_mask) | 0.004 |
def gate(self, name, params, qubits):
"""
Add a gate to the program.
.. note::
The matrix elements along each axis are ordered by bitstring. For two qubits the order
is ``00, 01, 10, 11``, where the the bits **are ordered in reverse** by the qubit index,
i.e... | 0.00722 |
def make_connection(self):
"Create a new connection"
if self._created_connections >= self.max_connections:
raise ConnectionError("Too many connections")
self._created_connections += 1
return self.connection_class(**self.connection_kwargs) | 0.007092 |
def present(name, containment='NONE', options=None, **kwargs):
'''
Ensure that the named database is present with the specified options
name
The name of the database to manage
containment
Defaults to NONE
options
Can be a list of strings, a dictionary, or a list of dictionar... | 0.003928 |
def build_final_response(request, meta, result, menu, hproject, proxyMode, context):
"""Build the final response to send back to the browser"""
if 'no_template' in meta and meta['no_template']: # Just send the json back
return HttpResponse(result)
# TODO this breaks pages not using new template
... | 0.002732 |
def _validate_ports_low_level(ports):
"""
Internal helper.
Validates the 'ports' argument to EphemeralOnionService or
EphemeralAuthenticatedOnionService returning None on success or
raising ValueError otherwise.
This only accepts the "list of strings" variants; some
higher-level APIs also ... | 0.001353 |
def parse_subnet(self, global_params, region, subnet):
"""
Parse subnet object.
:param global_params:
:param region:
:param subnet:
:return:
"""
vpc_id = subnet['VpcId']
manage_dictionary(self.vpcs, vpc_id, SingleVPCConfig(self.vpc_resource_types)... | 0.0059 |
def _find_complete_block_bounds(self, table, used_cells, possible_block_start,
start_pos, end_pos):
'''
Finds the end of a block from a start location and a suggested end location.
'''
block_start = list(possible_block_start)
block_end = list(p... | 0.002602 |
def _check_resolution_needed(path, project, folderpath, entity_name, expected_classes=None, describe=True,
enclose_in_list=False):
"""
:param path: Path to the object that required resolution; propagated from
command-line
:type path: string
:param project: T... | 0.000861 |
def sleep(duration: float) -> "Future[None]":
"""Return a `.Future` that resolves after the given number of seconds.
When used with ``yield`` in a coroutine, this is a non-blocking
analogue to `time.sleep` (which should not be used in coroutines
because it is blocking)::
yield gen.sleep(0.5)
... | 0.001577 |
def get_attribute_from_config(config, section, attribute):
"""Try to parse an attribute of the config file.
Args:
config (defaultdict): A defaultdict.
section (str): The section of the config file to get information from.
attribute (str): The attribute of the section to fetch.
Retur... | 0.0013 |
def splitext2(filepath):
"""Split filepath into root, filename, ext
Args:
filepath (str, path): file path
Returns:
str
"""
root, filename = os.path.split(safepath(filepath))
filename, ext = os.path.splitext(safepath(filename))
return root, filename, ext | 0.003344 |
def reconfigure(working_dir):
"""
Reconfigure blockstackd.
"""
configure(working_dir, force=True, interactive=True)
print "Blockstack successfully reconfigured."
sys.exit(0) | 0.005076 |
def save(self, *args, **kwargs):
"""
A custom save that publishes or unpublishes the object where
appropriate.
Save with keyword argument obj.save(publish=False) to skip the process.
"""
from bakery import tasks
from django.contrib.contenttypes.models import Cont... | 0.000846 |
def parse_options(metadata):
"""Parse argument options."""
parser = argparse.ArgumentParser(description='%(prog)s usage:',
prog=__prog__)
setoption(parser, metadata=metadata)
return parser | 0.004149 |
def emd(prediction, ground_truth):
"""
Compute the Eart Movers Distance between prediction and model.
This implementation uses opencv for doing the actual work.
Unfortunately, at the time of implementation only the SWIG
bindings werer available and the numpy arrays have to
converted by hand. Th... | 0.00315 |
def to_dict(self):
"""
Returns a dictionary that represents this object, to be used for JSONification.
:return: the object dictionary
:rtype: dict
"""
result = super(Actor, self).to_dict()
result["type"] = "Actor"
result["name"] = self.name
return... | 0.009174 |
def cb_add_plugins(self, name, value):
"""callback for option preprocessing (i.e. before option parsing)"""
self._plugins.extend(utils._splitstrip(value)) | 0.011765 |
def new_parallel(self, function, *params):
'''
Register a new thread executing a parallel method.
'''
# Create a pool if not created (processes or Gevent...)
if self.ppool is None:
if core_type == 'thread':
from multiprocessing.pool import ThreadPool
... | 0.00361 |
def _disambiguate_pos(self, terms, pos):
"""
Disambiguates a list of tokens of a given PoS.
"""
# Map the terms to candidate concepts
# Consider only the top 3 most common senses
candidate_map = {term: wn.synsets(term, pos=pos)[:3] for term in terms}
# Filter to ... | 0.001712 |
def get_buffer_status(self, device_from=None):
"""Main method to read from buffer. Optionally pass in device to
only get response from that device"""
device_from = device_from or ''
# only used if device_from passed in
return_record = OrderedDict()
return_record['success... | 0.002591 |
def _start_node(node):
"""
Start the given node VM.
:return: bool -- True on success, False otherwise
"""
log.debug("_start_node: working on node `%s`", node.name)
# FIXME: the following check is not optimal yet. When a node is still
# in a starting state, it wil... | 0.00211 |
def top_losses(self, k:int=None, largest=True):
"`k` largest(/smallest) losses and indexes, defaulting to all losses (sorted by `largest`)."
return self.losses.topk(ifnone(k, len(self.losses)), largest=largest) | 0.026549 |
def parse_JSON(self, JSON_string):
"""
Parses an *Ozone* instance out of raw JSON data. Only certain
properties of the data are used: if these properties are not found or
cannot be parsed, an error is issued.
:param JSON_string: a raw JSON string
:type JSON_string: str
... | 0.001729 |
def queryWorkitems(self, query_str, projectarea_id=None,
projectarea_name=None, returned_properties=None,
archived=False):
"""Query workitems with the query string in a certain
:class:`rtcclient.project_area.ProjectArea`
At least either of `projecta... | 0.002251 |
def to_representation(self, instance):
"""
Provides post processing. Sub-classes should implement their own
to_representation method, but pass the resulting dict through
this function to get tagging and field selection.
Arguments:
instance: Serialized dict, or object... | 0.002361 |
def on_item_toggled(self, index, state=None):
"""An item is requesting to be toggled"""
if not index.data(model.IsIdle):
return self.info("Cannot toggle")
if not index.data(model.IsOptional):
return self.info("This item is mandatory")
if state is None:
... | 0.001265 |
def ToName(param_type):
"""
Gets the name of a ContractParameterType based on its value
Args:
param_type (ContractParameterType): type to get the name of
Returns:
str
"""
items = inspect.getmembers(ContractParameterType)
if type(param_type) is bytes:
param_type = in... | 0.001976 |
def image_export(self, image_name, dest_url, remote_host=None):
"""Export the specific image to remote host or local file system
:param image_name: image name that can be uniquely identify an image
:param dest_path: the location to store exported image, eg.
/opt/images, the image will be... | 0.002857 |
def parse_JSON(self, JSON_string):
"""
Parses a list of *Observation* instances out of raw JSON data. Only
certain properties of the data are used: if these properties are not
found or cannot be parsed, an error is issued.
:param JSON_string: a raw JSON string
:type JSON... | 0.003994 |
def requeue(self, message_id, timeout=0, backoff=True):
"""Re-queue a message (indicate failure to process)."""
self.send(nsq.requeue(message_id, timeout))
self.finish_inflight()
self.on_requeue.send(
self,
message_id=message_id,
timeout=timeout,
... | 0.005682 |
def train_auto_encoder(self, generative_model, a_logs_list):
'''
Train the generative model as the Auto-Encoder.
Args:
generative_model: Generator which draws samples from the `fake` distribution.
a_logs_list: `list` of the reconstruction errors.
... | 0.006127 |
def cli(*args, **kwargs):
"""
通用自动化处理工具
详情参考 `GitHub <https://github.com/littlemo/mohand>`_
"""
log.debug('cli: {} {}'.format(args, kwargs))
# 使用终端传入的 option 更新 env 中的配置值
env.update(kwargs) | 0.004566 |
def remove_boards_gui(hwpack=''):
"""remove boards by GUI."""
if not hwpack:
if len(hwpack_names()) > 1:
hwpack = psidialogs.choice(hwpack_names(),
'select hardware package to select board from!',
title='select')
... | 0.003601 |
async def query(self, *args):
"""Send a query to the Watchman service and return the response."""
self._check_receive_loop()
try:
await self.connection.send(args)
return await self.receive_bilateral_response()
except CommandError as ex:
ex.setCommand(... | 0.00578 |
def get_gravatar_url(email, size=GRAVATAR_DEFAULT_SIZE, default=GRAVATAR_DEFAULT_IMAGE,
rating=GRAVATAR_DEFAULT_RATING, secure=GRAVATAR_DEFAULT_SECURE):
"""
Builds a url to a gravatar from an email address.
:param email: The email to fetch the gravatar for
:param size: The size (in pixels) of t... | 0.004985 |
def set_mode(self, value):
"""Set the currently active mode on the device (DAB, FM, Spotify)."""
mode = -1
modes = yield from self.get_modes()
for temp_mode in modes:
if temp_mode['label'] == value:
mode = temp_mode['band']
return (yield from self.han... | 0.005618 |
def call_on_each_endpoint(self, callback):
"""Find all server endpoints defined in the swagger spec and calls 'callback' for each,
with an instance of EndpointData as argument.
"""
if 'paths' not in self.swagger_dict:
return
for path, d in list(self.swagger_dict['pa... | 0.003745 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.