content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def getChunkId(dset_id, point, layout):
""" get chunkid for given point in the dataset
"""
chunk_id = "c-" + dset_id[2:] + '_'
rank = len(layout)
for dim in range(rank):
coord = None
if rank == 1:
coord = point # integer for 1d dataset
else:
coord =... | fd1fb147903c9b0f9b94f4f13b22d3f04db8dc90 | 677,998 |
from typing import List
from functools import reduce
from operator import mul
def multiples_of(numbers: List[int]):
"""
Calculate the number of numbers multiples in the range being their product.
Eg for 3, 5 compute amount of 3 & 5 multiples in frame size 3 * 5
"""
frame_size = reduce(mul, numbers... | 47cbcc7c23287c3863373ab1189ab8ef93a980a6 | 677,999 |
def get_size(data):
"""
get the total number of historical stock quotes
:param data: pandas DataFrame
:return: int
"""
data_predict = data
return int(data_predict.shape[0] * 0.8) | 78a5d5febc4fc3ff6fffc3d543df317323c0f0ca | 678,000 |
import sys
def list_ips(client, timeout, job_id):
"""Print a CSV of board hostnames for all boards allocated to a job.
Parameters
----------
client : :py:class:`.ProtocolClient`
A connection to the server.
timeout : float or None
The timeout for server responses.
job_id : int
... | 941e5d470a5bbb7fa79b65ebe75ac8ea0ae2001a | 678,001 |
def side_information(batch):
"""
inflection, inflection_lengths = batch.inflection
side_info = {"inflection": inflection,
"inflection_lengths": inflection_lengths}
if hasattr(batch, "language"):
side_info["language"] = batch.language
"""
side_info = dict()
for k in b... | 8e4d0b8d6d726caffe62bc1987151ca97f63bfeb | 678,002 |
def gen_gaussian_output(mae, indices_use_charge=None, title='Title',
charge='Charge', multiplicity='Multiplicity'):
"""
Generates strings for a Gaussian .com file.
Returns
-------
list of strings
"""
# This is stuff used on the ND CRC.
# new_lines = ['%chk={}.chk... | 8e824ffeeb13d458f3b55684ef30d579b00de34a | 678,003 |
def _get_sim_moments_est(model, alpha, delta, sim_param):
"""
"""
sim_moments = model._get_sim_moments(alpha, delta, sim_param)
return sim_moments | f6d9af85d7c33c783beff2a7697b6fe7017359af | 678,004 |
def concord(var_name, *var_adjs):
"""
Проверка согласования существительного и одного или нескольких прилагательных в роде/числе/падеже
"""
grams_name = set(var_name["info"].split(","))
good = []
for var_adj in var_adjs:
grams_adj = set(var_adj["info"].split(","))
diff = grams_ad... | 4665e852e5440d7fd0b0581a6d2078c7561d19a2 | 678,006 |
import os
def auto_renamed_writable_file(file_path, recursive_index=1):
"""
RETURNS THE ORIGINAL FILE PATH IF IT DOES NOT EXIST,
IF THE FILE PATH EXISTS, AUTO RENAMES THE PATH AND RETURNS NEW NON-EXISTENT PATH
"""
if not os.path.isfile(file_path):
return open(file_path, "w")
else:
... | 25733d53964552662e904f74b92bcab3b3775d41 | 678,007 |
def positive_percent(df):
"""
compute the percentage of positive Tweets: 2 is positive
:param df: a tweet dataframe
:return: percentage of positive tweets
"""
assert 'sentiment_vader_percent' in df, "The pandas dataframe should contain the sentiment of each tweet"
positive = 0
for sentim... | 39c0b1a9ec86bf91256728e7321fcd5c1896b8c9 | 678,008 |
def get_fields(line, field_ranges):
"""
@summary: Utility function to help extract all fields from a simple tabulate output line
based on field ranges got from function get_field_range.
@return: A list of fields.
"""
fields = []
for field_range in field_ranges:
field = line[field_ran... | cc929be129cd0e1be5ad5eea23745c7a2d846a85 | 678,009 |
def join(words, sep=' '):
"""join(list [,sep]) -> string
Return a string composed of the words in list, with
intervening occurrences of sep. The default separator is a
single space.
(joinfields and join are synonymous)
"""
return sep.join(words) | 5571e670707e30f402dba9fae0e2aaad52ddff36 | 678,010 |
import re
def read_cnf_file(cnf_file):
"""Read a cnf file and construct the cnf tuple"""
assert cnf_file.endswith('.cnf'), "Illegal file format."
with open(cnf_file, 'r') as f:
lines = [l for l in f.readlines() if not l.startswith('c')]
base_info = lines[0].split(' ')
var_num = int... | 1d719439cd831fe9d3c7fc0355c526959b56f8ab | 678,011 |
def gcd(a, b):
"""
Find the greatest common divisor of two integers a, b.
This uses Euclid's algorithm. For integer a, b, it holds that
a * b = LCM(a, b) * GCD(a, b).
Starting from range(1, 21), we replace two head elements x, y to LCM(x, y).
"""
dividend = max(a, b)
divisor = min(a, b)... | 7d5ec6818e73015d46c4d00e6842e81d48d3e4f0 | 678,012 |
def rot(c, n):
""" This function rotates a single character c forward by n spots in the alphabet. """
# check to ensure that c is a single character
assert(type(c) == str and len(c) == 1)
if 'a' <= c <= 'z':
new_ord = ord(c) + n
if new_ord > ord('z'):
new_ord = ord(c) + ... | 23923faa7aa96419152e0b9673f7a0d21b36d2e6 | 678,013 |
def check_guess(comp_numb, user_guess):
"""
Compare user guess with computer gen number
Input: computer gen number, user guess number
Output: a statement
"""
if comp_numb == user_guess:
return 'BREAK' | 4c8e41a9e2836ceade390a0ce67487f8483cbd31 | 678,014 |
def format_headers(headers):
"""
Return a list of column names formatted as headers
:param headers:
:return list:
"""
new_headers = []
for h in headers:
h: str = h
if '_' in h:
h = h.replace('_', ' ')
# if 'id' in h:
# h = h.replace('id', '')
... | 59c66c9edac91eea0e59889312c67cedda9f5fa9 | 678,015 |
def get_chebi_secondaries(chebi_ent):
"""
Get secondary accession identifiers from ChEBI result
:param chebi_ent:
:return:
"""
if hasattr(chebi_ent, 'SecondaryChEBIIds'):
return chebi_ent.SecondaryChEBIIds
else:
return [] | 9723d146a2b705cab9cf1838e60614ea6899184a | 678,016 |
import yaml
def build_content(csvdict):
"""
Construct a new dictionary that will be used to populate the template.
"""
yamlkeys = ['title', 'excerpt', 'tags', 'mentors', 'badge', 'level']
#yamlkeys = ['title', 'excerpt', 'tags']
yamldict = {}
content = csvdict.copy()
#sidekeys = ['me... | 283a102c83377e8e48e4a26c6d1ea1dd987290a4 | 678,017 |
def _kern_class(class_definition, coverage_glyphs):
"""Transpose a ttx classDef
{glyph_name: idx, glyph_name: idx} --> {idx: [glyph_name, glyph_name]}
Classdef 0 is not defined in the font. It is created by subtracting
the glyphs found in the lookup coverage against all the glyphs used to
define t... | 7ad1d9b84ec9a4af58e8aaed951d25030ceef82b | 678,019 |
import torch
from typing import Union
def normalize(
data: torch.Tensor,
mean: Union[float, torch.Tensor],
stddev: Union[float, torch.Tensor],
eps: Union[float, torch.Tensor] = 0.0,
) -> torch.Tensor:
"""
Normalize the given tensor.
Applies the formula (data - mean) / (stddev + eps).
... | cb0ad521d87a1a39c7cf9156c8dc79365c92df5b | 678,020 |
def colGrey():
"""List of 5 grey colors as RGB."""
col = [(207, 207, 207), (165, 172, 175), (143, 135, 130), (96, 99, 106), (65, 68, 81)]
# Scale the RGB values to the [0, 1] range, which is the format matplotlib accepts.
for j in range(len(col)):
r, g, b = col[j]
col[j] = (r / 255., g ... | 5893284c7ff5614664d807dedc2010fb5bf63d60 | 678,021 |
def get_xarray_subset( dataset, variable_name, time_step_indices, xy_slice_indices ):
"""
Returns a subset of the provided dataset. The source dataset is restricted to the
variable and indices supplied. When contiguous time step and XY slice indices are
supplied, the resulting DataArray is a view of t... | 649b77fad686cfc61ea17d7d0fb35cdb5ef27f44 | 678,022 |
def encrypt_letter(letter):
"""Encrypt a single letter
Arguments:
letter {char} -- The character to encrypt
Returns:
char -- The encrypted character
"""
inc_ord_char = ord(letter) + 3
if letter.isupper():
if inc_ord_char > 90:
inc_ord_char = inc_ord_c... | db25dd20f144a87317e064fabec276b68145fc51 | 678,023 |
def float_to_pcnt(x):
"""Convert a float to a percentage string, e.g. 0.4 -> '40%'."""
return '{}%'.format(round(x * 100)) | 7fd3fc10f5e4f9de99264908207f8588c269b1c0 | 678,024 |
def flatten_alongside(input_, alongside=None, op_tuple_list=None):
"""
Flattens some data alongside some other structure (not any further down the nested input_).
Args:
input_ (any): The structure to flatten.
alongside (Optional[dict]): If given, flatten only according to this dictionary, n... | ef79b314dc2c22444ece0a68cbbeefc1904e2295 | 678,026 |
import math
def wgs_lon_lat_to_epsg_code(lon, lat):
"""
Function to retreive local UTM EPSG code from WGS84 geographic coordinates.
"""
utm_band = str((math.floor((lon + 180) / 6 ) % 60) + 1)
if len(utm_band) == 1:
utm_band = '0'+utm_band
if lat >= 0:
epsg_code = '326' + utm_ba... | b793a90af5463e95d308697553e06960dfae8338 | 678,027 |
import argparse
def get_parser():
""" CLI Argument Parser."""
parser = argparse.ArgumentParser()
parser.add_argument("--arch", default="nn", type=str,
help="the ML model to be used.")
parser.add_argument("--batch_size", default=100, type=int,
help="size of the mini batch")
parser.... | e27b4bced9de18193cd37c56c29f3e5dbba6619c | 678,028 |
def resolve_integer_or_float(*numbers):
"""Cast float values as integers if their fractional parts are close to
zero.
Parameters
----------
numbers : sequence
Number(s) to process.
Returns
-------
A number or list of numbers, appropriately transformed.
"""
if len(number... | e8f3545afdebfda3028844c941eb331f3f9257fa | 678,029 |
def test_module(client):
"""
Returning 'ok' indicates that the integration works like it suppose to. Connection to the service is successful.
Args:
client: HelloWorld client
Returns:
'ok' if test passed, anything else will fail the test
"""
result = client.say_hello('DBot')
... | 77d9e604a4c42850753e81056a851a7dbdd83697 | 678,030 |
def db_is_outdated(database):
"""Return True if the database scheme is outdated."""
deprecated_indices = [
("name", "metadata.user"),
("name", "metadata.user", "version"),
"name_1_metadata.user_1",
"name_1_metadata.user_1_version_1",
]
index_information = database.index_... | 1bf28194f2313bac233c64b0bd95d17dcb0dd0fa | 678,031 |
from typing import OrderedDict
def groupby_name(bindings, tier=0):
"""
Groups bindings by the name fragment specified by tier. Input bindings
can be not sorted. The order of the bindings remains initial in scope of
its group.
Yields:
(name, [binding(s)...]) tuples.
"""
res = Order... | 3bdb7286ba7f3f54d7ffe279f048efe54c9764f6 | 678,032 |
def getCounts(arches_file):
""" gets the current resourceid and groupid for the input .arches file """
with open(arches_file,"r") as f:
lines = tuple(f)
long_resourceid = lines[-1].split("|")[0]
if long_resourceid == "RESOURCEID":
resourceid = 100000
groupid = 30... | 2bfd475898e70fdf773fdd57a080c1afff511e5a | 678,033 |
def get_location(datetime, position_df):
"""Create a tuple of the date_time, latitude and longitude of a location in a dataframe from a given date_time."""
latitude = position_df[position_df.date_time == datetime].latitude.item()
longitude = position_df[position_df.date_time == datetime].longitude.item()
... | bea3dc5cb58fb6965f263e95c56f510ffe7f413f | 678,034 |
def update_two_contribute_score(click_time_one,click_time_two):
"""
item cf update two sim contribution score by score
"""
delata_time = abs(click_time_one - click_time_two)
# 将时间戳的秒,变成天
total_sec = 60 * 60 * 24
delata_time = delata_time/total_sec
return 1/(1 + delata_time) | b7e4e2c204448d0dbffa19debecc985c4bd7598b | 678,036 |
def checksum_equal(chksum1, chksum2):
"""Compares two checksums in one's complement notation.
Checksums to be compared are calculated as 16 bit one's complement of the
one's complement sum of 16 bit words of some buffer.
In one's complement notation 0x0000 (positive zero) and 0xFFFF
(negative zero)... | 5d44a91ad25d99031e57e27440bf54fd8e285721 | 678,037 |
import torch
def gamma_compression(images, gamma=2.2):
"""Converts from linear to gamma space."""
# Clamps to prevent numerical instability of gradients near zero.
images = images.permute(0, 2, 3, 1) # Permute the image tensor to BxHxWxC format from BxCxHxW format
outs = torch.clamp(images, min=1e-8) ** (1.... | 9f1618ba7b79288fd96f0e1431ee40d4b335dc08 | 678,038 |
import math
def gen_abd_params(N, f, dummy=None):
""" Generate possible values of n, q1, q2
"""
quorum_params = []
quorum_params_append = quorum_params.append
for n in range(2*f+1, N+1):
for q1 in range(math.ceil((N-1)/2), n-f+1):
for q2 in range(math.ceil((N-1)/2), n-f+1):
... | 25b90d06ae6f6b5b4a9d2af443db815b1c9181cc | 678,039 |
def get_risk_table_str(risk_table, simdata, table):
"""Returns string for risk table output in CSV format.
Args:
risk_table: Numpy 2D array with the risk table, conveniently returned by
risk.get_risk_table().
simdata: SimData object containing the data.
table: Table identifier (integer or strin... | 94b0174b1066c430507a526e3a520a55406838a8 | 678,041 |
def restrict(dataset, fold):
"""
Restricts the dataset to use the specified fold (1 to 10).
dataset should be the training set.
"""
fold_indices = dataset.fold_indices
assert fold_indices.shape == (10, 1000)
idxs = fold_indices[fold, :] - 1
dataset.X = dataset.X[idxs, :].copy()
as... | 5234a1374e3be4b62ae93c393b803dbb585010d8 | 678,042 |
def is_close(a, b, rel_tol=1e-09, abs_tol=0):
"""Determines whether two numbers are nearly equal.
The maximum of the relative-based and absolute tolerances is used to test
equality.
This function is taken from `math.isclose` in Python 3 but is explicitly
implemented here for Python 2 compatibility... | fa9ea5a8c2e7088d1eb2d3223dd6b29d2d5dfefa | 678,043 |
import pickle
def load_pickle_file(file_name, encoding='latin1'):
"""Loads a pickle file.
:param file_name: File name (extension included).
:type file_name: pathlib.Path
:param encoding: Encoding of the file.
:type encoding: str
:return: Loaded object.
:rtype: object | list | dict | numpy.... | 1dca3fbf08bdd5e8982097a4e56561811d5207e3 | 678,044 |
def _give_default_names(list_of_objects, name):
"""Helper function to give default names to objects for error messages."""
return [name + '_' + str(index) for index in range(len(list_of_objects))] | 6f608ad70db21ba2b8154e06b4e756324df105f8 | 678,045 |
def translate (vector, obj):
""" Function translate
return openscad translate command
@param vector: [x, y, z] translation matrix
@param obj: text object to translate
"""
return "translate({}){{{}}}".format(vector, obj) | f2e745f4fa3eabf9f7934ce56826658805ea918d | 678,046 |
import logging
import os
def _check_bad_filenames(submission_dir):
"""Checks for filename errors.
Git does not like filenames with spaces or that start with ., or /. .
"""
logging.info('Running git-unfriendly file name checks.')
names = [
os.path.join(dirpath, filename)
for dirpath... | 11a0cf832dd31a04b2698e7f112090a662b9316f | 678,047 |
import subprocess
def get_git_hash():
"""
Returns:
git describe string
"""
try:
commit_id = subprocess.check_output(['git', 'describe', '--always'])
branch = subprocess.check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])
except:
commit_id = ''
branch ... | acd49527d6957cdb76e9bdd91bbaeb63a90469ff | 678,048 |
import ipaddress
def hops_to_str(hops):
"""Concatenate together a list of (host, port) hops into a string such as
'127.0.0.1:9001|192.168.1.1:9002|[::1]:9000' appropriate for printing or passing to
a zeromq connect() call (does not include the 'tcp://'' prefix)"""
formatted_hops = []
for host, por... | 01e958d84813604acbaf4c1beb37ee35ff844c8b | 678,049 |
import sys
import os
def detect_platform():
"""this function has been in the Utils module for some time.
It's hard to guess what people have used it for.
It seems its goal is to return an unversionned sys.platform, but it's not handling all platforms.
For example, the version is not removed on freebsd and netbsd,... | 6687a08d50a8ccbfccec3761835d3f73bfaecdd5 | 678,050 |
def compare_func_larger(val_s):
"""仅供 update_compare_pl 中比较函数使用"""
result = val_s['asset_1'] > val_s['asset_2']
shift_value = val_s['asset_2'] - val_s['asset_1']
shift_rate = shift_value / val_s['asset_1']
return [result, shift_value, shift_rate] | 300312b7fa18871e15ce520c37559ce63a7ef902 | 678,052 |
def _parse_package_name(name: str) -> str:
"""
Force lower case and replace underscore with dash to compare environment
packages (see https://www.python.org/dev/peps/pep-0426/#name)
Args:
name: Unformatted package name
Returns:
Formatted package name
"""
return name.lower()... | 0257cbae7d8c25b31d089c983a0185c67cff6e2d | 678,053 |
import argparse
def parser():
"""Returns an argparse parser."""
prsr = argparse.ArgumentParser(
description="Combine videos in a directory into one, de-identified, video.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
prsr.add_argument(
"-o",
"--output",
... | 2d7dd2758000a780da0236761598249f6ba9a8bb | 678,054 |
def add_ancestors_(compounds_map, compound):
"""adds field ANECESTORS and returns it"""
if 'ANCESTORS' in compound:
return compound['ANCESTORS']
ancestors = []
for p in compound.get('PARENTS', []):
ancestors += [p] + add_ancestors_(compounds_map, compounds_map[p])
compound['ANCESTO... | f56d9d771a0ff60b944ebe16149bd2426fdb753b | 678,055 |
from typing import List
from typing import Any
def is_accepted(algorithm: str, accepted: List[Any]) -> bool:
"""Check whether algorithm is accepted
@param algorithm: algorithm to be checked
@param accepted: a list of acceptable algorithms
"""
return algorithm in accepted | 82c74f6e7c4131abb028c39af09be25403231d42 | 678,056 |
from pathlib import Path
from typing import List
from typing import Dict
import csv
def get_production_for_one_day(csv_path: Path) -> List[Dict[str, float]]:
"""Get one hour of production for testing from csv file.
Type of source in columns, 24 rows for each hour in one day.
"""
with open(csv_path) a... | 126f8c0c01ea166d6b8b2cfe6fd2a2fe9b444429 | 678,057 |
def conservative_adjust(times, accum, multipler):
"""Adjust times to conserve precip, but change intensity, tricky."""
# We can't adjust by more than 50%
assert 0.5 < multipler < 1.5
# If this was a drizzle event, do nothing.
if accum[-1] < 5:
return times
# An algorithm was attempted wh... | d3dbbdff22dd07145c682ad3ae5b30fc818bbf9b | 678,058 |
import re
def replace_numbers(sequence):
"""Replace digits to words (necessary for modX format to work.
:param sequence:
:return:
"""
rep = {"1": "one",
"2": "two",
"3": "three",
"4": "four",
"5": "five",
"6": "six",
"7": "seven",
... | 657bfc79e2c3abc2ad24d9ad9a8fee53bc5056bc | 678,059 |
import json
import codecs
def encode_blob(data):
""" Encode a dictionary to a base64-encoded compressed binary blob.
:param data: data to encode into a blob
:type data: dict
:returns: The data as a compressed base64-encoded binary blob
"""
blob_data = json.dumps(data).encode('utf... | 266f0b6440adfae165a9d8d6877a111736e22488 | 678,060 |
import os
def getdirs(currentDir):
""" returns the names of all the directories under the given currentDir, where the user has access"""
try:
currentDir = currentDir.replace('\\','/')
if not currentDir.endswith('/'): currentDir += '/'
dirs = [ (currentDir + d) for d in os.listdir(curre... | a34a83edd756bcdb9c308c140e98c25b52d36aec | 678,061 |
import yaml
import json
def json_to_yamls(json_str, *args, **kwargs):
"""Json file to yaml string"""
return yaml.safe_dump(json.loads(json_str), *args, **kwargs) | 16e3773409efe70b6380c2dcd428cc4b6216095f | 678,062 |
import subprocess
def get_model():
"""Get the device model."""
return subprocess.check_output(
['adb', 'shell', 'getprop', 'ro.product.model']).rstrip() | da267da1e6e67d00a47110fc45847132d26f4308 | 678,064 |
import os
import shutil
def get_workingdir(repodir, subdir):
"""
Get the workingdir from description.
"""
if len(subdir) > 1:
sourcedir = os.path.join(repodir, subdir[0])
targetdir = os.path.join(repodir, subdir[1])
if not os.path.isdir(targetdir):
shutil.copytree(s... | c3f6a91ad284baf51b80c860bb570342f543426c | 678,065 |
def unbind_unit(name):
"""
Called every time an app adds an unit (container). This can be used to keep track of authentication details
related to the ipaddress of a container.
There seems to useful way to implement this function for now.
"""
return '', 200 | 3fb6ae9ea61325bcf0e32f4d88c2ec614cbc4209 | 678,066 |
import json
import sys
def read_dic(file_path):
""" dic = read_dic(file_path)
Read a json file from file_path and return a dictionary
Args:
file_path: string, path to the file
Returns:
dic: a dictionary
"""
try:
data = json.load( open(file_path) )
except IOError:
... | 5972fbd58689d81c4a0388ca1aca74ec10e7628f | 678,067 |
import time
def attributesFromDict(d):
"""build self attributes from a dictionary d."""
self = d.pop('self')
for name, value in d.items():
setattr(self, name, value)
"""Manage a log file"""
def __init__(self, logfile):
"""logfile is the file name or None"""
s... | f35f2c7a681f9d1aa1e2d7ed9de069459c641cf1 | 678,068 |
import os
def nancy(root_path, meta_file):
"""Normalizes the Nancy meta data file to TTS format"""
txt_file = os.path.join(root_path, meta_file)
items = []
speaker_name = "nancy"
with open(txt_file, 'r') as ttf:
for line in ttf:
utt_id = line.split()[1]
text = line[... | 6c5ca03a2f4639ed9b4a2bd0a718650dcd55632b | 678,069 |
def intro(secret):
"""
Returns opening instructions to player.
"""
return 1 | c5af34c1729f23e4b491f0f7b590022498266dbb | 678,070 |
def assign_groups(intervals, groupby=[]):
"""
Parameters
----------
intervals : TYPE
DESCRIPTION.
groupby : TYPE, optional
DESCRIPTION. The default is [].
Returns
-------
intervals : TYPE
DESCRIPTION.
"""
if not groupby:
intervals["group"] = "a... | c15aedb3251ba19a951b0021e9f562dc32f67cf7 | 678,071 |
def get_cat_year_data(df, filter_cat, filter_nme, col):
"""
Filter df filter_cat[i] == filter_nme
Collect all col data from per year
"""
collected_data = []
year_range = df['AADFYear'].unique()
for year in year_range:
collect_data = df[
(df[filter_cat] == filter_nme) & (d... | 1a012846c4dc6e533fc17e748b453948a072ee8e | 678,073 |
def check_for_essid(essid, lst):
"""Will check if there is an ESSID in the list and then send False to end the loop."""
check_status = True
if len(lst) == 0:
return check_status
for item in lst:
if essid in item["ESSID"]:
check_status = False
return check_status | 9035bf26f3cff1c9dda4cfa210a54daccbf6a580 | 678,074 |
import argparse
def parse_args():
"""parser
"""
parser = argparse.ArgumentParser(
description="annotate grammars with functions")
# required args
parser.add_argument(
"--grammar_summaries", nargs="+",
help="all grammar summaries to be annotated and compiled")
parser.ad... | bfdf0797e5d5a9efa993400bbfc772b88ff896e3 | 678,075 |
import struct
def readLEFloat(f):
"""Read 4 bytes as *little endian* float in file f"""
read_bytes = f.read(4)
return struct.unpack('<f', read_bytes)[0] | f7a27102da1fb941d15537821443f4d7b682a7a7 | 678,076 |
def Remove_Duplicat(seq):
"""
:param seq: list
:return: the same entry list removing duplicate elements
"""
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))] | c154931a88eb20033d77202fb8e0c93e36f6a9d8 | 678,077 |
import json
def is_conitain_object_and_scene_type(bdd100k_json_path,class_names):
"""
这是判断bdd100k数据集的json标签中是否包含候选目标实例并判断图片是否属于白天场景的函数
:param bdd100k_json_path: cityscapes数据集的json标签文件路径
:param class_names: 目标分类数组
:return:
"""
json_dict = json.load(open(bdd100k_json_path, 'r')) # 加载json标签
... | 0f89977cd0375e265c1cfe900e4d6d98e67876ee | 678,078 |
from abc import ABC
import inspect
def inspect_params(cls, name):
"""
Recursively parse function params.
Function parameters of the derived class overrides the base class ones.
"""
params = []
not_var_kind = lambda p: p.kind not in [p.VAR_POSITIONAL, p.VAR_KEYWORD]
mro = filter(lambda c:... | 9f15912a134812bac71fd37c560963cdfa13839c | 678,079 |
def n_filters(stage, fmap_base, fmap_max, fmap_decay):
"""Get the number of filters in a convolutional layer."""
return int(min(fmap_max, fmap_base / 2.0 ** (stage * fmap_decay))) | cefbbb8873c56fb5edd4b62a1418fc5d1b2757b4 | 678,080 |
from typing import Dict
def _compute_metrics(hits_or_lcs: int, pred_len: int, target_len: int) -> Dict[str, float]:
"""This computes precision, recall and F1 score based on hits/lcs, and the length of lists of tokenizer
predicted and target sentences.
Args:
hits_or_lcs:
A number of ma... | 630801f5c0821e774b9b2ac95c3d408afd5380a8 | 678,081 |
def string_diff_column(str1, str2):
"""
>>> string_diff_column("ab1", "ab2")
3
>>> string_diff_column("ab1c3e", "ab2c4e")
3
>>> string_diff_column("abc", "abcd")
3
>>> string_diff_column("abcd", "abc")
3
>>> string_diff_column("a", "")
1
>>> string_diff_column("", "a")
... | 7672aca6a74ed5496f5d1bb1f9b9da58f11ec4c5 | 678,082 |
def _set_type(values, new_type):
"""Transforms a list of values into the specified new type. If the value has zero length, returns none
Args:
values: A list of values
new_type: A type class to modify the list to
Returns:
The values list modified to the new_type. If an element is em... | d95aac651374a658e204da58094a4a0a56fea276 | 678,084 |
def first_true_pred(predicates, value):
"""
Given a list of predicates and a value, return the index of first predicate,
s.t. predicate(value) == True.
If no such predicate found, raises IndexError.
>>> first_true_pred([lambda x: x%2==0, lambda x: x%2==1], 13)
1
"""
for num, pred in enu... | bf72ce96833e1f501599aa7091de727f9eea4974 | 678,085 |
def M_TO_N_ONLY(m, n, e):
"""
:param:
- `m`: the minimum required number of matches
- `n`: the maximum number of matches
- `e`: the expression t match
"""
return r"\b{e}{{{m},{n}}}\b".format(m=m, n=n, e=e) | fda097fdd86e2db3166dfe77ee9cd4cd9ed9e98e | 678,086 |
def fgrowth(**cosmo):
""" Return Lahav et al. (1991) fit to dln(D)/dln(a) """
return ((cosmo['omega_M_0'] * (1. + cosmo['z']) ** 3.)
/ (cosmo['omega_M_0'] * (1. + cosmo['z']) -
(cosmo['omega_M_0'] + cosmo['omega_lambda_0'] - 1.)
* (1. + cosmo['z']) ** 2.
... | 63166676bbef9959a19024343dcabbf554ea3a6e | 678,087 |
def contract_list(filepath):
"""
Reads a file with given filepath with names and age
and returns a list of strings containing the
information in the file with each string containing
the person's name and age.
Parameters:
filepath: Path to file containing names and ages.
Returns:
... | 8a1a97835224f4b3b2d254ec637b8e8fe78c9fe8 | 678,089 |
def check_x_lim(x_lim, max_x):
"""
Checks the specified x_limits are valid and sets default if None.
"""
if x_lim is None:
x_lim = (None, None)
if len(x_lim) != 2:
raise ValueError("The x_lim parameter must be a list of length 2, or None")
try:
if x_lim[0] is not None and... | 6dda696f4a001d021c8074675e0905f049e88e70 | 678,090 |
def train_estimators(estimators, train_ds):
""" This method is responsible for training all estimators of the experiment.
A workaround had to be implemented since SeasonalNaivePredictor does not
have .train method."""
trained_estimators = [estimator.train(train_ds) for estimator in estimators[:-... | 326bd9c86078027fe37e3c5dc7f64daf84473a65 | 678,091 |
def balanced(node, height=None):
"""Return True if two trees are balanced, False if not"""
if node is None:
print(height)
return height
if height is None:
height = 0
return (balanced(node.left, height + 1) == balanced(node.right, height + 1)) or (balanced(node.left, height + 1) ... | 6c9457211f4f8ead70cedaa909aec4f4be917244 | 678,093 |
def get_model_device(model):
"""Return the device on which a model is."""
return next(model.parameters()).device | 2fb10d37811cfd86cf1500561b13befe6465fa05 | 678,094 |
def distx2(x1,x2):
"""
Calculate the square of the distance between two coordinates.
Returns a float
"""
distx2 = (x1[0]-x2[0])**2 + (x1[1]-x2[1])**2 + (x1[2]-x2[2])**2
return distx2 | ec54779bc477088c08be512dbb1a7a5cdeefb18b | 678,095 |
def remove_pacient(ime, priimek):
"""Funkcija poisce pacienta v doloceni bolnicni in ga odstrani iz baze. Pravice imajo samo zdravstveni delavci."""
return None | 62c519893bc3ce5ab8585c7af1e2a20222c72919 | 678,096 |
def sp(dividend, divisor):
"""Returns the percentage for dividend/divisor, safely."""
if not divisor:
return 0.
return 100. * float(dividend) / float(divisor) | ca027d5637738f3a268e24d329d2d876f855e794 | 678,098 |
def language_name_to_code():
"""
English language name to code language for Google Translate.\n
© Anime no Sekai - 2020
"""
data_dict = {
'automatic': 'auto',
'afrikaans': 'af',
'albanian': 'sq',
'amharic': 'am',
'arabic': 'ar',
'armenian': 'hy',
... | 0864ba5c57c795f2851e794ac85c951cc0ed6138 | 678,100 |
def html_table_header_row(data):
"""
>>> html_table_header_row(['administrators', 'key', 'leader', 'project'])
'\\n\\t<tr><th>Administrators</th><th>Key</th><th>Leader</th><th>Project</th></tr>'
>>> html_table_header_row(['key', 'project', 'leader', 'administrators'])
'\\n\\t<tr><th>Key</th><th>Proj... | 33eeb9abee9824d4f9e8f715386f51afe849b802 | 678,101 |
def write_timeseries(date_list, variable_name,
timeseries, missing_vals):
""" Create an output dictionary in timeseries form. """
output_strings = [datething.isoformat()
for datething in date_list]
output = {"times": output_strings,
variable_name: t... | d67752e0cf8095eca652edd9ea63e3ea85f91551 | 678,102 |
def form_covalent_radii():
"""
Dictonary of immutable tuples for link atom factor determination
"""
covalent_radii = {}
covalent_radii["H"] = (.32, -100, -100)
covalent_radii["He"] = (.46, -100, -100)
covalent_radii["Li"] = (1.33,1.24,-100)
covalent_radii["Be"] = (1.02,.90,.85... | 67e6410ee5ee095771bd1a3f712f2a97734ab6ce | 678,103 |
from typing import OrderedDict
def convert_state_dict(state_dict):
"""
Converts a state dict saved from a dataParallel module to normal module state_dict inplace
Args:
state_dict is the loaded DataParallel model_state
"""
state_dict_new = OrderedDict()
#print(type(state_dict))
f... | 9029ce13776cf869a7ae0ebf57d7c0e1d8a7e7f8 | 678,105 |
def recallAtK(target, results):
"""
Description:
Return 'recall at k' with target and results
Parameters:
target: list of K retrieved items (type: list, len: K)
[Example] [tag1, tag2, ..., tagK]
results: list of N retrieved items (type: list, shape: (N, ?))
... | 50c76a9d5dfa36c2926ce756b345bb0659fd33f8 | 678,106 |
def bdev_delay_create(client, base_bdev_name, name, avg_read_latency, p99_read_latency, avg_write_latency, p99_write_latency):
"""Construct a delay block device.
Args:
base_bdev_name: name of the existing bdev
name: name of block device
avg_read_latency: complete 99% of read ops with th... | 6625574dd46788eb2136ab06745ceadf5b167247 | 678,107 |
def sanitize_path_input(user_input: str) -> bool:
""" this function takes a file hash and validates it's
content to avoid RCE and XSS attacks
Args:
user_input: any user input which is used to write a path
"""
return True
# temporarily removed as it broke some tak clients
#if re.matc... | 2c6fc2456f2cefe05215fc9f2c9f09c75e295a67 | 678,108 |
from pathlib import Path
from typing import List
def make_files(tmp_path: Path) -> List[str]:
"""Helper function to create a list of pathlib Path objects."""
md = tmp_path / "intro.md"
py = tmp_path / "plot.py"
txt = tmp_path / "discussion.txt"
md.write_text("# Background\nMatplotlib is a Python p... | 205f168b423718c32470cdded8ce62134dac830d | 678,109 |
def onedecimal(a_float):
"""Example: 1234,5"""
return "{:.1f}".format(a_float).replace(".", ",") | b2596c97afe9252a64c203298c03d1263c3530b3 | 678,110 |
def get_scan_indices(data):
"""Get the line numbers where scans start
This finds all the lines starting with the word 'Scan'. Although
some of these lines have a source name, it appears to be correct
only for the first scans in the file.
Notes
=====
This is specific to Tid ASCII files
@param data : l... | 447a123f9db2b65469e3c72918e40d8ee70391ba | 678,111 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.