content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import numpy as np
def extrapolate_accel_data_testing(filename):
"""Extrapolate data from a txt file
data will have format:
x1,y1,z1;
x2,y2,z2;
..
xn,yn,zn;
:param filename: file to read from
:return: datax, datay, dataz vectors (np.array)
"""
x = []
y = []
z = []
... | 53d6f44450285306b41eb8e4969a32d4d1c3ceb7 | 3,619,300 |
import warnings
def get_loss_obj(cfg: Config) -> loss.BaseLoss:
"""Get loss object, depending on the run configuration.
Currently supported are 'MSE', 'NSE', 'RMSE', 'GMMLoss', 'CMALLoss', and 'UMALLoss'.
Parameters
----------
cfg : Config
The run configuration.
Returns
... | c01781431e7190b73c8b3c4bff6ac456a06463c3 | 3,619,301 |
def _melspecgrams_to_specgrams(melspecgrams: tf.Tensor, mel2l) -> tf.Tensor:
"""Converts melspecgrams to specgrams.
Args:
melspecgrams: Tensor of log magnitudes and instantaneous frequencies,
shape [..., channels, time, freq, 2], mel scaling of frequencies.
mel2l: Mel to linear matrix
Re... | 602348e81d8770249695dd5a65d03ca50b7b740c | 3,619,302 |
import time
def benchmark_descending_operator(rhoab, rhoba, w, v, u, num_layers):
"""
run benchmark for descending super operator
Args:
rhoab (tf.Tensor): reduced densit matrix on a-b lattice
rhoba (tf.Tensor): reduced densit matrix on b-a lattice
w (tf.Tensor): isometry
... | c64d34edbe31d33a1f172f591de6d1b4433d2cf2 | 3,619,303 |
import numpy
def extract_sun_angles(xml):
"""Extract Sentinel-2 solar angle bands values from MTD_TL.xml.
Parameters:
xml (str): path to MTD_TL.xml.
Returns:
str, str: sz_path, sa_path: path to solar zenith image, path to solar azimuth image, respectively.
"""
solar_zenith_values = n... | 801b5baeae3b863d9dec272ccf36143d3c69dff9 | 3,619,304 |
def get_citation_ids(semantic_results, direction: str = "citations", cit_n: int = 1):
"""Returns ids for AI paper citations and
references below a threshold and above a citation threshold"""
cit_df = pd.DataFrame(
chain(*[get_citation_meta(art, direction) for art in semantic_results])
)[["arxiv... | d1d1f66d5cd3e8feed6b1fa6faf70600d08e8067 | 3,619,305 |
def spiral_grating(medium_groove=mp.Medium(epsilon=2),
D=0.4, d=None, DBR_period=0.2, FF=0.5, N_rings=10,
N_arms=2, thickness=0, center=mp.Vector3(0, 0, 0)):
"""
Elliptic DBR cavity created as a sequence of concentric cylinders.
Parameters
----------
medium_gro... | 36dab4826a117b9f93d8b2fee82002cf954bba45 | 3,619,306 |
def getDailyData(word: str,
start_year: int = 2007,
stop_year: int = 2018,
geo: str = 'US',
tz: int = 240,
verbose: bool = True,
wait_time: float = 5.0) -> pd.DataFrame:
"""Given a word, fetches daily search volume... | 7409991a6ae805f34958586241a09e2afe296e6e | 3,619,307 |
from Framework.ClassUtils.json_utils_class import JsonUtils
import json
import difflib
def compare_xml(xml1, xml2, output_file=False, sorted_json=True,
remove_namespaces=False, tag_list=[], attrib_list=[]):
"""
This will compare two xml files or strings by converting to json
and then sorti... | 46d8fdf38e5d2debbc4d2fc1a6a1434ac2b40396 | 3,619,308 |
def model_repr(models, key):
"""Get a model representation."""
m = [(char, proba)
for char, proba in models[key].items() if proba > 0.0001]
m = sorted(m, key=lambda n: n[1], reverse=True)
s = ""
for char, prob in m:
s += u"{}={:4.2f}% ".format(char, prob * 100)
return s | a4b658b8a7fd7529e14f452e426ca35447991042 | 3,619,309 |
def read_file(filename):
"""
Read a whole file into memory.
Automatically detect gzipped files based on suffix.
Args:
filename (str): Name of file to read.
Returns:
str: Content of file as a string. Will return None if file cannot be read.
"""
try:
with open_file_h... | 440113df8851b4ef18006a3e0db1c90470dd1b48 | 3,619,310 |
import glob
def findNewFiles():
"""
Find all of the files that have been downloaded, and then determine all of
those that have not been decrypted. Return a list of those that need to be
decrypted now.
"""
allFiles = glob.glob('*.gpg')
oldFiles = glob.glob('*.gz')
retFiles = []
for... | 0d9052856e1cf8ba605026f1a74e259b06e5f342 | 3,619,311 |
import os
import yaml
import json
def load_global_params(path: str, report=True):
"""Load and return global paramss
Args:
path (str): path to param file
report (bool, optional): Add params to EuroPy report. Defaults to True.
Returns:
Dict[str:Any]: global params
"""
para... | 3d2601f720b61cfad55a26ce7d7b18fbd62f5bca | 3,619,312 |
from bs4 import BeautifulSoup
def parse_joa_html(inner_html):
"""
Retourne les cotes disponibles sur une page html joa
"""
match_odds_hash = {}
match = None
date_time = None
soup = BeautifulSoup(inner_html, features="lxml")
id_match = None
for line in soup.findAll():
if "cl... | 1a78a310092ef0d3b2272812b9847bc1aff29eee | 3,619,313 |
def create_or_update_pipeline(origin_pipeline, api_url):
"""Create or update Storage Location and return it."""
pipeline = Pipeline.query.filter_by(origin_pipeline=origin_pipeline).first()
request_url, request_url_without_api_key = get_storage_service_api_url(
api_url, origin_pipeline
)
resp... | b94cd89f6480bf920a05d171593697661d6bab4a | 3,619,314 |
from datetime import datetime, timedelta
import json
def wechat_pay_call_back(request):
"""
"""
try:
time_format = '%Y%m%d%H%M%S'
date_now = datetime.now()
after_2_hour = date_now + timedelta(hours=2)
logger.debug("wechat_pay_call_back")
pay_a = WeChatPayModeA(app... | 7f8291186cf26f743e838be63ce41137660f0806 | 3,619,315 |
def _validate_additional_args(param_dict):
"""
:param param_dict: parameters to enter into the backing store
:type param_dict: dictionary
:returns: a string that tidies up the additional arguments
:rtype: string
"""
if 'additional_arguments' not in param_dict:
return "{}"
param... | d711544761ac18b58b7ea5c3c1dc0135ebb68f9b | 3,619,316 |
def fib_dp(n):
"""
Series - 1, 1, 2, 3, 5, 8, 13
`n` starts from 0.
:param n:
:return:
"""
fib_arr = empty_1d_array(n)
if n < 2:
return 1
if fib_arr[n-1] is None:
fib_arr[n-1] = fib_rec(n-1)
if fib_arr[n-2] is None:
fib_arr[n-2] = fib_rec(n-2)
return ... | 43150d0d272315fd4651c4710722b9c06d540f97 | 3,619,317 |
def compute_distance_adjacent_finger(finger_name, adjacent_finger, hand_fingers_points):
"""
Cálcula a distância entre a ponta do dedo analisado e a ponta do dedo adjacente. Divide
por fator de correção (distância de referência).
:param finger_name: dedo analisado
:param adjacent_finger: dedo adjace... | c97ad838ce5456c10d1e6ff922234ab6e4499591 | 3,619,318 |
def get_linters(files_to_lint, file_cache):
"""Creates GeneralPurposeLinter object and returns it.
Args:
files_to_lint: list(str). A list of filepaths to lint.
file_cache: object(FileCache). Provides thread-safe access to cached
file content.
Returns:
tuple(GeneralPurpo... | 5b80cee233276a4aa6096c3bb3cb611904077aec | 3,619,319 |
import functools
def extract_common_countries(FILES, eu28_countries):
"""This function extract countries common to all
data sets.
Arguments of fucntion are FILES -> list of triples
where elements are data set filename, column/row/header
depending where the countries' names reside... | fe60673d09f36c444c1b70a45e1cd7cd4d61adc8 | 3,619,320 |
import functools
import subprocess
def catch_toil_exceptions(orig_func):
"""Catch uncaught exceptions and turn them into http errors"""
@functools.wraps(orig_func)
def catch_exceptions_wrapper(self, *args, **kwargs):
try:
return orig_func(self, *args, **kwargs)
except RuntimeE... | cf983d234aeba2977865309b96a237218cc022a9 | 3,619,321 |
def generateTmatrixFullRandom(N,badf=0.2):
# print("p_act01 < p01/(p01+p10)")
"""
Generates a Nx2x2x2 T matrix indexed as: T[patient_number][action][current_state][next_state]
action=0 denotes passive action, a=1 is active action
State 0 denotes NA and state 1 denotes A
"""
... | 83ed20f4cfbd386f43b4224988b5dba93d4ed4f3 | 3,619,322 |
def ResolveVersion(api_name, default_override=None):
"""Resolves the version for an API based on the APIs map and API overrides.
Args:
api_name: str, The API name (or the command surface name, if different).
default_override: str, The override for the default version.
Raises:
apis_internal.UnknownAP... | 533e858ce7095721a1cd71e416ce997fd2f4c66b | 3,619,323 |
import hashlib
def decrypt_master(master_pwd,master_dict):
"""Decrypt a master key with a master password"""
secondary = hashlib.pbkdf2_hmac('sha256',master_pwd.encode(),master_dict['salt'],2**14,16)
cipher = AES.new(secondary,AES.MODE_EAX,nonce=master_dict['nonce'])
master = cipher.decrypt_and_verify... | 1851be349280ef4f6ed8e0e1db6d912e90b45fd4 | 3,619,324 |
def runSingleFile(inputFile, outputDir, parser, databaseVersion, listOfExpRes,
timeout, development, parameterFile):
"""
Call testPoint on inputFile, write crash report in case of problems
:parameter inputFile: path to input file
:parameter outputDir: path to directory where output ... | 6ff64d6ce3516912ee1a4c1804e4d93b702d4b6d | 3,619,325 |
def new_pipeline(tickers, start_date, end_date):
"""The pipeline implemented with Dask"""
def compute():
# The pipeline construction will store 'get_signals', so we need to
# delay it until we enter the 'intercept_function_arguments' context
signals = get_full_pipeline(tickers, start_da... | 4a0a172f39f55ede87ceb472110d6b211ac1f295 | 3,619,326 |
def handleNonAscii(text):
"""
If default locale supports UTF-8 reencode the string otherwise
remove the offending characters.
"""
if preferred_encoding == 'ASCII':
return ''.join([i if ord(i) < 128 else ' ' for i in text])
else:
return text.encode(preferred_encoding) | 1abf77873b1b1f4474fa931a91003d93bedac6aa | 3,619,327 |
import pathlib
def folding(eventfile,Porb,nbins):
"""
Folding the events by some orbital period
"""
times = fits.open(eventfile)[1].data['TIME'] #getting array of times
gtis_data = fits.open(eventfile)[2].data #getting GTIs
T = sum([ gtis_data[i]['STOP']-gtis_data[i]['START'] for i in range(le... | 0da7863ee4ed1932cb12a0334a254af8278fcdb7 | 3,619,328 |
def is_global(wire):
"""Return true if a wire is part of the global clock network"""
return bool(global_spine_tap_re.match(wire) or
global_cmux_out_re.match(wire) or
global_cmux_in_re.match(wire) or
clock_pin_re.match(wire) or
pll_out_re.match(wire... | b8bf9e10291e698aecd675c18484f1b7a2df8825 | 3,619,329 |
def create_lookup_tables(
vocabulary_path, num_oov_buckets=1, as_asset=True, unk_token=None
):
"""Creates TensorFlow lookup tables from a vocabulary file.
Args:
vocabulary_path: Path to the vocabulary file.
num_oov_buckets: Number of out-of-vocabulary buckets.
as_asset: If ``True``, the v... | ea8cdbcb384c148f646c3cad9d038b7bfd0822fb | 3,619,330 |
def get_bprop_less_equal(self):
"""Grad definition for `LessEqual` operation."""
def bprop(x, y, out, dout):
return zeros_like(x), zeros_like(y)
return bprop | c7802cb01ee98ed8f718da872e114f4d325b62fd | 3,619,331 |
def group_by( l, key ):
"""
agrupa por alguna llave
Arguments
=========
l: list, tuple, finite iter
key: callable or str
funcion que separara los elementos
si es un string se asume que los elementos son dicionarios
y el valor de key se usara para obtener el valor
Re... | 3ab6b3ea7d9bcb7f0b864aee9382a7073cec2e1a | 3,619,332 |
def get_lr_rotate(current_step, lr_max, max_step):
"""
Warmup training strategy.
Args:
current_step (int): current step
lr_max (float): original learning rate
max_step (int): total steps
Returns:
list of learning rate at each step
"""
lr_each_step = []
deca... | 4a91e3821ac3bc82aabd8456ecb32706839e5065 | 3,619,333 |
from pathlib import Path
def walk(_path: str) -> tuple:
"""
:param _path:
:return: tuple(_path, tuple('dirs',), tuple('files',))
"""
dirs = []
files = []
path = Path(_path)
for i in path.iterdir():
if i.is_file():
files.append(str(i))
if i.is_dir():
... | 06c8a7daa310da8df3d52a05e3f950d9c1c5ef37 | 3,619,334 |
def zxxgamma(v, t, gamma, H0):
"""
Takes in:
v = values at z=0;
t = list of redshifts to integrate over;
gamma = interaction term.
Returns a function f = [dt/dz, d(a)/dz,
d(e'_m)/dz, d(e'_de)/dz,
d... | 4b3a5439a6187afe017c70c285ba89c12aa445bf | 3,619,335 |
def _meshgrid2d(x, y):
"""
Special-cased implementation of np.meshgrid.
For just two arguments, (x, y). Found to be about 3x faster on some simple
test arguments.
Parameters
----------
x : TYPE
DESCRIPTION.
y : TYPE
DESCRIPTION.
Returns
-------
r1 : TYPE
... | e5017bcf3fd1ba3ebe48209a3f04eb5a95ac53a1 | 3,619,336 |
def py(code, input):
"""python <commands> -- Execute Python inside of a sandbox"""
query = input.group(2)
try:
answer = web.exec_py(query)
if answer:
answer = answer.replace('\n', ' ').replace('\t', ' ').replace('\r', '')
return code.reply(answer)
return code.... | 32a6ffea112ab6a88e42d363291ef1b957445ef9 | 3,619,337 |
def get_participial_constructions(tokens):
"""Identify, color and count participial constructions"""
# get part pres and praets
part_pres = [t for t in tokens if t.full_pos == 'ADJD' and t.mo.part == '<PPRES' and t.function in ['root','pn']]
part_praet = [t for t in tokens if t.full_pos == 'VVPP' ... | 211ad63c56b21e50cbf13be3606a200b5f594565 | 3,619,338 |
from typing import Optional
from typing import Tuple
def bin_stats(predictions: tf.Tensor, labels: tf.Tensor, prefix: Optional[str]=None,
suffix: Optional[str]=None) -> Tuple[tf.Tensor, tf.Tensor, tf.Tensor]:
"""
Calculate f1, precision and recall from binary classification expected and predicte... | 3da2c15f9c468a5bd8f813ca90dab70b1bfa5e33 | 3,619,339 |
def idx2token(idx, reverse_vocab):
"""
index换取词
:param idx: index
:param reverse_vocab: 反查表 @see chatbot.build_vocab
:return: 词
"""
return reverse_vocab[idx] | 4ce26e6a6a103133ffe0212d01a4c52a8a23479d | 3,619,340 |
import requests
def bbc_news(to_say: str) -> str:
"""
This function provides the needed information for the news briefing.
:param to_say: str - to_say
:return: str - to say
"""
api_key2 = data["api_key2"]
url = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey="
final... | 8fe2925aade6088ccd8e66acbc50536096ccc11a | 3,619,341 |
def commandPanelOverride(*args, **kwargs):
"""
Returns an command panel override wrapper for the supplied function.
:rtype: method
"""
# Check number of arguments
#
numArgs = len(args)
if numArgs == 0:
return partial(commandPanelOverride, **kwargs)
elif numArgs == 1:
... | f9d2650143ebbb5506b789f0ab1ad104965d27c4 | 3,619,342 |
import os
def _process_video(filename, coder):
"""
Process a single video file using FFmpeg
Args
filename: path to the video file
coder: instance of ImageCoder to provide TensorFlow image coding utils.
Returns:
video_buffer: numpy array with the video frames
mask_buffer... | 2f4c2560920f725d30ad0bcf15ccdddc6b18d901 | 3,619,343 |
import collections
from dateutil import tz
def combine_multiple_callers(samples):
"""Collapse together variant calls from multiple approaches into single data item with `variants`.
"""
by_bam = collections.OrderedDict()
for data in (x[0] for x in samples):
work_bam = tz.get_in(("combine", "wor... | b00bf6edbd9f78a81d6bd3930d0194a6887cb6e8 | 3,619,344 |
def add_category():
"""Add a new category."""
if 'username' not in login_session:
flash("Please log in to continue.")
return redirect(url_for('login'))
elif request.method == 'POST':
if request.form['new-category-name'] == '':
flash('The field cannot be empty.')
... | 820804fbd4d404ed349a178d870e5d3bab2e1ae5 | 3,619,345 |
import typing
def formatString(format: str, data: typing.Dict, structure=None, language=None):
"""Central entryPoint
if string contains $( we use old formatstrings
else we use evalStrings (core 3.0 draft)
displayStrings actually only used in relations and records. This handler can be used with displ... | 9698dd17e12739c81c6b07b829bcdf0faa439937 | 3,619,346 |
from typing import List
def _analyzable_entities(ns: str, ws: str, workflow_name: str, etype: str, enames: List[str],
days_back: int or None, count: int or None) -> List[str]:
"""
Given a homogeneous (in terms of etype) list of entities, return a sub-list of them who are analyzable no... | e87887d51e2cf0b63b2a36aab78ce03f49f9f5bf | 3,619,347 |
def call(func: Types.Function) -> Types.Function:
"""
Call the function during module exection if microtest is running
or doing configuration.
"""
if core.running or core.config_in_process:
core.call_with_resources(func)
return func | 21867cea60940c9eddaee952190553869cfb13ae | 3,619,348 |
from datetime import datetime
def localize_utc(value):
"""
Localise a UTC datetime
"""
if isinstance(value, datetime):
return value.replace(tzinfo=tzutc()).astimezone(tzlocal())
else:
return value | 26a8ebd46bc1f2572d241b1fe35070e61d72c9e4 | 3,619,349 |
import math
def generate_init_tfs(pairs, n_slcs, n_tiles):
"""Find the transformation of each tile to tile[0,0]."""
tf0 = SimilarityTransform()
init_tfs = np.empty([n_slcs, n_tiles, 3])
for pair in pairs:
p, _, _, model, _ = pair
if (p[0][1] == 0) & (p[0][0] == p[1][0]): # referenced ... | c6bd976406c4338ab78dd6b4e20fd8175abf0d9c | 3,619,350 |
def matches(event, name):
"""
Returns True if the given event represents the same key as the one given in
`name`.
"""
if is_number(name):
return event.scan_code == name
normalized = _normalize_name(name)
matched_name = (
normalized == event.name
or 'left ' + normaliz... | 33a046925c018785647a27b5e4246664c09b1817 | 3,619,351 |
import logging
import csv
import subprocess
import os
import traceback
import sys
def process_csv(csv_file: str, store_name: str, store_list: list) -> int: # pragma: no cover
"""
Input the specified CSV file and process the narratives defined in it.
The format of the CSV MUST be:
Source,Title,Pers... | aba7f698a6140dc4df09608a20ba8909155880fc | 3,619,352 |
import time
def vectorize_unknown(content_to_analyze):
""" """
try:
start = time.time()
print("Tfidf Vectorizing data to be analyzed...")
unknown = pd.DataFrame({"content": [content_to_analyze]})
unknown_vectors = vectorizer.transform(unknown.content)
unknown_words_df ... | 8745ea362d34d9e6ffbb14dad4c60355719d2c39 | 3,619,353 |
def message_from_lax(data):
"""
format a message from a Lax response data
"""
return data.get("message") if data.get("message") else "(empty message)" | 81ba7399bc0e3e86ee1967988a17fd7f3524d8ab | 3,619,354 |
import pwd
import os
def get_username():
"""get the current users user name"""
return pwd.getpwuid(os.geteuid()).pw_name | 0748a32ba9925250f1cae6ff454d79ef3808c59a | 3,619,355 |
def b58decode(encoded):
"""Decodes a base58 string to its integer value"""
value = 0
multiplier = 1
for c in encoded[::-1]:
value += b58chars.index(c) * multiplier
multiplier *= b58base
return value | f5788a14d4ac0dc6e6f0296f4178c419d3173ffe | 3,619,356 |
def calc_geyser_rewards(badger, periodStartBlock, endBlock, cycle):
"""
Calculate rewards for each geyser, and sum them
userRewards = (userShareSeconds / totalShareSeconds) / tokensReleased
(For each token, for the time period)
"""
rewardsByGeyser = {}
# For each Geyser, get a list of user ... | 642320722579c0f0b431649decd6a3ec49be18fe | 3,619,357 |
def createWindow(mainWidget, theme=None, title='CandySweet', ico_path=''):
"""
快速创建彩色窗 (带TitleBar)
:param mainWidget:
:param theme:
:param title:
:param ico_path:
:return:
"""
coolWindow = WindowWithTitleBar.WindowWithTitleBar(mainWidget)
coolWindow.setWindowTitle(title)
cool... | 163e6785ec303a2d74473d93e3e9ca834993886e | 3,619,358 |
def center_image_in_frame3d(image, centroid, size):
"""Centers a point in an image.
Parameters
----------
image : 3d np.ndarray
Image.
centroid : 2-tuple of int/float
Point to center. Coordinates should be (rr, cc).
size : 2-tuple of int
Size of returned-image.
Re... | 18f9659384a14cfbca77aa4a3b913a03df0048fd | 3,619,359 |
def part1(_input):
"""
part 1
"""
dif1 = 0
dif3 = 0
for idx, num in enumerate(_input):
try:
nxt = abs(_input[idx+1] - num)
if nxt == 1:
dif1 += 1
if nxt == 3:
dif3 += 1
except IndexError:
break
#... | 5bd2e4edffe2cef9dc30d51025d54a7831675788 | 3,619,360 |
import itertools
def get_n_bits_combinations(num_bits: int) -> list:
"""
Function returning list containing all combinations of n bits.
Given num_bits binary bits, each bit has value 0 or 1,
there are in total 2**n_bits combinations.
:param num_bits: int, number of combinations to evaluate
:r... | 6813f76f856a639688d6b80ddce0e605707f8d1f | 3,619,361 |
import oe.recipeutils
import os
import fnmatch
def determine_file_source(targetpath, rd):
"""Assuming we know a file came from a specific recipe, figure out exactly where it came from"""
# See if it's in do_install for the recipe
workdir = rd.getVar('WORKDIR')
src_uri = rd.getVar('SRC_URI')
srcfi... | 7b42192f5c58ea605698c8466de37a3e359e4cc6 | 3,619,362 |
import sys
import json
def mastQuery(request):
"""Perform a MAST query.
Parameters
----------
request (dictionary): The Mashup request json object
Returns head,content where head is the response HTTP headers, and content is the returned data"""
server='mast.s... | b8798309b52e0d8d1d20a99ecd64c83e39facc50 | 3,619,363 |
def counting_sort(nums):
"""
counting sort algorithm's complexity is:
time = O(n + k)
space = O(n + k)
where k = max(nums)
Apply this algorithm when O(k) <= O(n), and when all numbers in nums are >= 0
"""
# get frequency list
num_max = max(nums)
freqs = [0] * (num_max + 1)
fo... | 7bfdd8db0f1b177d4e6d3749ef10b997c0c07f81 | 3,619,364 |
def make_dict(data_for_dict):
""" takes all text from nubbe list and makes a dictionary.
data_for_dict: nubbe list created with parse_file()
"""
column_name_list = data_for_dict[0]
db_list = data_for_dict[1:]
column_list1 = []
column_list2 = []
column_list3 = []
column... | cb4725d0d23a33ba9e0b699032478dd1e54940b2 | 3,619,365 |
def accuracy_wilson(y_true, y_pred):
"""Return a Wilson confidence interval for the accuracy metric.
Parameters
----------
y_true : array-like of shape (n_samples,)
Ground truth labels
y_pred : array-like of shape (n_samples,)
Predicted labels
Returns
-------
np.nda... | 84d9cec0e69828a57fc67139ee7c1334a7a81a6d | 3,619,366 |
def extract_object_boxes_for_scenes(name, scene_info, sids, padding, swap_yz,
box_delta_t):
"""Extracts object boxes given scene IDs.
Args:
name: The object name.
scene_info: The scene information.
sids: [R, 1] tf.int32. Scene IDs.
padding: float32. The amount of... | 67065a3bb05cd471b2e211a513fd77d05c428473 | 3,619,367 |
def api_get_and_validate_credentials() -> (str, str):
""" Sanitize access and secret keys from request """
access_key = request.values.get("access_key", None)
secret_key = request.values.get("secret_key", None)
# reject empty strings and value-not-present cases
if not access_key or not secret_key:
... | fcb94c52e3c98e9eb0c0137607357cdf8193426d | 3,619,368 |
import pkg_resources
def resource_exists(filename: str) -> bool:
"""
Check if a package resource exists.
Parameters
----------
filename : str
The filename.
Returns
-------
bool
True if the file exists otherwise False.
"""
return pkg_resources.resource_exists(... | 5daafd2f371de90316229ff4aad3ae69fa993346 | 3,619,369 |
import re
import urllib
import string
import time
from datetime import datetime
def getSerieData(serie, proxies=None, url="http://www.epguides.com/"):
"""Get all data for given series from epguides.com
@param series a dict of {<name on epguides>:<long name>, ...}
"""
# line example
# 1. 1-... | 9b1087771f3ae8e128a49290fe07ded263a7b364 | 3,619,370 |
def guess_type(val, empty_as_null: bool) -> ColumnType:
"""Guess type of a value"""
if val is None:
return ColumnType.NULL
assert isinstance(val, (int, float, str)), "Invalid column data"
if fastnumbers.isfloat(val):
return ColumnType.NUMBER
else:
if len(val.strip()) == 0 an... | 358c9ef76040251449d3516ea06dd4b21c627c12 | 3,619,371 |
def get_centers(bins):
"""Return the center of the provided bins.
Example:
>>> get_centers(bins=np.array([0.0, 1.0, 2.0]))
array([0.5, 1.5])
"""
bins = bins.astype(float)
return (bins[:-1] + bins[1:]) / 2 | 4f5b3454e1ef718302c7e5ea204954d498ca9e10 | 3,619,372 |
import six
import glob
def parse_all_validations_on_disk(path,
groups=None,
categories=None,
products=None):
"""Return a list of validations metadata which can be sorted by Groups, by
Categories or by Product... | 9f205ccb2bb19f41a71888a07800de5b0289b02d | 3,619,373 |
from typing import Concatenate
def create_alexnet_model_2d(input_image_size,
number_of_classification_labels=1000,
number_of_dense_units=4096,
dropout_rate=0.0,
mode='classification'):
"""
2-D imple... | ba24617a0bce806d5b0c9a9a5f512f1614268d03 | 3,619,374 |
def pretty_event_latex(event: EventType, nonexisting: str = r'\varnothing') -> str:
"""
Takes an event type an prettifies it.
:param event: event type to prettify
:param nonexisting: string to represent non-existing nodes
:return: prettified event type as string \makebox[\elen][c]{{{}}}
"""
... | 174816048511bc6e3a32a0eecf21bc91b918b5fb | 3,619,375 |
def hex_16bit(value):
"""Converts 16bit value into bytearray.
args:
16bit value
returns:
bytearray of size 2
"""
if value > 0xffff or value < 0:
raise Exception('Sar file 16bit value %s out of range' % value)
return value.to_bytes(2, 'little') | 1c5aab076798b40459bf5afab73fd92e8dbb93a1 | 3,619,376 |
import torch
def comp_subclusters_params_min_dist(codes_k, mu_sub_1, mu_sub_2):
"""
Comp assignments to subclusters by min dist to subclusters centers
codes_k (torch.tensor): the datapoints assigned to the k-th cluster
mu_sub_1, mu_sub_2 (torch.tensor, torch.tensor): the centroids of the first and sec... | 5ca26cebf2dd21da3f2ca2510e73edb01ec102d1 | 3,619,377 |
import os
import subprocess
def view_video(file_path):
"""View the video file
# Arguments
file_path [str]: the path to file
# Returns
[HTML Video]: the video prompt pointing to correct file
"""
relative_url = transfer_file_to_public_dir(file_path)
# convert to mp4 transferab... | d979ad24afaa949c392f0343dede6c75e74557db | 3,619,378 |
import os
def ensure_path( path, inc_file=False ):
"""
extension: ensures that the input path exists, creating directories as needed
input: string (path/to/file), Boolean (see notes)
output: None
notes: if inc_file is True the last element of path is assumed to be a file
this file is crea... | 30868d42ade7acc952d83b2bd208b5e9489c92f7 | 3,619,379 |
def matrix_active_subspaces(generators,rep_out,rep_in):
""" Like get_active_subspaces, this function returns function that maps to the
subspace of linear maps from the input representation to the output representation.
Inputs: [generators seq(tensor(d,d))] [rep_out seq(tuple(q,p)] [rep_in se... | 8f454e2917f3c5cd3f142d5faf162cb497c35e9d | 3,619,380 |
def compute_normalized_license(declared_license):
"""
Return a normalized license expression string detected from a list of
declared license items.
"""
if not declared_license:
return
detected_licenses = []
for declared in declared_license:
if isinstance(declared, str):
... | a1346ef583a07cc9da1456c6aa13f58917eae21c | 3,619,381 |
import copy
import json
import hashlib
def generate_key(dict_data, daily=True):
"""generate key from a dictionary"""
cache_dict = copy.copy(dict_data)
json_data = json.dumps(cache_dict)
return hashlib.md5(json_data.encode('utf-8')).hexdigest() | dee5f0519fccc89353be7fafe006a5280c535261 | 3,619,382 |
import copy
def caller_add_contexts(h_ea, mnem, ops, i_curf, er_ctx, dst_eas):
"""
At a function call, adds a caller context and callee context for the
callsite. Multiple caller contexts are created but only one callee context
is created
:param h_ea: effective address of the call instruction
:... | f091e8437fce6b026bbe1d4ec3b40d6a5c5c1551 | 3,619,383 |
def count_attrib_correct(pred, label, idx):
"""
:param pred:
:param label:
:param idx:
:return:
"""
assert pred.size(0) == label.size(0)
correct_num = 0
for one, two in zip(pred, label):
if one[idx] == two[idx]:
correct_num += 1
return correct_num | 5ad4b4191f99e379bfec14d2fd2fd954273e97f7 | 3,619,384 |
import sqlite3
def login():
"""Endpoint to manage user login"""
con = sqlite3.connect('example.db')
cur = con.cursor()
# Insert a row of data
uname = request.json["username"]
passwd = request.json["password"]
ns = request.json["ns"]
try:
if ns == net_sec :
temp = 0... | 637492089d224d6803a26ccdc1de0749a908b077 | 3,619,385 |
from typing import Dict
def extract_feature(sig1 : Dict[str, dict],
sig2 : Dict[str, dict],
attribute : str) -> float :
"""
Returns 1 if attribute is equal in sig1 and sig2 otherwise 0.
If attribute is missing, returns np.nan
"""
if (sig1.get(attribute, Non... | 79e775e02caf73843511c2c2cc366ebf65006faa | 3,619,386 |
import ast
import operator
def _eval_expr(expr):
"""
https://stackoverflow.com/questions/2371436/evaluating-a-mathematical-expression-in-a-string
>>> _eval_expr('2^6')
4
>>> _eval_expr('2**6')
64
>>> _eval_expr('1 + 2*3**(4^5) / (6 + -7)')
-5.0
"""
operators = {
ast.Add... | f32864007ed0b04d8cd538a18fce54bc238cbf1b | 3,619,387 |
def avg_fuel_per_hour(iterable):
"""
>>> round(avg_fuel_per_hour(clean_data(row_merge(log_rows))), 3)
0.48
"""
return mean(row.fuel_per_hour for row in iterable) | 0e6e5e57f2552693f3cc0c525631a753fcd34672 | 3,619,388 |
def transpose(matrix):
"""Transpose a list of lists.
>>> transpose([['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']])
[['a', 'd', 'g'], ['b', 'e', 'h'], ['c', 'f', 'i']]
>>> transpose([['a', 'b', 'c'], ['d', 'e', 'f']])
[['a', 'd'], ['b', 'e'], ['c', 'f']]
>>> transpose([['a', 'b'], ['d', '... | e96e7fbd074115a4291cc495c0251d1083f4592e | 3,619,389 |
from typing import Dict
from typing import Type
def get_handlers_callable() -> Dict[str, Type[PotentialHandler]]:
"""Map Foyer-style handlers from string identifiers."""
return {
"vdW": FoyerVDWHandler,
"Electrostatics": FoyerElectrostaticsHandler,
"Bonds": FoyerHarmonicBondHandler,
... | 6adb79f8988969c7171371122039267317669e99 | 3,619,390 |
import json
def get_json_line(data):
"""Get json string from data."""
return json.dumps(data,
ensure_ascii=False,
sort_keys=True,
cls=_MetaEncoder) | adf1f8d15107f7d74b54c7c45cb2f0cc2582c6a4 | 3,619,391 |
def fetch_group(gid):
"""Return the group with the specified gid, or 404 if there isn't one."""
groups = find_groups(gid=gid)
if groups:
return groups[0]._asdict()
return ("Not found", 404) | 07aa0a70ab72cd87aded3e30770c145cce7df0a9 | 3,619,392 |
import torch
def get_latent_variable(batchsize, latent_dimension, device):
"""Creates a random vector of size (batchsize, latent_dimension)
from normal distribution.
"""
latent_var = randn(
(batchsize, latent_dimension), requires_grad=True
).to(device)
return latent_var / torch... | ae34d4a47c3b445ddd2734c82fea484a01cc54bc | 3,619,393 |
import torch
def reduce(tensor: torch.Tensor, reduction: str) -> torch.Tensor:
"""Reduces the given tensor using a specific criterion.
Args:
tensor (torch.Tensor): input tensor
reduction (str): string with fixed values [elementwise_mean, none, sum]
Raises:
ValueError: when the re... | a77edd7f9a8486a8fd604b9a35c2ecfe28d43c8c | 3,619,394 |
def safe_read_tensor_value(variable):
"""Reads variable value or raises an exception."""
value = variable.tensor_value
if value is None:
raise ValueError("".join((
"Attempted to read a TensorVariable in a context where it has no ",
"value. This commonly happens for one of two reasons:",
... | a9242ed8913e16cf13eb4bf6dfc1625c3e93723b | 3,619,395 |
def wrap_insecure_channel(insecure_channel_func, tracer=None):
"""Wrap the grpc.insecure_channel."""
def call(*args, **kwargs):
channel = insecure_channel_func(*args, **kwargs)
try:
target = kwargs.get('target')
tracer_interceptor = OpenCensusClientInterceptor(tracer, ta... | 0058e712bd9fb62bfbc607bc1d87088ac40c4e95 | 3,619,396 |
def obliquity (T : float) -> float :
"""
Returns the obliquity angle of the ecliptic [rads]
"""
return pipe(obliq_pol(T)/3600.0,deg2rad) | 8a3b79a5f63a1bfb085045498fdb8c44e760a21d | 3,619,397 |
def learning_rate_scheduler(epoch):
"""Outputs the learning rate as a function of the current epoch (2^-n)"""
return args.learning_rate * (2 ** -epoch) | d35d5bfccc4347abb014f3311a457b07367e1f32 | 3,619,398 |
import os
def file_grey(db_path, image_path, suffix="_cv_grey", file_ext="png"):
"""
Generate the greyscale of an image file. Uses opencv cvtColor
for the conversion.
arguments:
db_path : string
POSIX path for the Cinema database
image_path : string
relative ... | 6137a9150d74d5503abaec49bc23fd41900fd132 | 3,619,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.