content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def recipe_clone_message(recipe):
"""
Renders the recipe clone message.
"""
return dict(recipe=recipe) | 09728b431966b12415861a212f2cb85af475dc37 | 3,653,500 |
def read_expression_file(file):
"""Reads a file with the expression profiles."""
D = []
genes = []
with open(file) as fp:
firstline = fp.readline()
classes = [c.strip() for c in firstline.split("\t")[1:]]
for line in fp.readlines():
items = [w.strip() for w in line.sp... | aa3465855eb75a731801660e8f7b22091aae0a36 | 3,653,501 |
def train(X, Y, n_h, num_iterations=10000, print_cost=False):
"""
定义神经网络模型,把之前的操作合并到一起
Args:
X: 输入值
Y: 真实值
n_h: 隐藏层大小/节点数
num_iterations: 训练次数
print_cost: 设置为True,则每1000次训练打印一次成本函数值
Return:
parameters: 模型训练所得参数,用于预测
"""
np.random.seed(3)
n_x... | 57efdadd744b9801227da87aed8ca458e2990c5c | 3,653,502 |
def get_drawdowns(cum_returns):
"""
Computes the drawdowns of the cumulative returns.
Parameters
----------
cum_returns : Series or DataFrame, required
a Series or DataFrame of cumulative returns
Returns
-------
Series or DataFrame
"""
cum_returns = cum_returns[cum_retu... | 1f4da9e405b8b4f8a691b09e42e479cd6fdec3ae | 3,653,503 |
def calc_recipe_quantity_ratio(
first_month: str,
first_recipe: str,
second_recipe: str,
file_name: str,
second_month: str = None) -> float:
"""
A function which calculates the ratio of quantity between two months.
:param first_month: str
:param first_recipe: str... | 284fd4c010c933523967a11f774fc7e220198e7f | 3,653,504 |
def teacher_add_to_db():
"""Adds a teacher to database
Returns:
Redirect: Redirects to teachers list route
"""
if request.method == "POST":
fet_name = request.form["fet_name"]
fullname = request.form["fullname"]
teacher_email = request.form["t_email"]
try:
... | 224f95f00e88dce00d21406883dd5655ed9e8fbd | 3,653,505 |
def authorize(app_id, channel_id, team_id):
"""Just double check if this app is invoked from the expected app/channel/team"""
if app_id != SLACK_APP_ID:
return f"app ID {app_id}"
if team_id not in SLACK_TEAM_IDS:
return f"team ID {team_id}"
if channel_id not in SLACK_CHANNEL_IDS:
... | ff1f43a2073e7a0a54bda709b41fce02475c48ec | 3,653,506 |
import random
def deal_one_card():
""" returns a random card from the deck """
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
return random.choice(cards) | e8836c6569ed5c9e48043c9b750e730c42781a14 | 3,653,507 |
def grey_pal(start=0.2, end=0.8):
"""
Utility for creating continuous grey scale palette
Parameters
----------
start : float
grey value at low end of palette
end : float
grey value at high end of palette
Returns
-------
out : function
Continuous color palett... | f38295a48120a3e17b000276797bfec78a644749 | 3,653,508 |
import re
import os
def prepare(path, data_id):
"""Process each dataset based on individual characteristics
Args:
path to pull data from
"""
# assert type(train) == bool, 'Wrong train/test selection input'
if train:
suffix = "_train"
else:
suffix = "_test"
if da... | cf4464b87eb1770b899debb6f2bb2aa96b0f853c | 3,653,509 |
def tags_to_matrix(events_df, tags_df, top_tags):
"""Converts tags to feature matrix
Args:
events_df: Events dataset
tags_df: Tags dataset
top_tags: Tags to include
Returns:
Feature matrix for tags
"""
# Combine tags into lists
tags = tags_df.groupby('id')['tag'... | ab9b6eec8aaa2bddeccdbbb923338dc6b32df649 | 3,653,510 |
from typing import Optional
from typing import Union
from typing import Any
from typing import Dict
def get_parameter_value_and_validate_return_type(
domain: Optional[Domain] = None,
parameter_reference: Optional[Union[Any, str]] = None,
expected_return_type: Optional[Union[type, tuple]] = None,
varia... | be1ab4c90942d69083b765194baa494658265275 | 3,653,511 |
def add_leaf_to_edge(t):
"""
Returns a `Shape` instance with a new root; both a new leaf and the input `Shape` pend from it.
:param t: `Shape` instance.
:return: `Shape` instance.
"""
return Shape([Shape.LEAF, t]) | 18d4a383dcc2873e506677f76501c76e36b99ac7 | 3,653,512 |
def create_simulation(parameter_values=None, experiment=None, make_inputs=False):
"""
Create a PyBaMM simulation set up for interation with liionpack
Parameters
----------
parameter_values : :class:`pybamm.ParameterValues`
The default is None.
experiment : :class:`pybamm.Experiment`
... | 0faf24958440e42b64ef8cc82b9ec478d4899dd2 | 3,653,513 |
def _logistic_loss_and_grad(w, X, y, alpha, mask, sample_weight=None):
"""Computes the logistic loss and gradient.
Parameters
----------
w : ndarray, shape (n_features,) or (n_features + 1,)
Coefficient vector.
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Training ... | 39a05f090807a6eb83000e6daf5f3719bbbe9aa1 | 3,653,514 |
import requests
def verify_status_code(request_response: requests.Response) -> tuple:
"""Verify the status code of the post request to the search url and raise exceptions if the code is unexpected
:type request_response: requests.Response
:return:
"""
if request_response.status_code == 200:
... | b5f686dfe11d7fd4bd9d5f32ccd51df9f2322a13 | 3,653,515 |
def instability_product_graphs(gra):
""" Determine if the species has look for functional group attachments that
could cause molecule instabilities
"""
# Build graphs for the detection scheme
rad_grp_dct = radical_group_dct(gra)
# Check for instability causing functional groups
prd_gra... | 42aba79627bd6343bd2e99bca9a099d1047a9f5c | 3,653,516 |
def build_pdb_rmsd_matrix(pdb_paths, pdb_diff_path=None):
"""
Returns rmsd difference matrix for multiple pdb files.
Returns rmsd_list (3-item list), pdb_comp_amount (int).
Optional with pdb_diff_path return pdb_diff_comp(int).
"""
# make 3 column list or ndarray for x, y = (pdb1-n * pdb1-n) and... | fe00efa6a853d0e77ae52c21267376eca25a110c | 3,653,517 |
import logging
import sys
def handle_options():
"""
Define default options for a complete and automatic process
then check the command line arguments for parts of the process to skip
Returns:
auto: whether or not we accept user inputs on job and location
scrap: whether or not we do th... | c1e68d57dc7a664691dc121654cb8ad1b701e36d | 3,653,518 |
from typing import Optional
def expected_response(y: np.ndarray, w: np.ndarray, policy: np.ndarray,
mu: Optional[np.ndarray]=None, ps: Optional[np.ndarray]=None) -> float:
"""Estimate expected response.
Parameters
----------
y: array-like of shape = (n_samples)
Observed ... | ffa6938914480f236d8b0aff7ebc993a2e714682 | 3,653,519 |
def get_type_for_field(field: Field) -> type:
"""
For optional fields, the field type_ is a :class:`typing.Union`, of
``NoneType`` and the actual type.
Here we extract the "actual" type from a Union with None
"""
if not field.sub_fields:
return field.type_
for f in field.sub_fields:... | 2d0163b6e92bcd67c2aaee60d7088cc70e9bd09b | 3,653,520 |
from typing import List
def read_program_data(program: List[str]) -> int:
"""Read program data from port computer system.
Args:
program (List[str]): the program code containing masks and memory
Returns:
int: sum of all values in memory
"""
memory = defaultdict(int)
for line ... | 7852d13f1de9cc04ee4170a10807b49ed2592905 | 3,653,521 |
def get_mgr_worker_msg(comm, status=None):
"""Get message to worker from manager.
"""
status = status or MPI.Status()
comm.probe(source=0, tag=MPI.ANY_TAG, status=status)
tag = status.Get_tag()
if tag in [STOP_TAG, PERSIS_STOP]:
return tag, None, None
Work = comm.recv(buf=None, sourc... | 76bf2be4707052ab5ea0f447822208eccb19f9ef | 3,653,522 |
import time
def retry(exceptions, tries=4, delay=3, backoff=2, logger=None):
"""
Retry calling the decorated function using an exponential backoff.
Args:
exceptions: The exception to check. may be a tuple of
exceptions to check.
tries: Number of times to try (not retry) before... | 8c0917ad45b2c000ced926f0457b9b9aebbc4543 | 3,653,523 |
def load_dictionary(dicttimestamp, server='postgres-cns-myaura'):
""" Load dictionary from database
Args:
dicttimestamp (string): the version of dictionary (ex: 20210131)
server (string): the server name in db_config.ini
Returns:
tuple (termdictparser, pandas.DataFrame): A TermDict... | 63df416815386c1bf4d6a820c98490ae5a6e4d08 | 3,653,524 |
def part1(data):
"""
>>> part1(((20, 30), (-10, -5)))
45
>>> part1(INPUT)
13203
"""
target_x, target_y = data
best = None
for dx in range(1, max(target_x) + 1):
for dy in range(0, - min(target_y) + 1):
hit_target, height = trajectory(target_x, target_y, dx, dy)
... | 293dd006caa20471cc849c1366f0610594279b8b | 3,653,525 |
def get_neighbors(p, exclude_p=True, shape=None, nNeighbors=1,
get_indices=False, direction=None, get_mask=False):
"""Determine pixel coordinates of neighboring pixels.
Includes also all pixels that neighbor diagonally.
Parameters
----------
p : tuple
Gives the coordinate... | 4dc68ed4f44667253c4bdb114a0d3034a65ef725 | 3,653,526 |
import torch
def make_coordinate_grid(spatial_size, type):
"""
Create a meshgrid [-1,1] x [-1,1] of given spatial_size.
"""
h, w = spatial_size
x = torch.arange(w).type(type)
y = torch.arange(h).type(type)
x = (2 * (x / (w - 1)) - 1)
y = (2 * (y / (h - 1)) - 1)
yy = y.view(-1, 1)... | 0bbbd2f0e0d588b58feebce19b3f2fd9c84934d8 | 3,653,527 |
def add_wrong_column(data_frame):
"""
Adds wrong column to dataframe
:params dataframe data_frame:
:returns dataframe:
"""
new_df = data_frame.copy()
new_df['Ducks'] = 0
return new_df | 0f3ae838c0975e8021cfeee258576afac75072c5 | 3,653,528 |
def p2l(X, Y, D, tol, inputTransform):
"""
Computes the Procrustean point-line registration between X and Y+nD with
anisotropic Scaling,
where X is a mxn matrix, m is typically 3
Y is a mxn matrix denoting line origin, same dimension as X
D is a mxn normalized matrix denoting line direction
R i... | 5b7b1143fd7dbbeae6767f8ef5f71464eb6220a0 | 3,653,529 |
def config_database(db_name):
"""
Create a database in sqlite3
:param db_name: The name of the file for the database
:return: A database objetc and his connections object
"""
db = Database()
connection = db.create_connection(db_name)
db.create_table(connection)
return db, connection | 42602f32a3cca0dfbbc791973acbf6279af7cde3 | 3,653,530 |
from pathlib import Path
def parse_main_argument(argument, export_folder):
"""Function parsing the main_argument argument.
Returns a dataframe containing the search terms (or the urls if main_argument is a youtube file."""
# File or string
if Path(argument).is_file():
is_file = True
ar... | f3cbd81e3fe98333fa2a4ad04f746c291dc9138a | 3,653,531 |
from datetime import datetime
def validate_auth_header(headers):
"""Validate and decode auth token in request headers.
This helper function is used in each of the below wrappers, and is responsible to
validate the format of the `Authorization` header where the Lowball token is
supposed to reside.
... | be75c33767a43f1482417277d6a41f887b26f388 | 3,653,532 |
def shared_random_seed():
"""All workers must call this function, otherwise it will deadblock.
"""
seed = np.random.randint(2 ** 31)
all_seeds = all_gather(seed)
return all_seeds[0] | bdf636ddc24defd13339c20fed0bb5896c35400e | 3,653,533 |
def _version(base):
"""Get a chronological version from git or PKG-INFO
Args:
base (dict): state
Returns:
str: Chronological version "yyyymmdd.hhmmss"
str: git sha if available
"""
v1 = _version_from_pkg_info(base)
v2, sha = _version_from_git(base)
if v1:
if... | 2d5b5e08fe44386347541634643e28e86cda5a44 | 3,653,534 |
def average_link_distance_segment(D,stop=-1,qmax=1,verbose=0):
"""
Average link clustering based on a pairwise distance matrix.
Parameters
----------
D: a (n,n) distance matrix between some items
stop=-1: stopping criterion, i.e. distance threshold at which
further merges are forbi... | 1be3da149a5ceb99ab94980b94caec0c42edb096 | 3,653,535 |
def _process_get_set_Operand(column, reply):
"""Process reply for functions zGetOperand and zSetOperand"""
rs = reply.rstrip()
if column == 1:
# ensure that it is a string ... as it is supposed to return the operand
if isinstance(_regressLiteralType(rs), str):
return str(rs)
... | b63de89b480ab263eb49c04dba47befb8bbe0997 | 3,653,536 |
def generic_laplace(input, derivative2, output=None, mode="reflect",
cval=0.0, extra_arguments=(), extra_keywords=None):
"""Multi-dimensional Laplace filter using a provided second derivative
function.
Args:
input (cupy.ndarray): The input array.
derivative2 (callable): ... | bc58a7ca79b551f4cba4c4c61855e027d666f2a0 | 3,653,537 |
import functools
def as_keras_metric(method):
""" from https://stackoverflow.com/questions/43076609/how-to-calculate-precision-and-recall-in-keras """
@functools.wraps(method)
def wrapper(self, args, **kwargs):
""" Wrapper for turning tensorflow metrics into keras metrics """
value, updat... | 17a6a6e39a25576215e0b426779df2ccac48e9b4 | 3,653,538 |
def do_get_video_capture_job(port_output_name: str = 'RAW') -> str:
"""
Function for configure the image retrieval job from video camera.
:param port_output_name: name you want to use for raw image in the application
:return: output image port name
"""
output_raw_port_name = transform_port_name_... | b7965cde58e6b562d289cc58ac25edfd400c3b8a | 3,653,539 |
from typing import Optional
import os
import subprocess
def sync_one(src: str, dst: str, *, dry_run: bool) -> Optional[date]:
"""
From the snapshots that are present in src and missing in dst, pick the one
that is closest to an existing snapshot in dst, and sync it. Returns the
snapshot synced, or non... | 1b2b8b273bf65e7654c9623a51ec3dbeb62b8ee3 | 3,653,540 |
def vgg8_S(*args, **kwargs):
"""VGG 16-layer model (configuration "D")
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = VGG(make_layers(cfg['YS']), final_filter=256, **kwargs)
return model | ec3824dbccbbca804ec5160c551bc7171a9b3866 | 3,653,541 |
from typing import IO
def createWords(word_str):
"""Cn Mandarin sentence to Cn Mandarin Words list"""
pre_func = IO.readList(r'docs/pre_punctuation.txt')[1:]
lat_func = IO.readList(r'docs/post_punctuation.txt')[1:]
en_letters = IO.readList(r'docs/special_English_letters.txt')[1:]
words = []
j ... | 7d7aad411773550e6a884539a1160218499dea73 | 3,653,542 |
def get_calib_driver(calib_dir: str):
""" Create left/right charuco point detectors and load calibration images from directory. """
reference_image = cv2.imread("tests/data/2020_01_20_storz/pattern_4x4_19x26_5_4_with_inset_9x14.png")
minimum_points = 50
number_of_squares = [19, 26]
square_tag_sizes... | 1c0b859327fefa983c68b2f70909f5d1ca8108cd | 3,653,543 |
def stop_loading() -> dict:
"""Force the page stop all navigations and pending resource fetches."""
return {"method": "Page.stopLoading", "params": {}} | fd46497cee6a87ca0b00cc6ceed487655361d896 | 3,653,544 |
def drop_duplicates(df):
"""Drop duplicate rows and reindex.
Args:
df (pd.DataFrame): Dataframe.
Returns:
pd.DataFrame: Dataframe with the replaced value.
Examples:
>>> df = pd.DataFrame({'letters':['b','b','c'], 'numbers':[2,2,3]})
>>> drop_duplicates(df)
... | 517d9faf09267df72def3fa7b90b0f59d819d660 | 3,653,545 |
def estimate_progress(ihash, peers):
"""Estimate a percentage done based on client stats"""
progress = count = 0
log.debug("peers: %s" % peers)
size = float(get_size(ihash))
if not size:
return "Unknown"
stats = get_clientstats(ihash)
# log.debug("%s" % stats)
for peer in peers:
... | 5f85b3157f6db12a468a9e94f7535b78a08e7788 | 3,653,546 |
def make_otf(
psf,
outpath=None,
dzpsf=0.1,
dxpsf=0.1,
wavelength=520,
na=1.25,
nimm=1.3,
otf_bgrd=None,
krmax=0,
fixorigin=10,
cleanup_otf=False,
max_otf_size=60000,
**kwargs
):
""" Generate a radially averaged OTF file from a PSF file
Args:
psf (str... | ad3fbdbea7562f766c53f26a82880f41002c893f | 3,653,547 |
def get_palette(dataset_name):
"""
Maps classes to colors in the style of PASCAL VOC.
Close values are mapped to far colors for segmentation visualization.
See http://host.robots.ox.ac.uk/pascal/VOC/voc2012/index.html#devkit
Takes:
num_classes: the number of classes
Gives:
palet... | 9253f633f7c3a6aa0c135af988125f3c144e3572 | 3,653,548 |
import unicodedata
def is_number(input_string):
"""
if input_string includes number only, return corresponding number,
otherwise return input_string
"""
try:
return float(input_string)
except ValueError:
pass
try:
return unicodedata.numeric(input_string)
except... | 2b435b1f23c8764e0ff6bf741678db91bb4a5b23 | 3,653,549 |
def latest_active(name, at_time=None, **kwargs): # pylint: disable=unused-argument
"""
Initiate a reboot if the running kernel is not the latest one installed.
.. note::
This state does not install any patches. It only compares the running
kernel version number to other kernel versions al... | 449819b4abb43b062514f0c8356f3fcd992198f7 | 3,653,550 |
import logging
def upload_file(file_name, bucket, object_name):
"""Upload a file to an S3 bucket
:param file_name: File to upload
:param bucket: Bucket to upload to
:param object_name: S3 object name. If not specified then file_name is used
:return: True if file was uploaded, else False
"""
... | 3db16ca5b2136995f4772dafa3778b54e5e41e5c | 3,653,551 |
def get_conf(bs_info, client_config, genesis_time, setup_oracle=None, setup_poet=None, args=None):
"""
get_conf gather specification information into one ContainerSpec object
:param bs_info: DeploymentInfo, bootstrap info
:param client_config: DeploymentInfo, client info
:param genesis_time: string... | c2d27fa1922be786b0afa9212864465e14ee3de7 | 3,653,552 |
def zeropad(tr, starttime, endtime):
"""
Zeropads an obspy.Trace so as to cover the time window specified by
`starttime`'and `endtime`
Parameters
----------
tr : obspy.Trace
starttime, endtime : obspy.UTCDateTime
Returns
-------
trace : obspy.Trace
Zeropadded c... | 417c17d8dea148f6534f204d064ba13665ede597 | 3,653,553 |
import time
import random
def deepwalk(G, _filepath, o=1, num_walks_node=10, walk_length=80,
representation_size=128, window_size=5,):
"""not going to deal with memory exceeding case"""
output = _filepath + G.name
print("Walking...")
time_start = time.time()
walks = gu.build_deepwalk... | a5b77e6485d29a6a08ca25aa9ea06507a7fae076 | 3,653,554 |
def logship_status(host):
"""Report log shipping retstore delta and latency"""
crit = warn = 0
msg = ''
sql = """SELECT secondary_server, secondary_database, primary_server, primary_database,
last_restored_date, DATEDIFF(mi, last_restored_date, GETDATE()) last_restored_delta,
last_resto... | 7b0ea3282d66dd7d354d4b6d14d54bfd826d85d9 | 3,653,555 |
def dice(y_true, y_pred):
"""
Attention:
y_true can be weighted to modify learning therefore
apply sign to get back to labels
y_pred have to be rounded to nearest integer to obtain labels.
"""
smooth = 1.
y_true_f = y_true.flatten()
y_pred_f = y_pred.flatten()
intersection = n... | 205d7cf0f09f702d7905d42c0dfbbd16738ed1e8 | 3,653,556 |
import os
def get_long_description(filename):
"""Return entire contents of *filename*."""
with open(os.path.join(WORKING_DIR, filename)) as fh:
return fh.read() | 6720da5b5e2a91a5ad62e4ac9bcc344e10a16656 | 3,653,557 |
def get_default_language():
"""
Returns the default language code based on the data from LANGUAGES.json.
"""
for language_code, language_data in MEDICINE_LANGUAGE_DATA.items():
if 'DEFAULT' in language_data:
if language_data['DEFAULT']:
return language_code
r... | 5bbfbc1060e52a4db957afd0eb8b45cdb60036f4 | 3,653,558 |
def triple_triple(r, p=qt.QH([1, 0, 0, 0])):
"""Use three triple products for rotations and boosts."""
# Note: 'qtype' provides a record of what algrabric operations were done to create a quaternion.
return triple_sandwich(r, p).add(triple_2_on_1(r, p), qtype="triple_triple") | 58b529faa97fae29fcc5b481263c0c84af2ddca2 | 3,653,559 |
def _pinv_trunc(x, miss):
"""Compute pseudoinverse, truncating at most "miss" fraction of varexp."""
u, s, v = linalg.svd(x, full_matrices=False)
# Eigenvalue truncation
varexp = np.cumsum(s)
varexp /= varexp[-1]
n = np.where(varexp >= (1.0 - miss))[0][0] + 1
logger.info(' Truncating at ... | fca4f8b7e118c88ed7be37553ede09275f8d06ec | 3,653,560 |
def mog_loglike(x, means, icovs, dets, pis):
""" compute the log likelihood according to a mixture of gaussians
with means = [mu0, mu1, ... muk]
icovs = [C0^-1, ..., CK^-1]
dets = [|C0|, ..., |CK|]
pis = [pi1, ..., piK] (sum to 1)
at locations given by x = [x1... | e907c642e664188cb838e89b889257ded2a5aed9 | 3,653,561 |
from typing import Sequence
def align_chunks(array: da.core.Array, scale_factors: Sequence[int]) -> da.core.Array:
"""
Ensure that all chunks are divisible by scale_factors
"""
new_chunks = {}
for idx, factor in enumerate(scale_factors):
aligned = aligned_coarsen_chunks(array.chunks[idx], ... | df8b845f10bc4a8fa72e1da53d655d25f73d971d | 3,653,562 |
def getWordScore(word):
"""
Computes the score of a word (no bingo bonus is added).
word: The word to score (a string).
returns: score of the word.
"""
if len(word) == HAND_SIZE:
score = 50
else:
score = 0
for letter in word:
score = score + SCRABBLE_LETTER_VALU... | 5d848b5ef5bb0e77d75a866300d9a87b557b5b1b | 3,653,563 |
import requests
import json
def get_lang_list(source_text, key=None, print_meta_data=False):
"""
Inputs:
source_text - source text as a string
key - google api key, needed or function will raise and error
returns list of language identifiers
"""
#set up url request to google translate api... | 720c3c9252535e82881411fa345734d984350537 | 3,653,564 |
def single_value_rnn_regressor(num_units,
sequence_feature_columns,
context_feature_columns=None,
cell_type='basic_rnn',
num_rnn_layers=1,
optimizer_type='SGD',
... | 4290d8b4e5ea069f58b7fc5a5734c16133b1a614 | 3,653,565 |
import uuid
def token():
""" Return a unique 32-char write-token
"""
return str(uuid.uuid4().hex) | f7dc5725cc1d11ee0ab9471d141a89178fa3d07c | 3,653,566 |
def _get_caller_caller_module_name():
"""Return name of module which calls the function from which this function is invoked"""
frame = currentframe().f_back.f_back
return getmodule(frame).__name__ | 4199207922db40424e1a4fa56ee662209de06830 | 3,653,567 |
from typing import Tuple
def percentile(x: np.ndarray, percentile: float = 99) -> Tuple[float, float]:
"""Get the (low, high) limit for the series by only including the data within the given percentile.
For example, if percentile is 99, (1st percentile, 99th percentile) will be returned.
Also, if percen... | 00a7c6561432da84f878985b1e3dba942d4ec478 | 3,653,568 |
from pathlib import Path
def get_versions_data(
hidden=None,
is_unreleased=None,
find_latest_release=None,
sort_key=None,
labels=None,
suffix_latest_release=' (latest release)',
suffix_unreleased=' (dev)',
find_downloads=None,
):
"""Get the versions data, to be serialized to json."... | 4232013fe403b3de54df571e13b881077145b61f | 3,653,569 |
import torch
from typing import Generator
import os
def cgan_training(Xtrain, Xdev, Ytrain, Ydev, use_gpu=False):
"""
Train using a conditional GAN
"""
if use_gpu:
device = torch.device("cuda")
else:
device = torch.device("cpu")
dtype = torch.double
vh = VariableHandler(de... | f7ad50dcc1b5bb7a86c97c00693adf55b64364c5 | 3,653,570 |
from wheel_filename import InvalidFilenameError, parse_wheel_filename
import json
from datetime import datetime
def wheels(
package_name: str = Argument(..., help="The name of the package to show wheel info for"),
version: str = Argument(
None,
help="The version of the package to show info for... | f57b577426dbd24b86d9eaa91b13c0b048d22afe | 3,653,571 |
from typing import List
import os
def _list_of_files() -> List[str]:
"""
Return the list of waypoint story files
:return:
"""
file_list = (
f for f in os.listdir(waypoint_directory_path) if f.endswith("." + "yml")
)
waypoint_list_file = []
for file in file_list:
if not... | dfc7033c2610b13fb3e3cae8e2074915a594caf5 | 3,653,572 |
def extract_pvdata(h5file, timestamp, pvnames=None):
"""
Extract as a snapshot (PV values) nearest a timestamp from a BSA HDF5 file.
Parameters
----------
h5file: str
BSA HDF5 file with data that includes the timestamp
timestamp: datetime-like, str, int, float
This ... | cd62b347735c97e962c8eec01d4344b4fb4e63f9 | 3,653,573 |
import functools
def decorate_func_with_plugin_arg(f):
"""Decorate a function that takes a plugin as an argument.
A "plugin" is a pair of simulation and postprocess plugins.
The decorator expands this pair.
"""
@functools.wraps(f)
def wrapper(self, plugins_tuple):
return f(self, plugi... | e90c86bfd6c3cada33c867d26ed64da3cac6f9c4 | 3,653,574 |
from datetime import datetime
def datestr(date=None):
"""Convert timestamps to strings in a predefined format
"""
if date is None:
date = datetime.utcnow()
if isinstance(date, str):
date = parse_time(date)
return date.strftime("%y-%m-%d %H:%M:%S") | 36505b926eef6aaa5bcbae011ba90931c20a5067 | 3,653,575 |
import re
import argparse
def validate_release_tag_param(arg_value):
"""
User defined helper function to validate that the release_tag parameter follows the correct naming convention
:param arg_value: release tag parameter passed through either the command line arguments
:return: arg_value
"""
... | 80ba82ad5d13d28349272e2c4b9831864e32fbf2 | 3,653,576 |
def init():
"""Connect to the keyboard, switch all lights off"""
global bufferC # Buffer with the full key/lights mapping
global device
device=hid.device()
# 0x17cc: Native Instruments. 0x1410: KK S88 MK1
device.open(0x17cc, pid)
device.write([0xa0])
bufferC = [0x00] * numkeys
... | 0edc2085cbd6b48fef85d5492e4093551a15aac1 | 3,653,577 |
def render(path):
"""
Render the knowledge post with all the related formatting.
"""
mode = request.args.get('render', 'html')
username, user_id = current_user.identifier, current_user.id
tmpl = 'markdown-rendered.html'
if mode == 'raw':
tmpl = 'markdown-raw.html'
elif mode == ... | 67d9f48c94d79ab069403457b63f31b495123363 | 3,653,578 |
def compute_acc_bin(conf_thresh_lower, conf_thresh_upper, conf, pred, true):
"""
# Computes accuracy and average confidence for bin
Args:
conf_thresh_lower (float): Lower Threshold of confidence interval
conf_thresh_upper (float): Upper Threshold of confidence interval
conf (numpy.n... | eb338800751de635e6b72213254287554cd34dc0 | 3,653,579 |
import importlib
def multi_backend_test(globals_dict,
relative_module_name,
backends=('jax', 'tensorflow'),
test_case=None):
"""Multi-backend test decorator.
The end goal of this decorator is that the decorated test case is removed, and
repla... | 1006e2bc983f7821138ab27b6d2465055a275c0d | 3,653,580 |
import random
def _get_typed_array():
"""Generates a TypedArray constructor.
There are nine types of TypedArrays and TypedArray has four constructors.
Types:
* Int8Array
* Int16Array
* Int32Array
* Uint8Array
* Uint16Array
* Uint32Array
* Uint8ClampedArray
... | 31eea5c66689584ff38eb8edad3a15231f7cd438 | 3,653,581 |
def _is_valid_requirement(requirement: str) -> bool:
"""Returns True is the `requirement.txt` line is valid."""
is_invalid = (
not requirement or # Empty line
requirement.startswith('#') or # Comment
requirement.startswith('-r ') # Filter the `-r requirement.txt`
)
return not is_invalid | 73b8ad139329698ad334b230cb04976db4ec05ba | 3,653,582 |
from kivy.clock import mainthread
from kivy.app import App
import threading
def execute(cmd):
"""Execute a random string in the app context
"""
_result = [None]
_event = threading.Event()
@mainthread
def _real_execute():
app = App.get_running_app()
idmap = {"app": app}
... | 2ec1850487d854a074dd60642ff38a7ec9fc7e97 | 3,653,583 |
import six
def is_scalar(element):
"""An `is_atomic` criterion. Returns `True` for scalar elements.
Scalar elements are : strings and any object that is not one of:
collections.Sequence, collections.Mapping, set, or attrs object.
```
import nifty_nesting as nest
flat = nest.flatten([1, [2,... | 07f280822a6167ab951942f6e2479476ceec2dc5 | 3,653,584 |
from typing import Union
from typing import Sequence
def wrap_singleton_string(item: Union[Sequence, str]):
""" Wrap a single string as a list. """
if isinstance(item, str):
# Can't check if iterable, because a string is an iterable of
# characters, which is not what we want.
return [i... | 6e0946fee8fddd23631ff66d405dce2ae8a15fa6 | 3,653,585 |
def view_milestone_history(request, chosen_year=None):
"""
http://127.0.0.1:8000/milestones/by-columns/
:param request:
:return:
"""
(chosen_year, basic_query) = get_basic_milestone_history_query(chosen_year)
milestones = basic_query.order_by('due_on')
open_closed_cnts = get_is... | 1d40c08701e9088682e9e0663c1538956b22770c | 3,653,586 |
def M_absolute_bol(lum):
"""Computes the absolute bolometric luminosity
Parameters
----------
lum : `float/array`
luminosity in solar luminosities
Returns
-------
M_bol : `float/array`
absolute bolometric magnitude
"""
log_lum = np.log10(lum)
M_bol = 4.75 - ... | dd3209fd6c91a7b1b51f43a7a15f9c5eaccd740d | 3,653,587 |
def codes_index_get_double(indexid, key):
# type: (cffi.FFI.CData, bytes) -> T.List[float]
"""
Get the list of double values associated to a key.
The index must be created with such a key (possibly together with other
keys).
:param bytes key: the keyword whose list of values has to be retrieved... | 9a0c2c27f917ecfe63ad1f6a797aa152928d294c | 3,653,588 |
from typing import Optional
def lemmatize(
nlp: Optional[Language] = None, name="lemmatize"
) -> ops.base.SpacyBasedOperation:
"""Helper function to return SpacyBasedOperation for lemmatizing.
This operation returns a stream.DataStream where each item is a string after
being lemmatized.
Parameter... | 797efa35320cf4b4e5e1176d1fbbcee13bbaa884 | 3,653,589 |
def mean_absolute_deviation(curve1: np.ndarray, curve2: np.ndarray, *args):
"""Calculate the mean deviation."""
diff = np.abs(curve1 - curve2)
return np.mean(diff) | 687fda24399bc71e1d1f0ca8b880a0eafc9a1a7d | 3,653,590 |
def get_segtype_hops(seg_type, connector=None): # pragma: no cover
"""
Request list of segments by type used to construct paths.
:param seg_type: The type of PathSegmentType requested.
:returns: List of SCIONDSegTypeHopReplyEntry objects.
"""
global _connector
if not connector:
con... | 525e9feb6ea5b0692ef67ec20aa967a60f65519b | 3,653,591 |
def build_moderation_channel_embed(ctx, channel, action):
"""
Builds a moderation embed which display some information about the mod channel being created/removed
:param ctx: The discord context
:param channel: The channel to be created/removed
:param action: either "Added" or "Removed" to tell the... | de0f32a29019a05125f2389286140bc6dcfff198 | 3,653,592 |
def print_settings(settings):
"""
This function returns the harmonic approximation settings .
Returns
-------
text: str
Pretty-printed settings for the current Quantas run.
"""
text = '\nCalculator: Equation of state (EoS) fitting\n'
text += '\nMeasurement units\n'
text +... | 4e64353e0c519a26ac210de1df39ce09fbf54045 | 3,653,593 |
def run_analysis(output, stimtype="gabors", comp="surp", ctrl=False,
CI=0.95, alg="sklearn", parallel=False, all_scores_df=None):
"""
run_analysis(output)
Calculates statistics on scores from runs for each specific analysis
criteria and saves them in the summary scores dataframe.
... | 5f6c44fcfc482c66ee318be3787419ee2e811962 | 3,653,594 |
from typing import List
from typing import Dict
def decrypt_ballots_with_all_guardians(
ballots: List[Dict], guardians: List[Dict], context: Dict
) -> Dict:
"""
Decrypt all ballots using the guardians.
Runs the decryption in batches, rather than all at once.
"""
ballots_per_batch = 2
decry... | 6aebf29e7d0b41fd3da23d6bbecf7e40c56e1c9f | 3,653,595 |
def getRealItemScenePos(item):
"""
Returns item's real position in scene space. Mostly for e.g. stranditems.
This will change as the root item is moved round the scene,
but should not change when zooming.
"""
view = pathview()
try:
vhitem = item.virtualHelixItem()
linepos = l... | cef292e25cd99886841bb5aa5d521c8630284210 | 3,653,596 |
def get_default_upload_mode():
"""
Returns the string for the default upload mode
:return: Default upload mode string
"""
return api.MODE_DEFAULT | 003672d478dc5754ba8b62833d9c8706b482bd0f | 3,653,597 |
def remove_multi_whitespace(string_or_list):
""" Cleans redundant whitespace from extracted data """
if type(string_or_list) == str:
return ' '.join(string_or_list.split())
return [' '.join(string.split()) for string in string_or_list] | a284eb1ea685fb55afeefe78d863a716475a9182 | 3,653,598 |
def validate_board(board: list) -> bool:
"""
Checks if board fits the rules. If fits returns True, else False.
>>> validate_board(["**** ****","***1 ****","** 3****","* 4 1****",\
" 9 5 "," 6 83 *","3 1 **"," 8 2***"," 2 ****"])
False
"""
if check_rows(board) and\
c... | 8f6b2cdf9e7cecd456378a11b580b6a69d52a308 | 3,653,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.