content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def flash(light, color, p_on, p_off):
"""
flashes color for [on] seconds, then off for [off] seconds, repeating.
"""
def ret(ticks, elapsed_time):
if isinstance(p_on, Parameter):
on = p_on.get()
else:
on = p_on
if isinstance(p_off, Parameter):
... | 8b9dcff67504647dd8ff0a4a8c4b357353560875 | 51,823 |
def solver_problem2(init_state, day):
"""
input initial state, day and output fish
a more efficiet way that only record a fish library with {timer: fish number}
"""
fish_lib = {timer: init_state.count(timer) for timer in set(init_state)}
for _ in range(day):
fish_lib = update_fish(fish_l... | 6f52b79659eba941f47844367686d2dec57707a4 | 51,825 |
def print_nodes_name(graph):
"""
input:
-------
graph: (tf.Graph() or tf.GraphDef()) graph in which prints only the nodes' name
return:
-------
None
"""
if isinstance(graph, graph_pb2.GraphDef):
for n in graph.node:
logger.info(n.name)
return [n.na... | 4e01f059ef646f98a6bc469f0b3c27add330a9c0 | 51,826 |
from typing import OrderedDict
def order_nested_object(nested_object):
"""
Simply recursively order the item. To be used for standardizing objects for JSON dumps
"""
if isinstance(nested_object, list):
if len(nested_object) > 0 and isinstance(nested_object[0], dict):
# Lists of dic... | 640fb552ebb714fa3489939198d282906cec05d3 | 51,828 |
def add_header(r):
"""
Add headers to both force latest IE rendering engine or Chrome Frame,
and also to cache the rendered page for 10 minutes.
"""
# clear browser cache
r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
r.headers["Pragma"] = "no-cache"
r.headers["Expires"] = "0"
r.headers['Ca... | ddf4b82b853947919535712c4ffe7bbed196a6cd | 51,829 |
def id_feat_meas_mz_rt(cursor, mz, rt, ccs, tol_mz, tol_rt, tol_ccs, esi_mode, norm='l2'):
"""
id_feat_meas_mz_rt
description:
identifies a feature on the basis of measured m/z and retention time
parameters:
cursor (sqlite3.Cursor) -- cursor for querying lipids.db
mz (float) -- m/z t... | 4d82194eb024f736ee56dec7aa6bb4d32cb62b9a | 51,830 |
import uuid
def generate_guid():
""" Generate a GUID
"""
return uuid.uuid4().hex | 11370892bd2e8b66d874c7e64ebda7ab41ac0d37 | 51,831 |
def get_data_ch7():
"""Get the data set used in Chapter 7"""
data = np.genfromtxt('../data/airfoil_self_noise.dat', delimiter='\t')
data = (data - data.mean(axis=0)) / data.std(axis=0)
return nd.array(data[:, :-1]), nd.array(data[:, -1]) | de1e706c62b8266390e04e4cff352ef211ffbea1 | 51,832 |
def is_iterable(obj) -> bool:
"""
Test if argument is iterable.
"""
return isiterable(obj) | c24323082b3ad290301e390b02ceb781e4c9104b | 51,834 |
def concat_name(name: str, *comp_names):
"""Add comp_name to name, e.g. ('dist', 'a2', 'a1')-->'a1__a2___dist'."""
comp_name = concat_comps(*comp_names)
if comp_name:
return f'{comp_name}{SPLITTER}{name}'
return name | 53ead1a50c6b87b26951bc9d613ab1d96528a9e1 | 51,835 |
def demedian_parcellate_func_combine_hemis(lh_func, rh_func, lh_parcel_path, rh_parcel_path):
"""
#Function that takes functional data in the form <num_verts, num_timepoints> for
#both the left and right hemisphere, and averages the functional time series across
#all vertices defined in a given par... | baea9d5e9c561c5cd8f806cf4c69c552c4398f54 | 51,836 |
def _cmpPair2(a, b):
"""Auxiliary comparision for sorting lists of pairs. Sorting on the second member of the pair."""
(x, y), (z, w) = a, b
if y < w:
return -1
elif y > w:
return 1
elif x < z:
return -1
elif x > z:
return 1
else:
return 0 | 5567ddc006756e224dde545503c427a3524c3c90 | 51,838 |
def linear_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, last_epoch=-1):
""" Create a schedule with a learning rate that decreases linearly after
linearly increasing during a warmup period.
"""
def lr_lambda(current_step):
if current_step < num_warmup_steps:
r... | b7109843869de325a03273a8245bbd04a5244fb4 | 51,839 |
def chooseStatic(schedule, staticDict, priorityQueue, modulo=24):
"""
given a scheudule and a priority queue,
it takes the next highest priority item and checks for conflicts and the event is added to the schedule only if there's no confict
if the duration of the event is less than the time... | 09616c2887172b7de1e5e8af2456af5ca2acafd0 | 51,840 |
import glob
def prepare_corsika_from_blacklist(path, oldEnding='', newEnding='nomissing'):
"""Takes the path of the corsika files (there should be only corsika files in a single directory)
and removes unuseable and too short keys and writes new hdf5 files"""
oldCorsika = [h5.File(file, 'r') for file in so... | a2bc2bef076d1010201bf1c7879b5e9b5a7b499f | 51,841 |
def toExport8F8(op):
"""Converts number to exportable 8.8 signed fixed point number."""
return int(round(op * 256.0)) | 3364703913e1c87223ffb11bdaf3b622db7eef1c | 51,842 |
def mkminim(grid, baseuri=None):
"""
Generate minim graph from supplied grid
Returns (status,mgr) where mgr is RDF graph containing minim description,
or None.
"""
# Decode the grid
try:
(d,(r,c)) = checklist_template.checklist.match(grid, 0, 0)
except Exception, e:
prin... | cb88bbc052378290d11ba1d49fd9c6531b40946a | 51,843 |
import math
def LogRegressNomalize(value):
"""Uses log regress to normalize (-inf, inf) to [0, 1]."""
value_exp = math.exp(value)
return value_exp / (value_exp + 1) | a5d30077df70b3795754d62c6534781e61482f13 | 51,845 |
def test_prob_wires_and_hermitian(hermitian):
"""Test that we can cannot give simultaneously wires and a hermitian."""
dev = qml.device("default.qubit", wires=2)
@qml.qnode(dev)
def circuit():
qml.PauliX(wires=0)
return qml.probs(op=qml.Hermitian(hermitian, wires=0), wires=1)
with... | 39f6b8ea07824063d4956290459838407d442cd2 | 51,846 |
def guess(intcos, geom, Z, connectivity=False, guessType="SIMPLE"):
""" Generates diagonal empirical Hessians in a.u. such as
Schlegel, Theor. Chim. Acta, 66, 333 (1984) and
Fischer and Almlof, J. Phys. Chem., 96, 9770 (1992).
"""
dim = len(intcos)
H = np.zeros((dim, dim), float)
for i... | 64e3466eb08ec8b80d72a1cd579de9da20bdc7d8 | 51,847 |
def get_cmap(n, name='Set1'):
"""
Source: https://stackoverflow.com/questions/14720331/how-to-generate-random-colors-in-matplotlib
Colormaps: https://matplotlib.org/tutorials/colors/colormaps.html
:param n: Number of classes.
:param name: The color map to be selected from.
:return: a function th... | e70c6d6cb9e86bdf2d4874cce1d54fee3da49254 | 51,848 |
def toy_classification(return_X_y=True, n=5000):
"""toy classification dataset with irrelevant features
fitting a logistic model on this data and performing a model summary
should reveal that features 2,3,4 are not significant.
Parameters
----------
return_X_y : bool,
if True, returns ... | d00ced30fc36047448f0c72737137e63d2e43c26 | 51,849 |
def cross_entropy_seq(logits, target_seqs, batch_size=None):
"""Returns the expression of cross-entropy of two sequences, implement
softmax internally. Normally be used for fixed length RNN outputs, see `PTB example <https://github.com/tensorlayer/tensorlayer/blob/master/example/tutorial_ptb_lstm.py>`__.
P... | a8b7382337228d7910b0e4d99540d626645e900f | 51,852 |
def recurse_files(dir: PathLike, *, channel: Channel = None) -> Channel:
"""
Starts a worker thread that finds all files in `dir` (recursively) and
writes them to a :obj:`Channel`. Each file found is written as a
:obj:`pathlib.Path` object.
:param dir: The directory to search.
:param channel: C... | 705b6a6f4f9d90970490f7e9b5de17425d2aa336 | 51,853 |
from typing import Union
def _choose_prior(
fun_params0: Union[pn.RandomVariable, np.ndarray, None]
) -> pn.RandomVariable:
"""
Initialize the prior distribution over the parameters.
Sets up a prior distribution if no prior or only a point estimate for the parameters
of the latent quadratic funct... | 7d4c363192d55d5a2946829bfa0586f093cd9dd5 | 51,854 |
import warnings
def write_stems(
path,
data,
sample_rate=44100,
writer=StreamsWriter(stem_names=None)
):
"""Write stems from numpy Tensor
Args:
path: str
Output file_name of the stems file. Note that the extension of the
path determines the used output containe... | 60cbb49fb1674b850927019dec0a291840bb12f6 | 51,855 |
import numpy
def njit_accumulated_matrix(s1, s2, mask):
"""Compute the accumulated cost matrix score between two time series.
Parameters
----------
s1 : array, shape = (sz1,)
First time series.
s2 : array, shape = (sz2,)
Second time series
mask : array, shape = (sz1, sz2)
... | 210d1d4554dfc470c4c3a37b2dc74a334a36b0ed | 51,856 |
def configuration_path():
"""File created by bin/combine."""
return 'config/swagger-combine.yml' | 3d75a3630bf56dcb51cf776a609fe3d21c111ead | 51,857 |
def padlist(container, size, default=None):
"""Pad list with default elements.
Examples:
>>> first, last, city = padlist(['George', 'Costanza', 'NYC'], 3)
('George', 'Costanza', 'NYC')
>>> first, last, city = padlist(['George', 'Costanza'], 3)
('George', 'Costanza', None)
... | 26c7cf9a106a5f58a385260c934323980cec598f | 51,858 |
def _conv1(in_channels, out_channels, bias=False):
"""point-wise convolution"""
return nn.Conv1d(in_channels, out_channels, kernel_size=1, bias=bias) | 0ad133715072687e1369a75c85cb49c344778da8 | 51,859 |
def pad_to_length(sequences, length, value=0):
"""Pads sequences to being the same length, truncating right if they are longer.
Attributes
----------
sequences
the sequences to pad
length : int
the length to pad to
value
the value to use to pad
Returns
-------
... | fa67e3cb1d3ccd04a526b04370d2b86b09eabd32 | 51,860 |
def comp_pca(usnap, n_trunc, detrend=True):
"""Perform Principal Component Analysis on data.
Parameters
----------
usnap : array
Data array, size (n_pts, n_dim).
n_trunc : integer
The number of PCA dimensions to be retained.
detrend : boolean, optional
Whether or not to... | a6111e14f750818da47f30764bf38fea5a072ad7 | 51,861 |
def generate_thickness_gradient(ri, ro, T1, T2, Tdot_hot, hold,
Tdot_cold = None, hold_together = 0.0, delay = 0.0):
"""
Generate our usual through-wall temperature gradient
Parameters:
ri inner radius
ro outer radius
T1 initial temperature
... | 27ca14bc660264fc3dd33fab17ec9dbceddff280 | 51,862 |
def output_to_firrtl(open_file, rom_blocks=None, block=None):
""" Output the block as FIRRTL code to the output file.
:param open_file: File to write to
:param rom_blocks: List of ROM blocks to be initialized
:param block: Block to use (defaults to working block)
If ROM is initialized in PyRTL cod... | 29bd2d1e489ae0584d59262711e9075aeddc68e1 | 51,863 |
def Fk(shear_stress, temperature, Tath=700, Uk=0.33 * 1.60217657e-19, sigmap=900*1e6):
"""
Parameters
----------
shear_stress : ndarray of shape (N,)
CRSS or maximum shear stress (in Pa or Nm-2)
temperature : float
Temperature (in Kelvin)
Tath : float
The athermal tempera... | ebb63ce29ca6549e41eaef514e65c14982cc7fd0 | 51,864 |
def increment(lhs, ctx):
"""Element ›
(num) -> lhs + 1
(str) -> replace spaces with 0s
"""
ts = vy_type(lhs)
return {
NUMBER_TYPE: lambda: lhs + 1,
str: lambda: lhs.replace(" ", "0"),
}.get(ts, lambda: vectorise(increment, lhs, ctx=ctx))() | e373ee47d8d28edfec895d7e173537d0433fe757 | 51,865 |
def _indices_3d_numba(f, y, x, py, px, t, nt, interp=True):
"""Compute time and space indices of parametric line in ``f`` function
using numba. Refer to ``_indices_3d`` for full documentation.
"""
tdecscan = f(y, x, t, py, px)
if not interp:
sscan = (tdecscan >= 0) & (tdecscan < nt)
else... | 656b409448849d7e30ef5adac87654a5bb40982d | 51,866 |
import requests
import json
def request_url(URL):
"""HTTP GET request and load into json"""
r = requests.get(URL)
if r.status_code == requests.codes.ok:
return json.loads(r.text)
else:
r.raise_for_status() | e237408de0fecb93ebededc66909ef49ada6b957 | 51,868 |
def getMultiTenantPath(api_name, method, app_name):
"""
This function will return the invoke path for a given api and http method (for a multi tenant setup)
:param api_name: Name of the API
:param method: Method of the API
:param app_name: Name of the application
:return: Invoke path
"""
... | fa369d325feb3ad3300d26e350f2cd73af898bfc | 51,869 |
import requests
import json
def get_txs_list(count=100, skip=0, filter={}):
"""
Fetch list of txs
"""
response = requests.post(
httpprovider,
data=json.dumps(
{
"jsonrpc": "2.0",
"id": 8,
"method": "tx_list",
... | 4b54f1059b2ab26a492cccbcb84f3376a224aa4c | 51,870 |
import math
def deep_tissue_segmentation( x, template=None, registration_map=None ):
"""
modified slightly more efficient deep atropos that also handles the
extra CSF issue. returns segmentation and probability images. see
the tissues csv available from get_data.
x: input image
template: MN... | 7efa1a12d8128884e4bc51adfeedbadb9173f533 | 51,871 |
def beta_utility_gen(X, x_max, a, b):
"""
Beta distribution over utility value
X : value of Vertical Illuminance (EV) at which to find the utility function value
x_max : max value of EV to be considered for getting the proper Beta distribution
a: Beta distribution parameter
b : Beta distribution... | feefd63d1e859d5643c6c74787a5a0b6d70c05ea | 51,873 |
def question(conversation):
"""Counts whether each utterance in the given conversation contains a question (yes: 1, no: 0)"""
num_turns = len(conversation)
is_question_in_utterance = np.zeros(num_turns)
for i, utterance in enumerate(conversation):
if any(question_word in utterance for question_... | 98aea41cbcdbdf229a6d6a6bf42d24a20958b176 | 51,874 |
def insert_new_artist(cursor, name, is_vocalist, is_composer):
"""
Insert a new artist in the database
"""
sql_insert_artist = "INSERT INTO artists(name, vocalist, composer) VALUES(?, ?, ?);"
run_sql_command(cursor, sql_insert_artist, [name, is_vocalist, is_composer])
return cursor.lastrowid | 02955ac38edb7f16d622ff86a3ebff58daf14fda | 51,875 |
def predict(notes, onsets, n_tracks, states):
"""Predict the labels."""
# Create the prediction array
predictions = np.zeros(len(notes), int)
# Initialize states (recording the time until when each track is active)
track_states = np.zeros(n_tracks, int) if states else None
# Initialize last pi... | 2a3d901507e38ff3bd7804c667c84bd729a0da3f | 51,877 |
def getTower(creep, maxEnergyPercentage = 0.7):
"""
Gets the closest tower in the same room as a creep
:param creep: The creep to run
:param maxEnergyPercentage: The max energy percentage of total that the tower is allowed to have, between 0 and 1. 0 means only totally empty towers, 1 means only full to... | 349eea9902cbf7b096a347ec737066d7c00c3ef2 | 51,878 |
def png_encode(input, compress_level=3):
"""
Encode the image with PNG encoder.
Args:
img (:class:`numpy.ndarray`): uint8 color image array
quality (int): quality for JPEG compression
Returns bytes: encoded image data
"""
assert len(input.shape) == 3 and input.shape[2] in [3, 4... | 17694f5d6ec8803db8c10f5ed9d863bca21cbc3d | 51,879 |
def find_chimera_indices(G):
"""Attempts to determine the Chimera indices of the nodes in graph G.
See the `chimera_graph()` function for a definition of a Chimera graph and Chimera
indices.
Parameters
----------
G : NetworkX graph
Should be a single-tile Chimera graph.
Returns
... | becad5e96aa879662bd893932527cc34f7f4fa5a | 51,881 |
def namespace(prefix):
"""Decorator that prefixes named variables.
Args:
prefix (str): Prefix to prepend to the name of named variables.
"""
def decorator(f_):
@wraps(f_)
def wrapped_f(*args, **kw_args):
# Replace all variable containers with their namespace variant... | f99d4014fc1be5894de0274176b5a74d7822e858 | 51,883 |
def serialize_representacion(declaracion):
"""
# $ref: '#/components/schemas/representaciones'
"""
representaciones = declaracion.representaciones_set.all()
to_be_add = []
for represent in representaciones:
titular = serialize_tipo_relacion(represent.cat_tipos_relaciones_personales)
... | e20c30b537c5089afa7f87208365279c76ca8f35 | 51,884 |
def calc_area(l, w):
"""
params: l and w are both real positive numbers representing the length and width of a rectangle
"""
if l <= 0 or w <= 0:
raise ValueError
return l * w | baf22572e8dcd9bf5c4c0fbe35c6d9aad82f6df5 | 51,885 |
def settings(request): # pylint: disable=unused-argument
"""Settings context_processor."""
db_settings = {}
default_settings = {
'title': 'Just another blog',
'tagline': '',
}
options = Option.objects.all()
for option in options:
db_settings[option.name] = option.value
... | bd1a226b967b13fae80963e7a8ceaedcc0ec847b | 51,886 |
from bs4 import BeautifulSoup
def get_games(soup=None):
"""Uses bs4 to get list of games on Steam Marketplace.
Argument:
(Optionally) soup: bs4 object to search on.
Returns:
Array of objects, containing all games on marketplace.
"""
if not isinstance(soup, BeautifulSoup):
... | 9dd5811ef5665a01691c105a8d751e95a49c2bc7 | 51,887 |
def print_summary(targets):
"""
Return 0 if all test passed
Return 1 if all test completed but one or more failed
Return 2 if one or more tests did not complete or was not detected
"""
passed = 0
failed = 0
tested = 0
expected = 0
return_code = 3
print("---------------------... | 47d38ba3dd9fb91b1384aa6e7fcbdfe71d560261 | 51,888 |
def get_names(line):
""" достаем из строки имена наташей """
names = []
matches = EXTRACTOR(line.title())
for match in matches:
fact = match.fact.as_json
if "first" in fact.keys() and "middle" in fact.keys() and "last" in fact.keys():
name = fact["first"][0].upper() + "." + f... | 1915eddf30e3a17310f44b9df93777187f69e4bc | 51,889 |
def logical_or(a, b):
"""A version of tf.logical_or that eagerly evaluates if possible."""
a_value = get_static_value(a)
if a_value is not None:
if np.isscalar(a_value):
if a_value:
return a_value
else:
return _maybe_static(b)
else:
return a_value | _maybe_static(b)
els... | 691eecb0b815806e2b2a30973ec983321fdba4c5 | 51,890 |
def massProperties(vertices, faces=None, factor=1.):
"""Compute the mass, center of mass, and inertia tensor of a polygon or polyhedron
Args:
vertices (list): List of (x, y) or (x, y, z) coordinates in 2D or 3D, respectively
faces (list): List of vertex indices for 3D polyhedra, or None for 2D.... | a4c66a407e83e96c5ad66ef88d30bede810aa184 | 51,891 |
def delate_materialslot_duplicate(arg_object:bpy.types.Object) -> bool:
"""指定オブジェクトのマテリアルスロットをソートする
Args:
arg_object (bpy.types.Object): 指定オブジェクト
Returns:
bool: 実行正否
"""
# オブジェクトがメッシュであるか確認する
if arg_object.type != 'MESH':
# 指定オブジェクトがメッシュでない場合は処理しない
return None
... | f2b87ae7ad99bbc9ab39af6664ae82253e09e33c | 51,894 |
def from_DataFrame(df,df_func=None,index_func=None,force_sharex=None):
"""
Create a sharex Pdata.Pdata object from pandas DataFrame
Parameters:
-----------
df_func: function that applies on DataFrame before feeding data into Pdata.
index_func: index function that will be applied before using th... | d5ac9e4e0146be1a85ba6007e092f465871f1c77 | 51,895 |
def run_dials_refine(experiments, reflections, params):
"""Functional interface to tasks performed by the program dials.refine.
This runs refinement according to the PHIL parameters in params, using
taking the initial experimental geometry from experiments, and the
observed reflection centroids from re... | 848aebc53483da9a9a87054e13110af29fce8cbb | 51,896 |
def clean_input(text):
"""
텍스트 정제 함수
:param text: 사용자가 입력한 텍스트
:return: ASCII 이외의 문자를 제거한 정제된 텍스트
"""
# 간단하게 시작하기 위해서 ASCII 문자만 사용합니다
return str(text.encode().decode("ascii", errors="ignore")) | a06f49cc5cc43516865a2b3a0b769e0802775e24 | 51,897 |
import sympy
def nearest_prime(lhs, ctx):
"""Element ∆p
(num) -> nearest prime to a
(str) -> python code from expression
"""
ts = vy_type(lhs)
if ts == NUMBER_TYPE:
if lhs < 2:
return 2
elif is_prime(lhs, ctx):
return lhs
return {
(NUMBER_TY... | 1411e3f79840c4039a95a467ef7f01f9fdcc2a5f | 51,898 |
def make_node2ancestors_recursively(node, node2ancestors):
"""
key=node, value=keyの全祖先のノードのセット
となる辞書を作る。
Args:
node: 全祖先を知りたいノード
node2ancestors: key=ノード, value=keyの全祖先のセット
Return:
nodeにターゲットが存在しない:要素がnodeのみのセット
nodeがnode2ancestors.keys()に存在する:node2ancestors[node]
... | cc48caf9af05bf906ac463af704c1522867ee986 | 51,899 |
def build(func, target=None, target_host=None, params=None):
"""Helper function that builds a Relay function to run on TVM graph
runtime.
Parameters
----------
func: relay.Function
The function to build.
target : str, :any:`tvm.target.Target`, or dict of str(i.e. device/context
nam... | ab3e450297ef810450aab35cd9a5f9f3915ed7ab | 51,901 |
def handle_response(resp, headers):
"""
return TRUE = HIT, FALSE = MISS
"""
val = resp.getvalue()
head_val = headers.getvalue()
index = head_val.find("X-CACHED-MIDDLEWARE: ")
if index == -1:
return False
response = head_val[index + len(HEADER_STRING)]
return response == "H" | c6670d1ca375949a93a046d7d0baa89de66ca820 | 51,902 |
def from_settings(request):
"""
Set context variables based on settings variables
"""
return {
'ENVIRONMENT_NAME': settings.ENVIRONMENT_NAME,
'ENVIRONMENT_COLOR': settings.ENVIRONMENT_COLOR,
} | ea9b48a4f8b5fca38f4c325910a1c6a9a507fb13 | 51,903 |
from typing import Dict
def count_words(text: str) -> Dict[str, int]:
"""This is a function
to count word frequencies or
to count how many times each unique word occurs in the text.
Args:
text (str): A long string
Returns:
Dict[str, int]: A dictionary with sorted word frequenci... | 59570f77f69648b91837b1011db1a228d868828f | 51,904 |
def output_xml(data, code, headers=None):
"""Makes a Flask response with a XML encoded body"""
resp = make_response(dumps({'response': data}), code)
resp.headers.extend(headers or {})
return resp | 33627bae15ea9a033c4a4fab534effbbf911c009 | 51,905 |
def to_dict(conf):
"""Converts a Config object to a dictionary.
Args:
conf (Config): A Config object
Returns:
dict: A multi-level dictionary containing a representation ogf the configuration.
"""
return conf._xpipe_to_dict() | 6c709e04f1ffb88b5b5563defc2a03fabfafbb1e | 51,906 |
def _recode_default(x, default, out_type):
"""Get right default for recoding"""
if default is None and (
out_type is None or isinstance(_get_first(x), out_type)
):
return x
return default | 291fc8427db7d6009c9bbfd3c2ad8c5b8fc25d39 | 51,907 |
def edge_uniform_weight(edge, goal, slicevars):
"""
Return a uniform view of the edge's log-probability.
:param edge: an edge
:param goal: the goal node (gets a special treatment because there are no slice variables for it)
:param slicevars: a SliceVariable object
:returns: 1/beta.pdf(u_s; a, b)... | 71bf32915375bbf8ecb8a212c50d267f30a3219d | 51,908 |
def add_query_params(url, params):
"""
Inject additional query parameters into an existing URL. If
parameters already exist with the same name, they will be
overwritten. Parameters with empty values are ignored. Return
the modified URL as a string.
"""
def encode(s):
return force_byt... | e84eb70c1d24754592847fd4913186003d21e4b0 | 51,909 |
def np_seq_similarity(seq1, seq2, substMat, normed, asDistance):
"""Computes sequence similarity based on the substitution matrix."""
if seq1.shape[0] != seq2.shape[0]:
raise IndexError("Sequences must be the same length (%d != %d)." % (seq1.shape[0], seq2.shape[0]))
"""Similarity between seq1 and ... | d45e7b7b98c63611aeb1d8d19e0677b568dc9e82 | 51,910 |
def loadkeys(filename):
""" "
load twitter api keys/tokens from CSV file with form
consumer_key, consumer_secret, access_token, access_token_secret
"""
with open(filename) as f:
items = f.readline().strip().split(", ")
return items | 5b8d1fa6810112c6ea2c8a93b336d2fecfc9a417 | 51,911 |
def query_db(query, args=(), one=False):
"""Query the database of the current application.
Return the first row of the result if the optional argument 'one'
is true, or the whole query result if not specified.
"""
cur = get_db().execute(query, args)
rv = cur.fetchall()
cur.close()
retu... | 9152bf81cd73b4dec06266b8e37784b8fac42a43 | 51,912 |
from typing import MutableMapping
def flatten_dict(d: MutableMapping, parent_key: str = "", delimiter: str = "."):
"""Flatten a nested dict into a single level dict."""
def _flatten_dict(d, parent_key="", delimiter="."):
for k, v in d.items():
key = str(parent_key) + delimiter + str(k) if... | 35b338a40bbf00079813037776f93a9a822264db | 51,913 |
def sample_pixels(slide_path, sample_fraction=None, magnification=None,
tissue_seg_mag=1.25, min_coverage=0.1, background=False,
sample_approximate_total=None, tile_grouping=256):
"""Generates a sampling of pixels from a whole-slide image.
Useful for generating statistics or... | 7efcc44f1613d26eb0d2b7562c28ba3469a47fb4 | 51,914 |
def valid_hex(value):
"""Check if the string is a valid hex number representation."""
try:
int(value, 16)
except Exception:
return False
return True | 4037b9103cd3308253f929d0a4cbbe3f37c1c219 | 51,916 |
def _get_webauthn_user_public_key_credential_descriptors(user, *, rp_id):
"""
Returns a webauthn.WebAuthnUser instance corresponding
to the given user model, with properties suitable for
usage within the webauthn API.
"""
return [
PublicKeyCredentialDescriptor(
id=base64url_t... | b3549ca3a161b1325cf0eb294fdce077d03a5270 | 51,917 |
def bert_encoder(s, no_wordpiece=0):
""" Compute semantic vector with BERT
Parameters
----------
s: string to encode
no_wordpiece: 1 if you do not use sub-word tokenization, otherwise 0
Returns
-------
np array in shape of (768,)
"""
if no_wordpiece:
words = s.split(... | c818cfabd8dbaf82b654c5b4f22d522595ae69a4 | 51,918 |
def get_mapvars(mapfile):
"""Read the sugar .map file and return a dictionary
where the key is the variable name and the value is the (start,r0,r1)
where r0 is the first ordinal and r1 is the last. Sugar uses uniary encoding."""
mapvars = {}
with open(mapfile,"r") as f:
for line in f:
... | c149270a4f1a86707b7ee5e2ed437b5736a2a986 | 51,919 |
def split_data(features, objectives, train_ratio):
"""Split data into a fitting and training set"""
assert len(features) == len(objectives)
total_envs = len(features)
training_index = int(train_ratio * total_envs)
X = np.copy(features[:training_index])
Y = np.copy(objectives[:training_index])
... | 00d35746cac588ae21dc7a1a211f3c78faea8670 | 51,920 |
import codecs
def _windows_31j(codec_name):
"""
Windows-31J用の検索関数。
一番近いと思われるShift_JISにマッピングする。
:param codec_name: コーデック名
:type codec_name: str
:return: Windows-31Jが指定された場合はShift_JIS、それ以外の場合はNone
:rtype: codecs.CodecInfo
"""
# Windows-31JをShift_JISにマッピングする
if codec_name.lower()... | 42b93b2b54c6bc3522a88402adc926212ad4bebb | 51,922 |
def delete(server_id, **kwargs):
"""Delete server."""
url = '/servers/{server_id}'.format(server_id=server_id)
return url, {} | ea00798b1f6adb1edc3ea025cec31ec9abdfd2d7 | 51,923 |
import re
def clean_tracklisting(string):
"""Clean tracklisting in track name: 'A1.', 'A2.', etc """
result = re.search(r'^([ABCD]{1}[1234]{0,1}\.\s?).*$', string, re.IGNORECASE)
if result is not None:
tracklisting = result.groups()[0]
string = string.replace(tracklisting, '')
return s... | 553f59de12950dc3e86f451cf263a6646938059f | 51,924 |
def T2_limit(conf_level: float = 0.95, n_components: int = 0, n_rows: int = 0) -> float:
"""Returns the Hotelling's T2 value at the given level of confidence.
Parameters
----------
conf_level : float, optional
Fractional confidence limit, less that 1.00; by default 0.95
Returns
-------... | 3c83f82e1431207e275d179a9c8b08c2421106f1 | 51,925 |
def names_limit(
names: list[str], min: int, max: int = __input_files_max__
) -> tuple[list[str], ErrMsg]:
"""清除 names 里的空字符串,并且限定其上下限。"""
temp = map(lambda name: name.strip(), names)
names = list(filter(lambda name: name != "", temp))
expected = ""
size = len(names)
if min == max and size ... | de83cdcd06ef5dc6b1407ca1f1821c38c519013b | 51,926 |
def return_plot_and_view_data(view_dict: dict, *args, **kwargs) -> tuple:
""" This function will take in a dict with 2 keys 'master' and
'primary_keys' from 'multiple_result_view'
and do the following:
1) clean up the data for unavailable and duplicate keys
2) create and returns the plot
3) calc... | d1c36a1cf20a5035b8126f48b194b665cf7bf236 | 51,927 |
def num_to_emoji(x: int) -> str:
"""Convet int to emoji."""
if x <= 20:
return {
-1: "💣",
0: "🟦",
1: "1️⃣",
2: "2️⃣",
3: "3️⃣",
4: "4️⃣",
5: "5️⃣",
6: "6️⃣",
7: "7️⃣",
8: "8️⃣",
... | a9b14e94f56b33b7f449ee46108303b99612244d | 51,928 |
import warnings
def __generate_permissions_dataframe(_permissions_dict_list):
"""This function converts a list of dictionaries containing space permissions into a pandas dataframe.
.. deprecated:: 2.0.0
The :py:func:`khorosjx.places.spaces.__generate_permissions_dataframe` function should be used.
... | ffd241c2fb948e857a134dcb807f1e8be12c14ba | 51,929 |
def is_in_period(month, period):
"""Return which months fall within a specified group of calendar months.
Parameters
----------
month : int or iterable of ints
One or a series of calendar month numbers [1..12].
period : tuple of ints
Group of calendar month numbers to match against.... | e973f1ec11ea4dc6b87834c75d6374bbbb152635 | 51,930 |
from datetime import datetime
def get_stock_quarterly_features_func(d_interval,d_offset):
""" Generates a function that returns quarterly features for a stock
Args:
d_interval: The data interval as a datetime.timedelta (e.g., 6*TIMEDELTA_QUARTER for 6 quarters of data)
d_offset: T... | 05c54d594f13424c394c6852e7cb9a2fb1e6a074 | 51,931 |
def once(f):
"""Decorator. Defer to f once and only once, caching the result forever.
Users with a functional background may recognize the concept of a `thunk`.
"""
unset = val = object()
def _helper(*args, **kwargs):
nonlocal val
if val is unset:
val = f(*args, **kwa... | 39e900779a6665155fe83770964e509ff88a12c4 | 51,932 |
def load_configuration(configuration_file_path, parameters_file_path, bundles):
"""Combines the configuration and parameters and build the configuration object"""
mappings = {}
for bundle in bundles:
if hasattr(bundle, "config_mapping"):
mappings.update(bundle.config_mapping)
loader ... | 4ef108e08f7a28f64a24fc8cfab8ccb624833c9d | 51,934 |
def delete():
"""
Delete a user
---
/api/users/delete/me:
delete:
summary: Return your user data.
security:
- APIKeyHeader: []
tags:
- User
responses:
'200':
description: An Access Token API to be used in Boleto Viewer
"""
user = UserModel.get_on... | e81715db34aa152807ecf0801f1b5a5ea00d9a5f | 51,936 |
def get_cached_dirlist(sample_method, path):
"""
get the list of Samples that have already run from a sample_method (illumina or nanopore) and path (prefix/shard)
"""
return list(dirlist.find({"sample_method": sample_method, "path": path}, {"samples": 1})) | 145e0c8303a1d05c272ad5a30a7d6f9ffdef0fc6 | 51,937 |
import ot
import torch
def pairwise_align(
slice1: AnnData,
slice2: AnnData,
spatial_key: str = "spatial",
alpha: float = 0.1,
numItermax: int = 200,
numItermaxEmd: int = 100000,
device: str = "cpu",
) -> np.ndarray:
"""Calculates and returns optimal alignment of two slices.
Args:... | 1aaed9425a1bf5115119f8b0bb8ab31b57d46dd9 | 51,938 |
import re
def normalize_number(text):
"""数字1文字を0に置き換える(桁数は変わらない)"""
return re.sub(r"\d", "0", text) | 386a5ca07bedd0d52b9e06e9cbd8342295b6d77c | 51,939 |
from typing import Any
def build_get_dictionary_request(**kwargs: Any) -> HttpRequest:
"""Get External Resource as a Dictionary.
See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder
into your code flow.
:return: Returns an :class:`~azure.core.rest.HttpReque... | a4f6b0d19b76b5ab456394ed3745e9f0593c7405 | 51,941 |
def gen_anchor(featuresize,scale):
"""
gen base anchor from feature map [HXW][9][4]
reshape [HXW][9][4] to [HXWX9][4]
"""
heights=[11, 16, 23, 33, 48, 68, 97, 139, 198, 283]
widths=[16,16,16,16,16,16,16,16,16,16]
#gen k=9 anchor size (h,w)
heights = np.array(heights).reshape(len(... | 6895e6b262ad9361c4ea8d94db3732ef1c13924e | 51,942 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.