code stringlengths 51 2.38k | docstring stringlengths 4 15.2k |
|---|---|
def value_at(self, x):
x = Quantity(x, self.xindex.unit).value
try:
idx = (self.xindex.value == x).nonzero()[0][0]
except IndexError as e:
e.args = ("Value %r not found in array index" % x,)
raise
return self[idx] | Return the value of this `Series` at the given `xindex` value
Parameters
----------
x : `float`, `~astropy.units.Quantity`
the `xindex` value at which to search
Returns
-------
y : `~astropy.units.Quantity`
the value of this Series at the given `... |
def chain_functions(functions):
functions = list(functions)
if not functions:
return _no_op
elif len(functions) == 1:
return functions[0]
else:
return partial(reduce, lambda res, f: f(res), functions) | Chain a list of single-argument functions together and return.
The functions are applied in list order, and the output of the
previous functions is passed to the next function.
Parameters
----------
functions : list
A list of single-argument functions to chain together.
Returns
--... |
def update(self, item, id_expression=None, upsert=False, update_ops={}, safe=None, **kwargs):
if safe is None:
safe = self.safe
self.queue.append(UpdateDocumentOp(self.transaction_id, self, item, safe, id_expression=id_expression,
upsert=upsert, update_ops=update_ops, **kwargs))
if self.autoflush:
r... | Update an item in the database. Uses the on_update keyword to each
field to decide which operations to do, or.
:param item: An instance of a :class:`~ommongo.document.Document` \
subclass
:param id_expression: A query expression that uniquely picks out \
the item which should be updated. If id_expre... |
def list_flavors(self, limit=None, marker=None):
return self._flavor_manager.list(limit=limit, marker=marker) | Returns a list of all available Flavors. |
def estimate(self, observations, weights):
N, M = self._output_probabilities.shape
K = len(observations)
self._output_probabilities = np.zeros((N, M))
if self.__impl__ == self.__IMPL_C__:
for k in range(K):
dc.update_pout(observations[k], weights[k], self._out... | Maximum likelihood estimation of output model given the observations and weights
Parameters
----------
observations : [ ndarray(T_k) ] with K elements
A list of K observation trajectories, each having length T_k
weights : [ ndarray(T_k, N) ] with K elements
A li... |
def _validate_geometry(self, geometry):
if geometry is not None and geometry not in self.valid_geometries:
raise InvalidParameterError("{} is not a valid geometry".format(geometry))
return geometry | Validates geometry, raising error if invalid. |
def get_all_subscriptions(self, next_token=None):
params = {'ContentType' : 'JSON'}
if next_token:
params['NextToken'] = next_token
response = self.make_request('ListSubscriptions', params, '/', 'GET')
body = response.read()
if response.status == 200:
retu... | Get list of all subscriptions.
:type next_token: string
:param next_token: Token returned by the previous call to
this method. |
def _make_style_str(styledict):
s = ''
for key in list(styledict.keys()):
s += "%s:%s;" % (key, styledict[key])
return s | Make an SVG style string from the dictionary. See also _parse_style_str also. |
def clean_path(path):
path = path.replace(os.sep, '/')
if path.startswith('./'):
path = path[2:]
return path | Clean the path |
def linear(self, x):
with tf.name_scope("presoftmax_linear"):
batch_size = tf.shape(x)[0]
length = tf.shape(x)[1]
x = tf.reshape(x, [-1, self.hidden_size])
logits = tf.matmul(x, self.shared_weights, transpose_b=True)
return tf.reshape(logits, [batch_size, length, self.vocab_size]) | Computes logits by running x through a linear layer.
Args:
x: A float32 tensor with shape [batch_size, length, hidden_size]
Returns:
float32 tensor with shape [batch_size, length, vocab_size]. |
def import_checks(path):
dir = internal.check_dir / path
file = internal.load_config(dir)["checks"]
mod = internal.import_file(dir.name, (dir / file).resolve())
sys.modules[dir.name] = mod
return mod | Import checks module given relative path.
:param path: relative path from which to import checks module
:type path: str
:returns: the imported module
:raises FileNotFoundError: if ``path / .check50.yaml`` does not exist
:raises yaml.YAMLError: if ``path / .check50.yaml`` is not a valid YAML file
... |
def to_unix(cls, timestamp):
if not isinstance(timestamp, datetime.datetime):
raise TypeError('Time.milliseconds expects a datetime object')
base = time.mktime(timestamp.timetuple())
return base | Wrapper over time module to produce Unix epoch time as a float |
def _init_entri(self, laman):
sup = BeautifulSoup(laman.text, 'html.parser')
estr = ''
for label in sup.find('hr').next_siblings:
if label.name == 'hr':
self.entri.append(Entri(estr))
break
if label.name == 'h2':
if estr:
... | Membuat objek-objek entri dari laman yang diambil.
:param laman: Laman respons yang dikembalikan oleh KBBI daring.
:type laman: Response |
def authorization_url(self, **kwargs):
kwargs.setdefault('access_type', 'offline')
url, state = self.oauth2session.authorization_url(
self.client_config['auth_uri'], **kwargs)
return url, state | Generates an authorization URL.
This is the first step in the OAuth 2.0 Authorization Flow. The user's
browser should be redirected to the returned URL.
This method calls
:meth:`requests_oauthlib.OAuth2Session.authorization_url`
and specifies the client configuration's authoriz... |
def set_expiration(self, key, ignore_missing=False,
additional_seconds=None, seconds=None):
if key not in self.time_dict and ignore_missing:
return
elif key not in self.time_dict and not ignore_missing:
raise Exception('Key missing from `TimedDict` and '
... | Alters the expiration time for a key. If the key is not
present, then raise an Exception unless `ignore_missing`
is set to `True`.
Args:
key: The key whose expiration we are changing.
ignore_missing (bool): If set, then return silently
if the key does not... |
def login(config, api_key=""):
if not api_key:
info_out(
"If you don't have an API Key, go to:\n"
"https://bugzilla.mozilla.org/userprefs.cgi?tab=apikey\n"
)
api_key = getpass.getpass("API Key: ")
url = urllib.parse.urljoin(config.bugzilla_url, "/rest/whoami")
... | Store your Bugzilla API Key |
def tokens(cls, tokens):
return cls(Lnk.TOKENS, tuple(map(int, tokens))) | Create a Lnk object for a token range.
Args:
tokens: a list of token identifiers |
def on_post(resc, req, resp):
signals.pre_req.send(resc.model)
signals.pre_req_create.send(resc.model)
props = req.deserialize()
model = resc.model()
from_rest(model, props)
goldman.sess.store.create(model)
props = to_rest_model(model, includes=req.includes)
resp.last_modified = model.up... | Deserialize the payload & create the new single item |
def kill(self, name):
if not name:
raise ValueError("Name can't be None or empty")
with self.__instances_lock:
try:
stored_instance = self.__instances.pop(name)
factory_context = stored_instance.context.factory_context
stored_instan... | Kills the given component
:param name: Name of the component to kill
:raise ValueError: Invalid component name |
def growthfromrange(rangegrowth, startdate, enddate):
_yrs = (pd.Timestamp(enddate) - pd.Timestamp(startdate)).total_seconds() /\
dt.timedelta(365.25).total_seconds()
return yrlygrowth(rangegrowth, _yrs) | Annual growth given growth from start date to end date. |
def winnow_by_keys(dct, keys=None, filter_func=None):
has = {}
has_not = {}
for key in dct:
key_passes_check = False
if keys is not None:
key_passes_check = key in keys
elif filter_func is not None:
key_passes_check = filter_func(key)
if key_passes_che... | separates a dict into has-keys and not-has-keys pairs, using either
a list of keys or a filtering function. |
def determine_repo_dir(template, abbreviations, clone_to_dir, checkout,
no_input, password=None):
template = expand_abbreviations(template, abbreviations)
if is_zip_file(template):
unzipped_dir = unzip(
zip_uri=template,
is_url=is_repo_url(template),
... | Locate the repository directory from a template reference.
Applies repository abbreviations to the template reference.
If the template refers to a repository URL, clone it.
If the template is a path to a local repository, use it.
:param template: A directory containing a project template directory,
... |
def pretty_dump(fn):
@wraps(fn)
def pretty_dump_wrapper(*args, **kwargs):
response.content_type = "application/json; charset=utf-8"
return json.dumps(
fn(*args, **kwargs),
indent=4,
separators=(',', ': ')
)
return pretty_dump_wrapper | Decorator used to output prettified JSON.
``response.content_type`` is set to ``application/json; charset=utf-8``.
Args:
fn (fn pointer): Function returning any basic python data structure.
Returns:
str: Data converted to prettified JSON. |
def _maybe_normalize(self, var):
if self.normalize:
try:
return self._norm.normalize(var)
except HGVSUnsupportedOperationError as e:
_logger.warning(str(e) + "; returning unnormalized variant")
return var | normalize variant if requested, and ignore HGVSUnsupportedOperationError
This is better than checking whether the variant is intronic because
future UTAs will support LRG, which will enable checking intronic variants. |
def addFailure(self, test, err, capt=None, tbinfo=None):
self.__insert_test_result(constants.State.FAILURE, test, err) | After a test failure, we want to record testcase run information. |
def add_code_mapping(self, from_pdb_code, to_pdb_code):
if from_pdb_code in self.code_map:
assert(self.code_map[from_pdb_code] == to_pdb_code)
else:
self.code_map[from_pdb_code] = to_pdb_code | Add a code mapping without a given instance. |
def create_query(self, fields=None):
if fields is None:
return Query(self.fields)
non_contained_fields = set(fields) - set(self.fields)
if non_contained_fields:
raise BaseLunrException(
"Fields {} are not part of the index", non_contained_fields
... | Convenience method to create a Query with the Index's fields.
Args:
fields (iterable, optional): The fields to include in the Query,
defaults to the Index's `all_fields`.
Returns:
Query: With the specified fields or all the fields in the Index. |
def tx_for_tx_hash(self, tx_hash):
try:
url_append = "?token=%s&includeHex=true" % self.api_key
url = self.base_url("txs/%s%s" % (b2h_rev(tx_hash), url_append))
result = json.loads(urlopen(url).read().decode("utf8"))
tx = Tx.parse(io.BytesIO(h2b(result.get("hex"))... | returns the pycoin.tx object for tx_hash |
def reset(self):
self.idx_annotations.setText('Load Annotation File...')
self.idx_rater.setText('')
self.annot = None
self.dataset_markers = None
self.idx_marker.clearContents()
self.idx_marker.setRowCount(0)
w1 = self.idx_summary.takeAt(1).widget()
w2 = s... | Remove all annotations from window. |
def eventsource_connect(url, io_loop=None, callback=None, connect_timeout=None):
if io_loop is None:
io_loop = IOLoop.current()
if isinstance(url, httpclient.HTTPRequest):
assert connect_timeout is None
request = url
request.headers = httputil.HTTPHeaders(request.headers)
els... | Client-side eventsource support.
Takes a url and returns a Future whose result is a
`EventSourceClient`. |
def frommembers(cls, members=()):
return cls.fromint(sum(map(cls._map.__getitem__, set(members)))) | Create a set from an iterable of members. |
def sort_dicoms(dicoms):
dicom_input_sorted_x = sorted(dicoms, key=lambda x: (x.ImagePositionPatient[0]))
dicom_input_sorted_y = sorted(dicoms, key=lambda x: (x.ImagePositionPatient[1]))
dicom_input_sorted_z = sorted(dicoms, key=lambda x: (x.ImagePositionPatient[2]))
diff_x = abs(dicom_input_sorted_x[-1... | Sort the dicoms based om the image possition patient
:param dicoms: list of dicoms |
def rebin_scale(a, scale=1):
newshape = tuple((side * scale) for side in a.shape)
return rebin(a, newshape) | Scale an array to a new shape. |
def active_days(records):
days = set(r.datetime.date() for r in records)
return len(days) | The number of days during which the user was active. A user is considered
active if he sends a text, receives a text, initiates a call, receives a
call, or has a mobility point. |
def mergeStyles(self, styles):
" XXX Bugfix for use in PISA "
for k, v in six.iteritems(styles):
if k in self and self[k]:
self[k] = copy.copy(self[k])
self[k].update(v)
else:
self[k] = v | XXX Bugfix for use in PISA |
def get_token(self, code=None):
tokenobj = self.steemconnect().get_access_token(code)
for t in tokenobj:
if t == 'error':
self.msg.error_message(str(tokenobj[t]))
return False
elif t == 'access_token':
self.username = tokenobj['user... | Uses a SteemConnect refresh token
to retreive an access token |
def _get_ruuvitag_datas(macs=[], search_duratio_sec=None, run_flag=RunFlag(), bt_device=''):
mac_blacklist = []
start_time = time.time()
data_iter = ble.get_datas(mac_blacklist, bt_device)
for ble_data in data_iter:
if search_duratio_sec and time.time() - start_time > search_... | Get data from BluetoothCommunication and handle data encoding.
Args:
macs (list): MAC addresses. Default empty list
search_duratio_sec (int): Search duration in seconds. Default None
run_flag (object): RunFlag object. Function executes while run_flag.running. Default new Run... |
def delete(self, exchange, if_unused=False, nowait=True, ticket=None,
cb=None):
nowait = nowait and self.allow_nowait() and not cb
args = Writer()
args.write_short(ticket or self.default_ticket).\
write_shortstr(exchange).\
write_bits(if_unused, nowait)
... | Delete an exchange. |
def createStopOrder(self, quantity, parentId=0, stop=0., trail=None,
transmit=True, group=None, stop_limit=False, rth=False, tif="DAY",
account=None):
if trail:
if trail == "percent":
order = self.createOrder(quantity,
trailingPerce... | Creates STOP order |
def to_bqm(self, model):
linear = ((v, float(model.get_py_value(bias)))
for v, bias in self.linear.items())
quadratic = ((u, v, float(model.get_py_value(bias)))
for (u, v), bias in self.quadratic.items())
offset = float(model.get_py_value(self.offset))
... | Given a pysmt model, return a bqm.
Adds the values of the biases as determined by the SMT solver to a bqm.
Args:
model: A pysmt model.
Returns:
:obj:`dimod.BinaryQuadraticModel` |
def get_grid_mapping_variables(ds):
grid_mapping_variables = []
for ncvar in ds.get_variables_by_attributes(grid_mapping=lambda x: x is not None):
if ncvar.grid_mapping in ds.variables:
grid_mapping_variables.append(ncvar.grid_mapping)
return grid_mapping_variables | Returns a list of grid mapping variables
:param netCDF4.Dataset ds: An open netCDF4 Dataset |
def absent(name, **connection_args):
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if __salt__['mysql.db_exists'](name, **connection_args):
if __opts__['test']:
ret['result'] = None
ret['comment'] = \
'Database... | Ensure that the named database is absent
name
The name of the database to remove |
def _remove_untraceable(self):
self._probe_mapping = {}
wvs = {wv for wv in self.tracer.wires_to_track if self._traceable(wv)}
self.tracer.wires_to_track = wvs
self.tracer._wires = {wv.name: wv for wv in wvs}
self.tracer.trace.__init__(wvs) | Remove from the tracer those wires that CompiledSimulation cannot track.
Create _probe_mapping for wires only traceable via probes. |
def _raw_input_contains_national_prefix(raw_input, national_prefix, region_code):
nnn = normalize_digits_only(raw_input)
if nnn.startswith(national_prefix):
try:
return is_valid_number(parse(nnn[len(national_prefix):], region_code))
except NumberParseException:
return Fal... | Check if raw_input, which is assumed to be in the national format, has a
national prefix. The national prefix is assumed to be in digits-only
form. |
def obj_deref(ref):
from indico_livesync.models.queue import EntryType
if ref['type'] == EntryType.category:
return Category.get_one(ref['category_id'])
elif ref['type'] == EntryType.event:
return Event.get_one(ref['event_id'])
elif ref['type'] == EntryType.session:
return Sessio... | Returns the object identified by `ref` |
def transform_attrs(obj, keys, container, func, extras=None):
cpextras = extras
for reportlab, css in keys:
extras = cpextras
if extras is None:
extras = []
elif not isinstance(extras, list):
extras = [extras]
if css in container:
extras.insert... | Allows to apply one function to set of keys cheching if key is in container,
also trasform ccs key to report lab keys.
extras = Are extra params for func, it will be call like func(*[param1, param2])
obj = frag
keys = [(reportlab, css), ... ]
container = cssAttr |
def send(self, to, from_, body):
try:
msg = self.client.sms.messages.create(
body=body,
to=to,
from_=from_
)
print msg.sid
except twilio.TwilioRestException as e:
raise | Send BODY to TO from FROM as an SMS! |
def _enable_logpersist(self):
if not self._ad.is_rootable:
return
logpersist_warning = ('%s encountered an error enabling persistent'
' logs, logs may not get saved.')
if not self._ad.adb.has_shell_command('logpersist.start'):
logging.warning... | Attempts to enable logpersist daemon to persist logs. |
def to_rest_models(models, includes=None):
props = {}
props['data'] = []
for model in models:
props['data'].append(_to_rest(model, includes=includes))
props['included'] = _to_rest_includes(models, includes=includes)
return props | Convert the models into a dict for serialization
models should be an array of single model objects that
will each be serialized.
:return: dict |
def _build_time(time, kwargs):
tz = kwargs.pop('tz', 'UTC')
if time:
if kwargs:
raise ValueError('Cannot pass kwargs and a time')
else:
return ensure_utc(time, tz)
elif not kwargs:
raise ValueError('Must pass a time or kwargs')
else:
return datetim... | Builds the time argument for event rules. |
def analyze(output_dir, dataset, cloud=False, project_id=None):
job = analyze_async(
output_dir=output_dir,
dataset=dataset,
cloud=cloud,
project_id=project_id)
job.wait()
print('Analyze: ' + str(job.state)) | Blocking version of analyze_async. See documentation of analyze_async. |
def revoke_token(token_id, user):
try:
token = TokenBlacklist.query.filter_by(id=token_id, user_identity=user).one()
token.revoked = True
db.session.commit()
except NoResultFound:
raise TokenNotFound("Could not find the token {}".format(token_id)) | Revokes the given token. Raises a TokenNotFound error if the token does
not exist in the database |
def convert_timestamp(timestamp):
datetime = dt.datetime.utcfromtimestamp(timestamp/1000.)
return np.datetime64(datetime.replace(tzinfo=None)) | Converts bokehJS timestamp to datetime64. |
def filter(objects, Type=None, min=-1, max=-1):
res = []
if min > max:
raise ValueError("minimum must be smaller than maximum")
if Type is not None:
res = [o for o in objects if isinstance(o, Type)]
if min > -1:
res = [o for o in res if _getsizeof(o) < min]
if max > -1:
... | Filter objects.
The filter can be by type, minimum size, and/or maximum size.
Keyword arguments:
Type -- object type to filter by
min -- minimum object size
max -- maximum object size |
def add_nodes_from(self, nodes, weights=None):
nodes = list(nodes)
if weights:
if len(nodes) != len(weights):
raise ValueError("The number of elements in nodes and weights"
"should be equal.")
for index in range(len(nodes)):
... | Add multiple nodes to the Graph.
**The behviour of adding weights is different than in networkx.
Parameters
----------
nodes: iterable container
A container of nodes (list, dict, set, or any hashable python
object).
weights: list, tuple (default=None)
... |
def add_crosshair_to_image(fname, opFilename):
im = Image.open(fname)
draw = ImageDraw.Draw(im)
draw.line((0, 0) + im.size, fill=(255, 255, 255))
draw.line((0, im.size[1], im.size[0], 0), fill=(255, 255, 255))
del draw
im.save(opFilename) | convert an image by adding a cross hair |
def supernodes(par, post, colcount):
snpar, flag = pothen_sun(par, post, colcount)
n = len(par)
N = len(snpar)
snode = matrix(0, (n,1))
snptr = matrix(0, (N+1,1))
slist = [[] for i in range(n)]
for i in range(n):
f = flag[i]
if f < 0:
slist[i].append(i)
el... | Find supernodes.
ARGUMENTS
par parent array
post array with post ordering
colcount array with column counts
RETURNS
snode array with supernodes; snode[snptr[k]:snptr[k+1]] contains
the indices of supernode k
snptr pointer array; snptr[k] is the index of... |
def rerun(version="3.7.0"):
from commandlib import Command
Command(DIR.gen.joinpath("py{0}".format(version), "bin", "python"))(
DIR.gen.joinpath("state", "examplepythoncode.py")
).in_dir(DIR.gen.joinpath("state")).run() | Rerun last example code block with specified version of python. |
def rebuild(self, image):
if isinstance(image, Image):
image = image.id
return self.act(type='rebuild', image=image) | Rebuild the droplet with the specified image
A rebuild action functions just like a new create. [APIDocs]_
:param image: an image ID, an image slug, or an `Image` object
representing the image the droplet should use as a base
:type image: integer, string, or `Image`
:re... |
def stream_fastq_full(fastq, threads):
logging.info("Nanoget: Starting to collect full metrics from plain fastq file.")
inputfastq = handle_compressed_input(fastq)
with cfutures.ProcessPoolExecutor(max_workers=threads) as executor:
for results in executor.map(extract_all_from_fastq, SeqIO.parse(inpu... | Generator for returning metrics extracted from fastq.
Extract from a fastq file:
-readname
-average and median quality
-read_lenght |
def check_cond_latents(cond_latents, hparams):
if cond_latents is None:
return
if not isinstance(cond_latents[0], list):
cond_latents = [cond_latents]
exp_num_latents = hparams.num_cond_latents
if hparams.latent_dist_encoder == "conv_net":
exp_num_latents += int(hparams.cond_first_frame)
if len(co... | Shape checking for cond_latents. |
def _sample_groups(problem, N, num_levels=4):
if len(problem['groups']) != problem['num_vars']:
raise ValueError("Groups do not match to number of variables")
group_membership, _ = compute_groups_matrix(problem['groups'])
if group_membership is None:
raise ValueError("Please define the 'grou... | Generate trajectories for groups
Returns an :math:`N(g+1)`-by-:math:`k` array of `N` trajectories,
where :math:`g` is the number of groups and :math:`k` is the number
of factors
Arguments
---------
problem : dict
The problem definition
N : int
The number of trajectories to ... |
def to_msgpack(self, path_or_buf=None, encoding='utf-8', **kwargs):
from pandas.io import packers
return packers.to_msgpack(path_or_buf, self, encoding=encoding,
**kwargs) | Serialize object to input file path using msgpack format.
THIS IS AN EXPERIMENTAL LIBRARY and the storage format
may not be stable until a future release.
Parameters
----------
path : string File path, buffer-like, or None
if None, return generated string
ap... |
def fuller_scaling(target, DABo, To, Po, temperature='pore.temperature',
pressure='pore.pressure'):
r
Ti = target[temperature]
Pi = target[pressure]
value = DABo*(Ti/To)**1.75*(Po/Pi)
return value | r"""
Uses Fuller model to adjust a diffusion coefficient for gases from
reference conditions to conditions of interest
Parameters
----------
target : OpenPNM Object
The object for which these values are being calculated. This
controls the length of the calculated array, and also pr... |
def pad(self, *args, **kwargs):
if not args:
start, end = self.padding
else:
start, end = args
if kwargs.pop('inplace', False):
new = self
else:
new = self.copy()
if kwargs:
raise TypeError("unexpected keyword argument %... | Apply a padding to each segment in this `DataQualityFlag`
This method either takes no arguments, in which case the value of
the :attr:`~DataQualityFlag.padding` attribute will be used,
or two values representing the padding for the start and end of
each segment.
For both the `s... |
def report_error_event(self, error_report):
logger = self.logging_client.logger("errors")
logger.log_struct(error_report) | Report error payload.
:type error_report: dict
:param: error_report:
dict payload of the error report formatted according to
https://cloud.google.com/error-reporting/docs/formatting-error-messages
This object should be built using
:meth:~`google.cloud.err... |
def import_module(modulename):
module = None
try:
module = importlib.import_module(modulename)
except ImportError:
if "." in modulename:
modules = modulename.split(".")
package = ".".join(modules[1:len(modules)])
module = importlib.import_module(package)
... | Static method for importing module modulename. Can handle relative imports as well.
:param modulename: Name of module to import. Can be relative
:return: imported module instance. |
def mechanism_indices(self, direction):
return {
Direction.CAUSE: self.effect_indices,
Direction.EFFECT: self.cause_indices
}[direction] | The indices of nodes in the mechanism system. |
def num_fmt(num, max_digits=None):
r
if num is None:
return 'None'
def num_in_mag(num, mag):
return mag > num and num > (-1 * mag)
if max_digits is None:
if num_in_mag(num, 1):
if num_in_mag(num, .1):
max_digits = 4
else:
ma... | r"""
Weird function. Not very well written. Very special case-y
Args:
num (int or float):
max_digits (int):
Returns:
str:
CommandLine:
python -m utool.util_num --test-num_fmt
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_num import * # NOQA
... |
def _point_plot_defaults(self, args, kwargs):
if args:
return args, kwargs
if 'ls' not in kwargs and 'linestyle' not in kwargs:
kwargs['linestyle'] = 'none'
if 'marker' not in kwargs:
kwargs['marker'] = 'o'
return args, kwargs | To avoid confusion for new users, this ensures that "scattered"
points are plotted by by `plot` instead of points joined by a line.
Parameters
----------
args : tuple
Arguments representing additional parameters to be passed to
`self.plot`.
kwargs : dict
... |
def extract_fields(self):
dm = IDataManager(self.context)
fieldnames = filter(lambda name: name not in self.ignore, self.keys)
out = dict()
for fieldname in fieldnames:
try:
fieldvalue = dm.json_data(fieldname)
except Unauthorized:
... | Extract the given fieldnames from the object
:returns: Schema name/value mapping
:rtype: dict |
def Get(self, flags, off):
N.enforce_number(off, N.UOffsetTFlags)
return flags.py_type(encode.Get(flags.packer_type, self.Bytes, off)) | Get retrieves a value of the type specified by `flags` at the
given offset. |
def assign_unassigned_members(self, group_category_id, sync=None):
path = {}
data = {}
params = {}
path["group_category_id"] = group_category_id
if sync is not None:
data["sync"] = sync
self.logger.debug("POST /api/v1/group_categories/{group_category_id... | Assign unassigned members.
Assign all unassigned members as evenly as possible among the existing
student groups. |
def reject(self, func):
return self._wrap(list(filter(lambda val: not func(val), self.obj))) | Return all the elements for which a truth test fails. |
def open_handle(self, dwDesiredAccess = win32.PROCESS_ALL_ACCESS):
hProcess = win32.OpenProcess(dwDesiredAccess, win32.FALSE, self.dwProcessId)
try:
self.close_handle()
except Exception:
warnings.warn(
"Failed to close process handle: %s" % traceback.forma... | Opens a new handle to the process.
The new handle is stored in the L{hProcess} property.
@warn: Normally you should call L{get_handle} instead, since it's much
"smarter" and tries to reuse handles and merge access rights.
@type dwDesiredAccess: int
@param dwDesiredAccess:... |
def ekopr(fname):
fname = stypes.stringToCharP(fname)
handle = ctypes.c_int()
libspice.ekopr_c(fname, ctypes.byref(handle))
return handle.value | Open an existing E-kernel file for reading.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekopr_c.html
:param fname: Name of EK file.
:type fname: str
:return: Handle attached to EK file.
:rtype: int |
def dumps(self, fd, **kwargs):
if 0 <= fd <= 2:
data = [self.stdin, self.stdout, self.stderr][fd].concretize(**kwargs)
if type(data) is list:
data = b''.join(data)
return data
return self.get_fd(fd).concretize(**kwargs) | Returns the concrete content for a file descriptor.
BACKWARD COMPATIBILITY: if you ask for file descriptors 0 1 or 2, it will return the data from stdin, stdout,
or stderr as a flat string.
:param fd: A file descriptor.
:return: The concrete content.
:rtype: str |
def _SerializeEntries(entries):
output = []
for python_format, wire_format, type_descriptor in entries:
if wire_format is None or (python_format and
type_descriptor.IsDirty(python_format)):
wire_format = type_descriptor.ConvertToWireFormat(python_format)
precondition.Ass... | Serializes given triplets of python and wire values and a descriptor. |
def add(self, template, resource, name=None):
if hasattr(resource, '_rhino_meta'):
route = Route(
template, Resource(resource), name=name, ranges=self.ranges)
else:
route = Route(
template, resource, name=name, ranges=self.ranges)
o... | Add a route to a resource.
The optional `name` assigns a name to this route that can be used when
building URLs. The name must be unique within this Mapper object. |
def discovery_mdns(self):
logging.getLogger("zeroconf").setLevel(logging.WARNING)
self.context.install_bundle("pelix.remote.discovery.mdns").start()
with use_waiting_list(self.context) as ipopo:
ipopo.add(rs.FACTORY_DISCOVERY_ZEROCONF, "pelix-discovery-zeroconf") | Installs the mDNS discovery bundles and instantiates components |
def associate_dhcp_options(self, dhcp_options_id, vpc_id):
params = {'DhcpOptionsId': dhcp_options_id,
'VpcId' : vpc_id}
return self.get_status('AssociateDhcpOptions', params) | Associate a set of Dhcp Options with a VPC.
:type dhcp_options_id: str
:param dhcp_options_id: The ID of the Dhcp Options
:type vpc_id: str
:param vpc_id: The ID of the VPC.
:rtype: bool
:return: True if successful |
def _outfp_write_with_check(self, outfp, data, enable_overwrite_check=True):
start = outfp.tell()
outfp.write(data)
if self._track_writes:
end = outfp.tell()
if end > self.pvd.space_size * self.pvd.logical_block_size():
raise pycdlibexception.PyCdlibIntern... | Internal method to write data out to the output file descriptor,
ensuring that it doesn't go beyond the bounds of the ISO.
Parameters:
outfp - The file object to write to.
data - The actual data to write.
enable_overwrite_check - Whether to do overwrite checking if it is enab... |
def get_job_log_url(self, project, **params):
return self._get_json(self.JOB_LOG_URL_ENDPOINT, project,
**params) | Gets job log url, filtered by parameters
:param project: project (repository name) to query data for
:param params: keyword arguments to filter results |
def wol(mac, bcast='255.255.255.255', destport=9):
dest = salt.utils.network.mac_str_to_bytes(mac)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
sock.sendto(b'\xff' * 6 + dest * 16, (bcast, int(destport)))
return True | Send a "Magic Packet" to wake up a Minion
CLI Example:
.. code-block:: bash
salt-run network.wol 08-00-27-13-69-77
salt-run network.wol 080027136977 255.255.255.255 7
salt-run network.wol 08:00:27:13:69:77 255.255.255.255 7 |
def diff_levenshtein(self, diffs):
levenshtein = 0
insertions = 0
deletions = 0
for (op, data) in diffs:
if op == self.DIFF_INSERT:
insertions += len(data)
elif op == self.DIFF_DELETE:
deletions += len(data)
elif op == self.DIFF_EQUAL:
levenshtein += max(inserti... | Compute the Levenshtein distance; the number of inserted, deleted or
substituted characters.
Args:
diffs: Array of diff tuples.
Returns:
Number of changes. |
def process_streamers(self):
in_progress = self._stream_manager.in_progress()
triggered = self.graph.check_streamers(blacklist=in_progress)
for streamer in triggered:
self._stream_manager.process_streamer(streamer, callback=self._handle_streamer_finished) | Check if any streamers should be handed to the stream manager. |
def _commit(self):
if not self.in_progress:
raise ValueError(_CANT_COMMIT)
commit_response = _commit_with_retry(self._client, self._write_pbs, self._id)
self._clean_up()
return list(commit_response.write_results) | Transactionally commit the changes accumulated.
Returns:
List[google.cloud.proto.firestore.v1beta1.\
write_pb2.WriteResult, ...]: The write results corresponding
to the changes committed, returned in the same order as the
changes were applied to this transact... |
def geo_search(user_id, search_location):
url = "https://api.twitter.com/1.1/geo/search.json"
params = {"query" : search_location }
response = make_twitter_request(url, user_id, params).json()
return response | Search for a location - free form |
def get_properties(attributes):
return [key for key, value in six.iteritems(attributes)
if isinstance(value, property)] | Return tuple of names of defined properties.
:type attributes: dict
:rtype: list |
def set_orient(self):
self.orient = RADTODEG(N.arctan2(self.cd12,self.cd22)) | Return the computed orientation based on CD matrix. |
def run(self):
if self.status:
self.set_status('aborted')
raise LimpydJobsException('This worker run is already terminated')
self.set_status('starting')
self.start_date = datetime.utcnow()
if self.max_duration:
self.wanted_end_date = self.start_date + ... | The main method of the worker. Will ask redis for list items via
blocking calls, get jobs from them, try to execute these jobs, and end
when needed. |
def _unpack(c, tmp, package, version, git_url=None):
real_version = version[:]
source = None
if git_url:
pass
else:
cwd = os.getcwd()
print("Moving into temp dir %s" % tmp)
os.chdir(tmp)
try:
flags = "--download=. --build=build --no-use-wheel"
... | Download + unpack given package into temp dir ``tmp``.
Return ``(real_version, source)`` where ``real_version`` is the "actual"
version downloaded (e.g. if a Git master was indicated, it will be the SHA
of master HEAD) and ``source`` is the source directory (relative to
unpacked source) to import into ... |
def setup_user_manager(app):
from flask_user import SQLAlchemyAdapter
from rio.models import User
init = dict(
db_adapter=SQLAlchemyAdapter(db, User),
)
user_manager.init_app(app, **init) | Setup flask-user manager. |
def make_scratch_dirs(file_mapping, dry_run=True):
scratch_dirs = {}
for value in file_mapping.values():
scratch_dirname = os.path.dirname(value)
scratch_dirs[scratch_dirname] = True
for scratch_dirname in scratch_dirs:
if dry_run:
print("mkdir... | Make any directories need in the scratch area |
def refresh(self):
j = self.vera_request(id='sdata', output_format='json').json()
devices = j.get('devices')
for device_data in devices:
if device_data.get('id') == self.device_id:
self.update(device_data) | Refresh the dev_info data used by get_value.
Only needed if you're not using subscriptions. |
def _rescale(self, points):
return [(
x, self._scale_diff + (y - self._scale_min_2nd) * self._scale
if y is not None else None
) for x, y in points] | Scale for secondary |
def get_health_events(self, recipient):
if recipient not in self.addresses_events:
self.start_health_check(recipient)
return self.addresses_events[recipient] | Starts a healthcheck task for `recipient` and returns a
HealthEvents with locks to react on its current state. |
def preprocess(net, image):
return np.float32(np.rollaxis(image, 2)[::-1]) - net.transformer.mean["data"] | convert to Caffe input image layout |
def sort(self):
beams = [v for (_, v) in self.entries.items()]
sortedBeams = sorted(beams, reverse=True, key=lambda x: x.prTotal*x.prText)
return [x.labeling for x in sortedBeams] | return beam-labelings, sorted by probability |
def principal_inertia_components(self):
components, vectors = inertia.principal_axis(self.moment_inertia)
self._cache['principal_inertia_vectors'] = vectors
return components | Return the principal components of inertia
Ordering corresponds to mesh.principal_inertia_vectors
Returns
----------
components : (3,) float
Principal components of inertia |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.