content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import torch
def train_epoch(loader, vae, optimizer, device, epoch_idx, log_interval,
loss_weights, stats_logger, clip_gradients=None):
"""Train VAE for an epoch"""
vae.train()
train_losses = {}
train_total_loss = 0
for batch_idx, data in enumerate(loader):
data = data.to(... | e846987844933359a67f7b6581a8429ef88bfb0b | 3,400 |
from mpl_toolkits.axes_grid1.parasite_axes import SubplotHost
def phased_multi_axes(times, data, std, ephemeris, thin=1,
colours='midnightblue', ylim_shrink=0.8,
subplot_kw=None, gridspec_kw=None, **kws):
"""
Parameters
----------
times
data
std
... | 32d2da62acde2a2424c310e1bd0196dbac9309cf | 3,401 |
def get_delta(K):
"""This function returns the delta matrix needed calculting Pj = delta*S + (1-delta)*(1-S)
Args:
inputs:
K: Integers below 2^K will be considered
outputs:
delta: Matrix containing binary codes of numbers (1, 2^K) each one arranged ro... | 84e72790024c7294e715dd5efc03f001a7ab887d | 3,402 |
def string_split_readable(inp, length):
"""
Convenience function to chunk a string into parts of a certain length,
whilst being wary of spaces.
This means that chunks will only be split on spaces, which means some
chunks will be shorter, but it also means that the resulting list will
only conta... | 1f1d3641cc293754c174d32d397dab252c009eca | 3,403 |
import torch
def get_similarity_transform_matrix(
from_pts: torch.Tensor, to_pts: torch.Tensor) -> torch.Tensor:
"""
Args:
from_pts, to_pts: b x n x 2
Returns:
torch.Tensor: b x 3 x 3
"""
mfrom = from_pts.mean(dim=1, keepdim=True) # b x 1 x 2
mto = to_pts.mean(dim=1, ... | 76524a1f85644cfedfda9dd60497768614a058b0 | 3,404 |
def get_current_daily_puzzle(**kwargs) -> ChessDotComResponse:
"""
:returns: ``ChessDotComResponse`` object containing
information about the daily puzzle found in www.chess.com.
"""
return Resource(
uri = "/puzzle",
top_level_attr = "puzzle",
**kwargs
) | 733ce2eaa45b773cdfc04395ceb4dbe101ae8b78 | 3,405 |
def stroke_negative():
"""
render template if user is predicted negative for stroke
"""
return render_template("negative.html") | 2f1a07b57b19143e6755f3067c4923bb7231fb89 | 3,406 |
import sirepo.sim_data
def default_data(sim_type):
"""New simulation base data
Args:
sim_type (str): simulation type
Returns:
dict: simulation data
"""
return open_json_file(
sim_type,
path=sirepo.sim_data.get_class(sim_type).resource_path(f'default-data{sirepo.c... | 47791f63a6b6c636d8e0a5513e47ab10bd2db209 | 3,407 |
def get_instance_name_to_id_map(instance_info):
"""
generate instance_name to instance_id map.
Every instance without a name will be given a key 'unknownx', where x is an incrementing number of instances without a key.
"""
instance_name_to_id = {}
unknown_instance_count = 0
for instance_id ... | 293923476a19362fbbc2b3bb0b34bc35523bdfa1 | 3,408 |
def log_get_stdio_record(log):
"""
Returns a darshan log record for STDIO.
Args:
log: handle returned by darshan.open
Returns:
dict: log record
"""
return log_get_generic_record(log, "STDIO", "struct darshan_stdio_file **") | 6438d1ca88357cb3928492ddb89c4beab643f9fb | 3,409 |
import subprocess
def gits_set_profile(args):
"""
Function that prints hello message
to user console
"""
# print(args.email)
# print("Hello from GITS Commandline Tools-Profile")
try:
# check regex
check_val = check(args.email)
# print(check_val)
if check_val... | 0235498f539046ea5eddedecec56be1980dbb129 | 3,410 |
def generate_spiral2d(nspiral=1000,
ntotal=500,
nsample=100,
start=0.,
stop=1, # approximately equal to 6pi
noise_std=.1,
a=0.,
b=1.,
savefig=T... | 4d5129f651fd3a817c9be3beb9c2358895dd3654 | 3,411 |
import math
def AUC_confidence(auc_value, num, interval=0.95):
"""
Calculate upper and lower 95% CI for area under the roc curve
Inspired by https://stats.stackexchange.com/questions/18887
:param r: spearman's rho
:param num: number of data points
:param interval: confidence interval (0-1.0)
... | 5beab0e62171d49dcfb0fbd126243e4906787273 | 3,412 |
def add_data(data):
""" This adds data """
item = data
db.insert(data)
return 'chain updated' | 52efd328097c95768de7f049335dbad9761e5715 | 3,413 |
import os
import logging
def detect_face(img_path, cc_path='../files/haarcascade_frontalface_default.xml'):
"""
Detect the face from the image, return colored face
"""
cc = cv2.CascadeClassifier(os.path.abspath(cc_path))
img_path = os.path.abspath(img_path)
img = cv2.imread(img_path)
gray... | 3d3d6786d7830bf1e03ab7bcc07052c5dd25a089 | 3,414 |
from typing import Counter
def build_node_to_name_map(head):
"""
:type head: DecisionGraphNode
:return:
"""
node_to_name_map = {}
name_to_next_idx_map = Counter()
def add_node_name(node):
assert node not in node_to_name_map
node_type_name = node.get_node_type_name()
... | 9d4b21317030c30539a5ec5947e574e3bd4fdd60 | 3,415 |
def ReduceFloat(f, op=None):
"""Reduce a single float value over MPI"""
if not hasMPI:
raise Exception("mpi4py required for Reduce operations: not found")
if op is None:
op = MPI.SUM
fa = np.array([f]) # can only reduce over numpy arrays
MPI.COMM_WORLD.Allreduce(MPI.IN_PLACE,
... | 12ca088e19a20eed145e1a90d8d88941f5d249ac | 3,416 |
def GetVerificationStepsKeyName(name):
"""Returns a str used to uniquely identify a verification steps."""
return 'VerificationSteps_' + name | e50e9bd7b586d8bbfaf8902ce343d35d752948a4 | 3,417 |
def annotate_ms1_peaks(ms1_data, ms2_data, analyte_list):
"""Interpolate MS1 intensities for the time points for the MS2 scans for the largest mass peak in each analyte.
Use relative changes in intensity between interpolated MS1 data and real MS2 data to find MS2 peaks that go with
each analyte. """
ms2... | 32e0712ed27d802d99290cf01ba1f5f0dc07bae2 | 3,418 |
def split_tblastn_hits_into_separate_genes(query_res_obj, max_gap):
"""Take a SearchIO QueryResult object and return a new object with hits
split into groups of HSPs that represent distinct genes. This is important,
because there may be multiple paralogous genes present in a single
nucleotide subject se... | f33bc8ed36343cb4e0c00c186546d6f979885c92 | 3,419 |
def to_entity_values(entity_group):
""" Parse current entity group content into a CreateEntity[]
"""
values = []
for _, row in entity_group.iterrows():
value = row[ENTITY_VALUE_COLUMN]
if not value: # Handle reserved entities
continue
synonyms = []
patterns ... | 278f9d5a7c8294338d83ba025c67fe23f36a8ac2 | 3,420 |
import codecs
import logging
def read_file(file_path):
"""
Read the contents of a file using utf-8 encoding, or return an empty string
if it does not exist
:param file_path: str: path to the file to read
:return: str: contents of file
"""
try:
with codecs.open(file_path, 'r', encod... | 13a72bc939021e3046243ed9afc7014cb403652a | 3,421 |
def scrub(data):
"""
Reads a CSV file and organizes it neatly into a DataFrame.
Arguments:
data {.csv} -- the csv file to be read and scrubbed
Returns:
DataFrame -- the logarithmic returns of selected ticker symbols
"""
df = pd.read_csv(data, header=0, index_col=0, parse_dates=... | cce082da1d1f4c4308b4f30df918750f91de3f3f | 3,422 |
import argparse
def parse_args():
"""read arguments from command line
"""
parser = argparse.ArgumentParser(
description='preprocess.py',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--dataset',
type=str,
... | 7896e1e6edf431a3293ecc2a3970714212132322 | 3,423 |
def _get_lto_level():
"""
Returns the user-specific LTO parallelism level.
"""
default = 32 if config.get_lto_type() else 0
return read_int("cxx", "lto", default) | 1d0279d363aaa02dcf820f3a064e9b2023ae36a4 | 3,424 |
from typing import List
from typing import Any
def slice_label_rows(labeldf: pd.DataFrame, label: str, sample_list: List[str],
row_mask: NDArray[Any]) -> NDArray[Any]:
"""
Selects rows from the Pandas DataFrame of labels corresponding to the samples in a particular sample_block.
Args... | 859bac2e577b534592a3428cd163f123608c9d72 | 3,425 |
def rollback(var_list, ckpt_folder, ckpt_file=None):
""" This function provides a shortcut for reloading a model and calculating a list of variables
:param var_list:
:param ckpt_folder:
:param ckpt_file: in case an older ckpt file is needed, provide it here, e.g. 'cifar.ckpt-6284'
:return:
"""
... | e434ba292b842ee29ca5e61e33b24089a34b52a8 | 3,426 |
import numpy
def read_interaction_file_mat(file):
"""
Renvoie la matrice d'adjacence associée au graph d'intéraction entre protéines ainsi que la liste
ordonnée des sommets
:param file: tableau contenant un graphe
:type file: dataframe
:return: une matrice d'adjascence de ce graphe et une list... | de62b45810ada6a69b779f42c39b589092d95428 | 3,427 |
def load_figures(fig_names):
"""
Uses a list of the figure names to load them into a list
@param fig_names:
@type fig_names:
@return: A list containing all the figures
@rtype: list
"""
fig_list = []
for i, name in enumerate(fig_names):
fig_list.append(pl.load(open(f"{name}.pi... | 6e90a2c9c7fbbbb89d793b8e0c8e7b521f797f64 | 3,428 |
def define_mimonet_layers(input_shape, classes, regularized=False):
"""
Use the functional API to define the model
https://keras.io/getting-started/functional-api-guide/
params: input_shape (h,w,channels)
"""
layers = { 'inputs' : None,
'down_path' : {},
'bottle_... | e3151f29590cbd523063e13fffc29290a19d071a | 3,429 |
import sys
def scattering_angle( sza, vza, phi, Expand=False, Degree=False ):
"""
Function scattering_angle() calculates the scattering angle.
cos(pi-THETA) = cos(theta)cos(theta0) + sin(theta)sin(theta0)cos(phi)
Input and output are in the unit of PI
Parameters
----------
sza: solar zenith angl... | c3c96ab2852857528495b932b7e42af9ebd719d5 | 3,430 |
def _list_subclasses(cls):
"""
Recursively lists all subclasses of `cls`.
"""
subclasses = cls.__subclasses__()
for subclass in cls.__subclasses__():
subclasses += _list_subclasses(subclass)
return subclasses | 4cebf48916c64f32fcd5dfff28ecde7a155edb90 | 3,431 |
import logging
def main(from_json: bool = True, filename: str = DEFAULT_ARGS['pipeline_config_save_path']):
"""
Calls the specified pipeline.
:param filename: json filename
:param from_json: whether to run pipeline from json file or not
:return: pipeline call function
"""
# Parsing argum... | ccd975889d639f3a642e820e4d7ce5e2ef583609 | 3,432 |
def put(url, **kwargs):
"""PUT to a URL."""
return session.put(url, **kwargs) | 64618fc239164a73fa90f2348de8402c5a593394 | 3,433 |
def cod_records(mocker, cod_records_json):
"""Fixture for COD records metric instance."""
mocker.patch.object(RecordsMetric, 'collect',
new=records_collect(cod_records_json))
return metrics.records('cod_records', 'http://www.google.com') | d4ac73421f3fcef9b175aa42c02354ff437581ad | 3,434 |
def add_computed_document_features(input_dict):
"""
TODO: Add a feature to Annotated Document Corpus.
:param adc: Annotated Document Corpus
:param feature_name: the name of new feature
:param feature_computation: "New Feature Computatation
:param feature_spec: Comma separated list of names of o... | 2673eae356c3fc5717d7ba6aa735aa8f6f129731 | 3,435 |
def get_lite_addons():
"""Load the lite addons file as a set."""
return set_from_file('validations/lite-addons.txt') | 68f26084b5e7e13492f61fc65fe504d1b5d53384 | 3,436 |
def GetApexPlayerStatus_TRN(api_key, platform, playerName):
"""
Get the status of a player on Apex Legends.
:param api_key: The API key to use.
:param platform: The platform to use.
:param playerName: The player name to use.
"""
platform = _fixplatform(platform)
if _checkplatform(platfo... | 296f9900e3e95afa24a0e643ed45563b57fb172a | 3,437 |
def subFactoryGet(fixture, **kwargs):
"""
To be used in fixture definition (or in the kwargs of the fixture constructor) to reference a other
fixture using the :meth:`.BaseFix.get` method.
:param fixture: Desired fixture
:param kwargs: *Optional:* key words to overwrite properties of this fixture
... | 480db102897a3edd682acef6ee95a42b6f937b03 | 3,438 |
def hello():
"""Return the dashboard homepage."""
return render_template('index.html') | adac182b3c8dd2ae0f17425205203c5493499f19 | 3,439 |
def rapid_ping(client, dst_ip):
"""TODO: Docstring for ping.
:returns: TODO
"""
status = False
# run ping command with count 10 rapidly
command = 'exec cli ping ' + dst_ip + ' count 10 rapid'
stdin, stdout, stderr = client.exec_command(command, get_pty=True)
for line in iter(stdout.read... | 9533995412eb10ee66b437c7e28b697dcb156b50 | 3,440 |
from pathlib import Path
def test_data_dir():
"""
Returns path of test datas like excel
Used for test or notebook
"""
path = Path(__file__).parent.parent / 'testdata'
return path | f410f26276797204dd100d884b162f893b5ce4aa | 3,441 |
import sys
def classify_audio(model, callback,
labels_file=None,
inference_overlap_ratio=0.1,
buffer_size_secs=2.0,
buffer_write_size_secs=0.1,
audio_device_index=None):
"""
Continuously classifies audio samples fro... | d8462b689b8e5e3ad24933265f4b6b740e71ace4 | 3,442 |
def is_leap_year(year: int) -> bool:
"""Returns whether the given year is a leap year"""
if year % 100 == 0:
return year % 400 == 0
else:
return year % 4 == 0 | fccaa3de6378e62b937748c671a21aa5427781e8 | 3,443 |
import os
def find_manifests(pkgnames, verbose=True):
""" return a dictionary keyed by pkgname with the found manifest's full path """
(abspath, dirname) = (os.path.abspath, os.path.dirname)
(ret,stdout,stderr) = spawn("git rev-parse --show-toplevel")
root = stdout[0] if ret == 0 else os.getcwd()
... | a23fdab47c8c26a154e484036c52d77b6b4d3ed1 | 3,444 |
def is_valid_distribution(qk: np.ndarray, axis: int) -> bool:
"""valid is e.g.: [], [1.0], [0.5, 0.5]"""
"""not valid is e.g.: [-1.0], [0.6, 0.6], [np.nan], [np.nan, 0.6], [1.2]"""
assert 0 <= axis < len(qk.shape)
if qk.shape[axis] == 0:
return True
if np.any(qk < 0.0):
return False
if np.any(qk > 1... | fdbb1ac82f2d5cf93843f3d8d1f4f4d02a3ab408 | 3,445 |
def srt(data, cube, **kwargs):
"""
Define Solar Rotational Tomography model with optional masking of
data and map areas. Can also define priors.
Parameters
----------
data: InfoArray
data cube
cube: FitsArray
map cube
obj_rmin: float
Object minimal radius. Ar... | e0af1f5d0d00e8651c3668091165beaf0aaa6f55 | 3,446 |
def get(status_id):
"""Fetches a status of previously submitted PushFunds request.
Returns a status of :func:`~pyvdp.visadirect.fundstransfer.MultiPushFundsTransactionsModel` request by transaction
identifier, returned with 202 response.
:param str status_id: **Required**. Transaction status identifi... | fb8951355f342405e93f44747e670afcaf094322 | 3,447 |
import os
def getLocalDir(jobdir, dirname=''):
"""
Assemble destination directory for job results.
Raises:
TargetDirExistsError: Destination for job results already exists.
"""
if dirname:
dstDir = os.path.join(dirname, jobdir)
else:
dstDir = os.path.join(os.getcwd(), ... | a7bd503b86a60761f09abb139e696efadbf899b5 | 3,448 |
def eval_pop_thread(args):
"""
Evaluates solutions, returns a list of floats, between 0 and 1
(probabilities of survival and reproduction).
"""
m_solutions, m_state_hash_table, id_mi = args[0], args[1], args[2]
step = int(N_POP/N_PROC)
prob_surv = np.zeros(step)
for index_sol in range(le... | 8acdb0acae737a8bf48578ec48c3dcc1b66c7adb | 3,449 |
def _mini_batch_convergence(model, iteration_idx, n_iter, tol,
n_samples, centers_squared_diff, batch_inertia,
context, verbose=0):
"""Helper function to encapsulate the early stopping logic"""
# Normalize inertia to be able to compare values when
# ba... | 701488e530913bfc2e5d382a544679315dc1f013 | 3,450 |
def rho_MC(delta, rhoeq=4.39e-38):
"""
returns the characteristic density of an
axion minicluster in [solar masses/km^3]
forming from an overdensity with
overdensity parameter delta.
rhoeq is the matter density at matter
radiation equality in [solar masses/km^3]
"""
return 140 * (1 + del... | f28e382cfcf661199728363b3ebe86f25e92760c | 3,451 |
from typing import Dict
from typing import Union
from typing import List
from typing import Optional
def _parse_parameter_from_value(
string: str,
parameter_to_wordlist_mapping: Dict[Union[TimeResolution, PeriodType, Parameter], List[List[str]]]
) -> Optional[Union[TimeResolution, PeriodType, Paramete... | 0fa1e2f7edf5e6be31e0e2ae514ecc22a512e8f7 | 3,452 |
def AffineMomentsF(I, returnShape=False):
"""
Input: - I: A 2D image
Output: - Out: A (1x6) vector containing 6 moment features
"""
# ************************************************************************
# Modified for MRI feature extraction by the Department of Diagnostic
# and ... | cb275aeacb4c4350a738b424bae0a284f4d40043 | 3,453 |
def render(scene):
"""
:param scene: Scene description
:return: [H, W, 3] image
"""
# Construct rays from the camera's eye position through the screen coordinates
camera = scene['camera']
eye, ray_dir, H, W = generate_rays(camera)
# Ray-object intersections
scene_objects = scene['ob... | 35f8cf34fea266034a76f3857213fcb83e334174 | 3,454 |
def state_fidelity(state1, state2):
"""Return the state fidelity between two quantum states.
Either input may be a state vector, or a density matrix. The state
fidelity (F) for two density matrices is defined as::
F(rho1, rho2) = Tr[sqrt(sqrt(rho1).rho2.sqrt(rho1))] ^ 2
For a pure state and m... | 9df10584ce9376df5690ebaccaa07046778b097c | 3,455 |
def process_state(request):
"""Procesa una request GET o POST para consultar datos de provincias.
En caso de ocurrir un error de parseo, se retorna una respuesta HTTP 400.
Args:
request (flask.Request): Request GET o POST de flask.
Returns:
flask.Response: respuesta HTTP
"""
r... | 8e748dd73845438f768ecd34730a94c2e8696387 | 3,456 |
def is_ascii(string):
"""Return True is string contains only is us-ascii encoded characters."""
def is_ascii_char(char):
return 0 <= ord(char) <= 127
return all(is_ascii_char(char) for char in string) | cd3aeddcad7610de83af6ec5a67ecbac95f11fd8 | 3,457 |
from typing import Union
from typing import Tuple
from typing import Optional
from typing import List
def _get_predictions_from_data(
model: Union[Model, SKLEARN_MODELS],
data: Union[
tf.data.Dataset,
Tuple[Inputs, Outputs],
Tuple[Inputs, Outputs, Paths],
],
batch_size: Optiona... | 29a91481989d283ac1dddd831a9746ada5971a5a | 3,458 |
import pickle
def get_data(data, frame_nos, dataset, topic, usernum, fps, milisec, width, height, view_width, view_height):
"""
Read and return the viewport data
"""
VIEW_PATH = '../../Viewport/'
view_info = pickle.load(open(VIEW_PATH + 'ds{}/viewport_ds{}_topic{}_user{}'.format(dataset, dataset, topic, usernum... | f78f3b7505b3ca5ab2cac67f2634b71cfa383707 | 3,459 |
import os
import requests
def getListGroups(config):
"""
Get list of groups
"""
print("Retrieve list of group")
data = None
grpList = None
__grpList = gitlabGroupList()
if (DUMMY_DATA):
curDir = os.path.dirname(os.path.abspath(__file__))
testFile = getFullFilePath(GROU... | 4c50964a5954d0132659297e0469119a150e20fd | 3,460 |
import copy
def call(args, version):
"""Converts callList into functionString."""
# Find keyword
keywords = [i for i in args if i in Variables.keywords(version)]
# Too many keywords is a syntax error.
if len(keywords) > 1:
raise UdebsSyntaxError("CallList contains to many keywords '{}'".f... | 0f5be8582903973ec3ae4077e51a11e084bcc2f8 | 3,461 |
from typing import List
from typing import Dict
from typing import Any
import ray
def get_object_locations(obj_refs: List[ObjectRef], timeout_ms: int = -1
) -> Dict[ObjectRef, Dict[str, Any]]:
"""Lookup the locations for a list of objects.
It returns a dict maps from an object to its... | c7b4aa6761024853468e09f846af0ada8f7ebbba | 3,462 |
from conf.hosts import getPlateformObject
from core.exceptions import EnvironmentDoesNotExist
def remove_host(plateform=None, name=None, environment=None):
""" Remove Host Object from Platform Object attribute hosts and return updated Platform Object.
:param: plateform: host's plateform (same as type yam... | bc8e8681718f763c382230297087b9ce27a37e20 | 3,463 |
import argparse
def command_line_parsing():
""" Parse the command line arguments, set global TESTING and return the
current position as a tuple (either default or one given on command line """
global TESTING
parser = argparse.ArgumentParser(description='Food Truck Finder.')
parser.add_argument('l... | 511fcd1893767fd93a73f112f7e6230d05ea2562 | 3,464 |
def read_samplesheet(config):
"""
read samplesheet
"""
sample_sheet = pd.read_csv(config["info_dict"]["flowcell_path"]+"/SampleSheet.csv",
sep = ",", skiprows=[0])
# sample_sheet = sample_sheet.fillna("no_bc")
sample_sheet['I7_Index_ID'] = sample_sheet['I7_Inde... | 7bd47c5af471862600fd9c2522f018a463ddeac4 | 3,465 |
def convert_to_float_if_possible(x, elsevalue=MISSING):
"""
Return float version of value x, else elsevalue (MISSING or other specified value
if conversion fails
"""
if isnonnumeric(x):
return elsevalue
else:
return float(x) | 74b1ca5d4ed63758ef9d56fb2be94cbbdec00b56 | 3,466 |
from typing import Union
import requests
def resolve(
names: Union[list, pd.Series, str],
data_source_ids: list = None,
resolve_once: bool = False,
best_match_only: bool = False,
with_context: bool = False,
with_vernaculars: bool = False,
with_canonical_ranks: bool = False
) -> pd.DataFram... | a25bd275e8222058e5926bf9a8b53de7a1cb3ccc | 3,467 |
import numpy
def polarisation_frame_from_wcs(wcs, shape) -> PolarisationFrame:
"""Convert wcs to polarisation_frame
See FITS definition in Table 29 of https://fits.gsfc.nasa.gov/standard40/fits_standard40draft1.pdf
or subsequent revision
1 I Standard Stokes unpolarized
2 Q Standard Stoke... | a2ed057be23add9a6c2041a243286bf06519306f | 3,468 |
import random
import json
import logging
def _update_traffic_class(class_name, class_type, **kwargs):
"""
Perform a PUT call to version-up a traffic class. This is required whenever entries of a traffic class are changed
in any way.
:param class_name: Alphanumeric name of the traffic class
:param... | 8a19fedcce20a94a3e5c8f06f7fb1ee901dcc6dd | 3,469 |
def eff_w_error(n_before, n_after):
"""
n_before = entries before
n_after = entries after
"""
eff = n_after/n_before
eff_error = np.sqrt(eff*(1-eff)/n_before)
return (eff, eff_error) | 307945af0acc2eb04686b5453f2905be1111944a | 3,470 |
import scipy
def hurst(x):
"""Estimate Hurst exponent on a timeseries.
The estimation is based on the second order discrete derivative.
Parameters
----------
x : 1D numpy array
The timeseries to estimate the Hurst exponent for.
Returns
-------
h : float
The estimatio... | 0632f0e4c5912410568c25774c1da66c160ff78e | 3,471 |
import yaml
def explode_on_matched_columns(df, safe_columns, other_columns):
"""Given the name of multiple columns where each entry is a string encoding
a list, and where for each row the lists in all columns are the same length,
return a dataframe where the each row is transformed into len(list)
rows... | 4f38310e563c8081ee7297ec2af2211ca8084504 | 3,472 |
import networkx
def plot_time_series_graph(val_matrix,
var_names=None,
fig_ax=None,
figsize=None,
sig_thres=None,
link_matrix=None,
link_colorbar_label='MCI',
save_name=None,
link_width=None,
arrow_linewidth=20.,
vmin_edges=-1,
vm... | e4acb78dbb8809f3b1604b4a44437c775c0cdfb7 | 3,473 |
def get_configuration_docname(doctype=None, txt=None, searchfield=None, start=None, page_len=None, filters=None):
"""get relevant fields of the configuration doctype"""
return frappe.db.sql("""select soi.configuration_docname, so.name, so.customer from `tabSales Order Item` soi
inner join `tabSales Order` so on ... | fb9494aacfbff6ec77f0e512daab35ffcd9c7fb9 | 3,474 |
import pickle
def run_cnn_dist(
X_bytes: bytes,
) -> bytes:
"""Run distributed CNN on bytes_in and return the calculated result."""
X = pickle.loads(X_bytes)
# TODO: <He> Process the X data with the fancy neural network.
result_data = X
# MARK: Metadata could be added here to mark the proces... | 4a1996ed0ddc0ae8be0543c1de016f845b99020e | 3,475 |
import requests
import re
def skymapper_search(searchrad,waveband,targetra,targetdec):
""" Search for stars within search radius of target in Skymapper
catalogue
"""
# set up arrays and url
star_ra = []
star_dec = []
star_mag = []
star_magerr = []
sky_ra = []
sky_dec = []
sky_u_petro = []
sky_u_petro_e... | 3ebed23f2ec73f6a8e859e645a2c3b5f936ac674 | 3,476 |
import random
def Decimal_to_Hexadecimal(x : str) -> str:
"""
It Converts the Given Decimal Number into Hexadecimal Number System of Base `16` and takes input in `str` form
Args:
x `(str)` : It is the Positional Argument by order which stores the Decimal Input from User.
Returns ... | ffe5050a834a9111a50f28c425f1bd21f60605ff | 3,477 |
def hardcorenas_d(pretrained=False, **kwargs):
""" hardcorenas_D """
arch_def = [['ds_r1_k3_s1_e1_c16_nre'], ['ir_r1_k5_s2_e3_c24_nre_se0.25', 'ir_r1_k5_s1_e3_c24_nre_se0.25'],
['ir_r1_k5_s2_e3_c40_nre_se0.25', 'ir_r1_k5_s1_e4_c40_nre_se0.25', 'ir_r1_k3_s1_e3_c40_nre_se0.25'],
['... | ff9be560a0061101fd672bd115fbfd8920537177 | 3,478 |
import tqdm
def refine(weights, trees, X, Y, epochs, lr, batch_size, optimizer, verbose):
"""Performs SGD using the MSE loss over the leaf nodes of the given trees on the given data. The weights of each tree are respected during optimization but not optimized.
Args:
weights (np.array): The weights o... | 6704e36b61ac9bda65ba0e118590aa2b627c8e2a | 3,479 |
from typing import ClassVar
from typing import Any
from typing import Dict
def fetch_db_object(cls: ClassVar, body: Any):
"""Fetch a database object via SQLAlchemy.
:param cls: the class of object to fetch.
:param body: the body of the object. If the body is None then None is returned (for the case where... | ae4a96ac9875d5b936df1d9c05f8a022a9a4b51e | 3,480 |
def should_skip_cred_test():
"""
Returns `True` if a test requiring credentials should be skipped.
Otherwise returns `False`
"""
if username is None or password is None:
return True
return False | c5f45a20f7febc100a2f2eb950697c91837e0281 | 3,481 |
from typing import List
from pathlib import Path
def list_input_images(img_dir_or_csv: str,
bucket_name: str = None,
glob_patterns: List = None):
"""
Create list of images from given directory or csv file.
:param img_dir_or_csv: (str) directory containing input... | 0dccd2d0356b8f89991a1ab1f8a621e696918ab5 | 3,482 |
def get_insta_links(L: Instaloader, url: str) -> tuple:
"""
Return list of shortcodes
:param url: URL
:return: success status and list of shortcodes
"""
try:
shortcode = get_insta_shortcode(url)
post = Post.from_shortcode(L.context, shortcode)
return True, post
exc... | 6ee9eac712d4603d1b7cffedd11cf07e4345ec0a | 3,483 |
import re
import os
def read_snli(data_dir, is_train):
"""将SNLI数据集解析为前提、假设和标签"""
def extract_text(s):
# 删除我们不会使用的信息
s = re.sub('\\(', '', s)
s = re.sub('\\)', '', s)
# 用一个空格替换两个或多个连续的空格
s = re.sub('\\s{2,}', ' ', s)
return s.strip()
label_set = {'entailment'... | 96f552d900327a2c78c69f1a0b9aa9188852cf89 | 3,484 |
async def http_request_callback(_request: HttpRequest) -> HttpResponse:
"""A response handler which returns some text"""
with open(__file__, 'rb') as file_pointer:
buf = file_pointer.read()
headers = [
(b'content-type', b'text/plain'),
(b'content-length', str(len(buf)).encode('ascii... | 2c5bdf2e4617c7780fe9c8d0b4a65b363e05babc | 3,485 |
import os
def ensure_directory_exists(directory, domain=None, permissions=0o777):
"""Create a directory and give access rights to all
Args:
directory (str): Root directory
domain (str): Domain. Basically a subdirectory to prevent things like
overlapping signal filenames.... | 0fe89ea6d23deffa67260bb9a465a3189fde6d0d | 3,486 |
from typing import Tuple
from typing import List
from typing import Union
def item_coverage(
possible_users_items: Tuple[List[Union[int, str]], List[Union[int, str]]],
recommendations: List[Tuple[Union[int, str], Union[int, str]]],
) -> float:
"""
Calculates the coverage value for items in possible_us... | f3eb59e0146561c8a18f74c548539b8cc9dcbb5b | 3,487 |
def calc_area(img_it, contours, conv_sq, list_save):
"""
Summary
Parameters
----------
yearstr : TYPE
DESCRIPTION.
Returns
-------
TYPE
DESCRIPTION.
"""
# Calculate areas
sum_file = 0
for c in contours:
M = cv2.moments(c)
area = M['m00']... | f3bdba8892041edfe5ba0497c927f846fd8110d9 | 3,488 |
def truth_seed_box(true_params, init_range, az_ind=4, zen_ind=5):
"""generate initial box limits from the true params
Parameters
----------
true_params : np.ndarray
init_range : np.ndarray
Returns
-------
np.ndarray
shape is (n_params, 2); returned energy limits are in units of... | 3c3087702be4b91589f7e75f5c7e2f18776a658a | 3,489 |
from xia2.Driver.DriverFactory import DriverFactory
from xia2.Handlers.Streams import Debug
def Report(DriverType=None):
"""A factory for ReportWrapper classes."""
DriverInstance = DriverFactory.Driver(DriverType)
class ReportWrapper(DriverInstance.__class__):
def __init__(self):
Dr... | 918ed6d0acad9d80fdd9c0a1ef6e33a19216c8c9 | 3,490 |
def summary(task):
"""Given an ImportTask, produce a short string identifying the
object.
"""
if task.is_album:
return u'{0} - {1}'.format(task.cur_artist, task.cur_album)
else:
return u'{0} - {1}'.format(task.item.artist, task.item.title) | 87387c47e90998c270f6f8f2f63ceacebd4cdc78 | 3,491 |
def ds_tc_resnet_model_params(use_tf_fft=False):
"""Generate parameters for ds_tc_resnet model."""
# model parameters
model_name = 'ds_tc_resnet'
params = model_params.HOTWORD_MODEL_PARAMS[model_name]
params.causal_data_frame_padding = 1 # causal padding on DataFrame
params.clip_duration_ms = 160
params... | b018fa56efd67d8378496d5b4b1975580fc92f89 | 3,492 |
def expected_calibration_error_evaluator(test_data: pd.DataFrame,
prediction_column: str = "prediction",
target_column: str = "target",
eval_name: str = None,
... | 0f34a5c0883325324b11fd9b97a8a55250574392 | 3,493 |
def format_bytes(size):
"""
Takes a byte size (int) and returns a formatted, human-interpretable string
"""
# 2**10 = 1024
power = 2 ** 10
n = 0
power_labels = {0: " bytes", 1: "KB", 2: "MB", 3: "GB", 4: "TB"}
while size >= power:
size /= power
n += 1
return str(round... | 332b9d43c044da92ef7a9b16e57cfa7d552de12f | 3,494 |
def load_input_data(filenames, Ag_class):
"""
Load the files specified in filenames.
Parameters
---
filenames: a list of names that specify the files to
be loaded.
Ag_class: classification of sequences from MiXCR txt file
(i.e., antigen binder = 1, non-binder = 0)
""... | 9ae9cc814f150168ca1703b1a4af54bc440b4425 | 3,495 |
from typing import Optional
def get_maximum_value(
inclusive: Optional[Edge] = None,
exclusive: Optional[Edge] = None,
ignore_unlimited: bool = False,
) -> Result[Boundary, TestplatesError]:
"""
Gets maximum boundary.
:param inclusive: inclusive boundary value or None
:param exclusive: e... | 3ef7557ed3f7f353e0765a92fb008449409039a8 | 3,496 |
from typing import List
def build_graph(order: int, edges: List[List[int]]) -> List[List[int]]:
"""Builds an adjacency list from the edges of an undirected graph."""
adj = [[] for _ in range(order)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
return adj | 86bdd0d4314777ff59078b1c0f639e9439f0ac08 | 3,497 |
import torch
import math
def construct_scheduler(
optimizer,
cfg: OmegaConf,
):
"""
Creates a learning rate scheduler for a given model
:param optimizer: the optimizer to be used
:return: scheduler
"""
# Unpack values from cfg.train.scheduler_params
scheduler_type = cfg.train.sche... | d0ed907aa3582978cb3adf5eada895366dc1282f | 3,498 |
import numpy
def GenerateSerialGraph(num_samples, block_size):
""" Generates a (consistent) serial graph. """
N = num_samples
num_blocks = N // block_size
if N % block_size != 0:
err = "num_samples(%d) must be a multiple of block_size (%d)" % (num_samples, block_size)
raise Exception(... | 7348c08051aa0b7ec51f79f1f6f2097ab5857ef8 | 3,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.