content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def xsec_NSI(E_R, E_nu, A, Z, Eps_u_e, Eps_d_e, Eps_u_mu=0, Eps_d_mu=0, Eps_u_tau=0, Eps_d_tau=0):
"""
Calculates the differential cross section for
Coherent Elastic Neutrino-Nucleus Scattering
including Non-standard Neutrino interactions (NSI)
Parameters
----------
E_R : float
... | e39c48e5ff1c0e8cf9b165a6b54d0f902bd0c440 | 3,599,400 |
def gen_callbacks(***kwargs):
"""
A callback is a set of functions to be applied at given stages of the training procedure.
Use callbacks to get a view on internal states and statistics of the model during training.
"""
#args
filepath = kwargs['filepath']
monitor = kwargs[... | 6d8b5dd7c7f99865698820cc296caf37ea18591e | 3,599,401 |
def read_wav(fname, verbose=None):
"""Read in a WAV file
Parameters
----------
fname : str
Filename to load.
verbose : bool, str, int, or None
If not None, override default verbose level.
Returns
-------
data : array
The WAV file data. Will be of datatype np.flo... | 2f21c125dd735b5b2a5ed1fde30fbfd48159ae07 | 3,599,402 |
def gradient_norm_func(A, theta):
"""
Returns the 2 norm of the gradient vector (more precisely,
2 norm of 1/2 of the gradient vector).
"""
return np.linalg.norm(trig.trig_grad(A, theta)) | 77c7b660a8f4941bc189c1e9e4d9821701a954ec | 3,599,403 |
import pandas
import scipy
import numpy
def scan_preprocessing_outlier(inp):
"""
LOESS outlier handling.
Outlier detection and removing for LOESS procedure.
Parameters
----------
inp : dict
Method dictionary.
Returns
-------
inp : dict
Method dictionary.
"""
... | 1a090286d4ff38fa3e692323a6ae6aa2a145f3b1 | 3,599,404 |
def get_all_rois_from_folder_v2(
gc, folderid, get_all_rois_kwargs, monitor=''):
"""Get all rois in a girder folder using get_all_rois_from_slide_v2().
Parameters
----------
gc : girder_client.Girder_Client
authenticated girder client
folderid : str
girder id of folder
g... | 5490b6fce217818dcb2d22cf0d51237d5db63f00 | 3,599,405 |
import os
def get_file_with_different_version_location(file_name):
"""
Gets file location
:param file_name: File name
:return : File location
"""
sample_app_dir = os.path.dirname(os.path.realpath(__file__))
return sample_app_dir + '\\Sample_Apps_2\\' + file_name | 8200ae91ddc2c3833a1975aec1ec4664e1149337 | 3,599,406 |
def rotate(A, turns=1):
"""A matrix which is formed by rotating the given matrix, n times, in clockwise sense.
Args
----
A (compulsory)
A matrix.
turns (int, optional)
The number of turns to rotate the matrix. Defaults to 1.
Returns
-------
Matrix
The matrix obt... | c6fb428c15317b314443101093ec96019be52bfa | 3,599,407 |
from pathlib import Path
import yaml
def read_config(config_file: Path="./config.yaml"):
"""
Reads the configuration file
:param config_file:
:return:
"""
with open(config_file) as file:
context = yaml.load(file, Loader=yaml.FullLoader)
return Box(context, default_box=True) | fb2fb0d1253d85a806d2f4020c4b4d347f94ec88 | 3,599,408 |
def distance(a, b):
"""
Clockwise distance
Based on the globally defined key size in bits -- k.
Max node id is 2 to the power of k.
"""
if a==b:
return 0
elif a<b:
return b-a;
else:
return (2**NUM_KEY_BITS)+(b-a); | 3680f98df5dacb8a0fee08469feb0050ea5f9ecd | 3,599,409 |
import time
import logging
import traceback
def run_selected_algorithm(timeseries, metric_name):
"""
Filter timeseries and run selected algorithm.
"""
# Get rid of short series
if len(timeseries) < MIN_TOLERABLE_LENGTH:
raise TooShort()
# Get rid of stale series
if time() - timese... | 709bdae02ad8e55682c25dff16671816caa9587d | 3,599,410 |
def determine_time_system(header: dict) -> str:
"""Determine which time system is used in an observation file."""
# Current implementation is quite inconsistent in terms what is put into
# header.
try:
file_type = header['RINEX VERSION / TYPE'][40]
except KeyError:
file_type = header... | 00a7908aa5eaf21eaaa39d97b23304644ebe27b4 | 3,599,411 |
def get_hyperparameter_search_space(seed: int) -> ConfigSpaceWrapper:
"""
The extra trees configuration space based on the search space from
auto-sklearn:
https://github.com/automl/auto-sklearn/blob/master/autosklearn/pipeline/components/classification/extra_trees.py
Parameters
----------
s... | 66da743cfc1d1d348afe578d67554cb39571c744 | 3,599,412 |
def _all(oper, left, right):
"""Short circuit all for ndarray."""
return all(oper(ai, bi) for ai, bi in zip(left, right)) | fe982f59086d2aa688004f83f9c63c6ecf6919f4 | 3,599,413 |
from typing import Iterable
def get_available_seats(*, trip: Trip, departure_station: BusStation, arrival_station: BusStation) -> Iterable[BusSeat]:
"""
return all non-reserved seats from `departure_station` to `arrival_station`
"""
# [StepPre] get corresponding trip stops from bus stations
de... | 0161ec6ec9adadb977d49a7556d8407eb62255ad | 3,599,414 |
def stats_demographic_data_controller():
"""
Function to be called from controller functions to display all
requests as a tab for a site.
"""
vars = current.request.vars
output = dict()
if "viewing" not in vars:
return output
else:
viewing = vars.viewing
if... | 327e7a11510e29d66f9e60007ffcb16833eba437 | 3,599,415 |
import requests
import json
def exchange(fr, number, to=user_currency):
"""
查询<number> <fr> 对应 多少 <to>
Query <number> <fr> corresponding <number?> <to>
:param to: 待查询的币种
:param number: 待查询的货币数量
:param fr: 目标币种
:return:
"""
try:
res = requests.get(v2_url + 'exchange',
... | 3ccc0f73cf11bcecb9c77fe91e08f5f1392d66ef | 3,599,416 |
def list_services(t, s='http://portainer:9000/api', e='1') :
"""List swarm services.
List the services on the swarm.
Args:
t: Authorization token
s: Portainer server api endpoint
e: Docker endpoint id
Returns:
List of sevice details
"""
return rt.get(s + '/endp... | 80c08f9ba283269cdae8302906252edca2c7613c | 3,599,417 |
def expand_header(row):
"""Parse the header information.
Args:
List[str]: sambamba BED header row
Returns:
dict: name/index combos for fields
"""
# figure out where the sambamba output begins
sambamba_start = row.index('readCount')
sambamba_end = row.index('sampleName')
... | 740790e5aa0f5415d3cb0fc22902403b16bef455 | 3,599,418 |
def _convert_types(image: tf.Tensor) -> tf.Tensor:
"""入力データセットを成型する
Args:
image (tf.Tensor): 入力画像
Returns:
tf.Tensor: 変換した画像
"""
image = tf.cast(image, tf.float32)
image /= 255.0
image = tf.reshape(image, [28, 28, 1])
return image | 5a07127c69cb382cce5c7dc6374d438a531e85b8 | 3,599,419 |
def file_get_contents(space, fname, num_args, use_include_path=False,
w_ctx=None, offset=-1, maxlen=0):
""" file_get_contents - Reads entire file into a string """
fname, read_filters, write_filters = _parse_wrapper(fname)
if fname == "" or fname is None:
space.ec.warn("file_ge... | 5b42104af22dcf4323153cb35dd05ec5b7c85906 | 3,599,420 |
def kernel_pdf_lognorm_(x, sample, bw):
"""Log-normal kernel for density, pdf, estimation, explicit formula.
Jin, Kawczak 2003
"""
term = 8 * np.log(1 + bw) # this is 2 * variance in normal pdf
pdf = (1 / np.sqrt(term * np.pi) / sample *
np.exp(- (np.log(x) - np.log(sample))**2 / term))... | 810b553d8aaf8bb5a4db4220f9fdc049245754e6 | 3,599,421 |
def get_carlyle_2017_dataframe():
"""
Return pandas dataframe for Carlyle 2017
:return:
pandas.core.frame.DataFrame: dataframe containing Carlyle 2017 data.
"""
print("Importing Carlyle 2017 pandas dataframe.")
# from 41593_2017_11_MOESM12_ESM data in 41593_2017_11_MOESM6_ESM is log10LFQ
... | 71ee70022b9f1165ca0e9c9e93c7c5375a34e618 | 3,599,422 |
def get_translations_diff(original_database, modified_database):
"""
Receive the databases names, get the translations and return a dict with the added,
modified and removed translations.
:param original_database: The name of the unmodified database.
:param modified_database: The name of the updated... | 380706f4eadb16d9438671dc6e03099355ab5b59 | 3,599,423 |
def cap_text(text):
"""
Capitalize first letter of a string
:param text: input string
:return: capitalized string
"""
return text.title() | 8403db85d37399db3b4b0693bc9e578ddcf01c3b | 3,599,424 |
import os
def SupportLibOnlyTestDir():
"""Returns the path to the directory with unit tests for support lib."""
return os.path.join(ThisScriptDir(), 'supportlibonlysrc', 'com',
'android', 'rs', 'unittest') | cb20feec7af87c4b80b6f0f3916bd6b44e44c568 | 3,599,425 |
def find_smalldim(imgs):
"""
Find smallest dimension of an image or list of images.
Parameters
----------
imgs : single 3D np.array or list of 3D np.arrays {
titles : str, default = None
Returns
-------
smallest_axis: int
"""
if isinstance(i... | bbcb95955e60e0ad038dbb112538d7bc0a9281fd | 3,599,426 |
def global_settings(request):
"""Expose TWILIO_FROM_NUM, DEBUG and site config in templates."""
return {
"CONFIG": SiteConfiguration.get_solo(),
"DISPLAY_GOOGLE_LOGIN": SocialApp.objects.filter(provider="google").count(),
"ROLLBAR_ACCESS_TOKEN_CLIENT": settings.ROLLBAR_ACCESS_TOKEN_CLIEN... | a36ddc21bea672bef6ada98bfd5bcfe5f4b08127 | 3,599,427 |
def htmlize_list(items):
"""
Turn a python list into an html list.
"""
out = ["<ul>"]
for item in items:
out.append("<li>" + htmlize(item) + "</li>")
out.append("</ul>")
return "\n".join(out) | f9ac8106d85bef8807b54deeb4781fa6323af9cf | 3,599,428 |
def extractGilaTranslation(item):
"""
# Gila Translation Monster
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
ltags = [tmp.lower() for tmp in item['tags']]
if 'dawn traveler' in ltags and 'translation' in l... | 442d591bb7f96a561531867f882eacc5bc68a15b | 3,599,429 |
def _assign(
old_data,
mask,
new_data,
band_offset,
band_axis,
band_selection,
subassign,
mask_type,
replace,
accum,
ot,
):
"""
Performs the actual GrB_assign:
old_data(mask, ...)[index] << obj
or GxB_subassign:
old_data[index](mask, ...) << obj
... | 0eb7fc61861b2ef047bcd82194be394b305320e5 | 3,599,430 |
def playbook_log(request):
"""Retrieve log entries."""
log = spotmax.SPOTLog()
log_entries = log.get_log_entries(50)
# Convert '_id' to string and remove '_' from the key
logs = list()
for log in log_entries:
log['id'] = str(log['_id'])
del log['_id']
logs.append(log)
return render(
... | c730f801b4a6b716e5bbd893225848571eb4a7d2 | 3,599,431 |
def size_as_recurrence_map(size, sentinel=''):
"""
:return: dict, size as "recurrence" map. For example:
- size = no value, will return: {<sentinel>: None}
- size = simple int value of 5, will return: {<sentinel>: 5}
- size = timed interval(s), like "2@0 22 * * *:24@0 10 *... | 203bc0697cca9b3710f4079de03e759659116883 | 3,599,432 |
import os
def download_video(url, path):
"""Download MP4 video from a provided URL.
:param url: User-inputted string from window.
:param path: File path to save video to.
:return: Video filename (None if error), error data if any.
"""
if not url or url == '':
return Non... | d8e183ccd30734063d0888d83ea9429529206d60 | 3,599,433 |
from typing import Optional
from typing import Any
from typing import Callable
def make_jac_jnp_to_onp(input_pytree_topology: PyTreeTopology,
output_pytree_topology: PyTreeTopology,
dtype: Optional[Any] = onp.float64) -> Callable:
"""Returns function "flattening" Jaco... | fd6a19bf881c36fc79b9201f055af5862e9ecd4d | 3,599,434 |
def create_app(testing: bool = False) -> Flask:
"""
Create and configure an instance of the Flask application.
"""
app = Flask(__name__)
if testing:
app.config['TESTING'] = True
@app.route('/')
def index():
return 'Hello, World!'
return app | 1cf39433e8526a3b22126f9b96e77102ca0387b7 | 3,599,435 |
def delete_dr_event(request, pk):
"""
:param pk: the pk of the event that is being cancelled
:param request: request object
:return: redirects user to homepage
"""
old_dr_event = DREvent.objects.get(pk=pk)
new_dr_event = old_dr_event
new_dr_event.pk = None
new_dr_event.deleted = True... | 07c741173431721bf3f39729ec52385ded207aee | 3,599,436 |
def getTrimBox(pdf, pagenumber):
"""Get a trim box given the document, page range, min x, max x,
min y, max y in points. Only suceeds if such a box exists, as checked by
hasBox"""
minx = c_double(0.0)
maxx = c_double(0.0)
miny = c_double(0.0)
maxy = c_double(0.0)
libc.pycpdf_getTrimBox(p... | f1bb4095ceba85582b3813b1383107edd2326e8b | 3,599,437 |
def map_gates_to_grid(
radars, grid_shape, grid_limits, grid_origin=None,
grid_origin_alt=None, fields=None, gatefilters=False, map_roi=True,
weighting_function='Barnes', toa=17000.0, roi_func='dist_beam',
constant_roi=500., z_factor=0.05, xy_factor=0.02, min_radius=500.0,
h_fact... | 1114b8135fd815a5c8e254791557555b25e8fb1a | 3,599,438 |
def interpolate_minus_plus_oxts(oxts_minus, oxts_plus, start_traveled):
"""Interpolate between closer and further points to get path point estimates."""
traveled_minus = oxts_minus.traveled.values - start_traveled
traveled_plus = oxts_plus.traveled.values - start_traveled
alpha = (PATH_POINTS - traveled... | 57ff28796375c93fc21d9c22ddc3827567cf9708 | 3,599,439 |
def cumulative_average_mask(sequence_length, maximum_length=None, dtype=tf.float32):
"""Builds the mask to compute the cumulative average as described in
https://arxiv.org/abs/1805.00631.
Args:
sequence_length: The sequence length.
maximum_length: Optional size of the returned time dimension. Otherwise
... | f4bfde66fd4e58f945e25e6c495fb0d09c909eb2 | 3,599,440 |
def U_sparse(angle1, angle2, angle3, invert):
"""Return scipy sparse CSR matrix with U gate (IBM)."""
return sparse.csr_matrix(U_np(angle1, angle2, angle3, invert)) | f744694cc619f44ae6709ad63795fcaedcacf9bb | 3,599,441 |
import logging
def query_handler(name, mode=None, pid=None, header=None, bytes=0, decoder=None, formula=None, unit=None, protocol="auto", baudrate=None, verify=False, force=False):
"""
Queries an OBD command.
Arguments:
- name (str): Name of the command.
Optional arguments:
- mode (str):... | 3cc9f10d518dbdd76c4f6c0bf2814611c83e5374 | 3,599,442 |
import os
def IsInternalRepoCheckout(root):
"""Returns whether root houses an internal 'repo' checkout."""
manifest_dir = os.path.join(root, '.repo', 'manifests')
manifest_url = git.RunGit(
manifest_dir, ['config', 'remote.origin.url']).output.strip()
return (os.path.splitext(os.path.basename(manifest_u... | 701c98646b01720aa60c11def9635399f3b398b5 | 3,599,443 |
from ..model.view_model import store
def marketplace():
"""Marketplace."""
return render_template('marketplace.html', store=store) | 3a73b6bce70d6e80a89e949355238ae56c829be4 | 3,599,444 |
import os
import random
def extract_augment_and_export_positions_data(is_normal=True,
generate_graph=False, show_graph=False):
"""
Generate augmented data from the dataset.
:return: Name of the augmented dataset
"""
data_type_name = 'normal... | b7688d7e87eca0e3b917e90487b017fab2be512d | 3,599,445 |
def get_field_kwargs(field_name, model_field):
"""
Creates a default instance of a basic non-relational field.
"""
kwargs = {}
return kwargs | d05d5f42a4ecc2669486d049918d271013a6969f | 3,599,446 |
def _check_same_loc(stp1, stp2, staypoints):
"""Check whether two staypoints are at the same location
Parameters
----------
stp1 : int
First staypoint id
stp2 : int
Second staypoint id
staypoints : Trackintel staypoints
GeoDataFrame with staypoints and also location ids
... | 88299b0ed42b7321e82b4309af77253d2eb88a0d | 3,599,447 |
from lib.sysinfo import sysinfo
import os
from datetime import datetime
import traceback
def crash_log():
""" Write debug_buffer to a crash log on crash """
path = os.getcwd()
filename = os.path.join(path, datetime.now().strftime("crash_report.%Y.%m.%d.%H%M%S%f.log"))
# Wait until all log items have ... | a7f3a3a3e8ca47f50fcd8205e09b81871f6a7be5 | 3,599,448 |
def Rabi_2nd_exc_seq(amps, pulse_pars, pulse_pars_2nd, RO_pars, n=1,
cal_points=True,
post_msmt_delay=3e-6, verbose=False):
"""
Rabi sequence for the second excited state
Input pars:
amps: array of pulse amplitudes (V)
pulse_pars: dic... | 276b38169012e36ac7ac06ec87d43c24a4b32b46 | 3,599,449 |
def _int64_feature(value: int) -> tf.train.Features.FeatureEntry:
"""Create a Int64List Feature
Args:
value: The value to store in the feature
Returns:
The FeatureEntry
"""
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) | da7bf0eae1ce7ceb072d1c6a7cea00795b129f97 | 3,599,450 |
from .png_2_ico import png_2_ico
def bat_2_exe(bat_file, exe_file, icon='', *options):
"""
Args:
bat_file: abspath
exe_file: abspath
icon: abspath *.ico
*options: suggested options below
/x64
/invisible
/password {your_password}
... | da768dbc4075971b4e7571b5128b1041713d0d6c | 3,599,451 |
import argparse
def parse_command_line_arguments():
""" Parse command line arguments.
:return: parsed arguments
"""
parser = argparse.ArgumentParser(description="Pure Python command-line RSS reader")
parser.add_argument(
"--version",
action="version",
version="Version 5.0... | b271785eb92ade63f0c103ac83f4e71910bd41cd | 3,599,452 |
from typing import Callable
from typing import Union
from typing import Sequence
from typing import Tuple
from typing import Any
def value_and_grad(
fun: Callable,
argnums: Union[int, Sequence[int]] = 0,
has_aux: bool = False,
holomorphic: bool = False,
allow_int: bool = False,
) -> Callable[..., ... | 33e2754ba0ae898dc29614236b55316c99754e20 | 3,599,453 |
import sys
def writeToConfigFile(text, mode):
"""Writes the 'text' to the configuration file in the output directory using the 'mode' specified. Mode should be
append or overwrite """
config_file = dirname(dirname(abspath(__file__))) + "/output/config.properties"
write_mode = 'w' if mode == 'overwrite... | 735de76326d48b4f353c930a3ff3cd41e1df87a1 | 3,599,454 |
import requests
import json
def get_mactable(auth):
"""
Function to get list of mac-addresses from Aruba OS switch
:param auth: AOSSAuth class object returned by pyarubaoss.auth
:return list of mac-addresses
:rtype list
"""
headers = {'cookie': auth.cookie}
url_mactable = "http://" + ... | 96c064696bf47872e5a1bec5e8770d6470b76bfc | 3,599,455 |
def es_primo(n: int) -> bool:
"""Determina si un número es primo.
:param n: número a evaluar.
:n type: int
:return: True si es primo, False en caso contrario.
:rtype: bool
"""
if n == 2 or n == 3:
return True
if n % 2 == 0 or n < 2:
return False
for i in range(3, int... | fff4802d6e47c379b6510f13e2ffe9a9d56429d2 | 3,599,456 |
def get_playlists(search_string=None):
"""
This function will be used to get playlists of a specified category
:param search_string: Category name whose playlists are required
"""
item_type = 'playlists'
info_dict = spotify.category_playlists(search_string)
items = info_dict[item_type]["ite... | 7a9c695f221e7284edc39fcfb5f3a450c561a92e | 3,599,457 |
def replace_string(string_value, replace_string, start, end):
"""
Replaces one string by another
:param string_value: str, string to replace
:param replace_string: str, string to replace with
:param start: int, string index to start replacing from
:param end: int, string index to end replacing
... | b79d685a13c427334149789195e5fbbb4a6ad28d | 3,599,458 |
from operator import concat
import torch
def collect_results(results):
"""
Converts a list of flat records/rows to a list of tall, row-wise concatenated columns
Useful for collecting a set of batches or individual samples of 0- and 1-dimensional tensors returned by each model step, collected in a list in model.o... | e6ca0388cc0bb13aa1a574bc584527e2d7fd48e6 | 3,599,459 |
import sys
def analyze_file(filename):
"""Run over the given file and count base pairs and sequences."""
bps = 0
seqs = 0
input_iter = screed.open(filename)
for record in input_iter:
if seqs % 100000 == 0:
print('...', filename, seqs, file=sys.stderr)
bps += len(record.... | 251c80bf76eec19485a23f6050389a79af35b3f1 | 3,599,460 |
def custom_exception_handler(exc, context):
""" This function runs after every exceptions raised anyware from code """
response = exception_handler(exc, context)
# Custom reposense data will be returned only if exception will be APIValidationError
if isinstance(exc, APIValidationError):
custom_... | 3dd228f3ed288ab0719376e4be6336b6f436c7d3 | 3,599,461 |
import hashlib
def hash_str(data, hasher=None):
"""Checksum hash a string."""
hasher = hasher or hashlib.sha1()
hasher.update(data)
return hasher | 5dd433a3cc04037bb439b64b71d3495d03f51ef1 | 3,599,462 |
def get_next_point(df, inc, axis):
"""
Increment to get the next points along.
Parameters
----------
df : pandas DataFrame
The dataframe of points
inc : int
The amount to increment
axis : str
The axis along which to increment. Can be 'x', 'y', or 'z'
"""
df =... | 5b91f2f23f188891ff04ded3f4a76e6b552fa2a0 | 3,599,463 |
import torch
import tqdm
def eval_epoch(model, loss_func, validation_data_generator, p_list=None):
"""Epoch operation in evaluation phase"""
bce_total_loss = 0
model.eval()
with torch.no_grad():
y_list, w_list, pred_list = [], [], []
bar = tqdm(range(update_num_per_eval_epoch), desc=' - (Validation) ', ... | 29d4a6aee8f441caa10730d1e59a1cdb16d30426 | 3,599,464 |
def CDLADVANCEBLOCK(barDs, count):
"""Advance Block"""
return call_talib_with_ohlc(barDs, count, talib.CDLADVANCEBLOCK) | fd6e98325e53238eed7333f4ea934a9c510bad45 | 3,599,465 |
def anchor_generator(input,
anchor_sizes=None,
aspect_ratios=None,
variance=[0.1, 0.1, 0.2, 0.2],
stride=None,
offset=0.5,
name=None):
"""
**Anchor generator operator**
Generate anc... | 49c7bb6376ea8163cb7d3f0635aa7fc1abebea8f | 3,599,466 |
import os
import hashlib
def get_file_and_hash(path):
"""Given a filepath, return a tuple of (file contents, sha256."""
text = ''
if os.path.isfile(path):
with open(path) as ifile:
text = ifile.read()
return text, hashlib.sha256(text).hexdigest() | 451be813f377e7070c28d5dfb2ea975bca1d6b75 | 3,599,467 |
def load_input(filename):
"""
Load poker hands from filename
"""
hands = []
with open(filename) as f:
for line in f.readlines():
tokens = line.strip().split(" ")
cards = []
for token in tokens:
value = token[0]
suit = token[... | ba79c8163098be587729f788ce231c02204f77ce | 3,599,468 |
def read_imagenet_label_map():
"""
load imagenet label map
"""
return callZooFunc("float", "readImagenetLabelMap") | 33c93638c47aac2ebd364ad3520420ffc5bc54e6 | 3,599,469 |
def string(value):
"""Validate that a configuration value is a string. If not, automatically converts to a string.
Note that this can be lossy, for example the input value 60.00 (float) will be turned into
"60.0" (string). For values where this could be a problem `string_string` has to be used.
"""
... | 5eeba7016308912f3f79abca9fd4c6e737dea672 | 3,599,470 |
from typing import IO
async def async_failure(
container: 'FutureResult[_ValueType, _ErrorType]',
) -> IO[_ErrorType]:
"""Async unwrap an error from container."""
return IO((await container._inner_value).failure()) | 66841dc44d79095e6359d1d35854330c1ccacea5 | 3,599,471 |
import json
def FormatChromeSettings(settings):
"""Makes adjustments to settings before presenting JSON."""
# Split textarea fields.
for text_field in GetTextFields():
if settings.get(text_field):
settings[text_field]['Value'] = settings[text_field]['Value'].split('\n')
return json.dumps(settings) | 89b2d7c92fabeeec5b423477d7a70616f26225fa | 3,599,472 |
def connect(*args, **kwargs):
"""Proxy connect with an additional kwarg set"""
kwargs["connection_factory"] = connection
return _2connect(*args, **kwargs) | 2d4a261d431a1f1a513b4a302e2499f0392cf81e | 3,599,473 |
def process(s):
"""Given a string with a bunch of markdown links in the style we use
in our changelog, generate the following material to insert in
the changelog.
>>> print(process("Hello [#123] [!456]"), end="")
[!456]: https://gitlab.torproject.org/tpo/core/arti/-/merge_requests/456
... | 394cf25b8e06ec2e2162f86a834e36e1a1c5d622 | 3,599,474 |
from typing import Iterable
def check(line: Iterable[str]) -> Result:
"""Run the syntax check on a line of bracket text."""
# Save the opening brackets on the stack, and pop them as they're closed.
stack = []
closing = {"(": ")", "[": "]", "{": "}", "<": ">"}
for c in line:
if c in "([{<":... | 1f75f53e77985f2d7f8199ecace52605a7208cc7 | 3,599,475 |
def _filter_and_buffer_points_by_year(
point_table, lat_field, long_field, year_field, point_buffer):
"""Separate points in Geopandas table by year.
Args:
point_table (geopandas.Dataframe): table with lat/lng and year fields
lat_field (str): fieldname for lat in ``table``
long_f... | 68c66d05d27e773d3a751d3a293b473da5c1aa5b | 3,599,476 |
from typing import Union
from typing import Iterable
from typing import Callable
from typing import List
def combine_requirements(
requirement: Union[_Requirement, Iterable[_Requirement]],
*requirements: _Requirement,
normalize_func: Callable[[str], str] = normalize
) -> List[ComparableRequirement]:
"""
Com... | d9c21bb2919229ac5e29be6ce20e23345bc11634 | 3,599,477 |
def getSlotsRedirect(entity, params):
"""Returns the slots redirect for the specified entity.
"""
return'/%s/slots/%s' % (
params['url_name'], entity.key().id_or_name()) | 1301bcd68a987b1a72f7ea82f55cf5a57e5ae8d2 | 3,599,478 |
import math
def parse_sudoku(file):
""" parses a sudoku from a given file """
parsed = []
try:
with open(file) as f:
for line in f:
parsed.append([item for item in parse_int(line)])
except IOError:
raise ValueError(""" The sudoku file is not there, please"... | 9a1c1ad18432210cd240bc0e3f2d58762a31dcf3 | 3,599,479 |
import os
def _get_dependency_version(env, dep):
"""
Gets the version of the dependency actually used. This may be different than what
we have set in our gradle.properties. We need to use the version of the dependency
actually downloaded
"""
dep_root = os.path.join(env.deps_dir, dep.name)
... | 3a6ecd1ab622247f06ec8feb2bbfb85df115434e | 3,599,480 |
def get_setting_type(setting_name: str) -> str:
"""
Return a string corresponding to the type of setting that is specified by setting_name.
:param setting_name: Name of the setting to change
:return: String corresponding to the type of setting that is specified by setting_name.
"""
if setting_na... | d03fa8be0052513425813c2ed769061472a3331d | 3,599,481 |
from datetime import datetime
def log_query(service, question: str, answer: str, sentiment: str = "N/A", spreadsheet_id: str = SPREADSHEET_ID) -> int:
"""
Logs a user query and chat bot response to a Google Sheet as well as the timestamp
:param service: Google Sheets API service
:param question: User... | 2a60bbb6526dfb366444947edc79434ae19b22a8 | 3,599,482 |
import urllib
import logging
import json
def get_weather(lat, long):
"""Return weather report for the next 24 hours"""
url = f"https://api.met.no/weatherapi/locationforecast/2.0/compact?lat={lat}&lon={long}"
req = urllib.request.Request(url, headers={"Accept" : "application/json"})
logging.info("Retri... | 8e0ac597a15f2aaf4ac96ee30b546a0a8e1c63a1 | 3,599,483 |
def read_reference(cursor: Cursor, reference_name: str, old_value):
"""
read a reference entry
:param cursor: for db access
:param reference_name: name of the reference
:param old_value: old value to look for
:return: found key or none
"""
my_logger.debug("Reading reference %s", referenc... | 2d46583afec6de74257e6eb59ddccf998f05dfa0 | 3,599,484 |
def recession_spans():
"""
recession span dates from:
THE AUSTRALIAN BUSINESS CYCLE: A COINCIDENT INDICATOR APPROACH
RBA Discussion Paper 2005-07
Christian Gillitzer, Jonathan Kearns and Anthony Richards
http://www.rba.gov.au/publications/rdp/2005/pdf/rdp2005-07.pdf
"""
recessions = [
... | a2070016c3a1cbc1a34f209912d10287c364ff15 | 3,599,485 |
def primal_dual_with_candidate(variables, theta_est_bk, candidate, *args, **kwargs):
"""
Primal dual interior method with candidate
Args:
variables(variables): variable parameters
theta_est_bk(matrix): theta estimation
candidate(list): candidate solvers
"""
candidate = map(l... | 52ae145d2803c682b967a9106140c558a1a6c400 | 3,599,486 |
from doorbirdpy import DoorBird
def setup(hass, config):
"""Set up the DoorBird component."""
# Provide an endpoint for the doorstations to call to trigger events
hass.http.register_view(DoorbirdRequestView())
doorstations = []
for index, doorstation_config in enumerate(config[DOMAIN][CONF_DEVI... | ad0a7cc55a35d0f117bff63603e6166758ea40c1 | 3,599,487 |
def swap(quoteAsset, baseAsset, quoteQty, recvWindow=""):
"""# Swap (TRADE)
#### `POST /sapi/v1/bswap/swap (HMAC SHA256)`
Swap `quoteAsset` for `baseAsset`.
### Weight:
2
### Parameters:
Name |Type |Mandatory |Description
--------|--------|--------|--------
quoteAsset |STRING |YES |
baseAsset |STRING |YES |
quoteQ... | 71ee6ff1a70687dd0fdf60081c4dc944dc4aa356 | 3,599,488 |
import os
def report_dir(request):
"""Returns report files"""
jobid = request.matchdict['jobid']
filename = request.matchdict['filename']
elmts = filename.split(os.sep)
for unsecure in ('.', '..'):
if unsecure in elmts:
return HTTPNotFound()
reports = dict(request.registry... | 19478ad2897d1e5ce45c622829a78dd5f45b4d41 | 3,599,489 |
def _getresponse(self):
"""Monkey-patched replacement getresponse method"""
intercept = self._intercept()
if intercept['mode'] == 'normal':
response = self._orig_getresponse()
if 'recorder' in intercept:
intercept['recorder']._record_response(response)
# ... | 9131ac0aa03c841cb971456d7b04b1e942dd1e78 | 3,599,490 |
def ebnbm_gamma(x, s, init=None, max_iters=10000, tol=1e-3, extrapolate=True,
fix_g=False, fix_theta=True):
"""Return fitted parameters and marginal log likelihood assuming g is a Gamma
distribution
Returns log mu, -log phi, log theta
x - array-like [n, p]
s - array-like [n, 1]
init - arra... | ff400ebb36487ac34cc69d619d85e781e6c113f4 | 3,599,491 |
import subprocess
import os
def exec_shell(cmd, stdin=None, stdout=None, stderr=None,
env=None, cwd=None, wait=False, timeout=None):
""" @brief Executes a given command with different options
@param cmd List of string for the command to execute
@param stdin File handler for command's stdin
... | 1b0e97579c677705931c36fce723f437bfaf31cb | 3,599,492 |
def push_data(metrics_payload, url=METRICS_COLLECTION_URL):
"""
Pushes individual Payload data (SA or RE Data) to specified url.
:param audit_data: Audit Data
:return: Request Object
"""
_session.post(url=url, json=metrics_payload)
return None | 14671e026af2bba2c997cc2aca19bf3fb7d6ed5b | 3,599,493 |
def oned_pitchfork(g0=.1,g1=2.5,N=50):
"""
get figure for 1d pitchfork bifurcation
"""
fig = plt.figure(figsize=(5,3))
ax = fig.add_subplot(111)
ax.set_xlabel(r'$g$')
ax.set_ylabel('Bump Velocity')
glist = np.linspace(g0,g1,N)
an_arr_plus = np.zeros(N) # analytic speed
num_arr_p... | 19da1f5111e977ebcd78c49bedb63736117d96ee | 3,599,494 |
from datetime import datetime
import math
def _stats(tracking_data):
"""
Get statistics on the word count over time, as per nanowrimo.
Input:
wordcount_list - a list of integer word counts, one per day
starting_date - a datetime.date object giving the starting point of the period.
... | 4bd8125273eab44d1e45f5fc371523f79de5c8c4 | 3,599,495 |
def elina_texpr0_array_is_scalar(texpr_array, size):
"""
Test if an ElinaTexpr0Array has only scalar coefficients (non-interval).
Parameters
----------
texpr_array : ElinaTexpr0Array
ElinaTexpr0Array that needs to be tested.
size : c_size_t
Size of the ElinaTexpr0Array.
Ret... | a1d430896b7f6d78ae133d45d257852292f2ab50 | 3,599,496 |
def onesample(data):
"""sample for semi-parametric bootstrap"""
fitted = powerlaw.Fit(data, discrete=True, verbose=False)
xmin = getattr(fitted, "power_law").xmin
lower = [n for n in data if n < xmin]
lower_sample = np.random.choice(lower, len(lower), replace=True)
upper_sample = getattr(fitted,... | 3ef80225488eb060692bcf01ef4b5ee8814bcff8 | 3,599,497 |
def validate_answer(value):
"""
Validate a JSON input for a single answer.
Parameters:
value (any): Input value
Returns:
boolean: True if value has the format required for an answer
"""
validators = {
"participant_id": validate_int,
"question_id": validate_int,
... | bc3087abc330bdcdf143a1b5a8c0da0238670a6d | 3,599,498 |
def _find_baseline_bxr(spectrum, noise_std=None, A=None, B=None,
A_star=5.*10e-9, B_star=1.25, max_iter=30,
min_err=10e-6):
"""Private function to estimate the baseline of an MRSI spectrum.
Parameters
----------
spectrum : ndarray, shape (n_samples, )
... | c7990d92326a2db8383fcbe977fea1f0cb36ad2f | 3,599,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.