content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _calculate_euclidean_similarity(distances, zero_distance):
"""Calculates the euclidean distance between two sets of detections, and then converts this into a similarity
measure with values between 0 and 1 using the following formula: sim = max(0, 1 - dist/zero_distance).
The default zero_distance of 2.0... | d14882504004220143c136e20a32290afe378e32 | 3,623,800 |
import json
import requests
def setInitialParameters(initialSuggestions):
"""Initial parameters for optimization problem being solved"""
global params
params = initialSuggestions
sugjson = json.dumps(list(initialSuggestions))
apipath = __SERVER_HOST__ + __SERVER_PARAMETERS_API__ + "/" + s... | c714663372e57f2d8475eef41d2ce6054a642c0a | 3,623,801 |
def compute_signature_strength(cpds_list, df, metadata_cols = metadata_cols):
"""Computes signature strength for each compound based on its replicates"""
cpds_SS = {}
for cpd in cpds_list:
cpd_replicates = df[df['pert_iname'] == cpd].copy()
cpd_replicates.drop(metadata_cols, axis = 1, i... | 6f5ac11cb5ded6aa1b6ae33cd11db872742335d6 | 3,623,802 |
from sys import path
def include_all_subfiles(*args):
"""Slurps up all files in a directory (non recursive) for data_files section
Note:
Not recursive, only includes flat files
Returns:
list: all non-directories in a file
"""
file_list = []
for path_included in args:
... | f51c0127478faee0ceeb2011a99dccfcf2928206 | 3,623,803 |
import os
import pickle
def _unpack_value(value):
"""
Unpack contents if it is pickled to a temporary file.
:param value:
A non-string variable or a string referring to a pickled file path.
:returns:
The original value, or the unpacked contents if a valid path was given.
"""
... | 47218e7f8ca079831fddf5c9adc6a02304b08a4c | 3,623,804 |
def join_3_query():
"""Finds all players from country X who scored at least one goal in a game played in Y city and Z year."""
desired_country = "Brazil"
desired_gameDest = "Europe"
desired_gameYear = 2017
sql = text('''SELECT distinct a.name, a.teamID, a.status, a.salary
FROM Ath... | 751a0be79e27e9f71e22d3f84a07399711dce7f2 | 3,623,805 |
def calc_ac_fit(df, objects):
"""
created dataframe of features
for train objects
"""
object_ids, ac_decay, ac_decay_err, ac_loss, ac_amp, ac_amp_err = (
[],
[],
[],
[],
[],
[],
)
for obj in objects:
obj_df = df[(df.object_id == obj)... | 12076c6021feaab949d5044766487558d24ca2a4 | 3,623,806 |
from typing import List
def get_forge_plugin_command_names() -> List[str]:
""" Returns a list of plugin command names"""
return [
get_command_from_config(plugin_config)
for plugin_config in get_plugins()
] | f6c747df98d418a90baeed5cffbbee77f18ee106 | 3,623,807 |
def array_to_datetime(array):
"""
Convert an 1d datetime array from various types into pandas.DatetimeIndex
(i.e., numpy.datetime64).
If the input array is not in legal datetime formats, raise a "ParseError"
exception.
Parameters
----------
array : list or 1d array
The input da... | 3fa1280ad9b84416f5000f01497a615bbba5099e | 3,623,808 |
import os
import subprocess
def _save_cover_image(dirname, filename):
"""Save the cover image to the album folder.
:arg str dirname: the album folder name
:arg str filename: the cover image file name
:return: ``True`` if the cover image was saved, otherwise ``False``
"""
image_ext = os.path.... | 5f9033c31e067feec74e5899a1b1c4f5f90e0d9c | 3,623,809 |
def then(name, converters=None):
"""Then step decorator.
:param name: Step name or a parser object.
:param converters: Optional `dict` of the argument or parameter converters in form
{<param_name>: <converter function>}.
:return: Decorator function for the step.
"""
retu... | 55baabeecb74f56390da45804091dab3ce755ab3 | 3,623,810 |
import json
def get_stored_username():
"""get stored username if available"""
file_name = 'chapter_10/remember.json'
try:
with open(file_name) as f_o:
usern = json.load(f_o)
except FileNotFoundError:
return None
else:
return usern | 6abe0542a882fe01f63c5392d112514595a167d7 | 3,623,811 |
import json
def evaluate(gt_file, re_file, logger=None):
"""
This function is reformed from MSCOCO evaluating code.
The reference sentences are read from gt_file,
the generated sentences to be evaluated are read from res_file
"""
gts = json.load(open(gt_file, 'r'))
scorers = [
(B... | a51e768a38c34add431cd5b20002fd63641a5151 | 3,623,812 |
def redis_error_handler(func):
"""Decorator for returning better errors if Redis is unreachable"""
def wrapper(*args, **kwargs):
try:
if 'body' in kwargs:
# Our get/patch functions don't take body, but the **kwargs
# in the arguments to this wrapper cause it t... | d699f4c846a3e0e6788e73bdd32ff894997a96a7 | 3,623,813 |
def find_versions_from_versioncontrol(dependencies):
"""Determine whether a file is under version control, and if so,
obtain version information from this."""
for dependency in dependencies:
if dependency.version == "unknown":
try:
wc = versioncontrol.get_working_copy(... | 631d2d193e8b4e066675e465c66da171b0e1417c | 3,623,814 |
import pdb
def findDistortionCoefficients(filename,Nx,Ny,method='cubic'):
"""
Fit L-L coefficients to distortion data produced by Vanessa.
"""
#Load in data
d = np.transpose(np.genfromtxt(filename,skip_header=1,delimiter=','))
#Compute angle and radial perturbations
x0,y0,z0 = d[2:5]
... | bb24aa3d0e44bf0bbf75966b8aa8b2df1fdded24 | 3,623,815 |
import six
def keras_test(func):
"""Function wrapper to clean up after TensorFlow tests.
# Arguments
func: test function to clean up after.
# Returns
A function wrapping the input function.
"""
@six.wraps(func)
def wrapper(*args, **kwargs):
output = func(*args, **kwarg... | 1d6224d91597cb1baf6a6ba92c9a228e9ca83304 | 3,623,816 |
def drawbox(img,bbox):
"""
skeleton function which draws bbox on an img
:param img:
:param bbox:
:return:
"""
return img | c1f56b17d3f78333f7c6e9cd5dcda0b0d792040c | 3,623,817 |
from typing import Any
def is_valid_route_protection(protection: Any) -> bool:
"""Checks if the protection text is a valid protection name.
Returns True if valid, False if not."""
if not isinstance(protection, str):
return False
# Once the protection scheme is established, this can be loosened... | 00ea1980fbd38523de0d39b63fa29d0d1f4626f7 | 3,623,818 |
from pathlib import Path
def open_CsvDataset(filename, delimiter=',', M='M', T='T', tlabels=False, varnames=False, parameter='climate_var'):
"""opens a .csv file formatted like n_samples x m_features. returns Xarray DataArray with X=0, Y=0, Samples=N, features=M.
Can include labels for each sample, and labels for e... | d4841240212d037006fe84768aaf1620fc02929e | 3,623,819 |
from io import StringIO
import sys
def paster(*args, **kwargs):
"""
Call a paster command.
All arguments are parsed and passed on to the command. The
``--config`` option is automatically appended.
By default, an ``AssertionError`` is raised if the command exits
with a non-zero return code or... | 81d515ab72768e96dde06d7fdec5a10f7d43ebbf | 3,623,820 |
def parse_coalesce_object_response(coalesce_object_response):
"""
Parse a response from RpcGetObject.
Returns (modification time, inode no., no. writes).
"""
return (_ctime_or_mtime(coalesce_object_response),
coalesce_object_response["InodeNumber"],
coalesce_object_response[... | 18af73840346f6770d464de94ca80cc692baae5a | 3,623,821 |
from typing import Dict
from typing import List
def make_hist_dict(
bin_edges: Dict[str, Dict[str, str]],
adj: bool,
hist_metric_list: List[str] = HISTS,
label_delimiter: str = "_",
) -> Dict[str, str]:
"""
Generate dictionary of Number and Description attributes to be used in the VCF header, ... | 01b2969900f9cb41a26d89e5779c565bd9002bbd | 3,623,822 |
def create_running_ema(alpha=0.95, initial=0):
"""
Returns a function to compute running
exponentially weighted averaging
Args:
alpha (0.95): relative importance of accumulated value
initial (0): initial value
"""
return partial(running_f,
f=lambda acc, elem: alpha*a... | c19d3df9fcb245d07e5eebba30ec5a1e967179dc | 3,623,823 |
from typing import Optional
def get_tarred_char_dataset(
config: dict, shuffle_n: int, global_rank: int, world_size: int, augmentor: Optional['AudioAugmentor'] = None
) -> audio_to_text.TarredAudioToCharDataset:
"""
Instantiates a Character Encoding based TarredAudioToCharDataset.
Args:
confi... | 8227bf532db08eefa44b71d069e6e6661e68b10f | 3,623,824 |
import sys
import os
def import_flow_env(env_name, render, shared, maddpg, evaluate):
"""Import an environment from the flow/examples folder.
This method imports the flow_params dict from the exp_configs folders in
this directory and generates an appropriate FlowEnv object.
Parameters
----------... | 970978dd15cc452d0a31b6d198d1aab459fa71d9 | 3,623,825 |
def gtf_row_to_bed(row):
""" Converts gtf row to bed format:
Args:
row (pd.Series): One GTF row
Returns:
pd.Series([chrom, start, end, ensID, "."])
"""
# Extract required fields
chrom = str(row[0])
strand = row[6]
# Take end of transcript for forward/reverse strand
if... | 06bfbaf6668758385dcc070d2504285fa7e465b2 | 3,623,826 |
import os
def getFileName(prompt):
"""Prompts the user for a valid file which it returns.
"""
while True:
fileName = input(prompt+" ")
if os.path.exists(fileName):
return fileName
else:
print("File not found! Make sure that the file is inside this directory.... | f1814ce49e79923a8c6e935d78b7362a2fba2f15 | 3,623,827 |
def mtotal_from_mtotal_source_z(total_mass_source, z):
"""Return the detector-frame total mass of the binary given samples for
the source-frame total mass and redshift
"""
return _detector_from_source(total_mass_source, z) | 715bd3d4b8a93d63ed51b7e7437d0dde88777acf | 3,623,828 |
def sim_spiketrain(spike_param, n_samples, method, refractory=None, **kwargs):
"""Simulate a spike train.
Parameters
----------
spike_param : float
Parameter value that controls the simulated spiking. rate or probability.
For `prob` or `binom` methods, this is the probability of spiking... | 73c4ec8519884374c34cb0cefd811a337a6c83a9 | 3,623,829 |
def weight_mask_variable(var, scope):
"""Create a mask for the weights.
This function adds a variable 'mask' to the graph.
Args:
var: the weight variable that needs to be masked
scope: The variable scope of the variable var
Returns:
the mask variable of the same size and shape as var, initialized... | 203d607fc203de794a5d13e19b1200cce80641f5 | 3,623,830 |
def youngest_oldest(_dict):
"""Return youngest and oldest billionaires."""
oldest = None
youngest = float('inf')
for person in _dict:
if person['age'] < 80:
if oldest is not None:
if person['age'] > oldest['age']:
oldest = person
else:
... | 9c7bd8834701fc6136447c6693c22efc2461f26b | 3,623,831 |
import torch
def build_optimizer(model: nn.Module, args: Namespace) -> Optimizer:
"""
Builds an Optimizer.
:param model: The model to optimize.
:param args: Arguments.
:return: An initialized Optimizer.
"""
if hasattr(model, 'ffn'):
ignored_params = list(map(id, model.ffn.paramete... | a2bff3a42713c36f361686dc73322eccebdeb5cb | 3,623,832 |
def mock_request(params: dict = None, data=None, **headers) -> Request:
"""
Mocks a Request object so the @pre_process decorator can inject it
as an APIRequest.
:param params: Optional query parameter dict for the request.
Will be set to {} if omitted.
:param data: Optional data/... | 4c06f33adf9098356305ded18593a9eafa2e9aa2 | 3,623,833 |
import requests
import time
def get_management_token() -> dict:
"""
Gets a token for contacting the management endpoint of auth0.
Returns:
dict -- Dictionary with token and expirey information.
"""
payload = {
'grant_type': 'client_credentials',
'client_id': CLIENT_ID,
... | c293ed416b6850033f2a9b3b82381008d2475bb5 | 3,623,834 |
def simulate(t=1000, poly=(0.,), sinusoids=None, sigma=0, rw=0, irw=0, rrw=0):
"""Simulate a random signal with seasonal (sinusoids), linear and quadratic trend, RW, IRW, and RRW
Arguments:
t (int or list of float): number of samples or time vector, default = 1000
poly (list of float): polynomial c... | d6c747937340a181b6eb99f3c5c539f7c920705e | 3,623,835 |
def get_rgb_image(image: Image):
"""Convert the image to rgb format."""
# logger.debug("Computing rgb image")
if image.band == 'rgb':
red = image['red']
green = image['green']
blue = image['blue']
rgb = np.ma.dstack([red, green, blue])
else:
gray = image[image... | 9aed7b48fe1619fd6cf182d75dde679a7b0f6b88 | 3,623,836 |
def gen_cookie(username, hash_password):
"""
Build secure cookie content as a string containing:
- content length (excluding length itself)
- role_name
- 16 first chars of the hash password
Part of hash password is there for 2 main reasons:
1/ If the cookie secret key is st... | 44b0ec056bd7002aea7b63fb57901dc1180cb45c | 3,623,837 |
def line_generic(pos, color=(1, 1, 1, 1), width=0.1, antialias=True, mode='line_strip'):
"""
Add a pyqtgraph.opengl.GLLinePlotItem to GPGLViewWidget, with exactly the same arguments.
For detail, consult documentation of pyqtgraph.opengl.GLLinePlotItem:
http://www.pyqtgraph.org/documentation/3dgraphic... | 749189775a45cf78e20000e17edc734eed6b6bfa | 3,623,838 |
def create_dict(obj, columns):
"""
Create a dict, given a database record and an ordered list of columns.
Mind the order of column names in the columns list
"""
try:
new_obj = {}
for col in range(len(columns)):
new_obj[columns[col]] = obj[col]
return new_obj
... | 9ac55086e8e6e584849deb93d79e148054e835f7 | 3,623,839 |
def filepath_result_format(classifier_name, task, res, filepath):
"""
Helper function to produce result dictionary using filepath
filepath (str) : (e.g. '../../inferred_features/code_ss_w2v_multiclass_7.pkl'
"""
filepath = filepath.split("/")[-1]
dims = filepath.split(".")[0].split("_")
if d... | 3b2d508f02963840ca7c467b40edfc2813fae73d | 3,623,840 |
def get_optimisation_status():
"""Get the status of an optimisation job."""
opt_job_id = request.args.get('opt-job-id')
opt_job = database.opt_jobs.find_one({'_id': ObjectId(opt_job_id)})
return jsonify({'_id': opt_job_id, 'status': opt_job['status']}) | c02707aedc5dea50389c0ef061b3df89f9024b95 | 3,623,841 |
def makeCorrelationMatrixFromDictionary(value_dictionary, keys=[], matrix_file_name="temporary_matrix_file.txt", key_file_name="temporary_key_file.txt"):
"""
Returns numpy.matrix: matrix object of correlation coefficients, symmetric matrix with a diagonal of ones
Returns list: list of keys that correspond to the row... | 6faa71bd32050ed5b9005de7f199e8ed05622f89 | 3,623,842 |
import itertools
def pad(value, seq: Seq, size: int = None, step: int = None) -> Iter:
"""
Fill resulting sequence with value after the first sequence terminates.
Args:
value:
Value used to pad sequence.
seq:
Input sequence.
size:
Optional minim... | b2ee68adf9e0bb760547fcc4c029b16df3f7dff3 | 3,623,843 |
def str_to_state(str_state):
""" Reads a sequence of 9 digits and returns the corresponding state. """
assert len(str_state) == 9 and sorted(str_state) == list('012345678')
return tuple(int(c) for c in str_state) | 8e9e8c2b70f86aa4798f9be14d39c43404336e7a | 3,623,844 |
def linearly_interpolate(colors: ColorMatrix, count: int):
"""
Generates :count: colors from this palette, interpolating
intermediate colors if necessary.
TODO(saumitro): Lift interpolation to perceptual space
"""
palette_size = len(colors)
if count <= palette_size:
return colors[:c... | f28422c33e3ee47e9af981732118ec02f2b11de0 | 3,623,845 |
def load_10x_h5(file, genome):
"""Load count matrix in 10x H5 format
Adapted from:
https://support.10xgenomics.com/single-cell-gene-expression/software/
pipelines/latest/advanced/h5_matrices
Args:
file (str): Path to H5 file
genome (str): genome, top level h5 group
Ret... | 743da441f08eceb211340d1078ad95ba0be99afc | 3,623,846 |
from typing import Optional
def to_dataset_entity_id(
full_name: str, platform: DataPlatform, account: Optional[str] = None
) -> EntityId:
"""
converts a dataset name, platform and account into a dataset entity ID
"""
return EntityId(
EntityType.DATASET,
DatasetLogicalID(name=full_... | cd93b34e43ef8f2b8cbda47ed1958430183fd57c | 3,623,847 |
import argparse
def parse_args():
"""parsing and configuration"""
parser = argparse.ArgumentParser(description="Generate ImageNet10 using BigGAN")
# for training generative model
parser.add_argument('--gan_type', type=str, default='BigGAN', help='The type of GAN')
parser.add_argument('--dataset',... | c1255653398aa6b1f964cf8ebbb8a1583bae6431 | 3,623,848 |
def get_collection_table_name(node, intermine_model):
"""
Get the table name for this collection
:param node:
:param intermine_model:
:return: (table-name, reference-column-name).
table-name will be null if there isn't a collection table for this node
"""
if 'reverse-reference' in ... | 06aff0058450263131ad27afbe136dd63eaf4320 | 3,623,849 |
import time
import gzip
def parse_xml(path: str) -> Element:
"""Parse an XML file from a path to a GZIP file."""
t = time.time()
log.info('parsing xml from %s', path)
with gzip.open(path) as xml_file:
tree = ET.parse(xml_file)
log.info('parsed xml in %.2f seconds', time.time() - t)
re... | 526908cc950339c5471c53613a096b3fb615a51e | 3,623,850 |
import string
def apply_qos():
"""POST QOS configuration from form data"""
find_int_num = [i for i in request.form.get("interface") if i not in string.ascii_letters]
find_int_type = [i for i in request.form.get("interface") if i in string.ascii_letters]
build_config = BuildConfig.build_interface_qos(... | c426b0c3bcd9ec75306475c43600cfff1f5da7ad | 3,623,851 |
def _readdir(DIR):
"""Implementation of perl readdir in scalar context"""
try:
result = (DIR[0])[DIR[1]]
DIR[1] += 1
return result
except IndexError:
return None | 0ebb237de9ea32fd11f7c6fc6e8a365420c65655 | 3,623,852 |
import sys
import os
import subprocess
def Update(version):
"""Requests an update of the toolchain to the specific hashes we have at
this revision. The update outputs a .json of the various configuration
information required to pass to vs_env.py which we use in
|SetEnvironmentForCPU()|.
"""
depot_tools_pa... | 8b1fb7ff7c62c54d3ebf9be7610fd6420892ccfb | 3,623,853 |
def compute_normalization(data):
"""
Write a function to take in a dataset and compute the means, and stds.
Return 6 elements: mean of s_t, std of s_t, mean of (s_t+1 - s_t), std of (s_t+1 - s_t), mean of actions, std of actions
"""
l = []
for a in [data['observations'], (data['next_observatio... | 521995f2611f66dc11bbe5cc3d3d40e04c97ff19 | 3,623,854 |
from typing import List
from typing import Callable
import tqdm
import os
def fast_back_test(bars: List[RawBar],
init_n: int,
strategy: Callable,
html_path: str = None,
max_bi_count: int = 50,
bi_min_len: int = 7,
... | c89e14d2a3cabb91010e15c226c15aa07e3b68e6 | 3,623,855 |
def convert_cidr_to_canonical_format(value):
"""CIDR is validated and converted to canonical format.
:param value: The CIDR which needs to be checked.
:returns: - 'value' if 'value' is CIDR with IPv4 address,
- CIDR with canonical IPv6 address if 'value' is IPv6 CIDR.
:raises: InvalidInpu... | a105c1eece32c0dd615fbe1e0082be95ade6666a | 3,623,856 |
def g_xyz_eclip_planet_eqxdate(name, jde):
"""
Parameters
----------
name : str
Name of the planet
jde : float
Julian Day of the ephemeris
Returns
-------
np.array[3]
"""
h_xyz_eclipt_earth = h_xyz_eclip_eqxdate("Earth",jde)
h_xyz_eclipt_planet = h_... | 9d8f29ca4af12cb369d89cc71e0428f571393d3d | 3,623,857 |
def get_cannot_db(state_brief_db):
"""
Determine for each position register (identified by acceptance_id) the set of
position registers. The condition for this is given at the entrance of this file.
RETURNS:
map:
acceptance_id --> list of pattern_ids that it cannot be c... | c889ef602ff7caff59974cbb2aa5cf47dafa7581 | 3,623,858 |
def _unique_numpy_dtype_string(dtype):
"""Private function providing a standardized string used to characterize
a Numpy dtype
"""
dt = np.dtype(dtype)
try:
s = dt[0].str
except KeyError:
s = dt.str
return s[1:] | 9764a029da8a947b0e04da11e822df00a6d7be21 | 3,623,859 |
from re import S
def powsimp(expr, deep=False):
"""
Usage
=====
powsimp(expr, deep) -> reduces expression by combining powers with
similar bases and exponents.
Notes
=====
If deep is True then powsimp() will also simplify arguments of
functions. By default deep... | 55b3a28e7fbeca72ad07d588151a29fa3a4cc4ed | 3,623,860 |
def dictize(aniter, mode, initial=None):
"""iter must contain (key,value) pairs. mode is a string, one of: replace, keep,
tally, sum, append, or a custom function that takes two arguments.
replace: default dict behavior. New value overwrites old if key exists. This
is essentially a pass-thru.
... | c56a2ad83ec9a45e87caa7def33c6b51f63655cb | 3,623,861 |
def flatten_composition(EXX):
"""Convert the ternary composition of B2 into
a binary by taking out the vacancy composition
degree of freedom.
:EXX: ndarray (E, xa, xb)
:returns: ndarray (E,x)
"""
E=EXX[:,0]
a=EXX[:,1]
b=EXX[:,2]
xNi=1+a-b
xAl=1-a
xVa=b
x=xNi/(xNi+... | 3f2c2340214bfb36c97ee5e78189202fef12d921 | 3,623,862 |
def param_Valide_Algo_3(Lambda) :
"""Il faut que lambda soit valide"""
return valide_Lambda(Lambda) | 8b93ec29b1bdc0c9e6e55b6c640e7a0ed6e3e760 | 3,623,863 |
def extract_from(treatment):
"""Extract the data from the genus treatment.
Parameters:
treatment - a pdf file name of the genus treatment.
data_type - "locations" or "classifiers"
Returns a dict of results with the following format
"locations" - a string of species names and locat... | fdae872f08757b990b3bd13cf3ab298b11caa9cf | 3,623,864 |
from typing import Dict
from typing import Any
from typing import List
def make_snapshots_of_each_scope_vars(
*, locals_: Dict[str, Any], globals_: Dict[str, Any]) -> str:
"""
Make snapshots of each scope's variables.
Parameters
----------
locals_ : dict
Local scope's variables.
... | 13747146eb30ffaf8629d30e8033adcd25ec9fe2 | 3,623,865 |
def get_registered_themes():
"""Get registered themes.
Gets a list of registered themes in form of tuple (plugin name, plugin
description). If not yet auto-discovered, auto-discovers them.
:return list:
"""
return get_registered_plugins(theme_registry) | 582dc847c1e7a1118669ee1fe991ac2546201f23 | 3,623,866 |
def polyfit2d(pmap):
"""
Fit a 2nd order polynomial surface (paraboloid) to the map of Pearson's correlation
coefficients (pmap) and return a list (a) containing the fit parameters.
Model: C(i, j) = a0*i*i + a1*j*j + a2*i*j + a3*i + a4*j + a5
where (i, j) are the rows and columns in pmap.
:pa... | dbf8416537219c8ad64b0dbb4909a07982d765db | 3,623,867 |
def apriori_zc(data_set, data_set_dict, min_support=5):
"""
Apriori算法过程
:param data_set: 数据集
:param min_support: 最小支持度,默认值 0.5
:return:
"""
c1 = init_c1(data_set_dict, min_support)
data = map(set, data_set) # 将dataSet集合化,以满足scanD的格式要求
freq_items = {}
l1 = scan_data(data, c1, min... | 5396c045e3e80bd3b2a5ca78b0cf4cca18c622b7 | 3,623,868 |
def find_replace_line_endings(fp_readlines):
"""
special find and replace function
to clean up line endings in the file
from end or starttag characters
"""
clean = []
for line in fp_readlines:
if line.endswith("=<\n"):
line = line.replace("<\n", "lt\n")
clean.appe... | 1fa3703b6d244d6b51c17c95a8cd71e48d5ebc9d | 3,623,869 |
def process_properties(partition, vfunction, params):
"""
Process the properties specified in the 'properties' module parameter,
and return two dictionaries (create_props, update_props) that contain
the properties that can be created, and the properties that can be updated,
respectively. If the reso... | 0bb17cca4f742fb909987d948145ce1bfb52285e | 3,623,870 |
def resize_and_project(features,
resize_size,
num_projection_layers,
num_projection_channels):
"""Resizes input features and passes them through a projection head.
Args:
features: A [batch_size, height, width, num_channels] tensor
resize_... | 1fcd54728f4ffc582d9863fe549ce21570b5e245 | 3,623,871 |
import requests
def _download_file_from_google_drive(id_file, destination, proxy=None):
"""
From https://stackoverflow.com/a/39225272/8195528.
"""
def get_confirm_token(response):
for key, value in response.cookies.items():
if key.startswith('download_warning'):
re... | 95647eeaa58cef7367adbae9015badde0aeeb4c6 | 3,623,872 |
from typing import Optional
def generate_text_consumer(filter_pattern: Optional[str]) -> ObservabilityEventConsumer:
"""
Creates a console event consumer, which is used to display events in the user's console
Parameters
----------
filter_pattern : str
Filter pattern is used to display cer... | 3c5d10b95b05bd2b61ad3b7be7381a16c3a9ee1b | 3,623,873 |
def verify_lacp_link_state(device,
interface,
links,
state_name,
expected_state,
max_time=30,
check_interval=10):
""" Verify links of lag interface
... | 900aee30781374e1ce61e38af6fb6c3393eec08a | 3,623,874 |
def wfc3_bandpass(request):
"""Fixture to read in the pysynphot bandpass for a WFC3 filter"""
return nebulio.Bandpass(','.join(['wfc3', 'uvis1', request.param])) | 62b461a5ffc9e063b43caec9942e8c6bcb1513dd | 3,623,875 |
import tqdm
def adaptive_basic_iterative_method(sess, model, X, Y, eps, eps_iter, nb_iter=50,
clip_min=None, clip_max=None, batch_size=256,
log_dir = None, model_logits = None,
binary_steps =2, attack_type = "bim-b",
... | 2bafcfd6bb07a1fb223fcfcb52fc829d31ea7037 | 3,623,876 |
def exists(profile, name):
"""Check if a role exists.
Args:
profile
A profile to connect to AWS with.
name
The name of a role.
Returns:
True if it exists, False if it doesn't.
"""
result = fetch_by_name(profile, name)
return len(result) > 0 | bebf4cd514e9cbb2896b439c245c75b9b2c1f019 | 3,623,877 |
def _right_h5(value: list, fmt: str, meta: dict) -> dict:
"""Right-aligned header 5."""
return Plain([RawInline(fmt, '<h5 style="text-align:right !important">')]
+ value + [RawInline(fmt, '</h5>')]) | 811c89673d88cc090861e23551481a85f9f5bbd7 | 3,623,878 |
from typing import List
def find_long_period(bool_array: List, min_duration:int, scale:int) -> List:
"""find_long_period. identify long period of motion
:param bool_array: bool array with check of motion
:type bool_array: List
:param min_duration: minimum duration in index unit
:type min_duration... | ab30167289045cc4ed7ee06acec669f933a1461f | 3,623,879 |
import torch
def nnc_compile(model: torch.nn.Module, example_inputs) -> torch.nn.Module:
"""
nnc_compile(model, example_inputs) returns a function with the same args
as `model.forward`, with an extra argument corresponding to where the
output is stored. This function takes the inputs (which must be Py... | 15c686ec6a2b850ca0d2ef50e0e90a15392bb289 | 3,623,880 |
def _DeleteGridCellMetaData(zoom, x, y, uss_id):
"""Removes the USS entry in the metadata stored in a specific GridCell.
Removes the USS entry in the metadata using optimistic locking behavior.
Args:
zoom: zoom level in slippy tile format
x: x tile number in slippy tile format
y: y tile number in sl... | c106116efe48ffdeb6e9093c04bb5fe1a5fc81b6 | 3,623,881 |
def compute_speed(pos, pos_tt):
"""Compute boolean of whether the speed of the animal was above a threshold
for each time point
Parameters
----------
pos: np.ndarray(dtype=float)
in meters
pos_tt: np.ndarray(dtype=float)
in seconds
smooth_param: float, optional
Returns
... | f3176e459108127f79790bb67057cd316b3092c6 | 3,623,882 |
def unitsapi_Check(*args):
"""
* Checks the coherence between the quantity <aQuantity> and the unit <aUnits> in the current system and //! returns False when it's WRONG.
:param aQuantity:
:type aQuantity: char *
:param aUnit:
:type aUnit: char *
:rtype: bool
"""
return _UnitsAPI.unit... | c5f5d7c1730ed7953cbda2f758186e3e39877c41 | 3,623,883 |
def read_txt_file(file_path, n_num=-1, code_type='utf-8'):
"""
read .txt files, get all text or the previous n_num lines
:param file_path: string, the path of this file
:param n_num: int, denote the row number decided by \n, but -1 means all text
:param code_type: string, the code of this file
... | 9c55d370d8e8610965e0f8c4b1bed85e6adcdc5b | 3,623,884 |
import json
import re
def load_cluster(args):
"""
Load a single CourtListener cluster with its opinions from disk, and return metadata.
This is called within a process pool; see ingest_courtlistener for how it's used.
"""
cluster_member, opinions_dir = args
with cluster_member.open() a... | 9d5335d72172ae933f9d2e94a8bb5a3f316fc5b9 | 3,623,885 |
def annotate(data, image_column=None, annotation_column='annotations', image_similarity=True):
"""
Annotate your images loaded in either an SFrame or SArray Format
The annotate util is a GUI assisted application used to create labels in
SArray Image data. Specifying a column, with dtype Ima... | 450f0563664fec098152b96e948beae6ddcdf2c0 | 3,623,886 |
import re
import logging
def ParseSuccessMsg(msg):
"""Attempt to parse the message for a user_op_manager SUCCESS line and extract user, device, op, class, and method.
Return None otherwise.
"""
parsed = re.match(kSuccessMsgRe, msg)
if not parsed:
return None
try:
user, device, op, class_name, meth... | 2e7edccb1a8d15e16aadfaa3fcf4465d755b46c8 | 3,623,887 |
import math
def pow(x, y):
"""Return the logarithm of x with base y (default to e)"""
if x <= 0 and not isinstance(y, int):
raise ValueError(f"Exponent must be an integer if negative base. Received base {x} with exponent {y}.")
return math.pow(x, y) | 6ceb9957be3805c44db7c6b00e170db7ce27354f | 3,623,888 |
def GetWavelength():
""" Get a single frequency reading """
return getwave(DZERO) | 4b60655932762ae5e8157f2d7df12691e8162eed | 3,623,889 |
def sum_while_same(xs, x):
"""Sum points for same date representation"""
if not xs:
return [x]
if xs[-1][0] == x[0]:
return xs[:-1] + [(xs[-1][0], xs[-1][1] + x[1])]
else:
return xs + [x] | 646fc1873b582b3d9825cc69816e97de6f91bf3b | 3,623,890 |
def download_artifact_from_aml_uri(uri: str, destination: str, datastore_operation: DatastoreOperations):
"""Downloads artifact pointed to by URI of the form `azureml://...` to destination
:param str uri: AzureML uri of artifact to download
:param str destination: Path to download artifact to
:param Da... | 5a59f74ed03b348960905c5f579ffb87a4edd076 | 3,623,891 |
import os
import errno
import sys
import stat
import pwd
import grp
import time
def get_file_metadata(file_path, if_noent=None):
"""
Get a string with the metadata for a file.
For purposes of this function, 'file' includes directories,
symlinks, etc.
Format is similar to 'ls -l':
mode l... | 5d1c69623a4a1b33834862e98f4b95be993a1802 | 3,623,892 |
import torch
def l1_loss(pred_traj, pred_traj_gt):
"""
Input:
:param pred_traj: Tensor of shape (batch, seq_len)/(batch, seq_len). Predicted trajectory along one dimension.
:param pred_traj_gt: Tensor of shape (batch, seq_len)/(batch, seq_len).
Groud truth predictions along on... | 3fb4dd2b7fc85e8f32610065078aa3dc98d728d5 | 3,623,893 |
import calendar
def calculate_summary_statistics(processed_fx_obs, categories):
"""
Calculate summary statistics for the processed data using the provided
categories and all metrics defined in :py:mod:`.summary`.
Parameters
----------
proc_fx_obs : datamodel.ProcessedForecastObservation
c... | 2871a0655e3a6b3a3df1ec137d536e3863299e72 | 3,623,894 |
import time
def splitting_division_semi(f, group, table, sample_indices, splitting_fold):
"""Saving indices of each splitting group to a list that will be fed later to the deep learning model.
Specific for the semi_resampling strategy, since there only training and validation need to be splitted."""
t0 = ... | 5179caf3ec3205fc56f0e1c6b77687cd15842556 | 3,623,895 |
from typing import Tuple
from typing import Any
def extract(keys: Tuple[str, ...], state: State) -> Tuple[Any, ...]:
"""Extract multiple values from dictionary.
Args:
keys: Tuple of key whose values should be extracted from the dictionary.
state: The dictionary where values need to be extract... | 917ba523594d10a7c4af40d7f15af6815e0a2e1b | 3,623,896 |
def distorted_bounding_box_crop(image,
bbox,
min_object_covered=0.1,
aspect_ratio_range=(0.75, 1.33),
area_range=(0.05, 1.0),
max_attempts=100):
"""Generate... | e788245b874c472368cba27389d15bfcf5ea0c88 | 3,623,897 |
def constructBoard(numCards=52):
""""Create a board out of a shuffled deck of numCards
numCards(default 52): number of cards in the board (even #, 8-52)"""
deck = pd.Deck()
## Split the deck using the initial set of cards if numCards < 52
if numCards < 52:
deck = splitDeck(deck, numCards)
... | 9e8a26685ec01c1b35f269b50aa417bb1f08255e | 3,623,898 |
import sys
import yaml
def load_config():
"""
Load plugin configurations.
:return: a namespace containing the configurations
:rtype: SimpleNamespace
"""
# load
with open(sys.argv[1], 'r') as f:
plugin_config = yaml.safe_load(f)
resources = plugin_config.get('resources', [])... | 880fb207acaff7c76dd74f0539b02f18699eb36a | 3,623,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.