content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def from_array(array, copy=True):
"""Convert a NumPy array to a tensor.
Initializes a taco tensor from a NumPy array and copies the array by default. This always creates a dense
tensor.
Parameters
------------
array: numpy.array
A NumPy array to convert to a taco tensor
copy: boo... | 189e5be32db3f411e0a649357a9f8a4e164093ac | 3,610,300 |
def maybeName(obj):
""" Returns an object's __name__ attribute or it's string representation.
@param obj any object
@return obj name or string representation
"""
try:
return obj.__name__
except (AttributeError, ):
return str(obj) | 2b83918c49fc6cd19a027c1d2db07fcb0d57166a | 3,610,301 |
from typing import List
import os
import subprocess
import glob
def ped_datasets() -> List[str]:
"""Returns paths after downloading pedestrian datasets."""
if not os.path.exists("datasets"):
subprocess.call(
["wget", "https://www.dropbox.com/s/8n02xqv3l9q18r1/datasets.zip"]
)
... | b322580b0ef544d0705d792c4be4f7cb13f2824e | 3,610,302 |
def compare(attr_a, attr_b=0, operation=0):
"""Create math_Compare-node to get boolean of logical comparison between given attrs.
Args:
attr_a (NcNode or NcAttrs or string): Maya node attribute.
attr_b (NcNode or NcAttrs or float): Maya node attribute.
operation (NcNode or NcAttrs or in... | 54d94c30984c52daf250e9bed83fba3d56844938 | 3,610,303 |
from sys import flags
def train_eval_input_fn(mode, params, restrict_classes=None, shift_classes=0):
"""Mode-aware input function.
restrict_classes: for use with intra fid
shift_classes: for use with restrict_classes
"""
is_train = mode == tf.estimator.ModeKeys.TRAIN
split = 'train' if is_train else fl... | 9b5bf8edf4d4d462e9a5ffba4751fedd429af777 | 3,610,304 |
import inspect
def gc_nc_60_79(mqc):
"""
Analogous to gc_nc_0_19.
"""
k = inspect.currentframe().f_code.co_name
try:
d = next(iter(mqc["multiqc_picard_gcbias"].values()))
v = d["GC_NC_60_79"]
v = np.round(v, DECIMALS)
except KeyError:
v = "NA"
return k, v | cb3febae5450c3662e8ce91175b5e8ecc42f52b1 | 3,610,305 |
import math
import random
def generate_random_pose():
"""
generate a random rod pose in the room
with center at (0, 0), width 10 meters and depth 10 meters.
The robot has 0.2 meters as radius
Returns:
random_pose
"""
def angleRange(x, y, room, L):
"""
Compute rod an... | 81c26bbabb6b4386b4086b20a09fe8691add2fed | 3,610,306 |
import logging
def version_description(project_arn: str, version_name: str = None):
"""[Describes a Project on Rekognition in AWS]
Args:
project_arn (str): [Unique Identifier for a Project on Rekognition in AWS]
version_name (str, optional): [Display Name]. Defaults to None.
Raises:
... | 3af2244c502a2599ad5c283b3e9147d785ef3a51 | 3,610,307 |
def feature_importance(residuals, analysis_type="collective", date_from=None, date_till=None, weigh=True):
"""Feature importance calculation
Parameters
----------
residuals : pandas.DataFrame()
analysis_type : str, "single"/"collective", "single" by default
date_from : str in format 'yyyy-mm-... | 45c66fa9ddae1b8e81e68c055de94a72a311c83f | 3,610,308 |
def utest(a, b):
"""
MannWhitney U statistic
scipy.stats.mannwhitneyu tests for a != b
Use only when the number of observation in each sample is > 20 and yo
have 2 independent samples of ranks.
Mann-Whitney U is significant if the u-obtained is LESS THAN or equal to
the critical value of U.... | 4628ef64e3a3aaf60dc88f750976b7f0147852bd | 3,610,309 |
from typing import Callable
from typing import Any
import asyncio
import time
async def run_async(func: Callable[..., Any], *args, **kwargs) -> Any:
"""
Runs a callable on the database thread pool executor using the current thread's
I/O loop instance.
Usage:
def blocking_task(arg1, arg2, ar... | 69f7bf02daa77bff85baa34139c8771b20660f1e | 3,610,310 |
def constant_schedule_with_warmup(epoch, warmup_epochs=0, lr_start=1e-4, lr_max=1e-3):
""" Create a schedule with a constant learning rate preceded by a warmup
period during which the learning rate increases linearly between {lr_start} and {lr_max}.
"""
if epoch < warmup_epochs:
lr = (lr_max - ... | e780c3946f0207f94065c3ce8333896c3513f25a | 3,610,311 |
def gen_lc(x,p0,struct,pmax=85.):
""" From gen_lc.pro """
#p0 = m0i, m0v, m0b, period, phase shift, tbreak1, tbreak2
p = np.array(p0).copy()
if len(p) < 11: # use the poly fits to fill in the pca1-pca4 coeffs
c_need = 11 - len(p0)
poly_fits = struct["POLY_FITS"][0]
new_coeffs = [... | 6a211bad9280dd2d78cc70ee95bd57e6c2d0439b | 3,610,312 |
def create_embed(author, level, ascendency_name, class_name, main_skill: Skill, is_support):
"""
Create the basic embed we add information to
:param author: of the parsed message - str
:param level: of the build
:param ascendency_name: to display
:param class_name: to display if no ascendency ha... | 4a116384d1507909addce61b51151c12f0d2a24b | 3,610,313 |
import os
import json
def getVersionFolder(baseVersioningFolder, versionNumber=None):
"""
If versionNumber is None the newest version is returned if available. If the specified version is not available None is returned.
"""
if not os.path.exists(baseVersioningFolder):
raise Exception(f"The gi... | 2c45a05d5a8368b1c124591f6884c4d5cb019f64 | 3,610,314 |
def get_cluster_name():
"""
Retrieves the current cluster name from the CLUSTERNAME environment variable
This should probably be in conf.py, but it creates dependency issues with ZMQ
:return: str cluster name
"""
return environ.get('CLUSTERNAME') | 25ce09ffce1654c5d316ee06b70187ed7d4dd9c0 | 3,610,315 |
def ml_ssl(stft, sv, compression=0, eps=1e-8, norm=False, mask=None):
"""
Maximum likelihood SSL
Arguments:
stft: STFT transform result, M x T x F
sv: steer vector in each directions, A x M x F
norm: normalze STFT or not
mask: TF-mask for source, T x F x (N)
Return:
... | aef6117f45de1f64b15449ae872e9ddc96455578 | 3,610,316 |
def vonMisesStressUtilization(axial_stress, hoop_stress, shear_stress, gamma, sigma_y):
"""combine stress for von Mises"""
# von mises stress
a = ((axial_stress + hoop_stress)/2.0)**2
b = ((axial_stress - hoop_stress)/2.0)**2
c = shear_stress**2
von_mises = np.sqrt(a + 3.0*(b+c))
# stress ... | 3b62b0c6e91eb6f244a70b60ab8b74fb712fac82 | 3,610,317 |
def fit(X, estimator, beta=0.05, N=None, start=1, step=1, tol=1e-5, max_iter=20, debug=False):
"""Run the StARS algorithm to select the regularization parameter for the given estimator.
Parameters:
- X (np.array): Array containing n observations of p
variables. Columns are the observations of a... | 8e6ef25545b702c9788c061bc45de5f9fe12020c | 3,610,318 |
def bar_chart(data2):
"""
A bar chart, like the one above but with small custom alterations title and size
"""
Chart2 = alt.Chart(data2).mark_bar().encode(
alt.X ('movies', title="My Favorite Movies"),
alt.Y ('num_oscars', title="# of Academy Awards"),
color='movies',
).... | aca1fd668a529b82b9293d54f99fa662a8da72b4 | 3,610,319 |
def nSpecies():
""" Returns the total number of species in the model. """
return 62 | b9e77841cb46bba4faa1fab3c1ea00875753aaf1 | 3,610,320 |
def plot_convergence(*args, **kwargs):
"""Plot one or several convergence traces.
Parameters
----------
* `args[i]` [`OptimizeResult`, list of `OptimizeResult`, or tuple]:
The result(s) for which to plot the convergence trace.
- if `OptimizeResult`, then draw the corresponding single t... | 81ad36bd5e1efeddee70e5899aed547a63909e7d | 3,610,321 |
def server_player_id(player_id):
"""Serve player ID endpoint.
This endpoint is used to indicate a buzzer has been triggered, or register
a buzzer.
Args:
player_id: Player identifier.
"""
gameshow = flask.current_app
gameshow.state_machine.process(
state_machine.Events.TRIGG... | 39220e2c66aeafbeb52d5176adcba8ead7faf91b | 3,610,322 |
import math
def crt(cong):
"""Use the Chinese Remainder THeorem to solve the given system of
congruences, cong = [(mod1, rem1), (mod2, rem2), ...] where
val = rem1 mod mod1
val = rem2 mod mod2
...
The val satisfying the congruences is returned.
"""
result = 0
nprod = math.prod([v[0... | 1b63975b769c8d8cf9e5dcf65b102a6a03a7e3c5 | 3,610,323 |
import base64
def compose_message(body, subject, contacts):
"""
composes message
using message text, subject, contacts
and returns it encoded
"""
message = MIMEMultipart()
message['subject'] = subject
message['from'] = me
message['to'] = contacts
plaintext_body = html_to_text(... | 77926afa9ac8d95f83b47a9d1a978008d2a5100d | 3,610,324 |
def getFileList(dbid, fnr, printi=0, type='A'):
""" Get list of Sdicfile objects from Predict file
:param dbid: dbid of Predic file
:param fnr: file number of Predic file
:param printi: print file list if True
:param type: select by file type ('A' is Adabas file)
:returns: list of Sdicfile na... | 09aba2798337b337981fcf8885e774b87ea00409 | 3,610,325 |
def insertWarnings(lines, badCommand):
"""Insert warnings after a command that is probably to be checked.
The text is to be given as a list of lines.
A command in this sense can be any text that is not to be
followed by an asciiletter
"""
lineNumber = 0
while lineNumber < len(lines):
... | 0b8dfb35f818cd74dea54846d9aca9abb9c42efe | 3,610,326 |
def rho_p(rank_vector):
"""Compares each element in the vector to its corresponding value in the null distribution
vector, using the probability mass function of the binomial distribution.
Assigns a p-value to each element in the vector, creating the betaScore vector.
Uses minimum betaScore as rho
... | ba35368b14c2ee0635ffd70e0a243b634698dda2 | 3,610,327 |
import copy
def occupy_seats(data, seat_tolerance, only_adjacent):
""" Occupies seats according to rules.
:param data: seat map (2d array)
:param seat_tolerance: number of discovered seats that can be occupied to still make the person occupy the seat
:param only_adjacent: boolean, if True only check ... | ab86082b0e6c0b4f453c7af2e6dfe383ed6b3054 | 3,610,328 |
def get_orthogonal_grid_edges(pix_x, pix_y, scale_aspect=True):
"""calculate the bin edges of the slanted, orthogonal pixel grid to
resample the pixel signals with np.histogramdd right after.
Parameters
----------
pix_x, pix_y : 1D numpy arrays
the list of x and y coordinates of the slanted... | 11f79e53b021c8744f047f47fb4699c277a3f3ab | 3,610,329 |
def rom(a, b,f, eps = 1e-8):
"""Approximate the definite integral of f from a to b by Romberg's method.
eps is the desired accuracy."""
R = [[0.5 * (b - a) * (f(a) + f(b))]] # R[0][0]
#print_row(R[0])
n = 1
while True:
h = float(b-a)/2**n
R.append((n+1)*[None]) # Add an empty r... | 3dfd00652837b999187a30ace3c3143fa381cb2a | 3,610,330 |
def map_pair_name_to_exchange_name(pair_name):
"""
We're preparing to add the notion that exchanges can have multiple trading pairs
into our system. Each exchange is going to have a single ExchangeData db object but
have one wrapper for each pair. Order.exchange_name is going to refer to the pair,
b... | 314d82d234eb5d096f7bad4c8e75e7f7bde32b75 | 3,610,331 |
from typing import Optional
async def handle_list_comparisons(
project_id: str,
session: Session = Depends(database.session_scope),
kubeflow_userid: Optional[str] = Header(database.DB_TENANT),
):
"""
Handles GET requests to /.
Parameters
----------
project_id : str
session : sqlal... | ff6737cf6811f8cd5fe5c75952702854d38806c1 | 3,610,332 |
import argparse
def get_args():
""" Get command-line arguments """
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description="Howler's Second Program")
parser.add_argument("input", type=str, nargs="+", metavar="str", help="Input messages or files")
parser.add... | 3aaef428ff1f2bc9cb1bc03072a6ed0caa5ccf8b | 3,610,333 |
import pickle
def load_model(file_name="model.pkl"):
"""
Parameters:
file_name (string): exact path of the target saved model
Returns:
built chefboost model
"""
f = open('outputs/rules/'+file_name, 'rb')
model = pickle.load(f)
#restore modules from its references
modules = []
for model_name in model["... | daf76d3a160090f9b706efa839a56c2669ca4edd | 3,610,334 |
import os
def locate_template(template):
"""Locate the template file of a given name."""
*base, ext = template.split('.')
if ext != 'yaml':
template += '.yaml'
return os.path.abspath(os.path.join(TEMPLATE_DIR, template)) | 14520d28e817d1933677b3a82ea5af45f227fa0d | 3,610,335 |
def lower_first(string):
"""Return a new string with the first letter capitalized."""
if len(string) > 0:
return string[0].lower() + string[1:]
else:
return string | fc6fba78d15633f1ab21105fbd46883797444fb1 | 3,610,336 |
def get_annotations_dict(members):
"""Get __annotations__ from a members map.
Returns None rather than {} if the dict does not exist so that callers always
have a reference to the actual dictionary, and can mutate it if needed.
Args:
members: A dict of member name to variable
Returns:
members['__an... | 36d296c880b43a434abbcd6412b76c4e6330b3c8 | 3,610,337 |
def exp(pda : pdarray) -> pdarray:
"""
Return the element-wise exponential of the array.
Parameters
----------
pda : pdarray
Returns
-------
pdarray
A pdarray containing exponential values of the input
array elements
Raises
------
TypeError
Rai... | 3374d1cb9d626d7929c62953a6fadecaf43dd035 | 3,610,338 |
from typing import Optional
def findchallenge(name: str) -> Optional[HTBChallenge]:
"""Finds a specific challenge by name.
Searches HTB for a specific challenge matching the specified name
and returns it if one is found. Otherwise returns None.
Args:
name: An exact challenge name to lookup.
... | b03a7da8177a64cc68567626981fe7ec32003d48 | 3,610,339 |
def create_result_dataframe(y_test: DataFrame, y_pred: DataFrame, model_name: str) -> DataFrame:
"""
:param y_test: DataFrame with target values
:param y_pred: DataFrame with predicted values
:param model_name: Actual model name
:return: DataFrame with models scores
"""
scores = _prepare_sc... | f7d3b8827664b1c7300fcb3ebcb371d1d3288d68 | 3,610,340 |
def create_custom_tiling_node(tile_mode,
tile_level=TileLevel.L1,
tensor_name=DEFAULT_STRING,
tile_pos=DEFAULT_VALUE,
tile_band=DEFAULT_VALUE,
tile_axis=DEFAULT_VALUE,
... | 2cd86602987f971fadc0d2a9e578fbb4212453af | 3,610,341 |
import torch
def get_surface_distance(seg_pred, seg_gt, distance_metric="euclidean"):
""" (from MONAI)
This function is used to compute the surface distances from `seg_pred`
to `seg_gt`.
Args:
seg_pred: the edge of the predictions.
seg_gt: the edge of the ground truth.
di... | 33bc2da4ef41398ec1ad64bc2c1a77509aa4f9cb | 3,610,342 |
def makeState(fromacct,toacct,amount):
"""
make a tranfer state parameter
currently due to the compiler problem,
must be created as this format
:param fromacct:
:param toacct:
:param amount:
:return:
"""
return state(fromacct, toacct, amount) | 79d43214656e7c8420732b945138bfaa39f251ba | 3,610,343 |
import os
def params_used(self):
"""Check for that params in ``nextflow.config`` are mentioned in ``main.nf``."""
ignore_params_template = [
"params.custom_config_version",
"params.custom_config_base",
"params.config_profile_name",
"params.show_hidden_params",
"params.... | a87bcb4a2bcba6094dfe64f35fc9459d2256c35e | 3,610,344 |
def brocher_vp(f):
"""
V_p derived from V_s via Brocher (2005) eqn 9.
"""
f *= 0.001
f = 0.9409 + f * (2.0947 - f * (0.8206 - f * (0.2683 - f * 0.0251)))
f *= 1000.0
return f | 20c8d4961f1660384ecccd081db84a5351ec4d6e | 3,610,345 |
from typing import Dict
def new_swapped_deployment(
old_deployment: Dict,
container_to_update: str,
run_id: str,
expose: PortMapping,
add_custom_nameserver: bool,
) -> Dict:
"""
Create a new Deployment that uses telepresence-k8s image.
Makes the following changes:
1. Changes to s... | fa40bfdc2d045928a8d8dc46999d628332e3490a | 3,610,346 |
def final(data):
"""
Last evolution time point, can be used to obtain parameters at the very end of the run.
:param data: numpy ndarray containing the history of the system.
:return: selection of the last evolution point.
"""
return ([data.shape[0]-1],) | 46a489d0674bece12476af74db4cf4d17f623c4b | 3,610,347 |
def detach_project_from_that_group(request):
"""
detach that group from the requested project
"""
id_project = request.matchdict[u'id']
id_group = request.matchdict[u'group_id']
project = request.dbsession.query(Project).options(
joinedload(Project.groups)).get(id_project)
group = r... | 8f782c4f92199201fdddad47677e1c0078e83b02 | 3,610,348 |
def dec_resource(resource_port, expr, stream_port):
"""Decrease the count of available resource by the specified number, waiting for the processes capturing the resource as needed."""
r = resource_port
e = expr
s = stream_port
expect_resource(r)
expect_expr(e)
expect_stream(s)
expect_sam... | 7ce455e33a22f3c4137e6449e92c956573d0d255 | 3,610,349 |
def _compute_v2_quantities(v2_arr, bias_arr, n_blocks):
"""Compute the squared visibilities quantities: - average ('v2') over the
cube, - covariance ('v2_cov'), - avar ('avar') and - 'err_avar'."""
n_ps = v2_arr.shape[0]
n_baselines = v2_arr.shape[1]
v2 = np.zeros(n_baselines)
v2_cov = np.zeros... | f281eeb58810caea461bc0156a35c43ed463b029 | 3,610,350 |
def make_default_config(project):
"""
Return a default configuration for exhale.
**Parameters**
``project`` (str)
The name of the project that will be searched for in
``testing/projects/{project}``.
**Return**
``dict``
The global default testing conf... | 7b913634f0df656a870d4886cf29391727eb4b21 | 3,610,351 |
def remove_bad_data(net, init='flat', tolerance=1e-6, maximum_iterations=10,
calculate_voltage_angles=True, rn_max_threshold=3.0):
"""
Wrapper function for bad data removal.
INPUT:
**net** - The net within this line should be created
**init** - (string) Initial voltage ... | 1fe5225f28d9119f8433b5b848dee7d2353d38c7 | 3,610,352 |
from imjoy_rpc.hypha import RPC
import msgpack
import json
async def execute_model(
inputs,
server_url=None,
model_name=None,
config=None,
select_outputs=None,
request_id="",
model_version="",
compression_algorithm="gzip",
serialization="triton",
decode_bytes=False,
decode_... | a5725c3978f7bc5e23608b67c19c962d00fe1fd3 | 3,610,353 |
def find_suspicious_regions(misassemblies, min_cutoff = 2):
"""
Given a list of miassemblies in gff format
"""
regions =[]
for misassembly in misassemblies:
regions.append([misassembly[0], misassembly[3], 'START', misassembly[2]])
regions.append([misassembly[0], misassembly[4], 'EN... | e05b359745cdfc97d4f4584d02254bbcc49e543b | 3,610,354 |
from typing import List
import uuid
from datetime import datetime
import pytz
def make_accounts(n) -> List[AccountSchema]:
"""Make n test accounts."""
return [
AccountSchema(
uuid=uuid.uuid4(),
bank_name=f"Starling Personal {i}",
account_name=f"Account {i}",
... | d8d9c069e10d36618f354dee5356556f871de2da | 3,610,355 |
def fabonacci(n):
"""
Return the n'th number of the fabonacci sequence
"""
if n == 0:
return 0
elif n == 1:
return 1
else:
return fabonacci(n-1) + fabonacci(n-2) | d644de5bd5a175d4995a3747df431c2b66695d00 | 3,610,356 |
def read_file(filepath, *args, **kwargs) -> str:
"""Try different encoding to open a file in readonly mode."""
for mode in ("utf-8", "gbk", "cp1252", "windows-1252", "latin-1", "ascii"):
try:
with open(filepath, *args, encoding=mode, **kwargs) as f:
content = f.read()
... | aa332522a08382f05e5da7b7cb890686db0131b5 | 3,610,357 |
def s3_set_extension(url, extension=None):
"""
Add a file extension to the path of a url, replacing all
other extensions in the path.
@param url: the URL (as string)
@param extension: the extension, defaults to the extension
of current. request
"""
... | a3d18dfd1859d328b2e4e795ba5e5839d8684e73 | 3,610,358 |
def fill_from_root(filename, spectrum_name="", config=None, spectrum=None,
bipo=False, **kwargs):
""" This function fills in the ndarray (dimensions specified in the config)
with weights. It takes the parameter specified in the config from the
events in the root file.
Args:
fil... | f42b96dec5f797ffb003d7abbc69c4d0a3066c3e | 3,610,359 |
def low_rank_cov_root(covs, rank, implementation='randomized_svd'):
"""
return X: (n_data, n_dim, rank) matrix so that X[i].dot(X[i].T) ~ covs[i]
"""
n_data, n_dim = covs.shape[:2]
if implementation == 'randomized_svd':
X = np.empty((n_data, n_dim, rank))
for i in xrange(n_data):
... | f5193d9ceb5671c6773fe7d28a75727d935bb917 | 3,610,360 |
def _map(term, predicate):
"""
A 'generic-function' verison of map, which defers
to term.map, if one exists, and otherwise calls predicate
on term.
Actually iterable mapping is handled by term.map
"""
# validate(predicate, collections.Callable)
if _IS_LOGICAL(term):
return term.m... | de50498a57a64ac1703dd4ba159a5be06355801a | 3,610,361 |
def has_byobu() -> bool:
"""Determines whether byobu can run."""
return _has_command('byobu') | f180b3df833f03c41b65f645280b4d152a8f65b7 | 3,610,362 |
def cylinder_divergence(xi, yi, zi, r, v):
"""
Calculate the divergence of the velocity field returned by
the cylinder_flow() function given the path of a streamtube
providing its path components xi, yi, zi.
The theoretical formula used to calculate the returned
variable 'div' has be... | 23ef35bee21270f2255e1b378c5e6cc5839b4d40 | 3,610,363 |
def aggregate(df, signal_names, geo_resolution='county'):
"""Aggregate signals to appropriate resolution and produce standard errors.
Parameters
----------
df: pd.DataFrame
County block group-level data with prepared signals (output of
construct_signals().
signal_names: List[str]
... | e2a29202fcfc532b05e2e0e36b2c5a687ff87571 | 3,610,364 |
def _equal_mstype(x, y):
"""
Determine if two mindspore types are equal.
Args:
x (mstype): first input mindspore type.
y (mstype): second input mindspore type.
Returns:
bool, if x == y return true, x != y return false.
"""
return const_utils.mstype_eq(x, y) | 7011dcd254c65f370571704a9b115bf1822c3a5e | 3,610,365 |
def LM(f, *gens, **args):
"""
Return the leading monomial of ``f``.
**Examples**
>>> from sympy import LM
>>> from sympy.abc import x, y
>>> LM(4*x**2 + 2*x*y**2 + x*y + 3*y)
x**2
"""
options.allowed_flags(args, ['polys'])
try:
F, opt = poly_from_expr(f, *gens, **arg... | bf5de86cc9c3b17bc1c4e9818d140e98be5ae25d | 3,610,366 |
from typing import Dict
def markers(
data: AnnData,
head: int = None,
de_key: str = "de_res",
sort_by: str = "auroc,WAD_score",
alpha: float = 0.05,
) -> Dict[str, Dict[str, pd.DataFrame]]:
"""
Parameters
----------
data: ``anndata.AnnData``
Annotated data matrix with rows... | fb9af8b4c75402f1c5224e7bfaeee2ea2824a519 | 3,610,367 |
def vggcif16_bn():
"""VGG 16-layer model (configuration "D") with batch normalization"""
return VGGcif(make_layers(cfg['D'], batch_norm=True)) | c289110f89c92016966bdc50d85496d42005dd3b | 3,610,368 |
def get_platforms():
"""Return the list of all the platforms"""
controller = PlatformController
return controller.get_list(MySQLFactory.get()) | 42eb217645fcf062ab181ae3afcb278a5e36cbd9 | 3,610,369 |
def metade(x=0, cvsao=False):
"""
==> Divide o valor de x pela metade
:param x: valor recebido.
:param cvsao: (opcional) Se deseja ou não exibir o valor convertido em moeda local
:return: valor de x pela metade com ou não conversão para moeda local.
"""
x /= 2
if cvsao:
x = moeda... | b852f5c002e29b1e0eb6f53ff53a972265211310 | 3,610,370 |
def to_conll_iob(annotated_sentence):
"""
`annotated_sentence` = list of triplets [(w1, t1, iob1), ...]
Transform a pseudo-IOB notation: O, PERSON, PERSON, O, O, LOCATION, O
to proper IOB notation: O, B-PERSON, I-PERSON, O, O, B-LOCATION, O
"""
proper_iob_tokens = []
for idx, annotated_token in enumerate(annotat... | 92fd0904782d241c9729df8a167840e38dfde605 | 3,610,371 |
def get_moves(player):
"""Based on th tuple of player's position, return the list of
acceptable moves
Parameters
----------
player : tuple
Player move data
>>> GAME_DIMENSIONS = (2, 2)
>>> get_moves((0, 2))
['RIGHT', 'UP', 'DOWN']
"""
x, y = player
moves = ['LEFT',... | 5bec5eac969a38e68b3ef8429423b7f160b1882c | 3,610,372 |
def get_models(model_names):
"""Retrieve Odoo models
:param model_names: a list of Odoo model names
:return: a list of dictionaries describing Odoo models
"""
query = create_model_query(model_names)
app.logger.debug(query)
return query_odoo("ir.model", "search_read", query) | b315dc5f2d058e0bf80488b327730649c592cfa6 | 3,610,373 |
def find_auto_threshold(trace_log, variants, decreasingFactor):
"""
Find automatically variants filtering threshold
based on specified decreasing factor
Parameters
----------
trace_log
Trace log
variants
Dictionary with variant as the key and the list of traces as the va... | 41cd3a5e96b148e86463c18b432fedf50464207f | 3,610,374 |
import re
def insert_references(text, last_ref=0):
"""
Insert references section to the page according to local manual of style.
last_ref parameter is used for transfering last reference position: it will be
used for additional checks. If last_ref equals -1, references section will not
be added.
... | 754e2b1d6b8089a2da3665cdfa45f0935f62ba29 | 3,610,375 |
def KK_RC44(w, Rs, R_values, t_values):
"""
Kramers-Kronig Function: -RC-
Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com)
"""
return (
Rs
+ (R_values[0] / (1 + w * 1j * t_values[0]))
+ (R_values[1] / (1 + w * 1j * t_values[1]))
+ (R_values[2] / (... | 628d19332ce3f7dcacc75e26074f4776453ace25 | 3,610,376 |
import torch
def collate_rank_eval(data):
"""Collate multiple datapoints for candidate product ranking during evaluation
Parameters
----------
data : list of 3-tuples
Each tuple is for a single datapoint, consisting of DGLGraphs for reactants and candidate
products, scores for candida... | b184992536128ed06a79a0ae19b649a5d9748148 | 3,610,377 |
import gc
def garbage():
"""
Collect garbage and return an :class:`~refcycle.object_graph.ObjectGraph`
based on collected garbage.
The collected elements are removed from ``gc.garbage``, but are still kept
alive by the references in the graph. Deleting the
:class:`~refcycle.object_graph.Obje... | 92e66329bfa32f25ab395505ba7efa7af62fb878 | 3,610,378 |
from typing import IO
from re import U
def fifo(FALL_THROUGH=0, DATA_WIDTH=32, DEPTH=8):
"""
args:
FALL_THROUGH: fifo is in fall-through mode
DATA_WIDTH: default data width if the fifo is of type
DEPTH: depth can be arbitrary from 0 to 2**32
"""
ADDR_DEPTH = int... | 706a906b4ba1374cf9b9281a0d623772dd7926a6 | 3,610,379 |
def from_snbt(snbt : str, pos : int = 0):
"""Create a TAG from SNBT when type is unknown"""
#print(f'Starting tests at {pos}')
for i in sorted(Base.subtypes, key = lambda i : i.snbtPriority):
try:
value, pos = i.from_snbt(snbt, pos)
except ValueError:
... | c4fe439ba11030737bba880943f5ac4255202ffa | 3,610,380 |
def parse_data_txt(zip_file_path):
"""
Extract the tables in fastqc_data.txt from FastQC results contained
in a zip file.
Returns a dictionary representing the tables in the file,
keyed by section headers in the form:
{u'Basic Statistics':
{'column_labels': (u'Measure', u'Value'),
... | d1c9329802d3f398b151d9007cd69562a75d358f | 3,610,381 |
def _construct_lookup(
orders,
dists,
growth,
recurrence_algorithm,
rules,
tolerance,
scaling,
n_max,
):
"""
Create abscissas and weights look-up table so values do not need to be
re-calculatated on the fly.
"""
x_lookup = []
w_look... | 7127bcc3c4884a2f4a757e3249e74f6902ff3464 | 3,610,382 |
def feedback_system(request):
"""
get:
Get the contents of the system feedback.
post:
Add a new system feedback from a user.
delete:
Delete a the user's system feedback.
"""
if request.method == 'GET':
feedback = SystemFeedback.objects.all()
serializer = S... | 36d285589a8dad6b3dd43f96ea6e5de6c43530f6 | 3,610,383 |
import requests
import os
def get_vm_by_id(id):
"""Returns the VM setting information of a VM"""
r = requests.get(api_url + '/vms/' + id, headers=headers).json()
# populate name
for vm in get_vms():
if vm['id'] == id:
r['name'] = os.path.split(vm['path'])[1].split('.')[0]
... | 342fe9b013fbd27717cc8d285285ad9b64df6168 | 3,610,384 |
def parse_mr_job_stderr(stderr, counters=None):
"""Parse counters and status messages out of MRJob output.
:param stderr: a filehandle, a list of lines (bytes), or bytes
:param counters: Counters so far, to update; a map from group (string to
counter name (string) to count.
Return... | 202115802abd963fc8389b12ec84997a24dbd531 | 3,610,385 |
def predict_coefficients(inputs: tf.Tensor,
hparams: tf.contrib.training.HParams,
reuse: object = tf.AUTO_REUSE) -> tf.Tensor:
"""Predict finite difference coefficients with a neural networks.
Args:
inputs: float32 Tensor with dimensions [batch, x].
hparams... | 4477f272ae48820ce899700b7a563ec23967c2e2 | 3,610,386 |
from typing import Union
def ckd(xparentkey: Octets, index: Union[Octets, int]) -> bytes:
"""Child Key Derivation (CDK)
Key derivation is normal if the extended parent key is public or
child_index is less than 0x80000000.
Key derivation is hardened if the extended parent key is private and
child... | 3c4f414763e8c862d947bfa5dcfc7a82707805c6 | 3,610,387 |
import copy
def _treeizeAvailabilityZone(zone):
"""Build a tree view for availability zones."""
AvailabilityZone = availability_zones.AvailabilityZone
az = AvailabilityZone(zone.manager,
copy.deepcopy(zone._info), zone._loaded)
result = []
# Zone tree view item
az.z... | d03c4d614b5fd424d3be656b311528cbdb5fd0da | 3,610,388 |
def reducer(state, action):
"""Add HTML loaded action to state"""
if isinstance(action, dict):
try:
action = forest.actions.Action.from_dict(action)
except TypeError:
# TODO: Remove try/except when Actions are supported
return state
if isinstance(state, di... | 712c88642425ca825878f823a5f0d45c84611eeb | 3,610,389 |
from typing import OrderedDict
def parseDisambig(html):
"""Parse disambiguation page and return list of (article, text) tuples."""
sections = OrderedDict()
soup = bs4.BeautifulSoup(html, 'lxml')
for i in soup.find_all(True, class_=skipclass):
i.decompose()
sections[''] = _processDisambigSe... | a7e4d998ef138f11db139c2d2819c9ead62c60ab | 3,610,390 |
import json
def get_rookie_prediction(input):
"""This function receives the data from the requests, parses it as a dictionary and gets the prediction
Args:
input (json) The request body
Returns:
The prediction for the input value
"""
try:
data = json.loads(input)
... | 5cedd4204187c898789697b42d20b86ef6a6abd0 | 3,610,391 |
import json
import logging
import os
def task_rebuild_lowering_directory(gearman_worker, gearman_job):
"""
Verify and create if necessary all the lowering sub-directories
"""
job_results = {'parts':[]}
payload_obj = json.loads(gearman_job.data)
logging.debug("Payload: %s", json.dumps(payload... | a2c3a9d263701713aa7b25273feeb5076952d2e9 | 3,610,392 |
import os
def make_makeblastdb_cmd(filename):
""" Construct a makeblastdb command line to make a BLAST nucleotide
database from the passed fragmented input sequence FASTA file.
- filename is the location of the fragmented input FASTA sequence
file, for constructing the database
... | 753cb0480d7ea525546ec188e3fe93c4a2c17153 | 3,610,393 |
def config_register(value):
"""Register a value or values.
Parameters:
-A Value
"""
return ConfigurationSettings().register(value) | 00fafeb6d288191e7306e637544bbc9cb29906c8 | 3,610,394 |
import unicodedata
import re
def normalize(text):
"""
Normalizes text before keyword matching. Converts to lowercase, performs KD unicode normalization and replaces
multiple whitespace characters with single spaces.
"""
return unicodedata.normalize('NFKD', re.sub(r'\s+', ' ', text.lower())) | c03a3148d39161cfd5751a306ca842362c46fb28 | 3,610,395 |
def gdb_path():
"""
Get path to the gdb
"""
return _get_ya_plugin_instance().gdb_path | 67fcce8eccd59ca981b08e7f55868e986ae29a81 | 3,610,396 |
import base64
def pass_to_key(password):
"""Return a key from the given password for encryption."""
byte_pass = password.encode()
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=b"\r7\xb6bT\xa0\xd5\xdcG.'+\xb7\xdb\r\xcd",
iterations=100000,
backend=defa... | ba5ee669edc02e80c700c257c2eaa08c1b2ed6f5 | 3,610,397 |
def _ProcessCards(data):
"""Process the set lines and corresponding data"""
# Reset all values
# -------------------------------------------------------------------------
setLine = []
sd = {"brN": None, "branches": None, "histN": None,
"histories": None, "times": None, "units": None}
... | 3ada5c8f85d3833e10626b82dce82a99492b8159 | 3,610,398 |
def sigmoid_backward(x):
""" derivation of sigmoid
Paras
-----------------------------------
x: output of the linear layer
Returns
-----------------------------------
max of nums
"""
s = sigmoid(x)
return s * (1 - s) | e165a08c0642257fcac163f3bc98c87f5dee6ab1 | 3,610,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.