content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _add_experimental_function_notice_to_docstring(doc):
"""Adds an experimental notice to a docstring for experimental functions."""
return decorator_utils.add_notice_to_docstring(
doc, '',
'EXPERIMENTAL FUNCTION',
'(experimental)', ['THIS FUNCTION IS EXPERIMENTAL. It may change or '
... | 449ab32b4ddae2d383776d0c90dbc56dc6041da6 | 25,993 |
def format_args(args):
"""Formats the command line arguments so that they can be logged.
Args:
The args returned from the `config` file.
Returns:
A formatted human readable string representation of the arguments.
"""
formatted_args = "Training Arguments: \n"
args = args.__dict_... | 22d4334daba7cdfd77329f5a6de93a2411f0594d | 25,994 |
import uuid
def generate_id() -> str:
"""Generates random string with length of `ID_LENGTH`"""
return int_to_base36(uuid.uuid4().int)[:LENGTH_OF_ID] | 8cf317741edf02ca79ef72bf51c7958877a98d98 | 25,995 |
def getHG37PositionsInRange(chromosome, startPos, endPos):
"""Return a DataFrame containing hg37 positions for all rsids in a range.
args:
chromosome (int or str): the chromosome number
startPos (int or str): the start position on the chromosome
endPos (int or str): the ... | 64107a375588737e6fedcd336fe5d1a648a93efc | 25,996 |
def spherical_from_cart_np(xyz_vector):
"""
Convert a vector from cart to spherical.
cart_vector is [idx][x, y, z]
"""
if len(xyz_vector.shape) != 2:
xyz_vector = np.expand_dims(xyz_vector, axis=0)
expanded = True
else:
expanded = False
sph_vector = np.zeros(xyz_vect... | 86da4d3426b6327c5fd00f431e36655b9213a027 | 25,997 |
def _execute_query(connection, query):
"""Executes the query and returns the result."""
with connection.cursor() as cursor:
cursor.execute(query)
return cursor.fetchall() | 9f71eb650d323f7a5ead3451810a7b9f9d77b4b0 | 25,998 |
def mediaValues(x):
"""
return the media of a list
"""
return sum(x)/len(x) | ab4a436d3383e5df7d8d891c9661eabb0af81ef8 | 25,999 |
def _plot_NWOE_bins(NWOE_dict, feats):
"""
Plots the NWOE by bin for the subset of features interested in (form of list)
Parameters
----------
- NWOE_dict = dictionary output of `NWOE` function
- feats = list of features to plot NWOE for
Returns
-------
- plots of NWOE for each fea... | 2c034c311ae406f1267256c3de975e021e9ba283 | 26,000 |
def net_model_fn(features, labels, mode, model,
resnet_size, weight_decay, learning_rate_fn, momentum,
data_format, resnet_version, loss_scale,
loss_filter_fn=None, dtype=resnet_model.DEFAULT_DTYPE,
conv_type=resnet_model.DEFAULT_CONV_TYPE,
... | a9758bbbf5220091ee8faffde82bc271ea676c44 | 26,002 |
def vectorvalued(f):
""" Decorates a distribution function to disable automatic vectorization.
Parameters
----------
f: The function to decorate
Returns
-------
Decorated function
"""
f.already_vectorized = True
return f | cc498fe0731acdbde0c4d9b820a1accb5dc94fea | 26,003 |
import unicodedata
def remove_diacritics(input_str: str) -> str:
"""Remove diacritics and typographical ligatures from the string.
- All diacritics (i.e. accents) will be removed.
- Typographical ligatures (e.g. ffi) are broken into separated characters.
- True linguistic ligatures (e.g. œ) will remain... | 23c3e9ce0029704f0012a825460f10f370e3c681 | 26,004 |
def extract_model_field_meta_data(form, attributes_to_extract):
""" Extract meta-data from the data model fields the form is handling. """
if not hasattr(form, 'base_fields'):
raise AttributeError('Form does not have base_fields. Is it a ModelForm?')
meta_data = dict()
for field_name, field_data... | e41a63935379c5d3310646c79c25a43ad7f6d5fe | 26,005 |
import json
def beam_search(image, encoder, embedder, attention, decoder,
beam_width=30, max_length=18, redundancy=0.4,
ideal_length=7, candidates=0, as_words=True):
"""
beam_search is a breadth limited sorted-search: from root <start> take next
best beam-width children out... | c55bcbbff739db7cb25513bdb62b4d165359ab1c | 26,006 |
def strip_leading_and_trailing_lines(lines, comment):
"""
Removes and leading and trailing blank lines and comments.
:param lines: An array of strings containing the lines to be stripped.
:param comment: The block comment character string.
:return: An updated array of lines.
"""
comment = ... | 19fe932532f12c5602c4c319c761fc5229efe37b | 26,007 |
def bold(msg: str) -> str:
"""Bold version of the message
"""
return bcolors.BOLD + msg + bcolors.ENDC | 25cca7e505b0d0155ff46b86f2f899830cce4216 | 26,008 |
def escape(value):
"""
extends the classic escaping also to the apostrophe
@Reviewer: Do you please have a better way?
"""
value = bleach.clean(value)
value = value.replace("'", "'")
return value | 7c048a915b1d11ededd45042040215c0089e019b | 26,009 |
def login(request):
"""
:param request:
:return:
"""
if request.user.is_authenticated:
return redirect('/')
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=passw... | 13482776aabe90eaeec6cbc730945df816897471 | 26,010 |
def plot_date_randomisation(
ax: plt.axes,
replicates: np.array or list,
rate: float,
log10: bool = True
) -> plt.axes:
""" Plot distribution of substitution rates for date randomisation test
:param ax: axes object to plot the date randomisation
:param replicates: list of replicate substit... | 35b99e0f464149e9b948203209ea4ad0fb9c52ef | 26,011 |
def dict(filename, cols=None, dtype=float, include=None, exclude='#',
delimiter='', removechar='#', hmode='1', header_start=1,
data_start=0, hsep='', lower=False):
"""
Creates a dictionary in which each chosen column in the file is an
element of the dictionary, where keys correspond to col... | ffa00f53a52e84143cb3a612730db1a57c130d87 | 26,013 |
def solution(p, flux, error, line, cont, sens, model_wave, coeffs, fjac=None):
""" Fitting function for mpfit, which will minimize the returned deviates.
This compares the model stellar spectra*sensitivity to observed spectrum
to get wavelength of each pixel."""
# Convert pixels to wavelengths
xre... | 0568751e1e564ae01ee72af28446d8cfdac50324 | 26,014 |
import torch
def filter_image(image, model, scalings):
"""
Filter an image with the first layer of a VGG16 model.
Apply filter to each scale in scalings.
Parameters
----------
image: 2d array
image to filter
model: pytorch model
first layer of VGG16
scalings: list of i... | 031bdf98d0220437afedd489068abb195866ed13 | 26,015 |
def gen_init_params(m_states: int, data: np.ndarray) -> tuple:
"""
Generate initila parameters for HMM training.
"""
init_lambda = gen_sdm(data, m_states)
init_gamma = gen_prob_mat(m_states, m_states)
init_delta = gen_prob_mat(1, m_states)
return init_lambda, init_gamma, init_delta | 7d57ccb5ba9144ba78be9486795638f6409a6730 | 26,016 |
import tempfile
def generate_temp_csvfile(headers: list, data: list) -> object:
"""
Generates in-memory csv files
:param
headers: list
A list of file headers where each item is a string
data: list
A list containing another list representing the rows for the CSV
... | 6d527794fbfee8c045e2bee31c0d85997beb371b | 26,017 |
def read_raw_antcnt(input_fname, montage=None, eog=(), event_id=None,
event_id_func='strip_to_integer', preload=False,
verbose=None):
"""Read an ANT .cnt file
Parameters
----------
input_fname : str
Path to the .cnt file.
montage : str | None | instanc... | db1ff04097b1ea8125aec90dfd308023cc5b3dba | 26,018 |
def addrstr(ip: netaddr.IPNetwork) -> str:
"""
helper for mapping IP addresses to config statements
"""
address = str(ip.ip)
if netaddr.valid_ipv4(address):
return "ip address %s" % ip
elif netaddr.valid_ipv6(address):
return "ipv6 address %s" % ip
else:
raise ValueError("invalid address... | 2faf35da4f6739db5b3e5eece92366e44595c11b | 26,019 |
def upload_fixture_file(domain, filename, replace, task=None, skip_orm=False):
"""
should only ever be called after the same file has been validated
using validate_fixture_file_format
"""
workbook = get_workbook(filename)
if skip_orm is True:
return _run_fast_fixture_upload(domain, wor... | ac61bbd25a4605a11a9133ef7d4340444be46d8a | 26,020 |
def lambda_plus_mu_elimination(
offspring: list, population: list, lambda_: int):
""" Performs the (λ+μ)-elimination step of the evolutionary algorithm
Args:
offspring (list): List of the offspring
population (list): List of the individuals in a population
lambda_ (int): Number ... | d4f55fa621e3f33e2773da81a6cf0b2fc0439ba9 | 26,021 |
def dVdtau(z):
""" cosmological time-volume element [Mpc^3 /redshift /sr]
it is weighted by an extra (1+z) factor to reflect the rate
in the rest frame vs the observer frame
"""
DH=c_light_kms/cosmo.H0
return DH*(1+z)*DA(z)**2/E(z) | 80384549a5ab30bcccbd45076f0b25044402abc0 | 26,022 |
def receive(message):
"""
Function to read whatever is presented to the serial port and print it to the console.
Note: For future use: Currently not used in this code.
"""
messageLength = len(message)
last_message = []
try:
while arduinoData.in_waiting > 0:
for i in range... | b526d1888d089f77dc0953488bbafeaa74e5ba45 | 26,023 |
from typing import List
from typing import Optional
from typing import Callable
def fit(model_types: List[str],
state_cb_arg_name: Optional[str] = None,
instance_arg_name: Optional[str] = None) -> Callable:
"""Decorator used to indicate that the wrapped function is a fitting
function. The deco... | 0b8217184118269dab7095e424550736e495ba04 | 26,024 |
def infer_filetype(filepath, filetype):
"""
The function which infer file type
Parameters
----------
filepath : str
command line argument of filepath
filetype : str
command line argument of filetype
Returns
-------
filepath : str
filepath
filetype : str
... | 6e47f60dd8cabe8ba14d26736c3d2508952c1334 | 26,025 |
def suite_for_devices(devices):
"""Create a TyphonSuite to display multiple devices"""
suite = TyphonSuite()
for device in devices:
suite.add_device(device)
return suite | 08911e85b775e98cdb09b96daaa74f27076c51f6 | 26,026 |
def get_3d_points(preds_3d):
"""
Scales the 3D points.
Parameters
----------
preds_3d : numpy.ndarray
The raw 3D points.
Returns
-------
preds_3d : numpy.ndarray
The scaled points.
"""
for i,p in enumerate(preds_3d):
preds_3d[i] = preds_3d[i] - preds_3d[... | e0c93af3f1d803a9276deb86fb3a3bcb2d90859f | 26,027 |
from datetime import datetime
import logging
def mms_load_data(trange=['2015-10-16', '2015-10-17'], probe='1', data_rate='srvy', level='l2',
instrument='fgm', datatype='', anc_product=None, descriptor=None,
varformat=None, prefix='', suffix='', get_support_data=False, time_clip=False,
no_update=False, ... | 85d4e6b2b28bbcbe9dd7854f306f8b11131cb274 | 26,028 |
def get_random_card_id_in_value_range(min, max, offset):
"""
Randomly picks a card ranged between `min` and `max` from a given offset.
The offset determines the type of card.
"""
card_id = roll(
min + offset,
max + offset)
return card_id | dd888f1ace9638d68e611763bd7d844b43309594 | 26,029 |
def task_configuration(config_path):
""" NLP-Task configuration/mapping """
df = pd.read_json(config_path)
names = df.name.values.tolist()
mapping = {
df['name'].iloc[i]: (
df['text'].iloc[i],
df['labels'].iloc[i],
df['description'].iloc[i],
df['m... | be794664800189ac42e39cc8639598f488a91e4d | 26,030 |
def train(model, optimizer, criterion, data_loader, imshape=(-1, 1, 299, 299),
device='cpu'):
"""
Train a model given a labeled dataset
Args:
model (nn.Module): Model
criterion (torch.nn.optim): Criterion for loss function calculation
data_loader (DataLoader): DataLoader f... | 4b1d769adbef1c9b3d97d1e38bc9828a0fc48178 | 26,031 |
def get_random_rep(embedding_dim=50, scale=0.62):
"""The `scale=0.62` is derived from study of the external GloVE
vectors. We're hoping to create vectors with similar general
statistics to those.
"""
return np.random.normal(size=embedding_dim, scale=0.62) | eed26688657121c7651a611bf49fd7549f3f639f | 26,032 |
def calculate_pretrain_epoches(stage_ds:DatasetStage,
train_batch_size:int,
train_steps_per_epoch:int=DEF_STEPS_PER_EPOCH)->int:
""" Calculate the number of epoches required to match the reference model in
the number of parameter updates.
Ref. https:/... | 72a51eb842d79fe575e97a8059705220d145e0de | 26,033 |
def get_container_info(node, repositories):
"""Check the node name for errors (underscores)
Returns:
toscaparser.nodetemplate.NodeTemplate: a deepcopy of a NodeTemplate
"""
if not repositories:
repositories = []
NodeInfo = namedtuple(
"NodeInfo",
[
"name"... | f2fbdcee89f869f9ec4b5347ad1667e2ea23c427 | 26,034 |
def query_db_to_build_2by2_table(
db,
drug1_id,
drug2_id,
drug1_efficacy_definition_query_sql,
drug2_efficacy_definition_query_sql,
environment,
):
"""
Query the given DB to build a 2-by-2 table comparing the given
drugs.
Return a 2-by-2 table where the e... | bb10095c692cb81182bb79140af30a9e742d3106 | 26,035 |
def rmedian(image, r_inner, r_outer, **kwargs):
"""
Median filter image with a ring footprint. This
function produces results similar to the IRAF
task of the same name (except this is much faster).
Parameters
----------
image : ndarray, MaskedImageF, or ExposureF
Original image dat... | 9614b6f964e8f6031ad08743c0f614e2bcb25753 | 26,036 |
def docstring():
"""
Decorator: Insert docstring header to a pre-existing docstring
"""
sep="\n"
def _decorator(func):
docstr = func.__doc__
title = docstr.split("Notes",1)[0]
docstr = docstr.replace(title,"")
func.__doc__ = sep.join([docstr_header(title,func.__name__... | 5157cdfe25bc346bbf10c6a2368a6a78539d5160 | 26,037 |
def load_class_names():
"""
Load the names for the classes in the CIFAR-10 data-set.
Returns a list with the names. Example: names[3] is the name
associated with class-number 3.
"""
# Load the class-names from the pickled file.
raw = _unpickle(filename="batches.... | 668f01e943b2dcd99dd7b98266a8553fb8395251 | 26,039 |
def categories():
"""Router for categories page."""
categories = get_categories_list()
return render_template('categories.html',
categories=categories) | 2bcc78a7bb1fceeb0aeff1c8edd49d804a4f5c5c | 26,040 |
def load_images(imgpaths, h, w, imf='color'):
"""Read in images and pre-processing 'em
Args:
imgpaths: a list contains all the paths and names of the images we want to load
h: height image is going to resized to
width: width image is going to resized to
imf: image format when loaded as color or gr... | 008c265354da9c545edcfeb72484786923dcf1f6 | 26,041 |
def nextpow2(value):
"""
Find exponent such that 2^exponent is equal to or greater than abs(value).
Parameters
----------
value : int
Returns
-------
exponent : int
"""
exponent = 0
avalue = np.abs(value)
while avalue > np.power(2, exponent):
exponent += 1
... | 1c856a64c578e88aacd931c0e15ba4756c7d9d4f | 26,042 |
def clarkezones(reference, test, units,
numeric=False):
"""Provides the error zones as depicted by the
Clarke error grid analysis for each point in the reference and test datasets.
Parameters
----------
reference, test : array, or list
Glucose values obtained from the refer... | 4fe3544649e28ccf06cb1c74f282f1963da0854d | 26,043 |
def normalize_graph(graph):
"""
Take an instance of a ``Graph`` and return the instance's identifier and ``type``.
Types are ``U`` for a :class:`~rdflib.graph.Graph`, ``F`` for
a :class:`~rdflib.graph.QuotedGraph` and ``B`` for a
:class:`~rdflib.graph.ConjunctiveGraph`
>>> from rdflib import ... | 478987e943e27077e1f2ecce454b33dfd347812b | 26,044 |
def findTargetNode(root, nodeName, l):
"""
Recursive parsing of the BVH skeletal tree using breath-first
search to locate the node that has the name of the targeted body part.
Args:
root (object): root node of the BVH skeletal tree
nodeName (string): name of the targeted body part
l (list): e... | 81d63c032260b496b29dd2890e32753554b93e1a | 26,045 |
def ddtodms(decLat: float, decLon: float):
""" Converts coord point from decimal degrees to Hddd.mm.ss.sss """
try:
lat = float(decLat)
lon = float(decLon)
except ValueError as e:
raise e
# Get declination
ns = "N" if lat >= 0 else "S"
ew = "E" if lon >= 0 else "W"
la... | e1d05d5edf274427b42cb88496fe41ddaf58f7fd | 26,046 |
def gen_colors(img):
""" Ask backend to generate 16 colors. """
raw_colors = fast_colorthief.get_palette(img, 16)
return [util.rgb_to_hex(color) for color in raw_colors] | 6a780cdff2e4aebbe90667da584ad4f1e2692347 | 26,048 |
import html
import time
import http
import json
def request(match, msg):
"""Make an ESI GET request, if the path is known.
Options:
--headers nest the response and add the headers
"""
match_group = match.groupdict()
if "evepc.163.com" in (match_group["esi"] or ""):
base_url =... | 963482efa0bdb02fbfcf1f6ce0b107718c69563a | 26,049 |
def __getattr__(attr):
"""
This dynamically creates the module level variables, so if
we don't call them, they are never created, saving time - mostly in the CLI.
"""
if attr == "config":
return get_config()
elif attr == "leader_hostname":
return get_leader_hostname()
else:
... | f080f3b82afa6050dbaf870e11d1651faded6361 | 26,050 |
import numpy
def _diff_st(p,dl,salt,temp,useext=False):
"""Calculate sea-ice disequilibrium at ST.
Calculate both sides of the equations
given pressure = pressure of liquid water
chemical potential of ice = potential of liquid water
and their Jacobians with respect to pressu... | 11c3c09deeea9e36d1a9dc25bfae4609c982c082 | 26,051 |
def getNormalizedISBN10(inputISBN):
"""This function normalizes an ISBN number.
>>> getNormalizedISBN10('978-90-8558-138-3')
'90-8558-138-9'
>>> getNormalizedISBN10('978-90-8558-138-3 test')
'90-8558-138-9'
>>> getNormalizedISBN10('9789085581383')
'90-8558-138-9'
>>> getNormalizedISBN10('9031411515')
... | 986dcd09470cc3bf0badb59f8c0ba069382f0c7c | 26,052 |
import json
import logging
def hashtag_is_valid(tag, browser, delay=5):
"""
Check if a given hashtag is banned by Instagram
:param delay: Maximum time to search for information on a page
:param browser: A Selenium Driver
:param tag: The hashtag to check
:return: True if the hashtag is valid, ... | 15e88713670454a713d27650b61672ecc06a9d53 | 26,053 |
import json
def get_price_data(startdate, enddate):
"""
returns a dataframe containing btc price data on every day between startdate and enddate
:param startdate:
:param enddate:
:return:
"""
url = 'https://api.coindesk.com/v1/bpi/historical/close.json?start=' + startdate + '&end=' + endda... | b506069c7246c64530906ff86a743b0d717ec173 | 26,055 |
import csv
def read_keywords(fname):
"""Read id file"""
with open(fname, 'r') as f:
reader = csv.reader(f)
header = next(reader)
assert header == ['keyword']
return list(row[0] for row in reader) | 566c1924ae8d4ae7316a2c5e3947170fe23af45d | 26,058 |
def inscribe(mask):
"""Guess the largest axis-aligned rectangle inside mask.
Rectangle must exclude zero values. Assumes zeros are at the
edges, there are no holes, etc. Shrinks the rectangle's most
egregious edge at each iteration.
"""
h, w = mask.shape
i_0, i_1 = 0, h - 1
j_0, j_1 =... | 06042faebedb82dc0044cf2108fae7a3570895e0 | 26,059 |
def vaf_above_or_equal(vaf):
"""
"""
return lambda columns, mapper: float(columns[mapper['Variant_allele_ratio']]) >= vaf | 4b2134d63193699f8ca490a8d7537ba8aaf4c8cf | 26,060 |
from typing import Dict
def user_token_headers(client_target: TestClient, sql_session: Session) -> Dict[str, str]:
"""fake user data auth"""
return auth_token(
client=client_target, username="johndoe", sql=sql_session) | e230762c82e6c81e493430f2ffe59f97f7e33721 | 26,061 |
def conv_1_0_string_to_packed_binary_string(s):
"""
'10101111' -> ('\xAF', False)
Basically the inverse of conv_packed_binary_string_to_1_0_string,
but also returns a flag indicating if we had to pad with leading zeros
to get to a multiple of 8.
"""
if not is_1_0_string(s):
raise Va... | 65555abe9eae515c41ddf422bec28394b7612e37 | 26,063 |
def accuracy_win_avg(y_true, y_proba):
"""
Parameters
----------
y_true: n x n_windows
y_proba: n x n_windows x n_classes
"""
y_pred = win_avg(y_proba)
return accuracy(y_true[:,0], y_pred) | ca2629127dd0fca3591f8e6ae30f337cd3b92b69 | 26,064 |
def ortho_projection(left=-1, right=1, bottom=-1, top=1, near=.1, far=1000):
"""Orthographic projection matrix."""
return np.array((
(2 / (right-left), 0, 0, -(right+left) / (right-left)),
(0, 2 / (top-bottom), 0, -(top+bottom) / (top-botto... | cdd00f1fcb706a1a19476f8fa387fe45a11deebd | 26,065 |
def ais_InitLengthBetweenCurvilinearFaces(*args):
"""
* Finds attachment points on two curvilinear faces for length dimension. @param thePlaneDir [in] the direction on the dimension plane to compute the plane automatically. It will not be taken into account if plane is defined by user.
:param theFirstFace:
... | 992f2c26c87f07a0460ef56cff784b00185cf3b0 | 26,066 |
def get_methylation_dataset(methylation_array, outcome_col, convolutional=False, cpg_per_row=1200, predict=False, categorical=False, categorical_encoder=False, generate=False):
"""Turn methylation array into pytorch dataset.
Parameters
----------
methylation_array : MethylationArray
Input Methy... | 709d1eb5f5887b9f0ff0724e8a4aa18d86020fb5 | 26,068 |
def es_config_fixture() -> ElastalkConf:
"""
This fixture returns an `ElasticsearchConf` (configuration) object.
:return: the configuration object
"""
return ElastalkConf() | 2479bf01f454ea409e36647a417b3dcee82fafd0 | 26,069 |
def axis_angle_to_quaternion(rotation: ArrayOrList3) -> np.ndarray:
"""Converts a Rodrigues axis-angle rotation to a quaternion.
Args:
rotation: axis-angle rotation in [x,y,z]
Returns:
equivalent quaternion in [x,y,z,w]
"""
r = Rotation.from_rotvec(rotation)
return r.as_quat() | 002970755835395bc349c418de94455ac0ce52c3 | 26,071 |
def encode(encoding, data):
"""
Encodes the given data using the encoding that is specified
:param str encoding: encoding to use, should be one of the supported encoding
:param data: data to encode
:type data: str or bytes
:return: multibase encoded data
:rtype: bytes
:raises ValueError... | 08ffd6540ed6da7728b6725e035afb652bf8893e | 26,072 |
import json
def tiny_video_net(model_string,
num_classes,
num_frames,
data_format='channels_last',
dropout_keep_prob=0.5,
get_representation=False,
max_pool_predictions=False):
"""Builds TinyVideoNet ba... | 854f8bd2315c3d529c4691b66d1ee6bc00465fac | 26,073 |
def get_tensor_from_cntk_convolutional_weight_value_shape(tensorValue, tensorShape):
"""Returns an ell.math.DoubleTensor from a trainable parameter
Note that ELL's ordering is row, column, channel.
4D parameters (e.g. those that represent convolutional weights) are stacked vertically in the row dimens... | 69191e295abfd818d380e626db1276687c1e7a8b | 26,074 |
from typing import TextIO
from typing import List
from typing import Optional
import csv
def load_f0(fhandle: TextIO) -> annotations.F0Data:
"""Load a Dagstuhl ChoirSet F0-trajectory.
Args:
fhandle (str or file-like): File-like object or path to F0 file
Returns:
F0Data Object - the F0-tr... | 84bea706b1d985f91c872764e8e388ec8fe7f576 | 26,075 |
def to_str_constant(s: str, quote="'") -> str:
"""
Convert a given string into another string that is a valid Python representation of a string constant.
:param s: the string
:param quote: the quote character, either a single or double quote
:return:
"""
if s is None:
raise ValueErro... | bfd1fd2989a96cd5fdadc01e7a0e1e0f2846db97 | 26,076 |
def signum(x):
"""
Return -1 if x < 0, 1 if 0 < x, or 0 if x == 0
"""
return (x > 0) - (x < 0) | 59568d4fbf1f5a226528b7f12f8c5011b641bc4e | 26,077 |
def _construct_dataloader(dataset, batch_size, shuffle, seed=0, num_workers=0, class_balance=False):
"""Construct a data loader for the provided data.
Args:
data_set ():
batch_size (int): The batch size.
shuffle (bool): If True the data will be loaded in a random order. Defaults to True... | 7fd7a7b3eaa4c82473978735167067c64533adcb | 26,078 |
import platform
def _get_cpu_type():
"""
Return the CPU type as used in the brink.sh script.
"""
base = platform.processor()
if not base:
base = platform.machine()
if base == 'aarch64': # noqa:cover
return 'arm64'
if base == 'x86_64':
return 'x64'
if base =... | b8a81367d1a4a7ac34e2965cfedcb947f6a66165 | 26,079 |
def DatesRangeFieldWidget(field, request): # pylint: disable=invalid-name
"""Dates range widget factory"""
return FieldWidget(field, DatesRangeWidget(request)) | 0e692d025b458340e2c0d588cd73b7ea206beca6 | 26,080 |
def get_aux_dset_slicing(dim_names, last_ind=None, is_spectroscopic=False):
"""
Returns a dictionary of slice objects to help in creating region references in the position or spectroscopic
indices and values datasets
Parameters
------------
dim_names : iterable
List of strings denoting ... | 3a254dea086227354030fd6b13ef33182fe505f0 | 26,081 |
def make_etag(value, is_weak=False):
"""Creates and returns a ETag object.
Args:
value (str): Unquated entity tag value
is_weak (bool): The weakness indicator
Returns:
A ``str``-like Etag instance with weakness indicator.
"""
etag = ETag(value)
etag.is_weak = is_weak
... | 2d2d2f7f7d0fc59f89b20cfb79932c16ade90e35 | 26,082 |
def is_closer_to_goal_than(a, b, team_index):
""" Returns true if a is closer than b to goal owned by the given team """
return (a.y < b.y, a.y > b.y)[team_index] | 016cb7f19b2d0046d4f349dbf52da93ca0e9a2cc | 26,084 |
def is_url(url):
"""
Check if given URL is a valid URL.
:param str url: The url to validate
:returns: if the url is valid or not
:rtype: bool
"""
return urlparse(url).scheme != "" | 10b7b37e4d6075877388b6564e004b1775a4ea71 | 26,086 |
def star(locid, tmass_id):
"""Return data on an individual star.
"""
apstar_id = 'apogee.apo25m.s.stars.{0:d}.{1}'.format(locid, tmass_id)
data = stars[apstar_id]
flagtxt = ", ".join(starflag.flagname(stars[apstar_id].ORstarflag))
return render_template('star.html',
ti... | 9762fd912b6dbbf4088333c4cf9d0689c04b99c7 | 26,087 |
def dot_product_attention(q,
k,
v,
bias,
dropout_rate=0.0,
image_shapes=None,
name=None,
save_weigths_to=None,
d... | 3efc760516b37656f1d6e2e71c30ed37c3d6e298 | 26,088 |
def extract_words(text):
"""Return the words in a tweet, not including punctuation.
>>> extract_words('anything else.....not my job')
['anything', 'else', 'not', 'my', 'job']
>>> extract_words('i love my job. #winning')
['i', 'love', 'my', 'job', 'winning']
>>> extract_words('make justin # 1 by... | 720095b29c8bdd5427796afd34385dcaae5fa8d8 | 26,090 |
async def async_setup_platform( # pylint: disable=too-many-locals
hass: HomeAssistant,
config: ConfigType, # pylint: disable=unused-argument
async_add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the Calibration sensor."""
if discovery_in... | 4af7dcfa49bebccc991b4e91550fbac570301192 | 26,091 |
from typing import Tuple
from typing import Mapping
from typing import Dict
from typing import Set
def calculate_subgraph_edge_overlap(
graph: BELGraph,
annotation: str = 'Subgraph',
) -> Tuple[
Mapping[str, EdgeSet],
Mapping[str, Mapping[str, EdgeSet]],
Mapping[str, Mapping[str, EdgeSet]],
Ma... | 9ac07522d16976f52fa38690bdcd77f9f19b61e0 | 26,092 |
def d2logistic_offset_p(x, p):
"""
Wrapper function for :func:`d2logistic_offset`: `d2logistic_offset(x, *p)`
"""
return d2logistic_offset(x, *p) | 1aa6a291af76d92273b71bd3a0d738aac4fb366c | 26,093 |
def extract_coeffs_knots_from_splines(attitude_splines, k):
"""
Extract spline characteristics (coeffs, knots, splines). The spline being
defined as
.. math:: S(t) = \sum_{n=0}^{N-1} a_n B_n(t)
where :math:`c_n` are the spline coefficients and :math:`B_n(t)` is the
spline basis evaluated at ti... | 306702c3abf49b2b9f93a3c261fbfbfae0a47297 | 26,094 |
import requests
def get_token(username: str = AUTH[0], password: str = AUTH[1]):
"""
Gets an access token from Cisco DNA Center always-on sandbox. Returns the token
string if successful; False (None) otherwise
"""
# Declare Useful local variabales to simplify request process
api_path = "https... | ab40a1de758dccc4e8f65021b4122c3b866b2671 | 26,095 |
def disk_info(hard_disk):
"""Return a dictionary with information regarding a virtul hard disk.
The dictionary with information regarding hard disk image
contains:
:VHD_UUID:
:VHD_PARENT_UUID:
:VHD_STATE:
:VHD_TYPE:
:VHD_PATH: the path for virtual hard driv... | b12befa8ef3082b755b18fe17d62f3221648c050 | 26,096 |
def get_corporation(corporation_id):
"""
Get corporation details for a corporation id from ESI
:param corporation_id: ID for the required corporation
:return: Dictionary containing corporation details
"""
op = esiapp.op['get_corporations_corporation_id'](corporation_id=corporation_id)
retur... | 42b6ec8b4ed0d5e278d56a359ce8a8bc668007e3 | 26,097 |
def _is_list(v):
"""
Returns True if the given value is a @list.
:param v: the value to check.
:return: True if the value is a @list, False if not.
"""
# Note: A value is a @list if all of these hold True:
# 1. It is an Object.
# 2. It has the @list property.
return _is_object(v) a... | 2568e7dc5035f8a3006dd39be0a04538e29c27b1 | 26,098 |
def _find_onehot_actual(x):
"""Map one-hot value to one-hot name"""
try:
value = list(x).index(1)
except:
value = np.nan
return value | 6bafb852e89479803ab824b3f621863724b12146 | 26,099 |
def lower_text(text: str) -> str:
"""Transform all the text to lowercase.
Args:
text : Input text
Returns:
Output text
"""
return text.lower() | 2a657464a014703464ca47eeb77ed6a630535819 | 26,101 |
def pca(X,keep=2):
"""Perfrom PCA on data X. Assumes that data points correspond to columns.
"""
# Z = (X.T - mean(X,1)).T # subtract mean
C = dot(X,X.T)
V,D = eig(C)
B = D[:,0:keep]
return dot(B.T,X) | 01cd4414ac881b986d74247aeaa7dc96dd456721 | 26,102 |
import array
def stock_span(prices: array) -> list:
"""
Time Complexity: O(n*n)
"""
span_values: list = []
for i, price in enumerate(prices):
count: int = 1
for j in range(i - 1, -1, -1):
if prices[j] > price:
break
count += 1
span... | 5a619bb1ce31c0e65dd5fc3d52af2e8b881a87b7 | 26,103 |
def get_replication_tasks(replication_instance_arn):
"""Returns the ist of replication tasks"""
existing_tasks = []
dms_client = boto3.client('dms')
replication_tasks = dms_client.describe_replication_tasks()
for task in replication_tasks['ReplicationTasks']:
if task['ReplicationInstanceArn'... | 2ee3f7ca108f502fa1e512319e6f630a1b0f54ff | 26,104 |
def getProgramFields():
"""
Get the data element names and return them as a list.
"""
_, progFields = callAPI("GET", "program-fields", quiet='True')
return progFields | 92799c4147ad86d2d52ade676953d2a1e60dbece | 26,105 |
import base64
def base64url_decode(msg):
"""
Decode a base64 message based on JWT spec, Appendix B.
"Notes on implementing base64url encoding without padding"
"""
rem = len(msg) % 4
if rem:
msg += b'=' * (4 - rem)
return base64.urlsafe_b64decode(msg) | f0f46749ae21ed8166648c52c673eab25f837881 | 26,106 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.