content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def gravatar_url(email, size=16):
"""Return the gravatar image for the given email address."""
return 'http://www.gravatar.com/avatar/%s?d=identicon&s=%d' % \
(md5(email.strip().lower().encode('utf-8')).hexdigest(), size) | d3e24e1898d41df791368e7909461135c8118f90 | 3,646,000 |
def x2bin(v):
"""
convert a value into a binary string
v: int, bytes, bytearray
bytes, bytearray must be in *big* endian.
"""
if isinstance(v, int):
bits = bin(v)
size = 8
elif isinstance(v, (bytes,bytearray)):
bits = bin(int.from_bytes(v, "big"))
size = l... | fcb4f1ab05b5a3878939c84074e70fc2d5ee6397 | 3,646,001 |
import re
def normalize_url(url):
"""Function to normalize the url. It will be used as document id value.
Returns:
the normalized url string.
"""
norm_url = re.sub(r'http://', '', url)
norm_url = re.sub(r'https://', '', norm_url)
norm_url = re.sub(r'/', '__', norm_url)
return norm_url | 79197b9fa1c47da601bdb9c34d626d236b649173 | 3,646,002 |
import fsspec
def is_remote_filesystem(fs: fsspec.AbstractFileSystem) -> bool:
"""
Validates if filesystem has remote protocol.
Args:
fs (``fsspec.spec.AbstractFileSystem``): An abstract super-class for pythonic file-systems, e.g. :code:`fsspec.filesystem(\'file\')` or :class:`datasets.filesystem... | c40f9bb4845bbd1fc1a4cf9fce2c1b366cd22354 | 3,646,003 |
def get_element_attribute_or_empty(element, attribute_name):
"""
Args:
element (element): The xib's element.
attribute_name (str): The desired attribute's name.
Returns:
The attribute's value, or an empty str if none exists.
"""
return element.attributes[attribute_name].va... | dbc7f5c24d321c40b46f1c78950d7cf254719b5c | 3,646,004 |
def Matcher(y_true, y_pred_logits, y_pred_bbox):
"""
y_true: GT list of len batch with each element is an array of
shape (n_gt_objects, 5) ; n_gt_objects are number of
objects in that image sample and 5 -> (cx,cy,w,h,class_label)
where cordinates are in [0,1]... | 0918becd40feca73a54ce158a3cb86946cb377ff | 3,646,005 |
import os
def set_test_variables():
"""
Sets up variables for the unit tests below.
:return: dictionary of test input variables for the unit tests.
"""
test_variables = {
"asl_valid_full": os.path.join(
SRC_ROOT, "resources/schemas/tests_jsons/asl_valid/test_asl_schema001.json"... | 67dbf1cdb8f99bc05350b5ccf3c81bb5892ce47f | 3,646,006 |
import warnings
def _addBindInput(self, name, type = DEFAULT_TYPE_STRING):
"""(Deprecated) Add a BindInput to this shader reference."""
warnings.warn("This function is deprecated; shader references have been replaced with shader nodes in 1.38.", DeprecationWarning, stacklevel = 2)
return self.addInput(nam... | 79404122d895814f64000876e8f926ecc7d54e3e | 3,646,007 |
import mpmath
def sf(x, c, d, scale):
"""
Survival function of the Burr type XII distribution.
"""
_validate_params(c, d, scale)
with mpmath.extradps(5):
x = mpmath.mpf(x)
c = mpmath.mpf(c)
d = mpmath.mpf(d)
scale = mpmath.mpf(scale)
if x < 0:
re... | 2e2649eeb4d32739027eb6ad5a0f3b8c50f7e341 | 3,646,008 |
def substitute_word(text):
"""
word subsitution to make it consistent
"""
words = text.split(" ")
preprocessed = []
for w in words:
substitution = ""
if w == "mister":
substitution = "mr"
elif w == "missus":
substitution = "mrs"
else:
... | 0709f4223cb06ddfdc5e9704048f418f275429d1 | 3,646,009 |
import re
import requests
from bs4 import BeautifulSoup
def google_wiki(keyword, langid='en', js={}):
"""Google query targets, output if English wikipedia entry is found"""
targets = []
headers = {'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:32.0) Gecko/20100101 Firefox/32.0',}
googl... | 23a449b0b8825d043d1ca3722cba4c373fcc5c3c | 3,646,010 |
from .compile_words import read_words
import os
def _get_test_words() -> WordDict:
"""
>>> _get_test_words()['?og']
['dog', 'log']
"""
dir_path = os.path.dirname(os.path.realpath(__file__))
return read_words(os.path.join(dir_path, 'test_data.txt')) | d97d3125101096a3acba11705f4b9318386e8ae9 | 3,646,011 |
def escape(line, chars):
"""Escapes characters 'chars' with '\\' in 'line'."""
def esc_one_char(ch):
if ch in chars:
return "\\" + ch
else:
return ch
return u"".join([esc_one_char(ch) for ch in line]) | f69409c92eacbbcab4232f7bb0ee244c77a4f219 | 3,646,012 |
def polinomsuzIntegralHesapla(veriler):
"""
Gelen verileri kullanarak integral hesaplar.
:param veriler: İntegrali hesaplanacak veriler. Liste tipinde olmalı.
"""
a,b=5,len(veriler)
deltax = 1
integral = 0
n = int((b - a) / deltax)
for i in range(n-1):
integral += deltax * (v... | 468e02da8ff077b04456f71f0af6d77bf5a47d68 | 3,646,013 |
def _keep_extensions(files, extension):
""" Filters by file extension, this can be more than the extension!
E.g. .png is the extension, gray.png is a possible extension"""
if isinstance(extension, str):
extension = [extension]
def one_equal_extension(some_string, extension_list):
return... | 009233e381e2015ff4d919338225057d94d40a82 | 3,646,014 |
from typing import Dict
def make_all_rules(
schema: "BaseOpenAPISchema", bundles: Dict[str, CaseInsensitiveDict], connections: EndpointConnections
) -> Dict[str, Rule]:
"""Create rules for all endpoints, based on the provided connections."""
return {
f"rule {endpoint.verbose_name}": make_rule(
... | 3b92fdea984b5bfbe2b869640b978398106f098b | 3,646,015 |
def audio_to_magnitude_db_and_phase(n_fft, hop_length_fft, audio):
"""This function takes an audio and convert into spectrogram,
it returns the magnitude in dB and the phase"""
stftaudio = librosa.stft(audio, n_fft=n_fft, hop_length=hop_length_fft)
stftaudio_magnitude, stftaudio_phase = librosa.magp... | b9927f11bc353610fe7edbee9b710bd78fc13899 | 3,646,016 |
import os
def check_racs_exists(base_dir: str) -> bool:
"""
Check if RACS directory exists
Args:
base_dir: Path to base directory
Returns:
True if exists, False otherwise.
"""
return os.path.isdir(os.path.join(base_dir, "EPOCH00")) | efad779a5310b10b2eeefdc10e90f0b78d428bf4 | 3,646,017 |
def has_rc_object(rc_file, name):
"""
Read keys and values corresponding to one settings location
to the qutiprc file.
Parameters
----------
rc_file : str
String specifying file location.
section : str
Tags for the saved data.
"""
config = ConfigParser()
try:
... | e7edd4ba8545257d7d489a7ac8f6e9595b4f087d | 3,646,018 |
import torch
def apply_transform_test(batch_size, image_data_dir, tensor_data_dir, limited_num = None, shuffle_seed = 123, dataset = None):
"""
"""
std = [1.0, 1.0, 1.0]
mean = [0.0, 0.0, 0.0]
# if dataset is None:
# std = [1.0, 1.0, 1.0]
# mean = [0.0, 0.0, 0.0]
# elif dataset... | 664e9fadeb4897aee7ef26abeec9c128ec7cef56 | 3,646,019 |
import re
import collections
import os
def split_datasets(data_dir, word_dict, num_folds, fold_idx):
"""Split known words (including silence) and unknown words into training
and validation datasets respectively.
"""
modes = ['training', 'validation']
knowns = {m: [] for m in modes}
unknowns = {m: [] for... | 1ac3e2d38bb331f8525f095740024cbaa02264d6 | 3,646,020 |
def take_t(n):
"""
Transformation for Sequence.take
:param n: number to take
:return: transformation
"""
return Transformation(
"take({0})".format(n), lambda sequence: islice(sequence, 0, n), None
) | 1e485cc59160dbec8d2fa3f358f51055115eafdd | 3,646,021 |
def metric_fn(loss):
"""Evaluation metric Fn which runs on CPU."""
perplexity = tf.exp(tf.reduce_mean(loss))
return {
"eval/loss": tf.metrics.mean(loss),
"eval/perplexity": tf.metrics.mean(perplexity),
} | 3614ed0ccc3e390aeaf4036805dfeff351d4d150 | 3,646,022 |
def gensig_choi(distsmat, minlength=1, maxlength=None, rank=0):
""" The two dimensional sigma function for the c99 splitting """
if rank:
distsmat = rankify(distsmat, rank)
def sigma(a, b):
length = (b - a)
beta = distsmat[a:b, a:b].sum()
alpha = (b - a)**2
if minlen... | 75568f854eff9c3bbc13b4a46be8b1a2b9651b9b | 3,646,023 |
from typing import Optional
def check_ie_v3(base, add: Optional[str] = None) -> str:
"""Check country specific VAT-Id"""
s = sum((w * int(c) for w, c in zip(range(8, 1, -1), base)),
9 * (ord(add) - ord('@'))) # 'A' - 'I' -> 1 - 9
i = s % 23
return _IE_CC_MAP[i] | 19fd495db8301ed7193881cc637e3ce1b75e368c | 3,646,024 |
def filter_experiment_model(faultgroup, faultmodel, interestlist=None):
"""
Filter for a specific fault model. If interestlist is given only experiments
in this list will be analysed.
0 set 0
1 set 1
2 Toggle
"""
if not isinstance(faultmodel, int):
if "set0" in faultmodel:
... | 7594f7f5a410c3bf9231996989259d1267ed250b | 3,646,025 |
import argparse
def _str2bool(v):
"""Parser type utility function."""
if v.lower() in ('yes', 'true', 't', 'y', 'on', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', 'off', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean type expected. '
... | 7fa90cdff3f2dbe161d28555ec0ef65bae8b6bf3 | 3,646,026 |
import inspect
def _default_command(cmds, argv):
"""Evaluate the default command, handling ``**kwargs`` case.
`argparse` and `argh` do not understand ``**kwargs``, i.e. pass through command.
There's a case (`pykern.pkcli.pytest`) that requires pass through so we wrap
the command and clear `argv` in t... | aecaaba610ec473b41f1cd546cb5c551541d9fab | 3,646,027 |
import os
def keypair_to_file(keypair):
"""Looks for the SSH private key for keypair under ~/.ssh/
Prints an error if the file doesn't exist.
Args:
keypair (string) : AWS keypair to locate a private key for
Returns:
(string|None) : SSH private key file path or None is the private ke... | 0f544fd7d67530853bc4d8a91df01458d6408255 | 3,646,028 |
def nameable_op(node_factory_function): # type: (Callable) -> Callable
"""Set the name to the ngraph operator returned by the wrapped function."""
@wraps(node_factory_function)
def wrapper(*args, **kwargs): # type: (*Any, **Any) -> Node
node = node_factory_function(*args, **kwargs)
node = ... | 0230c96e40b91772dc06a0b2c9cf358d1e0b08c7 | 3,646,029 |
import os
import yaml
def load_mlflow(output):
"""Load the mlflow run id.
Args:
output (str): Output directory
"""
with open(os.path.join(output, STAT_FILE_NAME), 'r') as stream:
stats = load(stream, Loader=yaml.FullLoader)
return stats['mlflow_run_id'] | 01b2c05a9d3d8f4c83f7997cdb31d213cbce342a | 3,646,030 |
import re
def by_pattern(finding: finding.Entry, ignore: ignore_list.Entry) -> bool:
"""Process a regex ignore list entry."""
# Short circuit if no pattern is set.
if not ignore.pattern:
return False
# If there's a match on the path, check whether the ignore is for the same module.
if re.... | bbeb7d8ab740273bd21c120ca7bc42dc205e4a2b | 3,646,031 |
def hex2int(s: str):
"""Convert a hex-octets (a sequence of octets) to an integer"""
return int(s, 16) | ecdb3152f8c661c944edd2811d016fce225c3d51 | 3,646,032 |
from operator import index
def into_two(lhs, ctx):
"""Element I
(num) -> push a spaces
(str) -> equivlaent to `qp`
(lst) -> split a list into two halves
"""
ts = vy_type(lhs, simple=True)
return {
NUMBER_TYPE: lambda: " " * int(lhs),
str: lambda: quotify(lhs, ctx) + lhs,
... | 6fae5eb7c5ae58a0e7faef6e46334201ccc6df10 | 3,646,033 |
def find_renter_choice(par,sol,t,i_beta,i_ht_lag,i_p,a_lag,
inv_v,inv_mu,v,mu,p,valid,do_mu=True):
""" find renter choice - used in both solution and simulation """
v_agg = np.zeros(2)
p_agg = np.zeros(2)
# a. x
iota_lag = -1
i_h_lag = -1
LTV_lag = np.nan
_m... | f6cffb4ce6ed3ddaa98edefefdb6962536fbffb8 | 3,646,034 |
def met_zhengkl_gh(p, rx, cond_source, n, r):
"""
Zheng 2000 test implemented with Gauss Hermite quadrature.
"""
X, Y = sample_xy(rx, cond_source, n, r)
rate = (cond_source.dx() + cond_source.dy()) * 4./5
# start timing
with util.ContextTimer() as t:
# the test
zheng_gh = cgo... | 41bef090ccc515be895bd08eda451864c330327e | 3,646,035 |
from typing import Optional
from typing import Sequence
def get_domains(admin_managed: Optional[bool] = None,
include_unverified: Optional[bool] = None,
only_default: Optional[bool] = None,
only_initial: Optional[bool] = None,
only_root: Optional[bool] =... | e7cb3a42ec7be45153c67d860b4802669f8043e5 | 3,646,036 |
import six
def get_writer(Writer=None, fast_writer=True, **kwargs):
"""
Initialize a table writer allowing for common customizations. Most of the
default behavior for various parameters is determined by the Writer class.
Parameters
----------
Writer : ``Writer``
Writer class (DEPRECA... | 0e51b930d90585905b37ddd585cdfd53de111aa9 | 3,646,037 |
def find_last_service(obj):
"""Identify last service event for instrument"""
return Service.objects.filter(equipment=obj).order_by('-date').first() | 5c7c74b376568fc57268e8fe7c1970c03d61ad2c | 3,646,038 |
def SectionsMenu(base_title=_("Sections"), section_items_key="all", ignore_options=True):
"""
displays the menu for all sections
:return:
"""
items = get_all_items("sections")
return dig_tree(SubFolderObjectContainer(title2=_("Sections"), no_cache=True, no_history=True), items, None,
... | ea3766d923337e1dffc07dec5e5d042e2c85050c | 3,646,039 |
def perform_save_or_create_role(is_professor, created_user, req_main, is_creating):
"""Performs update or create Student or Professor for user"""
response_verb = 'created' if is_creating else 'updated'
if is_professor is True:
professor_data = None
if 'professor' in req_main.keys():
... | 6161aaf886b31209a8387426f812cda73b739df2 | 3,646,040 |
def ecg_rsp(ecg_rate, sampling_rate=1000, method="vangent2019"):
"""Extract ECG Derived Respiration (EDR).
This implementation is far from being complete, as the information in the related papers
prevents me from getting a full understanding of the procedure. Help is required!
Parameters
---------... | ec4ecdbf4489216124ef82399c548461968ca45b | 3,646,041 |
def bootstrap(request):
"""Concatenates bootstrap.js files from all installed Hue apps."""
# Has some None's for apps that don't have bootsraps.
all_bootstraps = [(app, app.get_bootstrap_file()) for app in appmanager.DESKTOP_APPS if request.user.has_hue_permission(action="access", app=app.name)]
# Iterator ov... | 94be21562c383ad93c7a0530810bb08f41f3eb26 | 3,646,042 |
def get_selection(selection):
"""Return a valid model selection."""
if not isinstance(selection, str) and not isinstance(selection, list):
raise TypeError('The selection setting must be a string or a list.')
if isinstance(selection, str):
if selection.lower() == 'all' or selection == '':
... | 996d0af844e7c1660bcc67e24b33c31861296d93 | 3,646,043 |
def getAllImageFilesInHierarchy(path):
"""
Returns a list of file paths relative to 'path' for all images under the given directory,
recursively looking in subdirectories
"""
return [f for f in scan_tree(path)] | 821147ac2def3f04cb9ecc7050afca85d54b6543 | 3,646,044 |
def list_package(connection, args):
"""List information about package contents"""
package = sap.adt.Package(connection, args.name)
for pkg, subpackages, objects in sap.adt.package.walk(package):
basedir = '/'.join(pkg)
if basedir:
basedir += '/'
if not args.recursive:
... | 7c8e0cb8a6d5e80a95ae216ad2b85309f0b4d45c | 3,646,045 |
def calc_hebrew_bias(probs):
"""
:param probs: list of negative log likelihoods for a Hebrew corpus
:return: gender bias in corpus
"""
bias = 0
for idx in range(0, len(probs), 16):
bias -= probs[idx + 1] + probs[idx + 5] + probs[idx + 9] + probs[idx + 13]
bias += probs[idx + 2] +... | 565be51b51d857c671ee44e090c5243e4d207942 | 3,646,046 |
import pickle
def load_wiki(size = 128, validate = True):
"""
Return malaya pretrained wikipedia ELMO size N.
Parameters
----------
size: int, (default=128)
validate: bool, (default=True)
Returns
-------
dictionary: dictionary of dictionary, reverse dictionary and vectors
"""... | 6daaa592000f8cb4ac54632729bda60c7325548d | 3,646,047 |
def generate_pibindex_rois_fs(aparc_aseg):
""" given an aparc aseg in pet space:
generate wm, gm and pibindex rois
make sure they are non-overlapping
return 3 rois"""
wm = mask_from_aseg(aparc_aseg, wm_aseg())
gm = mask_from_aseg(aparc_aseg, gm_aseg())
pibi = mask_from_aseg(aparc_aseg, pibi... | 35023b9084bb90f6b74f3f39b8fd79f03eb825d9 | 3,646,048 |
from datetime import datetime
import sys
import glob
import os
def get_log_name(GLASNOST_ROOT, start_time, client_ip, mlab_server):
"""Helper method that given a test key, finds the logfile"""
log_glob = "%s/%s.measurement-lab.org/%s_%s_*" % (start_time.strftime('%Y/%m/%d'), mlab_server, start_time.strftim... | 2492ad96563a7a93a9b00d9e5e20742b7f645ec3 | 3,646,049 |
import torch
def generate_mpc_imitate(dataset, data_params, nn_params, train_params):
"""
Will be used for imitative control of the model predictive controller.
Could try adding noise to the sampled acitons...
"""
class ImitativePolicy(nn.Module):
def __init__(self, nn_params):
... | 2aefbb10256a008e58f329cb84f0351255deb304 | 3,646,050 |
import logging
def rescale(img, mask, factor):
"""Rescale image and mask."""
logging.info('Scaling: %s', array_info(img))
info = img.info
img = ndimage.interpolation.zoom(img, factor + (1,), order=0)
info['spacing'] = [s/f for s, f in zip(info['spacing'], factor)]
mask = rescale_mask(mask, fac... | 9f8676a34e58eec258227d8ba41891f4bab7e895 | 3,646,051 |
def get_data_all(path):
"""
Get all data of Nest and reorder them.
:param path: the path of the Nest folder
:return:
"""
nb = count_number_of_label(path+ 'labels.csv')
data_pop = {}
for i in range(nb):
label, type = get_label_and_type(path + 'labels.csv', i)
field, data =... | 94409d671b287ce213088817a4ad41be86126508 | 3,646,052 |
def from_tfrecord_parse(
record,
pre_process_func=None,
jpeg_encoded=False):
"""
This function is made to work with the prepare_data.TFRecordWriter class.
It parses a single tf.Example records.
Arguments:
record : the tf.Example record with the features of
... | 2e32accfe7485058fa4aff7c683265b939184c94 | 3,646,053 |
def load_shapes_coords(annotation_path):
"""
> TODO: Ensure and correct the clockwise order of the coords of a QUAD
"""
quads_coords = pd.read_csv(annotation_path, header=None)
quads_coords = quads_coords.iloc[:,:-1].values # [n_box, 8]
quads_coords = quads_coords.reshape(-1, 4, 2)
if... | 8761ccfa1dac718c4a7df7cb6ced12df3e656a7a | 3,646,054 |
import sys
import os
def caller_path(steps=1, names=None):
"""Return the path to the file of the current frames' caller."""
frame = sys._getframe(steps + 1)
try:
path = os.path.dirname(frame.f_code.co_filename)
finally:
del frame
if not path:
path = os.getcwd()
if na... | 74d617d970df49854e98c7147d7b830e2dc230cf | 3,646,055 |
import json
import re
def reader_json_totals(list_filenames):
"""
This reads the json files with totals and returns them as a list of dicts.
It will verify that the name of the file starts with totals.json to read it.
This way, we can just send to the function all the files in the directory and it wil... | 57f27dbb3eabee014a23449b7975295b088b5e72 | 3,646,056 |
def is_hitachi(dicom_input):
"""
Use this function to detect if a dicom series is a hitachi dataset
:param dicom_input: directory with dicom files for 1 scan of a dicom_header
"""
# read dicom header
header = dicom_input[0]
if 'Manufacturer' not in header or 'Modality' not in header:
... | c039c0535823edda2f66c3e445a5800a9890f155 | 3,646,057 |
def index_of_first_signal(evt_index, d, qsets, MAXT3):
""" Check the evt_index of the last signal triplet (MC truth).
Args:
Returns:
"""
first_index = -1
k = 0
for tset in qsets:
for ind in tset: # Pick first of alternatives and break
#[HERE ADD THE OPTION TO CHOOSE ... | cd156faceaf3cf3261b2ba217cda5a6c0e3ce4b8 | 3,646,058 |
import numpy
def readcrd(filename, REAL):
"""
It reads the crd file, file that contains the charges information.
Arguments
----------
filename : name of the file that contains the surface information.
REAL : data type.
Returns
-------
pos : (Nqx3) array, positions of the... | efafc2e53eebeacbe6a1a5b1e346d0e121fa7a62 | 3,646,059 |
def load_and_initialize_hub_module(module_path, signature='default'):
"""Loads graph of a TF-Hub module and initializes it into a session.
Args:
module_path: string Path to TF-Hub module.
signature: string Signature to use when creating the apply graph.
Return:
graph: tf.Graph Graph of the module.
... | b04b5f77c7e0207d314ebb5910ec1c5e61f4755c | 3,646,060 |
def get_mention_token_dist(m1, m2):
""" Returns distance in tokens between two mentions """
succ = m1.tokens[0].doc_index < m2.tokens[0].doc_index
first = m1 if succ else m2
second = m2 if succ else m1
return max(0, second.tokens[0].doc_index - first.tokens[-1].doc_index) | 84052f805193b1d653bf8cc22f5d37b6f8de66f4 | 3,646,061 |
def shlcar3x3(x,y,z, ps):
"""
This subroutine returns the shielding field for the earth's dipole, represented by
2x3x3=18 "cartesian" harmonics, tilted with respect to the z=0 plane (nb#4, p.74)
:param x,y,z: GSM coordinates in Re (1 Re = 6371.2 km)
:param ps: geo-dipole tilt angle in radius.
... | 5729e0999ddefaf2ee39ad9588009cc58f983130 | 3,646,062 |
def raan2ltan(date, raan, type="mean"):
"""Conversion to True Local Time at Ascending Node (LTAN)
Args:
date (Date) : Date of the conversion
raan (float) : RAAN in radians, in EME2000
type (str) : either "mean" or "true"
Return:
float : LTAN in hours
"""
if type == ... | 90956203d7b5787f5d49941f89b7871d021e5e74 | 3,646,063 |
def _extract_bbox_annotation(prediction, b, obj_i):
"""Constructs COCO format bounding box annotation."""
height = prediction['eval_height'][b]
width = prediction['eval_width'][b]
bbox = _denormalize_to_coco_bbox(
prediction['groundtruth_boxes'][b][obj_i, :], height, width)
if 'groundtruth_area' in pred... | c79a066b719e33704d50128f4d01420af0be27ce | 3,646,064 |
def value_and_entropy(emax, F, bw, grid_size=1000):
"""
Compute the value function and entropy levels for a θ path
increasing until it reaches the specified target entropy value.
Parameters
==========
emax: scalar
The target entropy value
F: array_like
The policy function t... | c9b215d91c6a0affbb4ad8f344614a1f2b6b9a13 | 3,646,065 |
import os
import glob
def browse_directory():
"""
Browse the local file system starting at the given path and provide the following information:
- project_name_unique: If the given project name is not yet registered in the projects list
- project_path_prefix: The given path with a final separator, e.g... | e8daa6cb0c28f50f536223bf9aac0ae1008d9001 | 3,646,066 |
def _biorthogonal_window_loopy(analysis_window, shift):
"""
This version of the synthesis calculation is as close as possible to the
Matlab implementation in terms of variable names.
The results are equal.
The implementation follows equation A.92 in
Krueger, A. Modellbasierte Merkmalsverbesser... | 5fc5dd23cb0b01af93a02812210d3b44b2fe84ab | 3,646,067 |
def depthwise(data, N, H, W, CI, k_ch, KH, KW, PAD_H, PAD_W, SH, SW, block_size, use_bias=False):
"""
Depthwise 5-D convolutions,every channel has its filter-kernel
Args:
data (list):a list,the size is 3 if use_bias else the size is 2;
data[0] tvm.tensor.Tensor of type float16 ,shape ... | c47ef1cc929ecc9b26550f1eabe1e52073b82028 | 3,646,068 |
import json
async def get_last_recipe_json():
""" Doc Str """
with open(DEBUG_DIR.joinpath("last_recipe.json"), "r") as f:
return json.loads(f.read()) | 71122ff4b4580f30f9d1cec33891289ecb7c574a | 3,646,069 |
def FindDescendantComponents(config, component_def):
"""Return a list of all nested components under the given component."""
path_plus_delim = component_def.path.lower() + '>'
return [cd for cd in config.component_defs
if cd.path.lower().startswith(path_plus_delim)] | f9734442bbe3a01460970b3521827dda4846f448 | 3,646,070 |
def _get_source(loader, fullname):
"""
This method is here as a replacement for SourceLoader.get_source. That
method returns unicode, but we prefer bytes.
"""
path = loader.get_filename(fullname)
try:
return loader.get_data(path)
except OSError:
raise ImportError('source not ... | af43b79fa1d90abbbdb66d7d1e3ead480e27cdd1 | 3,646,071 |
from pathlib import Path
def get_source_files(sf: Path) -> list:
"""
Search for files ending in .FLAC/.flac and add them to a list.
Args:
sf (str/pathlib.Path): Folder location to search for files.
Returns:
list: List of file locations found to match .FLAC/.fladc.
"""
return ... | 3828d81528b144367c3d5a74ee212caf2a01b111 | 3,646,072 |
import io
def extract_features(clip):
"""
Feature extraction from an audio clip
Args:
clip ():
Returns: A list of feature vectors
"""
sr, clip_array = wav_read(io.BytesIO(clip))
if clip_array.ndim > 1:
clip_array = clip_array[:, 0]
segments = frame_breaker.get_frames(... | 13c6c18be92067847eaabada17952a0dab142a3f | 3,646,073 |
def comparison_func(target: TwoQubitWeylDecomposition,
basis: TwoQubitBasisDecomposer,
base_fid: float,
comp_method: str):
"""
Decompose traces for arbitrary angle rotations.
This assumes that the tq angles go from highest to lowest.
... | a222138a8c3a01aaf6c3657c6bbbaca284332b76 | 3,646,074 |
from bs4 import BeautifulSoup
def create_bs4_obj(connection):
"""Creates a beautiful Soup object"""
soup = BeautifulSoup(connection, 'html.parser')
return soup | b3956b13756e29cd57a0e12457a2d665959fb03d | 3,646,075 |
def __create_dataframe_from_cassandra(query,con):
"""
Function to query into Cassandra and Create Pandas DataFrame
Parameter
---------
query : String - Cassandra Query
con : cassandra connection object
Return
------
df : pd.DataFrame - DataFrame created using the ... | af839ce372af100b4a496350ed6e21ae12b82444 | 3,646,076 |
import os
import pickle
import tqdm
def get_onehot_attributes(attr_dict, attr2idx, split):
"""get the labels in onehot format
Args:
attr_dict (dict: the dictory contains image_id and its top 5 attributes
attr2idx (dict): the dictory contains corresponding index of attributes
split (st... | 51352fa5ccd24104830d4a4fc4100382055949a4 | 3,646,077 |
from typing import List
from typing import Tuple
from typing import Optional
import ssl
from typing import Iterable
from typing import Union
async def post(
url: str,
content: bytes,
*,
headers: List[Tuple[bytes, bytes]] = None,
loop: Optional[AbstractEventLoop] = None,
... | 8aa95bb43f3937ea09ffa0a55b107bf367ffa5bc | 3,646,078 |
import toml
def parse_config_file(path):
"""Parse TOML config file and return dictionary"""
try:
with open(path, 'r') as f:
return toml.loads(f.read())
except:
open(path,'a').close()
return {} | 599164f023c0db5bffa0b6c4de07654daae1b995 | 3,646,079 |
def wordnet_pos(tag):
"""
Transforms nltk part-of-speech tag strings to wordnet part-of-speech tag string.
:param tag: nltk part-of-speech tag string
:type: str
:return: the corresponding wordnet tag
:type: wordnet part-of-speech tag string
"""
return getattr(nltk_wordnet_pos_dict, tag[0... | 66b915cb63036553d765af5474d690ea4e0f3859 | 3,646,080 |
import requests
def call_telegram_api(function: str, data: dict):
"""Make a raw call to Telegram API."""
return requests.post(
f'https://api.telegram.org/bot{TELEGRAM_TOKEN}/{function}', data=data) | 547626545942b290dc64cd4f1d75277205751eaf | 3,646,081 |
def test_POMDP(POMDP, policy, test_data, status):
"""simulation"""
# Basic settings
p = POMDP
ind_iter = 0
horizon = len(test_data)
state = status
action = p.actions[0]
belief = p.init_belief
reward = 0
state_set = [state]
action_set = []
observation_set = ["null"]
al... | 0f2dfe7c18d254ca0b2953b11aaac2386d4fe920 | 3,646,082 |
import matplotlib.pyplot as plt
import numpy as np
from copy import deepcopy
def compute_bkr_collection(myCollection,percentile=10,make_images=False,image_name=''):
""" Computes a synthetic background value for a given collection, based on
the lowest values at each point for each image. it treats row (long ax... | 61d4e73bca55e24c934d7a34888316232cd6e7ff | 3,646,083 |
def courses_to_take(input):
"""
Time complexity: O(n) (we process each course only once)
Space complexity: O(n) (array to store the result)
"""
# Normalize the dependencies, using a set to track the
# dependencies more efficiently
course_with_deps = {}
to_take = []
for course, deps in input.items():
... | eb0fe7271497fb8c5429360d37741d20f691ff3c | 3,646,084 |
def _merge_GlyphOrders(font, lst, values_lst=None, default=None):
"""Takes font and list of glyph lists (must be sorted by glyph id), and returns
two things:
- Combined glyph list,
- If values_lst is None, return input glyph lists, but padded with None when a glyph
was missing in a list. Otherwise, return value... | cc671625bcaa2016cb8562c5727d7afa624699a9 | 3,646,085 |
def sig_for_ops(opname):
"""sig_for_ops(opname : str) -> List[str]
Returns signatures for operator special functions (__add__ etc.)"""
# we have to do this by hand, because they are hand-bound in Python
assert opname.endswith('__') and opname.startswith('__'), "Unexpected op {}".format(opname)
n... | 7f5850c5719ed631d4aabc22b757969d1161eee2 | 3,646,086 |
def add_qos(tenant_id, qos_name, qos_desc):
"""Adds a qos to tenant association."""
LOG.debug(_("add_qos() called"))
session = db.get_session()
try:
qos = (session.query(network_models_v2.QoS).
filter_by(tenant_id=tenant_id).
filter_by(qos_name=qos_name).one())
... | a9186776eada52c35a38bc02667284575bed33d6 | 3,646,087 |
def lstm2(hidden_nodes, steps_in=5, steps_out=1, features=1):
"""
A custom LSTM model.
:param hidden_nodes: number of hidden nodes
:param steps_in: number of (look back) time steps for each sample input
:param steps_out: number of (look front) time steps for each sample output
:param features: ... | c84c1d4a3cb31ca74fd3d135a9c48c72f5f6c715 | 3,646,088 |
def build_carousel_scroller(items):
"""
Usage:
item_layout = widgets.Layout(height='120px', min_width='40px')
items = [pn.Row(a_widget, layout=item_layout, margin=0, background='black') for a_widget in single_pf_output_panels]
# items = [widgets.Button(layout=item_layout, description=st... | 2c48ef11de7647320833c74e5dc155365c0ae847 | 3,646,089 |
import sys
def smolsolve(x, xBound, f0, t, K_A, source, Nt):
""" solve Smoluchowski equations
Input: x, initial condition, time, kernel, # timestep
Output: solution f(t,x)
"""
dx = xBound[1] - xBound[0]
Nx = x.size
dt = t / Nt
g = x * f0
for t in range(Nt):
JL = 0*x
fsrc = 0*x
# source t... | 8503f13ae0031ab80fd6f83a1ba36dc512cc701f | 3,646,090 |
def base_round(x, base):
"""
This function takes in a value 'x' and rounds it to the nearest multiple
of the value 'base'.
Parameters
----------
x : int
Value to be rounded
base : int
Tase for x to be rounded to
Returns
-------
int
The rounded value
... | e5b1a1b81c7baf990b7921fe27a20075c0305935 | 3,646,091 |
def _update_schema_1_to_2(table_metadata, table_path):
"""
Given a `table_metadata` of version 1, update it to version 2.
:param table_metadata: Table Metadata
:param table_path: [String, ...]
:return: Table Metadata
"""
table_metadata['path'] = tuple(table_path)
table_metadata['schema... | 6b0c8bc72100cceeb1b9da5552e53bc3c9bad3fa | 3,646,092 |
def train_cnn_7layer(data, file_name, params, num_epochs=10, batch_size=256, train_temp=1, init=None, lr=0.01, decay=1e-5, momentum=0.9, activation="relu", optimizer_name="sgd"):
"""
Train a 7-layer cnn network for MNIST and CIFAR (same as the cnn model in Clever)
mnist: 32 32 64 64 200 200
cifar: 64 6... | c2d020b4390aca6bb18de6f7e83c801475ac1a03 | 3,646,093 |
def validate():
"""
Goes over all season, make sure they are all there, and they should have length 52, except last one
"""
input_file = processedDatafileName
clusters_file = 'data/SeasonClustersFinal'
seasonDic = {}
allSeasons = {}
for line in open(clusters_file):
... | 883d21b656730c3e26a94ba8581107f359b337b4 | 3,646,094 |
def get_registry(): # noqa: E501
"""Get registry information
Get information about the registry # noqa: E501
:rtype: Registry
"""
try:
res = Registry(
name="Challenge Registry",
description="A great challenge registry",
user_count=DbUser.objects.count(... | 7798da55bee2ad1d6edce37f7c00e4597412491d | 3,646,095 |
def get_fraction_vaccinated(model, trajectories, area=None, include_recovered=True):
"""Get fraction of individuals that are vaccinated or immune (by area) by
state.
Parameters
----------
model : amici.model
Amici model which should be evaluated.
trajectories : pd.DataFrame
Tra... | f11cbeb737c8592528441293b9fd25fed4bee37f | 3,646,096 |
def test_function(client: Client) -> str:
"""
Performs test connectivity by valid http response
:param client: client object which is used to get response from api
:return: raise ValueError if any error occurred during connection
"""
client.http_request(method='GET', url_suffix=URL_SUFFIX['TEST... | 8c773fd9a87a45270157f682cb3229b83ba4a9e0 | 3,646,097 |
import pkgutil
import doctest
def load_tests(loader, tests, ignore):
"""Create tests from all docstrings by walking the package hierarchy."""
modules = pkgutil.walk_packages(rowan.__path__, rowan.__name__ + ".")
for _, module_name, _ in modules:
tests.addTests(doctest.DocTestSuite(module_name, glo... | d8495b32c6cb95a94857f611700f07b9183a9b63 | 3,646,098 |
def k_hot_array_from_string_list(context,
typename,
entity_names):
"""Create a numpy array encoding a k-hot set.
Args:
context: a NeuralExpressionContext
typename: type of entity_names
entity_names: list of names of type typename
Retu... | 66c987f7c5d1e3af2b419d0db301ad811a8df5b7 | 3,646,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.