content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
# (batch, feature),从每个feature选择topk
_, pred = output.topk(maxk, 1, True, True)
# 转置
pred = pred.t()
correct = pred.eq(target.view(1, -1).exp... | a0b57d35d85e58adbf4e9c9e405c440925ee1e0b | 3,604,800 |
def qdqL2(x, levels, bucket_size=1024):
"""
Quantize and dequantize with L2 norm.
x: the input vector (numpy.ndarray)
levels: either levels_uni for QGSD or levels_exp for NUQSGD
bucket_size: we split our big vector to multiple buckets of size
bucket_size for quantizing
returns... | 90fe7f06c0772a4d117d60f91abac990203a0041 | 3,604,801 |
def _PromptForRegion():
"""Prompt for region from list of available regions.
Returns:
The region specified by the user, str
"""
if not console_io.CanPrompt():
return None
all_regions = constants.SUPPORTED_REGIONS_WITH_GLOBAL
idx = console_io.PromptChoice(
all_regions, message=('Please specif... | 761bc801b511bff63691496fb5d145804c897061 | 3,604,802 |
def solution(limit: int = 1000000) -> int:
"""
Return the number of different square laminae that can be formed using up to
one million tiles.
>>> solution(100)
41
"""
answer = 0
for outer_width in range(3, (limit // 4) + 2):
if outer_width**2 > limit:
hole_width_low... | ab0392b83d71d63fc6beeabd6c2a8b43d49de8db | 3,604,803 |
def get_user(user_id: int, user_serivce: UserSerivce = Depends()):
"""Get particular user."""
return user_serivce.get(user_id) | f201069bee6c1b08e888e69ceec8f371153e555f | 3,604,804 |
import argparse
def get_args():
"""Fetch our command line arguments"""
parser = argparse.ArgumentParser(
description='''Delete a set of objects from an s3 bucket.
Objects to be deleted are supplied in a line delimited file''',
formatter_class=lambda prog: argparse.Help... | 39247407e2bc9a2f771f5427825a3ceba7f0e9a5 | 3,604,805 |
import argparse
def get_options():
"""Process command line options"""
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--record',
action='store_true',
help='Set the sample to record mode, ... | f8dc6813db4d3a2094b4f4cc93593fdb8ed5cc90 | 3,604,806 |
def compute_paglm_weights(f,suff,interval,dt,Cinv=None):
"""
This function computes the paglm weights given a nonlinearity, sufficient
statistics, bin size, and optional prior over an approximation interval.
"""
# if Cinv is none, make prior a matrix of zeros
if Cinv is None:
Cinv = np.... | 64dc99377ffda2b7b0382ab11075513172de77eb | 3,604,807 |
def inner_info_nec_lower(scores):
"""InfoNCE estimator for I(diX;T) - van den Oord et al. (2018):"""
nll = np.mean(np.diag(scores) - jax.scipy.special.logsumexp(scores, axis=1))
K = scores.shape[1]
mi = np.log(K) + nll
return mi | f0ec7ec3461cf3a0b664866930bb85ab247d7768 | 3,604,808 |
def imputation(matrix, nan_filling):
"""
takes in matrix dataframe and value for filling in NaNs for imputation
Parameters: matrix dataframe, NaN filling value
Returns: imputed matrix dataframe
"""
matrix.fillna(nan_filling, inplace=True)
return matrix | a6981e54f6228e9ebfcbb6ea65e5305f50a327ca | 3,604,809 |
def compute_precision(model, x, y, reverse_data_dictionary, next_compatible_tools, usage_scores, actual_classes_pos, topk):
"""
Compute absolute and compatible precision
"""
absolute_precision = 0.0
test_sample = np.reshape(x, (1, len(x)))
# predict next tools for a test path
prediction = m... | f8df82ffafa4f9923b4f401538cd29ca29eb5ffe | 3,604,810 |
def get_app_foldername(path):
"""Gets the app name based on a path"""
if not is_file(path):
return ""
s = path.split("/")
if not (len(s) >= 2):
return ""
if s[0] == "examples":
if s[-1].endswith(".py"):
return ((s[-1])[:-3])
else:
return ""
else:
return s[-2] | d7943202bf7034ae06c43b0b3ea309bc9141ba04 | 3,604,811 |
import uuid
import html
def make_individual_project_explorer_layout(rubicon_model, commit_hash, page_size):
"""The html layout for an individual project explorer view determined by
`commit_hash` in the dashboard.
A project explorer view shows a subset of experiments logged
to a project in a tabular f... | 1424ab76090c4c8d123799fe30711f21e07eda39 | 3,604,812 |
def constant(interp, constname):
""" Returns the value of a constant"""
w_obj = _lookup_constant(interp, constname)
if w_obj is None:
interp.warn("constant(): Couldn't find constant %s" % constname)
return interp.space.w_Null
return w_obj | 02ed99875283d05b01e2f0e2534a3ebf9f7e9371 | 3,604,813 |
def display_select(context, element, options, id_object):
"""displays a select list based on the element"""
sel_part = "<select class=\"%s form-control\" name=\"%s\" id=\"%s\">" % (
layout_extras.tooltip_class(element.name),
element.name,
element.name,
)
selected = _form_value(co... | b3cbdfcfff0309a54b9ab81df4ccc1e7fa9e64b2 | 3,604,814 |
def stratified_grouped_fold(D, stats, K, strata='runs'):
"""Add a folding to the data.
Args:
D (pd.DataFrame): The data with measurements with colund id.
stats (pd.DataFrame): Statistics of data D, containing per peptide info.
K (int): The number of folds.
strata (str): String w... | 1829da91b40bd1d64818e65cfdb61475aa6f2427 | 3,604,815 |
def index_types():
"""Returns a list of the supported index types"""
return ["UNIQUE", "CLUSTERED", "NONCLUSTERED"] | e6f8989b23c1800c8aec8aff12555c6ba0fb8c12 | 3,604,816 |
def set_ownertrust(userid, gpghome, trustlevel=5):
""" edit a already imported key and change the trustlevel (default 5=ultimate trust) """
args = ["--homedir", gpghome, "--batch", "--yes", "--import-ownertrust"]
batch_args = userid + ":" + str(trustlevel) + ":\n"
returncode, stdout, stderr = _gpg(args,... | 7213e2a77ca5f471fe0c54f11c986af20d9d7d16 | 3,604,817 |
def fft(lc, bintime):
"""A wrapper for the fft function. Just numpy for now.
Parameters
----------
lc : array-like
bintime : float
Returns
-------
freq : array-like
ft : array-like
the Fourier transform.
"""
nbin = len(lc)
ft = np.fft.fft(lc)
freqs = np.fft... | 6ba9aacad4d617641a2d0e3a1bd034ce37ad7b10 | 3,604,818 |
import argparse
def str2bool(v):
"""用于命令行解析bool类型的参数"""
if v.lower() in ("yes", "true", "t", "y", "1"):
return True
elif v.lower() in ("no", "false", "f", "n", "0"):
return False
else:
raise argparse.ArgumentTypeError("Boolean value expected.") | 51a8a46b1d8bea66514e455e7925ba4a1fd14ca0 | 3,604,819 |
def plot_mcmc_diagnostic(chain):
"""
TODO:
"""
names = [r'$\ln P$', r'$\sqrt{K}\,\cos M_0$', r'$\sqrt{K}\,\sin M_0$',
r'$\sqrt{e}\,\cos \omega$', r'$\sqrt{e}\,\sin \omega$',
'$v_0$']
ndim = chain.shape[-1]
assert ndim == len(names)
fig, axes = plt.subplots(ndim, ... | e1958783a0dc8ddefbf946977a9eea52056297d1 | 3,604,820 |
import torch_xla.core.xla_model as xm
import smdistributed.dataparallel.torch.distributed as dist
import torch
def total_processes_number(local_rank):
"""
Return the number of processes launched in parallel. Works with `torch.distributed` and TPUs.
"""
if is_torch_tpu_available():
return xm.x... | 6595354a73b8d824585778e85b5a14d4f9edfa4e | 3,604,821 |
def _wrap_execution(ctx, fn, args, kwargs):
"""
Intermediate target function that is executed in a new thread;
it receives the original function with arguments and keyword
arguments, including our tracing `Context`. The current context
provider sets the Active context in a thread local storage
v... | f29339aad9db96363e59e925b74710ebadcc4b10 | 3,604,822 |
def create_operator_element(operator):
"""
Creates a PunctuationElement instance containing an operator token of the specified type. The operator
should be a TOML source str.
"""
operator_type_map = {
',': tokens.TYPE_OP_COMMA,
'=': tokens.TYPE_OP_ASSIGNMENT,
'[': tokens.TYPE... | c57ba1ec34c7263cf946968fcc48f1b8250272ea | 3,604,823 |
def Elem_Type \
( elem_type
, bases = None
, front_args = ()
, rest_args = None
, init_arg_defaults = {}
, _autoconvert = {}
, ** attributes
) :
"""Return a new subclass of XML.Element"""
if bases is None :
b... | c36d1591bf7c98d8d9262da4bf07f0988391ca88 | 3,604,824 |
import calendar
def get_casefile_id_sample(year, month, n):
"""
Get random sample of casefile IDs
Parameters
----------
year : int
Sample year
month : int
Sample month
n : int
Number of casefiles to return
Returns
-------
Shuffled list of casefile ID... | 3c30f3bb25377a8bf98d73856e75d2cf69a84115 | 3,604,825 |
import os
from typing import OrderedDict
def load_HZ_max_dam(filename,sheet_name,usecols):
"""
Loads the maximum damages according to Huizinga from an Excel file
Argument:
*filename* (string) - name of the Excel file (should be located in the input_path dir)
*sheet_name* (string) - na... | e0a996d23bcdacb3225662e30763ca19e7305f47 | 3,604,826 |
def parse(card_info):
"""
Parse an iterable containing the lines of a single card into a dict.
The format of the lines should be:
Name
Mana Cost
Supertype Type -- Subtype
Abilities (one per line)
Set Appearances (comma separated, with rarity)
Any missing fields... | 7a69714d5de025af149288b24121edb4c4405709 | 3,604,827 |
def get_corp_for_id(id):
"""Takes a character's id and returns their corporation name.
Args:
name (str): full character name
Returns:
str: value of their corporation's name
"""
return eveapi['xml'].eve.CharacterAffiliation(ids=id)['rowset']['row']['@corporationName'] | 2f6fb9e5224a4781d234bd82057a28df0eff0db1 | 3,604,828 |
def pnas_conv1x1(in_channels,
out_channels,
stride=1):
"""
1x1 version of the PNASNet specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int o... | bbb23c33dcfead5ab2b5dfed94b1a06d3e7d3e99 | 3,604,829 |
import dateutil
def put_assets_asset_id_owners_team_id(asset_id, team_id, body):
"""Request handler for the API endpoint
``PUT /v1/assets/{asset_id}/owners/{team_id}."""
cli = get_inventory_client()
owns = Owns(team_id, asset_id)
start_time = dateutil.parser.isoparse(body['start_time'])
end_... | 34698080a23664fe1533ab85ab2aa576bc555175 | 3,604,830 |
import os
def get_status_output(cmd, wdir=None):
"""
Runs a command via the shell.
Returns:
tuple: (exit_code, text_output)
"""
log.command(cmd)
status = None
output = None
if wdir:
origwdir = os.getcwd()
os.chdir(wdir)
status, output = getstatusoutpu... | dd7299595c2f903b67ec26c60edeb0ef4dab3c36 | 3,604,831 |
import pkg_resources
def is_version_greater_equal(version1, version2):
"""Returns True if version1 is greater or equal than version2 else False"""
return (pkg_resources.parse_version(version1) >=
pkg_resources.parse_version(version2)) | 0618f18c22121d954ae156af7bb6eff80236ae29 | 3,604,832 |
def evaluate(model, env, num_steps=1000):
"""
Evaluate a RL agent
:param model: (BaseRLModel object) the RL Agent
:param num_steps: (int) number of timesteps to evaluate it
:return: (float) Mean reward for the last 100 episodes
"""
episode_rewards = [0.0]
obs = env.reset()
for i in ... | 098083fc4248450402495166ae23f04a785c30ce | 3,604,833 |
def vegenere_decrypt(key: int, cipher_text: str) -> str:
"""
Decrypt and print ciphertext encrypted using a shift cipher using key
Input:
key: the word the message m is encrypted with
cipher_text: the ciphertext we are decrypting
"""
decrypted_text = ""
index = 0
for letter ... | 1923f653e1d3cd3900dad38834024deb843fd2ba | 3,604,834 |
from typing import List
import re
def cut_by_words(text: str, seg_size: int, overlap: int,
last_prop: float) -> List[str]:
"""Cut the input text into segments by number of words in each segment.
Cuts the text into equally sized segments, where the segment size is
measured by counts of wo... | 6d6b2dabc56c2d119160faf15be60ea83c026db3 | 3,604,835 |
from typing import List
def get_valid_cameras(cameras: List[Camera], exit_event: ExitEvent, pixels_per_meter: float, capture_radius: float) -> List[Camera]:
"""Gets a list of valid cameras based on an exit event's velocity and the location of the cameras.
:param cameras: The list of cameras that exist.
... | ce85555efc7b6b695cf124713bd72b6b83bc0d1b | 3,604,836 |
def part1(moons):
"""
>>> part1(input_moons())
6849
"""
simulate(moons, 1000)
return sum(moon.energy() for moon in moons) | 7475399ecc35a1d1f09116efe9aa172c9aca9856 | 3,604,837 |
def hilbert_2D(Volume_spectra: cp.ndarray) -> cp.array:
"""
Compute the analytic signal, using the Hilbert transform. \
The transformation is done along the last axis.
Args:
Volume_spectra::cp.ndarray
2nd order tensor containing spectras raw data. Last dimension is depth encoding.
... | 2b5905242a2ef9e015db77aaf9a566a80d03a84e | 3,604,838 |
def create_model(config: ml_collections.ConfigDict,
deterministic: bool) -> nn.Module:
"""Creates a Flax model, as specified by the config."""
if config.model == 'GraphNet':
return models.GraphNet(
latent_size=config.latent_size,
num_mlp_layers=config.num_mlp_layers,
mes... | 30af3b47269f20080a5e0beb047aa983965430d4 | 3,604,839 |
def u(X, _, mu):
"""The 1D-Shekel function."""
x = X[0]
sep = int(mu.shape[0] / 2)
bet = mu[:sep]
gam = mu[sep:]
u_sum = np.zeros_like(x)
for i in range(len(bet)):
i_sum = (x - gam[i])**2
u_sum += 1 / (bet[i] + i_sum)
return u_sum.reshape((1, u_sum.shape[0])) | b5ff9029a035410433f3e504ba5c07e1935d7ce0 | 3,604,840 |
def parse_itypes(item_types_txt):
"""
Reads each item type in ItemTypes.txt and builds a dictionary of ITypeNode
objects keyed by itype code.
"""
itype_nodes = {}
parent_codes = {}
for item_type in item_types_txt:
code = item_type["Code"]
if not code:
continue
... | 31d38b631e3c53d454d7dc084b65d5fbdd21f0ed | 3,604,841 |
import ast
def ReverseComplementMembership(x, y, **kwargs):
"""Change (x doesn't contain y) to not(y in x)."""
return ast.Complement(
ast.Membership(y, x, **kwargs), **kwargs) | d5a5457874f482eaa09f05b2b07ef9e26cbf961b | 3,604,842 |
import json
def _getAllMarkets():
"""
Retrieves all available markets.
bitcoincharts.com offers a JSON of current status (high, low, etc.) for every available market. From this data
we extract only market names.
:return: (list) all available markets
"""
try:
logger.info('getAllMar... | def62eefda8474dbe46b0d8711012ddb849e5e59 | 3,604,843 |
from matplotlib.widgets import Slider, Button
def interactive_plot(x, func, params, ymin=None, ymax=None, parnames=None, parunits=None, \
fig=None, ax=None, axmodel=None, parstart=None, iparstart=None, \
plotbutton=False, fixedpar=None, returnipar=False, block=False, ... | 11c16ebf3775555808cf92507f405d0d5999028a | 3,604,844 |
def percent_change(data, axis=-1):
"""Convert data to percent signal change over specified axis.
Parameters
----------
data : numpy array
Input data to convert to percent signal change.
axis : int
Axis of the ``data`` array to compute mean over.
Returns
-------
pch_data... | 6cf146b55a0d774816dcdf37b2f1d41c5c71bb6b | 3,604,845 |
def parseconfig(ui, raw):
"""Parse sparse config file content.
Returns a tuple of includes, excludes, and profiles.
"""
includes = set()
excludes = set()
profiles = set()
current = None
havesection = False
for line in raw.split('\n'):
line = line.strip()
if not line... | 17a214b7392ad452f995264711b93ef703ed4083 | 3,604,846 |
def export(request, type):
"""
Export the RMG database to the old RMG-Java format.
"""
# Build archive filenames from git hash and compression type
sha = subprocess.check_output(['git', 'rev-parse', 'HEAD'],
cwd=rmgweb.settings.DATABASE_PATH)[:7]
base = 'RMG_da... | bb337985b700969c8c210f7a227debcd058b9d48 | 3,604,847 |
def getLastStepVehicleIDs(loopID):
"""getLastStepVehicleIDs(string) -> list(string)
Returns the list of ids of vehicles that were on the named induction loop in the last simulation step.
"""
return _getUniversal(tc.LAST_STEP_VEHICLE_ID_LIST, loopID) | 5672cc2c36a46af7dfd2e8c1fdd214ca7a7c94f7 | 3,604,848 |
import warnings
def p_to_f(*period_derivatives):
"""Convert periods into frequencies, and vice versa.
For now, limited to third derivative. Raises when a
fourth derivative is passed.
Parameters
----------
p, pdot, pddot, ... : floats
period derivatives, starting from zeroth and in
... | defb9cd4bc0fa61368cd00577e92ab49cfaf88d2 | 3,604,849 |
def distance_check(list_of_comparison, time):
"""test function, no longer used"""
list_of_comparison=np.array(list_of_comparison)
condition = list_of_comparison - time < 1
return condition | 0cad6e4ab37df62664f0f440d1a2b41be5e4307e | 3,604,850 |
def get_config(config, group):
"""Return the tuple of song_data, log_data and output_data paths.
Arguments:
config -- ConfigParser object used to extract data values
group -- Top-level grouping of config values (AWS or LOCAL)"""
group = group.upper()
return config[group]['SONG_DATA'], c... | 62af332b29e0a901c14143bd8b77834229ce0013 | 3,604,851 |
import argparse
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='Train a Fast R-CNN network')
parser.add_argument('--dataset', dest='dataset',
help='training dataset',
default='vg1', type=str)
parse... | a344976a710182d05c006149c46e928c1b21383c | 3,604,852 |
def _check_crs(input_crs, return_rasterio=False):
"""Convert CRS to the ``pyproj.CRS`` object passed by ``solaris``."""
if not isinstance(input_crs, pyproj.CRS) and input_crs is not None:
out_crs = pyproj.CRS(input_crs)
else:
out_crs = input_crs
if return_rasterio:
if LooseVersi... | a472d194f68f09025e1f109ea1ed2ea4447df569 | 3,604,853 |
import os
import shutil
def decrypt_file(filename, blob_dir):
""" Reads the import "filename" decrypts it
and writes the decrypted data to a temp file in
tmp directory parallel to the 'blobstorage'.
IF the file doesn't exists in temp_dir
ELSE it just returns the path in temp_dir.
If the file... | 1418a9492134e732ba9e5f64185c9b5b550b515a | 3,604,854 |
def composite_stage_with_expanding_resource(
mock_stage_archive, mock_expand_resource):
"""Sets up a composite for expanding resources prior to staging."""
composite_stage = StageComposite()
archive = mock_stage_archive()
root_stage = Stage(archive.url)
composite_stage.append(root_stage)
... | 4f8ad599d10e8c90107cf1a2df7c11f3659f81f0 | 3,604,855 |
def singleton(cls):
"""
decorate a class and make it to generate singleton entity
@singleton
class xxx:
"""
instances = {}
def _singleton(*args, **kw):
"""
a closure function for decorator to execute each time
"""
if cls not in instances:
instances... | 7a599472b7d1ba4a6f1b2a13fb600c98144c6ef5 | 3,604,856 |
def target_encoding(cols, target_cols, aggregation='mean', sep='_te_'):
""" Template for creating target encoding FeatureConstructors
:param cols: columns to encode
:param target_cols: columns which values are aggregated
:param aggregation: name of built-in pandas aggregation or @helper-function
:p... | 8f921a788537bb39640073d6644923139760c3d6 | 3,604,857 |
def opt_single_property(pairs, return_removed=False, goal='max',\
scoring_function=num_bps):
"""Return single pseudoknot-free Pairs object with max number of bps
pairs -- Pairs object or list of tuples. One base can only interact
with one other base, otherwise an error will be raised.
return_re... | fa9c17ac99521ce3cefbb28da522b045ba7dbd48 | 3,604,858 |
import re
def sanitize_jinja(arg):
"""
For some string, prevent usage of Jinja-like flags
"""
if isinstance(arg, str):
# If the argument looks like it contains Jinja expressions
# {{ x }} ...
if re.search(r'\{\{[^}]+}}', arg) is not None:
raise ValueError('Inline Ji... | 7c28e987b18e4395d2d80dead85f1ee699515309 | 3,604,859 |
def ancestor(synset1, synset2):
""" Returns the common ancestor of both synsets.
For example synsets("cat")[0].ancestor(synsets("dog")[0]) => Synset("carnivore")
"""
h1, h2 = synset1.hypernyms(recursive=True), synset2.hypernyms(recursive=True)
for s in h1:
if s in h2:
return ... | 4f37b5895c7455e560847f00358b3538b43aff03 | 3,604,860 |
def generate_bbox(cls_map, reg, scale, threshold, stride=2, cell_size=12):
"""
generate bbox from feature cls_map
Parameters:
----------
cls_map: numpy array , n x m
detect score for each position
reg: numpy array , n x m x 4
bbox
scale: float number
... | efcf026a489bc445a3e9f7904d3e328df1efbd63 | 3,604,861 |
import logging
def get_encoder_from_hub(hub_model) -> tf.keras.Model:
"""Gets an encoder from hub.
Args:
hub_model: A tfhub model loaded by `hub.load(...)`.
Returns:
A tf.keras.Model.
"""
input_word_ids = tf.keras.layers.Input(
shape=(None,), dtype=tf.int32, name='input_word_ids')
input_ma... | f2fe21506840bbad89b58368646d54af78b8c0d9 | 3,604,862 |
def get_sparse_vector(ids, length, values=None):
"""Sparse vector generation.
If "values" is None, the elements are set to 1.
:param ids:
:param length:
:param values:
:return:
"""
n = len(ids)
if values is None:
return ssp.coo_matrix((np.ones(n), (ids, np.zeros(n))), (lengt... | 83a173aaa0b3ca8d9a68acd613dd7bf1da5088c1 | 3,604,863 |
def one_hot_encode(pad_ques_input, pad_ans_input, pad_ans_target, vocab_size):
"""
Pads the input sequences to the max_len
Returns:
-- pad_ques_input: one hot encoded padded tokens of questions to input to encoder
-- pad_ans_input: one hot encoded padded tokens of answers to input to decoder
... | ba4d3b237e124c64c1ea67f227ae15a26ec961f0 | 3,604,864 |
import importlib
import logging
def get_resource_task(resource_path, config=Injected):
# type: (str, Config) -> Callable[[str, Dict, Dict], Union[List[AppModel], AppModel, ResourceResult]]
"""Search and return a bounded method for given path.
:param resource_path: resource path
:type resource_path: s... | 855865cb6c02d2a2b7859eebcfbd82abda3e962b | 3,604,865 |
import os
def load_pcba(featurizer='ECFP', split='random'):
"""Load PCBA datasets. Does not do train/test split"""
current_dir = os.path.dirname(os.path.realpath(__file__))
print("About to load PCBA dataset.")
dataset_file = os.path.join(current_dir, "../../datasets/pcba.csv.gz")
# Featurize PCBA data... | 931ef59169e3bde5e8ddf3b3f3abb59e8079d397 | 3,604,866 |
def make_id_number(
date_of_birth: date, gender: Gender, citizenship: Citizenship
) -> str:
"""Construct a valid RSA ID number from the given information.
Args:
date_of_birth: The date of birth.
gender: The gender indicator.
citizenship: The citizenship indicator.
Returns:
... | 420a05fe4cbf4469bfa44541ffd00bd263a0beed | 3,604,867 |
def parse_escape(s, fg=None, bg=None, style=None):
"""Parses an escape sequence.
Not sure if this is very accurate.
"""
if style is None:
style = []
if not s:
return (None, None)
parts = _iter_escape(s)
for p in parts:
if p == 38:
fg = _parse_colors(par... | dd37430de86dbc811cde57df3d4d7f3efa6dc909 | 3,604,868 |
def add_biodata_args(parser):
"""Add standard arguments for preparing biological data to a command line arg parser.
"""
parser.add_argument("--genomes", help="Genomes to download",
action="append", default=[],
choices=SUPPORTED_GENOMES)
parser.add_argument... | 5d2eb97878ee19b6d7efe9ad301f0298f98d8b2c | 3,604,869 |
def Iq(q,
scale=1.0,
gamma=3.0,
q_0=0.1):
"""
:param q: Input q-value
:param scale: Scale factor
:param gamma: Exponent
:param q_0: Correlation peak position
:return: Calculated intensity
"""
with errstate(... | b9f65d9fb3f47d8f67158b194493bc9cddde6c6b | 3,604,870 |
import asyncio
def run_coro(coro):
"""Runs a co-routing in the default event loop and retuns it result."""
return asyncio.get_event_loop().run_until_complete(coro) | 62f109ef4440ecb2807640ff91b27f07e91d8f9f | 3,604,871 |
from datetime import datetime
def _init_campaign(
context,
csv_output,
xlsx_output,
only_activated=True,
confirmation_tokens=False,
skip_agendas=False,
stdout=None,
):
"""Initialises campaign based on manifest data.
Parameters:
- context:dict[str]->any dictionary containing ma... | fe9681e3d4b3b7a0906e2ff495b80ce56e25f652 | 3,604,872 |
def get_help(command_name):
"""Get help output of command."""
return mirtk.check_output([command_name, '-h']).splitlines() | aa92bb5890382e8b44fad1acba55bfaeb6736c34 | 3,604,873 |
from typing import Dict
from typing import Any
import os
import json
import yaml
def _read_data(path: str) -> Dict[str, Any]:
"""
Read data from JSON and YAML files.
"""
with open(path, "r") as f:
ext = os.path.splitext(path)[-1]
if ext == ".json":
return json.load(f)
... | d3ff635c028cef9bc1be05a5c0c9be7e6d4f30c2 | 3,604,874 |
import copy
def count(df):
"""
A function to count numbers for each prediction cases
:param df: A dataframe of raw prediction result
:return:
- df_count
Column: Ground Truth
Row: Predicted label
TP: df_count[ground truth label, ground truth ... | 64c1f42748acde3ed6b251025b3f7f88a23b0e08 | 3,604,875 |
import numpy
def charge_exchange(ods, nc=10):
"""
Adds some FAKE CER channel locations so that the overlay plot will work in tests. It's fine to test
with dummy data as long as you know it's not real. This function can overwrite existing data if you're not careful.
The original is modified, so deepcop... | 1e0f169ffa12263715fffdd6476da37300340c66 | 3,604,876 |
import subprocess
def run_pedr2tab(pedrlist):
"""
Use subprocess to call the external program, "pedr2tab."
Relies on the external program to decide if arguments are valid or not.
Pipe STDERR to STDOUT.
Parameters
----------
pedrlist : str
path to file containing list o... | 05e16ebd12468a1e0c1bf30a6e928ece16c09022 | 3,604,877 |
def _format_creators(value: list) -> dict:
""" Creators require special formatting.
$a Personal name (ex: Griesinger, Peggy)
$b Numeration (ex. III) (used for royalty or people who are Jrs. or Srs.)
$c Titles and other words associated with a name (ex. King of England)
$d Dates assoc... | 43f372d5075ee2186e57737b717b3432ace1a0d3 | 3,604,878 |
def create_pk(overview, absorption, distribution, elimination, special_populations, ddi_studies):
"""create pk on pk class"""
pk = Pharmacokinetics(overview=overview,
absorption=absorption,
distribution=distribution,
elimination=elimina... | 26937f554e58a4bf0d6622aa17bee0557d271e6b | 3,604,879 |
def buildaff(ulx: float, uly: float, pixelres: float) -> tuple:
"""
Build a gdal GeoTransform tuple
Args:
ulx: projected geo-spatial upper-left x reference coord
uly: projected geo-spatial upper-left y reference coord
pixelres: pixel resolution
Returns:
affine tuple
... | 43e593050a6b3ebef876f4347d3df787e2a49795 | 3,604,880 |
def parse_oauth_callback(url: str):
"""Parse the URL to which an OAuth login redirected to obtain two
tokens: an access token for API credentials, and a refresh token for
getting updated access tokens.
"""
params = parse_qs(urlparse(url).query)
return {k: v[0] for k, v in params.items()} | 32c86c635440283538c40f6051dc57bfa61ddeb8 | 3,604,881 |
from operator import and_
def unfollow(id):
"""
Unfollow a user.
"""
user = session['user']
if user == None:
abort(404)
followed = User.query.get(id)
if followed == None:
abort(404)
if followed.id == user.id:
# don't follow self
return redirect(url_for... | 7fde25cee21b92388f575de3eca18b5429d33cc6 | 3,604,882 |
def giscube_search_get_app_modules():
"""Return the Python module for each installed app"""
return [i.module for i in apps.get_app_configs()] | c71b05590b0cda84a150e82a32ae5c88a23dd50c | 3,604,883 |
def parse_search_result_data(api_response):
"""
Parse the search result data from the given raw json by following the response style of tokopedia
Arg:
- api_response (list): list of products
Returns:
- product_list (list): list of compiled product properties
"""
product_list =... | ee1314589e1599f2d4a58523077abc8a7f270f88 | 3,604,884 |
def emc_status(hardware, emc, dgtype):
"""
Make a EMC diagnostic message
Fields:
- 'val': 0
"""
# Make EMC diagnostic status
d_emc = DiagnosticStatus(name='jetson_stats {type} emc'.format(type=dgtype),
message='{val}%'.format(val=emc['val']),
... | 9176e5bd2cce9f6da2954b3b770a281853ccda30 | 3,604,885 |
def check_bal_of_tree(node):
"""."""
if node is None:
return True
to_visit = [node]
while to_visit:
curr_node = to_visit.pop(0)
if check_bal_of_node(curr_node) > 1:
return False
if curr_node.left:
to_visit.append(curr_node.left)
if curr_n... | 081a352d7870a551e44f4404a929fc4bd961d250 | 3,604,886 |
from typing import Optional
def combine_masks(
mask1: Optional[np.ndarray], mask2: Optional[np.ndarray]
) -> Optional[np.ndarray]:
"""Combine two masks as mask1 AND mask2.
Ignore any missing mask argument.
"""
if mask1 is None:
if mask2 is None:
return None
else:
... | 15bf7898a5aff7428c11ac534a406a03cb168009 | 3,604,887 |
import io
from pathlib import Path
def _integrate(
poni_file: str,
img_file: str,
bg_img_file: str = None,
mask_file: str = None,
output_dir: str = ".",
bg_scale: float = None,
mask_setting: tp.Union[dict, str] = None,
integ_setting: dict = None, plot_setting: tp.Union[dict, str] = Non... | 73ee451f9c3b365c9773e79385692918797697c7 | 3,604,888 |
def get_categories(head):
"""Get the list of categories containing a given head"""
# MySQL lib takes care of escaping quotes (in a weird way)
query = "SELECT category_name FROM node WHERE is_prominent=true AND head_of_name=%s"
CURSOR.execute(query, (head,))
# TODO Exhaustive skip filter
return [... | 9a973a842ca58d4118e55c6685aee616c89a382c | 3,604,889 |
def magnify_heatmap(df,cm=sns.diverging_palette(5, 250, as_cmap=True)):
"""Color negative and positive vals for each column to display
overall trends per column and row and provide hover function
for inspecting individual values."""
cmap = cm
bigdf = df.style.background_gradient(cmap, axis=1)\
... | a55c2aeb8ba06230db878f750e014ad19122ccdb | 3,604,890 |
import torch
from datetime import datetime
import time
def trainning(model: GCN_Class or GCN_Reg,
criterion: torch.nn.modules.loss.NLLLoss or torch.nn.modules.loss.MSELoss,
train: torch.utils.data.dataloader.DataLoader,
test: torch.utils.data.dataloader.DataLoader,
... | 05b090f5a735ca4e16f35f94cdfbd1218f5792c5 | 3,604,891 |
def check_annulus(args):
"""
Checks and formats the annulus values.
:param args: The command-line arguments.
:type args: argparse.ArgumentParser Namespace
:returns: argparse.ArgumentParser Namespace -- The updated command-line
arguments.
"""
if not (args.annulus1 and args.annulus... | cd99b7200d226d9e36c644351d8e696a25a1a81d | 3,604,892 |
def computeSignalValueInFrame(startbit, ln, fmt, value):
"""
compute the signal value in the frame
"""
frame = 0
if fmt == 1: # Intel
# using "sawtooth bit counting policy" here
pos = ((7 - (startbit % 8)) + 8*(int(startbit/8)))
while ln > 0:
# How many bits can we ... | f35a63ea4811b248430ee457c64fda98ea17134d | 3,604,893 |
def submit():
"""
Process form's data or redirect if data is not correct.
Also redirects if methods!=POST
"""
if request.method != 'POST':
return redirect('/form')
if request.form['name'] and request.form['address'] and request.form['postcode'] and request.form['city'] and request.form... | fa241589b7eb7e87e551b90a6d255763415f4dc5 | 3,604,894 |
def faceOrientation2Euler(r: np.ndarray, degrees:bool=True) -> np.ndarray:
"""Converts rodriguez representation of a rotation to euler angles
Args:
r (np.ndarray): The rodriguez representation vector (angle*u in form x,y,z)
degrees (bool): If True, the outputs will be in degrees otherwize in ra... | 1576114004127484f91fd7bc8138b9eb1dfc8754 | 3,604,895 |
def image_data(xr, x_range, y_range):
"""Create a tile"""
canvas = datashader.Canvas(plot_width=256,
plot_height=256,
x_range=x_range,
y_range=y_range)
xri = canvas.quadmesh(xr)
image = np.ma.masked_array(xri.va... | a2daa2b493b537e66058ba0eba74086e354431d4 | 3,604,896 |
import re
def parse_show_spanning_tree_mst_config(raw_result):
"""
Parse the 'show spanning-tree mst-config' command raw output.
:param str raw_result: vtysh raw result string.
:rtype: dict
:return: The parsed result of the show spanning-tree \
mst-config command in a dictionary of the for... | 2f07e13ff7f79e4c15e0fe5111cbc18fb638dae8 | 3,604,897 |
from survey.txx.helpers import finalize_resp
def handle_task_done(base, response_to_result_func=None, response_to_bonus=None, numeric_fields=None, unique_fields=None):
"""
:param base: (str)
:param response_to_result_func: (func)
:param response_to_bonus: (func)
:param numeric_fields: (None| '*' |... | 63b844a806d6d193e90e7862dd1a67b4851d6cf5 | 3,604,898 |
from numpy_sugar.linalg import economic_qs
from numpy import pi, var, diag
from glimix_core.glmm import GLMMExpFam
from glimix_core.lmm import LMM
def estimate(y, lik, K, M=None, verbose=True):
"""
Estimate the so-called narrow-sense heritability.
It supports Normal, Bernoulli, Probit, Binomial, and Pois... | 2c41e519fb9c5adefb01c8d38a62da1b87d1992d | 3,604,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.