content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Callable
from re import T
from typing import Iterable
def space(fn: Callable[[State], T], verbose: bool=False) -> Iterable[T]:
"""
Return an iterable that generates values from ``fn``
fully exhausting the state space.
During iteration, the function ``fn`` is called repeatedly with ... | b901a3936b6e1020db123bce9f72b600117f5825 | 3,638,300 |
import json
def get_menu_as_json(menu):
"""Build Tree-like JSON structure from the top menu.
From the top menu items, its children and its grandchildren.
"""
top_items = menu.items.filter(parent=None)
menu_data = []
for item in top_items:
top_item_data = get_menu_item_as_dict(item)
... | f191d883f44b5cbed729ebcee7670ba99e28d941 | 3,638,301 |
import numpy
def vortex_contribution_normal(panels):
"""
Builds the vortex contribution matrix for the normal velocity.
Parameters
----------
panels: 1D array of Panel objects
List of panels.
Returns
-------
A: 2D Numpy array of floats
Vortex contribution matr... | e5089509646be80307210cad528357d3f85774e9 | 3,638,302 |
def find_template(raw, name):
"""Return Template node with given name or None if there is no such template"""
e=Expander('', wikidb=DictDB())
todo = [parse(raw, replace_tags=e.replace_tags)]
while todo:
n = todo.pop()
if isinstance(n, basestring):
continue
if isi... | ec74c099a810126b798c83fdac50bbb3d79c37cd | 3,638,303 |
def app():
"""Required by pytest-tornado's http_server fixture"""
return tornado.web.Application() | 556ac2b69eaca3d8c4f934fba0deea820ab4e1ff | 3,638,304 |
import inspect
def is_bound_builtin_method(meth):
"""Helper returning True if meth is a bound built-in method"""
return (inspect.isbuiltin(meth)
and getattr(meth, '__self__', None) is not None
and getattr(meth.__self__, '__class__', None)) | a7a45f0f519119d795e91723657a1333eb6714e4 | 3,638,305 |
def normalize(adj):
"""Row-normalize sparse matrix"""
rowsum = np.array(adj.sum(1))
r_inv = np.power(rowsum, -1).flatten()
r_inv[np.isinf(r_inv)] = 0.
r_mat_inv = np.diag(r_inv)
mx = r_mat_inv.dot(adj)
return mx | c342890befeddd3db01403914e80b9e89dc4f20d | 3,638,306 |
def get_recommendation_and_prediction_from_text(input_text, num_feats=10):
"""
Gets a score and recommendations that can be displayed in the Flask app
:param input_text: input string
:param num_feats: number of features to suggest recommendations for
:return: current score along with recommendations... | 6f5737c5ac293a3e33fed7a95119c30c72fafa1e | 3,638,307 |
def set_title(title, uid='master'):
"""
Sets a new title of the window
"""
try:
_webview_ready.wait(5)
return gui.set_title(title, uid)
except NameError:
raise Exception('Create a web view window first, before invoking this function')
except KeyError:
raise Except... | e2ad0fd3673ab2ad0966527b394e9afdf8e2a531 | 3,638,308 |
def FK42FK5MatrixOLDATTEMPT():
"""
----------------------------------------------------------------------
Experimental.
Create matrix to precess from an epoch in FK4 to an epoch in FK5
So epoch1 is Besselian and epoch2 is Julian
1) Do an epoch transformation in FK4 from input epoch to
1984 January 1d 0h
2) Apply... | bbf98f3073fda4a248190e417332d72645faf5c1 | 3,638,309 |
def _lg_undirected(G, selfloops=False, create_using=None):
"""Return the line graph L of the (multi)graph G.
Edges in G appear as nodes in L, represented as sorted tuples of the form
(u,v), or (u,v,key) if G is a multigraph. A node in L corresponding to
the edge {u,v} is connected to every node corresp... | 172fbe2e1d2ec425c3b37c97429df67d789f2c9c | 3,638,310 |
def get_utxo_provider_client(utxo_provider, config_file):
"""
Get or instantiate our blockchain UTXO provider's client.
Return None if we were unable to connect
"""
utxo_opts = default_utxo_provider_opts( utxo_provider, config_file )
try:
utxo_provider = connect_utxo_provider( utxo_opts )
... | 79d72221f707f36bdb07a57b634a57bb42942b2e | 3,638,311 |
from typing import Dict
from typing import Any
def metadata(
sceneid: str,
pmin: float = 2.0,
pmax: float = 98.0,
hist_options: Dict = {},
**kwargs: Any,
) -> Dict:
"""
Return band bounds and statistics.
Attributes
----------
sceneid : str
CBERS sceneid.
... | c3b5203ddbec575f791bef1fb6689088dfa666a2 | 3,638,312 |
def size_to_string(volume_size):
# type: (int) -> str
"""
Convert a volume size to string format to pass into Kubernetes.
Args:
volume_size: The size of the volume in bytes.
Returns:
The size of the volume in gigabytes as a passable string to Kubernetes.
"""
if volume_size >=... | b1b30f4a383d29951d12189180271a9752e5ba61 | 3,638,313 |
def argToDic(arg):
"""
Converts a parameter sequence into a dict.
Args:
arg (string): specified simulation parameters."""
params = dict()
options = arg.split("_")
if "=" in options[0]:
params["mode"] = ""
else:
params["mode"] = options.pop(0)
# parse arguments ... | 173284e8ee45d9e61d786be33d6d6df60e0f9389 | 3,638,314 |
import glob
import os
def _installed_snpeff_genome(config_file, base_name):
"""Find the most recent installed genome for snpEff with the given name.
"""
data_dir = _find_snpeff_datadir(config_file)
dbs = [d for d in sorted(glob.glob(os.path.join(data_dir, "%s*" % base_name)), reverse=True)
... | 07f6de2665bb61cc195c515e9750a143f5ec4358 | 3,638,315 |
def geth2hforplayer(matches,name):
"""get all head-to-heads of the player"""
matches = matches[(matches['winner_name'] == name) | (matches['loser_name'] == name)]
h2hs = {}
for index, match in matches.iterrows():
if (match['winner_name'] == name):
if (match['loser_name'] not in h2hs)... | 5bcf3e520085acd00e607cad386708b490937e9f | 3,638,316 |
import random
def backtracking_solver(
starting_event: Event,
**kwargs) -> FiniteSequence:
"""Compose a melodic sequence based upon the
domain and constraints given.
starting_event: Event dictate the starting pitch.
All subsequent events will be of similar duration.
constraints -... | 86f33615a2bb72e0f656ba7e021ab3f49dcc79e2 | 3,638,317 |
def jdos(bs, f, i, occs, energies, kweights, gaussian_width, spin=Spin.up):
"""
Args:
bs: bandstructure object
f: final band
i: initial band
occs: occupancies over all bands.
energies: energy mesh (eV)
kweights: k-point weights
gaussian_width: width of gau... | adc2a9c6c91da91b02c0ed9823016b3f256625fb | 3,638,318 |
def findConstantMetrics(inpath):
"""
Simple function that checks which metrics in a dictionary (read from a CSV) are constant and which change over time.
As a reference, the first record read from the file is used
:param inpath: The path to the CSV file that must be analyzed
:return: The list of me... | 0faefe77cfea5e1d74d2bb0dda33ed622ce87f02 | 3,638,319 |
def scoreGold(playerList, iconCount, highScore):
"""Update each players' score based on the amount of gold that they have collected.
Args:
playerList: A list of all PlayerSprite objects in the game.
iconCount: A list of integers representing how many times each player has gained points from the... | 255b4ee987a6ac4a5274ad5ae7b5bf6698840407 | 3,638,320 |
def image_2d_transformer(pretrained=False, **kwargs):
"""
modified copy from timm
DeiT base model @ 384x384 from paper (https://arxiv.org/abs/2012.12877).
ImageNet-1k weights from https://github.com/facebookresearch/deit.
"""
model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads... | c5891105446ffc4fac5f19f73b5f401bfc769827 | 3,638,321 |
import torch
def create_fourier_heatmap_from_error_matrix(
error_matrix: torch.Tensor,
) -> torch.Tensor:
"""Create Fourier Heat Map from error matrix (about quadrant 1 and 4).
Note:
Fourier Heat Map is symmetric about the origin.
So by performing an inversion operation about the origin, ... | 25a4a4e2aa2ffda317f28d85c3798682fd72c466 | 3,638,322 |
from ostap.logger.logger import colored_string
def _sc_print_ ( sc ) :
"""Print the Status Code
>>> st = ...
>>> print st
"""
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = list ( range ( 8 ) )
##
if sc.isSuccess () : return colored_string( 'SUCCESS' , WHITE , GREEN ,... | 504f7c662e93fd1e1c1c1759143fa8d77e9b89cc | 3,638,323 |
def get_state_name(state):
"""Maps a mongod node state id to a human readable string."""
if state in REPLSET_MEMBER_STATES:
return REPLSET_MEMBER_STATES[state][0]
else:
return 'UNKNOWN' | ddfbfa53c05941747ebedc242baa8e29bddf6771 | 3,638,324 |
import sysconfig
import sys
from pathlib import Path
def _get_platform_information():
"""Return a dictionary containing platform-specific information."""
system_information = {"platform": sysconfig.get_platform()}
system_information.update({"python version": sys.version_info})
if sys.platform == "win3... | 0fe475f8aecb72be45d613cf80d08353cebf34af | 3,638,325 |
def compute_resilience(ugraph, attack_order):
"""
Alias to bfs or union find
:param ugraph:
:param attack_order:
:return:
"""
if USE_UF:
return uf.compute_resilience_uf(ugraph, attack_order)
else:
return bfs_visited.compute_resilience(ugraph, attack_order) | db623ae30b20a076ff8e0f45fb84a9bb24fa414a | 3,638,326 |
def NumericalFlux(b, r, c):
"""Compute the flux by numerical integration of the surface integral."""
# I'm only coding up a specific case here
assert r <= 1, "Invalid range."
if b < 0:
b = np.abs(b)
# No occ
if b >= 1 + r:
return 1
# Get points of intersection
if b > 1 ... | c2e5918702dfd99f7710adf29eb2e8d668cb1cc0 | 3,638,327 |
from typing import Container
def build_volume_from(volume_from_spec):
"""
volume_from can be either a service or a container. We want to return the
container.id and format it into a string complete with the mode.
"""
if isinstance(volume_from_spec.source, Service):
containers = volume_from... | ee5b997ea1832aa490501da3556faa52c611ada9 | 3,638,328 |
def generate_peripheral(csr, name, **kwargs):
""" Generates definition of a peripheral.
Args:
csr (dict): LiteX configuration
name (string): name of the peripheral
kwargs (dict): additional parameterss, including
'model' and 'properties'
Returns:
stri... | 154428b153b804c23eb9b2a99380e987402c9fb4 | 3,638,329 |
import os
def export_file(isamAppliance, instance_id, component_id, file_id, filepath, check_mode=False, force=False):
"""
Exporting the transaction logging data file or rollover transaction logging data file for a component
"""
if os.path.exists(filepath) is True:
logger.info("File '{0}' alr... | 1e040a5d9b827fbcf95c2443755201710ce2c79b | 3,638,330 |
def map_vocabulary(docs, vocabulary):
"""
Maps sentencs and labels to vectors based on a vocabulary.
"""
mapped = np.array([[vocabulary[word] for word in doc] for doc in docs])
return mapped | b5b39aeac6306709a4b4ac10a29d40a2006d57ff | 3,638,331 |
def mobilenetv3_large_minimal_100(pretrained=False, **kwargs):
""" MobileNet V3 Large (Minimalistic) 1.0 """
# NOTE for train set drop_rate=0.2
model = _gen_mobilenet_v3('mobilenetv3_large_minimal_100', 1.0, pretrained=pretrained, **kwargs)
return model | 717a67b1ab7cb0ad7a6c8d40ea4b0b29108eff94 | 3,638,332 |
def get_identity(user, identity_uuid):
"""
Given the (request) user and an identity uuid,
return None or an Active Identity
"""
try:
identity_list = get_identity_list(user)
if not identity_list:
raise CoreIdentity.DoesNotExist(
"No identities found for use... | 800e47d8782fc5e71e97192f76713032eade9441 | 3,638,333 |
def same_strange_looking_function(param1, callback_fn):
"""
This function is documented, but the function is identical to some_strange_looking_function
and should result in the same hash
"""
tail = param1[-1]
# return the callback value from the tail of param whatever that is
return callback... | 438becf6803e6b25a200a34e18eb648aaa4b6fbb | 3,638,334 |
import os
import shutil
def put_output(dir_in, opts, Flowcell, Lane):
"""Uses shutil to move the output into galaxy directory"""
seq1_name = '%(code)s_%(Flowcell)s_s_%(lane)s_fastq.txt'%\
({'code': 'R1samplecode123','Flowcell':Flowcell, 'lane':Lane})
seq2_name = '%(code)s_%(Flowcell)s_s_%(... | bc91a83cbf14d91dc3a82fbb21d1b3ceb15351fb | 3,638,335 |
def __extractFunction(text, jsDoc, classConstructor):
"""
Extracts a function depending of its pattern:
'function declaration':
function <name>(<parameters>) {
<realization>
}[;]
'named function expression':
<variable> = function <name>(<... | 992604ccd1e56da6706cf2e4ec2955c2c9ecfa7e | 3,638,336 |
def vocabulary_size(tokens):
"""Returns the vocabulary size count defined as the number of alphabetic
characters as defined by the Python str.isalpha method. This is a
case-sensitive count. `tokens` is a list of token strings."""
vocab_list = set(token for token in tokens if token.isalpha())
return ... | 5e26e1be98a3e82737277458758f0fd65a64fe8f | 3,638,337 |
from typing import Dict
from typing import Any
from typing import Optional
from typing import Tuple
def max_iteration_for_analysis(query: Dict[str, Any],
db: cosem_db.MongoCosemDB,
check_evals_complete: bool = False,
conv_it:... | b5d0bebd2af634ac72f8bc318276d0f7c03114f2 | 3,638,338 |
def getMatirces(Dynamics, Cost):
"""
This functions takes the dynamics class as input and outputs the required
matrices and cvxpy.variables to turn the covariance steering problem into a
finite dimensional optimization problem.
"""
Alist = Dynamics.Alist
Blist = Dynamics.Blist
Dlist = Dy... | 50de11ba3f3d1528f7ff577861613b96f8e35254 | 3,638,339 |
def get_transit_boundary_indices(time, transit_size):
""" Determines transit boundaries from sorted time of transit cut out
:param time (1D np.array) sorted times of transit cut out
:param transit_size (float) size of the transit crop window in days
:returns tuple:
[0... | cd3775d72690eb4539e0434b0ac7f715d14374a6 | 3,638,340 |
from urllib.error import HTTPError
from time import time
import gc
import os
import tempfile
def example_3():
"""Loads into tempory storage'
"""
def cleanup(path):
# Clean up the temp folder to remove the BerkeleyDB database files...
for f in os.listdir(path):
os.unlink(path ... | 643d5b658c02398d7159b66c98b9d14ad2b87517 | 3,638,341 |
def decode_gbe_string(s):
"""This helper function turns gbe output strings into dataframes"""
columns, df = s.replace('","',';').replace('"','').split('\n')
df = pd.DataFrame([column.split(',') for column in df.split(';')][:-1]).transpose().ffill().iloc[:-1]
df.columns = [c.replace('tr_','') for c in co... | 0a2d262b2653f736ef8ae7c7ed4b969faf80e9bf | 3,638,342 |
import re
def get_scihub_namespaces(xml):
"""Take an xml string and return a dict of namespace prefixes to
namespaces mapping."""
nss = {}
matches = re.findall(r'\s+xmlns:?(\w*?)\s*=\s*[\'"](.*?)[\'"]', xml.decode('utf-8'))
for match in matches:
prefix = match[0]; ns = match[1]
... | b1d5a32d7583a655c59fa5175bdd133899bf6223 | 3,638,343 |
def valid_verify_email(form, email):
"""
Returns true if "email" is equal the first email
"""
try:
if(form.email.data!=form.email_verify.data):
raise ValidationError('Email address is not the same')
if models.Account.pull_by_email(form.email.data) is not None:
pri... | 16073bb559e06759632323289f49e127bb9f8cb1 | 3,638,344 |
def _computePolyVal(poly, value):
"""
Evaluates a polynomial at a specific value.
:param poly: a list of polynomial coefficients, (first item = highest degree to last item = constant term).
:param value: number used to evaluate poly
:return: a number, the evaluation of poly with value
"""
#return numpy.polyval... | 0377ba0757439409824b89b207485a99f804cb41 | 3,638,345 |
from io import StringIO
def fix_e26(source):
"""Format block comments."""
if '#' not in source:
# Optimization.
return source
string_line_numbers = multiline_string_lines(source,
include_docstrings=True)
fixed_lines = []
sio = Strin... | ec569e442c2244421afa94cc8316478c55377220 | 3,638,346 |
def graph_distance(tree, node1, node2=None):
""" Return shortest distance from node1 to node2,
or just update all node.distance shortest to node1 """
for node in tree.nodes():
node.distance = inf
node.back = None # node backwards towards node1
fringe = Queue([node1])
while fri... | 0764d2a687933631d592e1b6d40ceec8d629036c | 3,638,347 |
def trunicos(b):
"""Return a unit-distance embedding of the truncated icosahedron graph."""
p0 = star_radius(5)*root(1,20,1)
p1 = p0 + root(1,20,1)
p2 = mpc(b, 0.5)
p3 = cu(p2, p1)
p4 = cu(p3, p1*root(1,5,-1))
p5 = cu(p4, p2*root(1,5,-1))
return (symmetrise((p0, p1, p2, p3, p4, p5), "D5"... | 018112497882a6f0a572cf2c1c222cdf36ca95e9 | 3,638,348 |
import torch
def histogram2d(
x1: torch.Tensor, x2: torch.Tensor, bins: torch.Tensor, bandwidth: torch.Tensor, epsilon: float = 1e-10
) -> torch.Tensor:
"""Function that estimates the 2d histogram of the input tensor.
The calculation uses kernel density estimation which requires a bandwidth (smoothing) p... | 5e360f1e9350a29664e3beb1d0cc6ba3024647b9 | 3,638,349 |
import json
def webhooks_v2(request):
"""
Handles all known webhooks from stripe, and calls signals.
Plug in as you need.
"""
if request.method != "POST":
return HttpResponse("Invalid Request.", status=400)
event_json = json.loads(request.body)
event_key = event_json['type'].repla... | afa86e189c417a147ae05fa46e89d985207c403b | 3,638,350 |
def nth(iterable, n, default=None):
"""
Returns the nth item or a default value
:param iterable: The iterable to retrieve the item from
:param n: index of the item to retrieve. Must be >= 0
:param default: the value to return if the index isn't valid
:return: the nth item, or the default value i... | 9f0eb8a31d8b4499d8538f6aefc9dba8231b27e0 | 3,638,351 |
import types
def _dict_items(typingctx, d):
"""Get dictionary iterator for .items()"""
resty = types.DictItemsIterableType(d)
sig = resty(d)
codegen = _iterator_codegen(resty)
return sig, codegen | 6435320c6ba490b85c3ef4c065f55cef0d7d2c8e | 3,638,352 |
def odd_desc(count):
"""
Replace ___ with a single call to range to return a list of descending odd numbers ending with 1
For e.g if count = 2, return a list of 2 odds [3,1]. See the test below if it is not clear
"""
return list(reversed(range(1,count*2,2))) | 2f90095c5b25f8ac33f3bb86d3f46e67932bc78a | 3,638,353 |
def retrieval_score(test_ratings: pd.DataFrame,
recommender,
remove_known_pos: bool = False,
metric: str = 'mrr') -> float:
"""
Mean Average Precision / Mean Reciprocal Rank of first relevant item @ N
"""
N = recommender.N
user_scores = []
... | c7167eef0195496ea460dcbe63926028c430433e | 3,638,354 |
def test_dump_load_keras_model_with_dict(tmpdir, save_and_load):
"""Test whether tensorflow ser/de-ser work for models returning dictionaries"""
class DummyModel(tf.keras.Model):
def __init__(self):
super().__init__()
def _random_method(self):
pass
def call(sel... | 5fcaf73e5a0b138a04091573782a2c03f4459f15 | 3,638,355 |
def stemmer_middle_high_german(text_l, rem_umlauts=True, exceptions=exc_dict):
"""text_l: text in string format
rem_umlauts: choose whether to remove umlauts from string
exceptions: hard-coded dictionary for the cases the algorithm fails"""
# Normalize text
text_l = normalize_middle_high_german(
... | 608ec49ad36ee5ae7ad41fe4eab5d9f7c65eb609 | 3,638,356 |
def test_queue_trials(start_connected_emptyhead_cluster):
"""Tests explicit oversubscription for autoscaling.
Tune oversubscribes a trial when `queue_trials=True`, but
does not block other trials from running.
"""
cluster = start_connected_emptyhead_cluster
runner = TrialRunner()
def creat... | fed9fe1458db15f871ccd4afff942c0d022a9b8a | 3,638,357 |
def get_bboxes(outputs, proposals, num_proposals, num_classes,
im_shape, im_scale, max_per_image=100, thresh=0.001, nms_thresh=0.4):
"""
Returns bounding boxes for detected objects, organized by class.
Transforms the proposals from the region proposal network to bounding box predictions
... | 09e5eb94f35672e77980c89e71fcb9ed6b460ab4 | 3,638,358 |
def air_transport_per_year_by_country(country):
"""Returns the number of passenger carried per year of the given country."""
cur = get_db().execute('SELECT Year, Value FROM Indicators WHERE CountryCode="{}" AND IndicatorCode="IS.AIR.PSGR"'.format(country))
air_transport = cur.fetchall()
cur.close()
... | 4ca85c537c5bc7ccda332af977f1252b14672235 | 3,638,359 |
def outside_range(number, min_range, max_range):
"""
Returns True if `number` is between `min_range` and `max_range` exclusive.
"""
return number < min_range or number > max_range | dc3889fbabb74db38b8558537413ebc5bc613d05 | 3,638,360 |
import re
def is_string_constant(node):
"""Checks whether the :code:`node` is a string constant."""
return is_leaf(node) and re.match('^\"[^\"]*\"$', node) is not None | 5a62c513bc856571e62c40b9d14bdefb67be4c79 | 3,638,361 |
from typing import List
def is_list_type(t) -> bool:
"""
Return True if ``t`` is ``List`` python type
"""
# print(t, getattr(t, '__origin__', None) is list)
return t == list or is_pa_type(t, pa.types.is_list) or (
hasattr(t, '__origin__') and t.__origin__ in (list, List)
) or (
... | 7da1ea98dccc4341a6db7a3e13e9f9bd278bd984 | 3,638,362 |
from datetime import datetime
def get_measure_of_money_supply():
""" 从 Sina 获取 中国货币供应量数据。
Returns: 返回获取到的数据表。数据从1978.1开始。
Examples:
.. code-block:: python
>>> from finance_datareader_py.sina import get_measure_of_money_supply
>>> df = get_measure_of_money_supply()
... | 304cf05be6a226e7da46ec16e36a6632f02848c5 | 3,638,363 |
def _SparseMatrixAddGrad(op, grad):
"""Gradient for sparse_matrix_add op."""
# input to sparse_matrix_add is (a, b, alpha, beta)
# with a, b CSR and alpha beta scalars.
# output is: alpha * a + beta * b
# d(a*A + b*B)/dA . grad = a * grad
# May have gotten the transposes wrong below.
# d(a*A + b*B)/da .... | 43485431ca2e7028e005dc6a49adf96bb990770f | 3,638,364 |
def make_inverter_path(wire, inverted):
""" Create site pip path through an inverter. """
if inverted:
return [('site_pip', '{}INV'.format(wire), '{}_B'.format(wire)),
('inverter', '{}INV'.format(wire))]
else:
return [('site_pip', '{}INV'.format(wire), wire)] | 066c4bbad0f65fec587b12fc7a2947246401b877 | 3,638,365 |
import sys
def get_install_path():
"""Use registry and asking the user to better determine the install directory."""
reg_likely_path = get_registry_path()
if reg_likely_path:
user_path = get_user_path(initial_dir=reg_likely_path.as_posix())
else:
user_path = get_user_path(initial_dir=r... | e6960014d926d0fac14190288d06eac13289cdc7 | 3,638,366 |
def constant(t, length):
""" ezgal.sfhs.constant( ages, length )
Burst of constant starformation from t=0 to t=length """
if type(t) == type(np.array([])):
sfr = np.zeros(t.size)
m = t <= length
if m.sum(): sfr[m] = 1.0
return sfr
else:
return 0.0 if t > length el... | bfbc32042512465c7fecc50d976b369ac8e2c9fe | 3,638,367 |
def model_setup_fn(attrs):
"""Generate the setup function for models."""
model = load_model(attrs['type'], attrs['data'])
def func(self):
self.model = model
self.type = attrs['type']
self.data = attrs['data']
self.network_type = attrs['network_type']
self.dto = attr... | 4f0ffa9e1de3f60edef847faf319f3c5a4bef28d | 3,638,368 |
def _mkdir(space, dirname, mode=0777, recursive=False, w_ctx=None):
""" mkdir - Makes directory """
mode = 0x7FFFFFFF & mode
if not _valid_fname(dirname):
space.ec.warn("mkdir() expects parameter 1 to "
"be a valid path, string given")
return space.w_False
if not ... | c16b5e0100c50e300fcf9268383f20b1cb5c11b5 | 3,638,369 |
import decimal
def prepare_fixed_decimal(data, schema):
"""Converts decimal.Decimal to fixed length bytes array"""
if not isinstance(data, decimal.Decimal):
return data
scale = schema.get('scale', 0)
size = schema['size']
# based on https://github.com/apache/avro/pull/82/
sign, digit... | 5dc5ae8355842e175e1fa83394a63b37c04bdade | 3,638,370 |
from typing import Any
def device_traits() -> dict[str, Any]:
"""Fixture that sets default traits used for devices."""
return {"sdm.devices.traits.Info": {"customName": "My Sensor"}} | 1ccaeac4a716706915654d24270c24dac0210977 | 3,638,371 |
import os
def writeOutput(ipData,outfilename):
""" Writes the text output """
# Get the current working directory so we can write the results file there
outfilename = os.path.join(os.getcwd(),outfilename+'.txt')
file1 = open(outfilename,'w')
numPoints = ipData.size
for i in xrang... | ea2d3814f3e39ef01015cb6b33d5f883f1dd9bd7 | 3,638,372 |
def calculate_equivalent_diameter(areas):
"""Calculate the equivalent diameters of a list or numpy array of areas.
:param areas: List or numpy array of areas.
:return: List of equivalent diameters.
"""
areas = np.asarray(areas)
diameters = np.sqrt(4 * areas / np.pi)
return diameters.tolis... | a353883cf148819d9f298167e73acd60b89720e5 | 3,638,373 |
def truncation_error(stencil: list, deriv: int, interval: str = DEFAULT_INTERVAL):
"""
derive the leading-order of error term
in the finite difference equation based on the given stencil.
Args:
stencil (list of int): relative point numbers
used for discretization.
deriv (int... | e3b8d312d551ed88ead3690b285659d56865e6e0 | 3,638,374 |
def _get_parameter_defaults(fpm, metadata, readout_mode, subarray, frame_time,
temperature, cosmic_ray_mode, verbose=2,
logger=LOGGER):
"""
Helper function to obtain appropriate defaults for parameters
that have not been explicitly set.
(Saves... | 59431a086b15748cec45fd879bef8bdcd9af00c3 | 3,638,375 |
def cmd_renderurl(cfg, command, argv):
"""Renders a single url of your blog to stdout."""
parser = build_parser('%prog renderurl [options] <url> [<url>...]')
parser.add_option('--headers',
action='store_true', dest='headers', default=False,
help='Option that caus... | 2073c71c459357c0b6a9661596cad34196fd6c24 | 3,638,376 |
def combine_expressions(expressions, relation='AND', licensing=Licensing()):
"""
Return a combined license expression string with relation, given a list of
license expressions strings.
For example:
>>> a = 'mit'
>>> b = 'gpl'
>>> combine_expressions([a, b])
'mit AND gpl'
>>> assert ... | 8955522546a8b803caf0b1c6a3c6e8752cb35a19 | 3,638,377 |
import torch
def parrallelize(model: nn.Module) -> nn.Module:
""" Make use of all available GPU using nn.DataParallel
NOTE: ensure to be using different random seeds for each process if you use techniques like data-augmentation or any other techniques which needs random numbers different for each steps. TODO:... | 8579086103c30664d91c37dee90353fe9d4b4c6b | 3,638,378 |
import sqlite3
def get_prof_details(prof_id):
"""
Returns the details of the professor in same order as DB.
"""
cursor = sqlite3.connect('./db.sqlite3').cursor()
cursor.execute("SELECT * FROM professor WHERE prof_id = ?;", (prof_id))
return cursor.fetchone() | 668652474009abdda36d3e97fb5d30074f0a2755 | 3,638,379 |
import sys
import os
def get_process_path(tshark_path=None, process_name='tshark'):
"""
Finds the path of the tshark executable. If the user has provided a path
or specified a location in config.ini it will be used. Otherwise default
locations will be searched.
:param tshark_path: Path of the tsh... | 71bc7179379387da15cc38fee0ca19a01c1798e2 | 3,638,380 |
import logging
import scipy
def stats_per_gop(processed_video_sequence, needed=[]):
"""
general helper to extract statistics on a per gop basis
"""
logging.debug(f"calculate {needed} gop based for {processed_video_sequence}")
results = []
for gop in by_gop(processed_video_sequence, columns=nee... | 296593578cbf131dcee6a9746b1d1a5f696c4989 | 3,638,381 |
def available_help(mod, ending="_command"):
"""Returns the dochelp from all functions in this module that have _command
at the end."""
help_text = []
for key in mod.__dict__:
if key.endswith(ending):
name = key.split(ending)[0]
help_text.append(name + ":\n" + mod.__dict__... | 9afa1525c016aa74dd4b3eb91851890da3590524 | 3,638,382 |
from functools import reduce
import operator
def __s_polynomial(g, h):
"""
Computes the S-polynomial of g, h. The S-polynomial is a polynomial built explicitly so that the leading terms
cancel when combining g and h linearly.
"""
deg_g = __multidegree(g)
deg_h = __multidegree(h)
max_deg =... | 49aa5b5b1dbebde1309aaa9fd2cb5947a010709f | 3,638,383 |
def generate_map_chunk(size_x: int, size_y: int, biome_type: str, x_offset: int = 0, y_offset: int = 0):
"""
Function responsible for generating map chunk in specified or random biome type,
map chunk is basically a rectangular part of a map;
generated array is basically nested list representing ... | 42863b7058bfce23b1123c14db562483254bdc21 | 3,638,384 |
import math
import base64
import os
def newid(length=16):
"""
Generate a new random string ID.
The generated ID is uniformly distributed and cryptographically strong. It is
hence usable for things like secret keys and access tokens.
:param length: The length (in chars) of the ID to generate.
... | b287a929f0dde6244b66bb8d9d9289b97f2d090b | 3,638,385 |
def test_process_cycle(zs2_file_name, verbose=True):
"""This is a test to check if util output changed
in an incompatible manner. A zs2 file is read, converted to XML,
and back-converted to a raw datastream."""
if verbose:
print('Decoding %s...' % zs2_file_name)
data_stream = _parser.l... | 6417362a9bdaa4086865f0b8fc510dda186534f7 | 3,638,386 |
def get_dev_risk(weight, error):
"""
:param weight: shape [N, 1], the importance weight for N source samples in the validation set
:param error: shape [N, 1], the error value for each source sample in the validation set
(typically 0 for correct classification and 1 for wrong classification)
"""
... | 7278a8827dd48c341d9f294a3fed3a8b2e3c71ae | 3,638,387 |
import torch
def skewness_fn(x, dim=1):
"""Calculates skewness of data "x" along dimension "dim"."""
std, mean = torch.std_mean(x, dim)
n = torch.Tensor([x.shape[dim]]).to(x.device)
eps = 1e-6 # for stability
sample_bias_adjustment = torch.sqrt(n * (n - 1)) / (n - 2)
skewness = sample_bias_a... | ae0bdea16c1461a2e407ed57279557bc8c7f56de | 3,638,388 |
import random
def encrypt(message):
""" Self-developed encryption method that uses base conversion """
base = random.randint(3, 9)
number_list = []
for i in message:
number_list.append(keys.index(i)+1)
converted_number_list = []
for i in number_list:
converted_number_list.appen... | 967d45341fb8a5ec87f946ba6fc0a603f491485e | 3,638,389 |
def get_signature_algorithm(algorithm_type_string):
"""convert a string into a key_type (TFTF_SIGNATURE_TYPE_xxx)
returns a numeric key_type, or raises an exception if invalid
"""
try:
return TFTF_SIGNATURE_ALGORITHMS[algorithm_type_string]
except:
raise ValueError("Unknown algorith... | 41ca226dc7e6c1c0f8d5b8592803d6555630902c | 3,638,390 |
def bending_without_n_iteration(model, values, concrete_type, exp):
"""Calculate the necessery longitudial reinforcment of a
beam that is loaded by a torque load without normal forces.
Parameters
----------
model : class
class method that contains the Finite Element Analysis
Returns
... | 6beca7f38f993f25bd468e0ff5eb0342b1bf85b0 | 3,638,391 |
def corrgroups60(display=False):
""" A simulated dataset with tight correlations among distinct groups of features.
"""
# set a constant seed
old_seed = np.random.seed()
np.random.seed(0)
# generate dataset with known correlation
N = 1000
M = 60
# set one coefficent from each grou... | 5a80116890ff262a164f48421871107c4cdaf8a6 | 3,638,392 |
def alpha_nu_gao08(profile, **kwargs):
"""log normal distribution of alpha about the
alpha--peak height relation from Gao+2008"""
z = kwargs["z"]
alpha = kwargs["alpha"]
# scatter in dex
if "sigma_alpha" in kwargs:
sigma_alpha = kwargs["sigma_alpha"]
else:
# take scatter fr... | 393fdc6c87d4bf61fc367e7f9033bac24b9d6cea | 3,638,393 |
import base64
def get_feed_entries(helper, name, stats):
"""Pulls the indicators from the minemeld feed."""
feed_url = helper.get_arg('feed_url')
feed_creds = helper.get_arg('credentials')
feed_headers = {}
# If auth is specified, add it as a header.
if feed_creds is not None:
auth = '... | e881eebaaa9c31bc8d0abdd8b8f4aaeb9efcffe6 | 3,638,394 |
def get_skeleton_definition(character):
"""
Returns skeleton definition of the given character
:param character: str, HIK character name
:return: dict
"""
hik_bones = dict()
hik_count = maya.cmds.hikGetNodeCount()
for i in range(hik_count):
bone = get_skeleton_node(character, i)... | f76d4613f3a8adec649ea689d049ccff2966783c | 3,638,395 |
def get_f_a_st(
fuel="C3H8",
oxidizer="O2:1 N2:3.76",
mech="gri30.cti"
):
"""
Calculate the stoichiometric fuel/air ratio of an undiluted mixture using
Cantera. Calculates using only x_fuel to allow for compound oxidizer
(e.g. air)
Parameters
----------
fuel : str
... | ecd711d8a1d5499e47ccbedebfb5641aec7c7a8b | 3,638,396 |
def get_parser_args(args=None):
"""
Transform args (``None``, ``str``, ``list``, ``dict``) to parser-compatible (list of strings) args.
Parameters
----------
args : string, list, dict, default=None
Arguments. If dict, '--' are added in front and there should not be positional arguments.
... | 41b607a6ebf12526efcd38469192b398419327bf | 3,638,397 |
def parse_time_to_min(time):
"""Convert a duration to an integer in minutes.
Example
-------
>>> parse_time_to_min("2m 30s")
2.5
"""
if " " in time:
return sum([parse_time_to_min(t) for t in time.split(" ")])
time = time.strip()
for unit, value in time_units.items():
... | 6bf9656694ba4787bf9fd3e7c269d9c84e3ed143 | 3,638,398 |
def relate_stream_island(stream_layer, island_layer):
"""
Return the streams inside or delimiting islands.
The topology is defined by DE-9IM matrices.
:param stream_layer: the layer of the river network
:stream_layer type: QgisVectorLayer object (lines)
:param island_layer: the layer of the... | 1d6c90349808f6364cc8b1461b09a0c31df6d9d3 | 3,638,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.