content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def is_context_spec(mapping):
"""Return True IFF `mapping` is a mapping name *or* a date based mapping specification.
Date-based specifications can be interpreted by the CRDS server with respect to the operational
context history to determine the default operational context which was in use at that dat... | a44af272dc18aa6c2a872309d89e9b4695114056 | 3,634,400 |
def find_pair(cards):
"""
Find best pair of cards + three highest ranked cards
Parameters
----------
cards : TYPE
DESCRIPTION.
Returns
-------
prevCard : TYPE
DESCRIPTION.
"""
PokerCard.cardsRank(cards)
PairsList = []
try:
prevCard = cards[... | 3e11ca68667b3be3fb900d5a65e8c4d21b216b13 | 3,634,401 |
def mergeSort(nums):
"""归并排序"""
if len(nums) <= 1:
return nums
mid = len(nums)//2
#left
left_nums = mergeSort(nums[:mid])
#right
right_nums = mergeSort(nums[mid:])
print(left_nums)
print(right_nums)
left_pointer,right_pointer = 0,0
result = []
while left_pointer < len(left_nums) and right_pointer < le... | 708166485cf3e916bbde12edec7057c404ee830d | 3,634,402 |
def readProtectedRegistry(protectedRegistryFile):
"""
Reads records from a protected registry and divides into two dictionaries
that map record->(recordId, siteId).
@return: (exactMatchDict, partialMatchDict)
"""
exactMatch, partialMatch = {}, {}
# Iterate the protected registry file one li... | b02c185f8369775b113cc9d7386f448660fd8885 | 3,634,403 |
import torch
def get_graph_feature(x, xyz=None, idx=None, k_hat=20):
"""
Get graph features by minus the k_hat nearest neighbors' feature.
:param x: (B,C,N)
input features
:param xyz: (B,3,N) or None
xyz coordinate
:param idx: (B,N,k_hat)
kNN graph index
:param k_hat: (... | cb18e6d673bdc59b25e8d3135a0bca3014707319 | 3,634,404 |
def get_poly(time, npoly=3):
"""Returns a matrix of polynomial """
# Time polynomial
t = (time - time.mean())
t /= (t.max() - t.min())
poly = np.vstack([t**idx for idx in np.arange(0, npoly + 1)]).T
return poly | d5f830c0c247f4a77e4ea16e1536ff03f7143188 | 3,634,405 |
from typing import Match
def match(first_name, last_name, province, date_of_birth, record_id):
"""Find the Type of Match, if there is any and create Match object"""
def update_match(notice, match_type):
"""Create Match object"""
try:
record = Record.objects.get(id=record_id)
... | 12b426b44427b2f3d1de0c14f83f50586ea6add6 | 3,634,406 |
def rmse(adata):
"""Calculate the root mean squared error.
Computes (RMSE) between the full (or processed) data matrix and a list of
dimensionally-reduced matrices.
"""
(
adata.obsp["kruskel_matrix"],
adata.uns["kruskel_score"],
adata.uns["rmse_score"],
) = calculate_rm... | ccaa4eae7ea9bc4e68ca59cd9c52d8d69344635b | 3,634,407 |
def format_dic(dic):
"""将 dic 格式化为 JSON,处理日期等特殊格式"""
for key, value in dic.iteritems():
dic[key] = format_value(value)
return dic | d532e02f77a5d596e4ddf19b5b65c91bc10f79cc | 3,634,408 |
def validate_task(task, tasks=None):
"""
Validate the jsonschema configuration of a task
"""
name = task['name']
config = task.get('config', {})
schema = getattr(TaskRegistry.get(name)[0], 'SCHEMA', {})
format_checker = getattr(TaskRegistry.get(name)[0], 'FORMAT_CHECKER', None)
try:
... | c1cbd326df171d0ff524761a84f923cfe1d1a05c | 3,634,409 |
import os
def pred_data_2D_per_sample(model, x_dir, y_dir, fnames, pad_shape = (256, 320), batch_size = 2, \
mean_patient_shape = (115, 320, 232), ct = False):
"""
Loads raw data, preprocesses it, predicts 3D volumes slicewise (2D) one sample at a time, and pads to the original sha... | 4d564b0d114f0f30261a7b37132147546a65aab6 | 3,634,410 |
from scipy.signal._arraytools import odd_ext
import scipy.fftpack
def cogve(COP, freq, mass, height, show=False, ax=None):
"""COGv estimation using COP data based on the inverted pendulum model.
This function estimates the center of gravity vertical projection (COGv)
displacement from the center of press... | 4b7809f3a50ffab09ed9d6740782ad76b0687926 | 3,634,411 |
def locked_view_with_exception(request):
"""View, locked by the decorator with url exceptions."""
return HttpResponse('A locked view.') | 13eb49ed7d3385c9a5bb870e8c91883f1582c63d | 3,634,412 |
import json
def generate_api_queries(input_container_sas_url,file_list_sas_urls,request_name_base,caller):
"""
Generate .json-formatted API input from input parameters. file_list_sas_urls is
a list of SAS URLs to individual file lists (all relative to the same container).
request_name_base is a ... | fa6ba9bbbfa26af9a7d1c6e6aa03d0e53e16f630 | 3,634,413 |
def estimate_H_unbiased_parallel(X, Y, n_jobs, freq_dict = None):
"""Parallelised estimation of H with unbiased HSIC-estimator"""
assert Y.shape[0] == X.shape[0]
p = X.shape[1]
x_bw = util.meddistance(X, subsample = 1000)**2
kx = kernel.KGauss(x_bw)
if freq_dict is not None:
ky = KDiscre... | eb2f768d2c48251d56551d70f8a53833ba775ef3 | 3,634,414 |
import torch
def logsumexp_across_rois(roi_inputs, rois):
"""
Args:
roi_inputs (torch.Tensor): shape (bn, chn, rh, rw)
rois (torch.Tensor): shape (bn, 5)
Returns:
Tensor, shape (bn, chn, rh, rw)
"""
bn, kn, rh, rw = roi_inputs.size()
# allocate memory, (bn, chn, rh, rw)... | 0ca53a1b2565da615ff9f159299fcab41aa8442e | 3,634,415 |
import re
def add_symbol_and_color(df: pd.DataFrame, colormap: dict):
"""
Color logic happens here. Use nowcast's precipitation, when it is available and
otherwise forecast's weather symbol (defined by YR).
:param df: DataFrame containing weather data
:param colormap: color definitions to use
... | f03448fcddd069f599e61cda8ce8c00ec1dbd7c0 | 3,634,416 |
def ignore_troublesome_polymer(polymer):
"""
See what the possible shortest string is by ignoring one of the polymers and its polymer of inverse polarity.
:param polymer: the string representing the polymer
:return: the simplified polymore
>>> ignore_troublesome_polymer('dabAcCaCBAcCcaDA')
'daD... | 98e92c6e221ca0899311fa28d8637af963180366 | 3,634,417 |
def add_version(match):
"""return a dict from the version number"""
return {'VERSION': match.group(1).replace(" ", "").replace(",", ".")} | 101578396425aceaacc2827ef6f362c382aaa89b | 3,634,418 |
from typing import Sequence
def replace_cryptomatte_hashes_by_asset_index(
segmentation_ids: ArrayLike,
assets: Sequence[core.assets.Asset]):
"""Replace (inplace) the cryptomatte hash (from Blender) by the index of each asset + 1.
(the +1 is to ensure that the 0 for background does not interfere with asse... | 342324b5b694b0934c17e3aa8a26513dafca669c | 3,634,419 |
def getValueBetweenKey1AndKey2(str, key1, key2):
"""得到关键字1和关键字2之间的值
Args:
str: 包括key1、key2的字符串
key1: 关键字1
key2: 关键字2
Return:
key1 ... key2 内的值(去除了2端的空格)
"""
offset = len(key1)
start = str.find(key1) + offset
end = str.find(key2)
value = ... | 02337550db4b9e230261e325443fdeadf90664ee | 3,634,420 |
def sample_function_parameter(parameter_name, return_variable_name=None):
""" Returns sample function that extracts a parameter from current state
Args:
parameter_name (string): atrribute in sampler.parameters
(e.g. A, C, LRinv, R)
return_variable_name (string, optional): name of re... | 6e5c9ca13be7302d8f2fefdf000e76a67fe63bff | 3,634,421 |
def generate_linear_probe(num_elec=16, ypitch=20,
contact_shapes='circle', contact_shape_params={'radius': 6}):
"""
Generate a one-column linear probe
"""
probe = generate_multi_columns_probe(num_columns=1, num_contact_per_column=num_elec,
... | 9e06e85870bff8ace43a0dbb4351956958524b03 | 3,634,422 |
from sys import path
import requests
def subview(request, subid):
"""present an overview page about the substance in sciflow"""
substance = Substances.objects.get(id=subid)
ids = substance.identifiers_set.values_list('type', 'value', 'source')
descs = substance.descriptors_set.values_list('type', 'val... | cc15d6d209ce666674422b27f2c1ebc208760a9b | 3,634,423 |
from typing import Union
from typing import Dict
from typing import Any
import types
import copy
def convert_to_attributes(
raw: Union[Dict[str, Any], types.Attributes]
) -> types.Attributes:
"""Convert dict to mapping of attributes (deep copy values).
Values that aren't str/bool/int/float (or homogeneou... | 4df605f0c4492d35bc3df34939a3b9a0e2d00d8e | 3,634,424 |
import time
import logging
def shouldpoll(name, curtime):
""" check whether a new poll is needed. """
global lastpoll
try: lp = lastpoll.data[name]
except KeyError: lp = lastpoll.data[name] = time.time() ; lastpoll.sync()
global sleeptime
try: st = sleeptime.data[name]
except KeyError: st ... | fb647ac1a81edecd10002a175c105f4c4445bc86 | 3,634,425 |
def submit_task(pipeline_name, accession, rest_api_key, priority="MEDIUM", starting_index=0):
"""
Submits a Conan task. Sending post request to ``api/submissions`` with data similar to the following JSON
{
"priority": `priority`,
"pipelineName": `pipeline_name`,
"startingProcessIndex": `starting... | 1232c9842500ff71a4c73d7d3b8947c19bb016bb | 3,634,426 |
def puissance(poly, n):
"""Renvoie le polynôme _poly_ à la puissance _n_"""
if n == 0: return [1]
poly = clear_poly(poly)
result = poly.copy()
for i in range(n-1):
result = mult_poly(result,poly)
return result | 92bba8acb3c5350b0c8c99b4d8c4a9a6817525bc | 3,634,427 |
import math
def getGridSample(lat, lon, n):
"""
Get a random sampling of n locations within k km from (lat, lon)
param: lat latitude of grid center point
param: lon longitude of grid center point
param: n number of locations to sample
return: array of length n of latit... | 24986c11f81fa8a237ef4f742f5c70934435e070 | 3,634,428 |
def multiplication(integer_one, integer_two):
"""
It multiplies two numbers
Args:
integer_one: The original integer
integer_two: The integer which needs to be multiplied with integer_one
Returns:
an integer with the value: integer_one*integer_two
"""
mul... | c16c5928541d0e28ef854ff2a18c97d7908e5114 | 3,634,429 |
def group_obs_table(obs_table, offset_range=[0, 2.5], n_off_bin=5,
eff_range=[0, 100], n_eff_bin=4, zen_range=[0., 70.],
n_zen_bin=7):
"""Helper function to provide an observation grouping in offset,
muon_efficiency, and zenith.
Parameters
----------
obs_tabl... | 94a31b3647e99b843696e1d70c180b8895fa4f1f | 3,634,430 |
def dist_matrix(n, cx=None, cy=None):
"""
Create matrix with euclidian distances from a reference point (cx, cy).
Parameters
----------
n : int
output image shape is (n, n)
cx,cy : float
reference point. Defaults to the center.
Returns
-------
im : ndarray with shap... | f4a15645bbaa91cbf8c0e97f5a61f595cbafee10 | 3,634,431 |
from typing import Union
def by_srid(
srid: int,
authority: Union[Authorities, str] = Authorities.EPSG.name,
validate: bool = True
) -> Sr:
"""
Get a spatial reference (`Sr`) by its SRID and, optionally, the authority
(if it isn't an `EPSG <http://www.epsg.org/>`_ spatial reference... | 9ff6e68a3a090cae293847027fa75a86cb624b4b | 3,634,432 |
def admin_cli(request, rancher_cli) -> RancherCli:
"""
Login occurs at a global scope, so need to ensure we log back in as the
user in a finalizer so that future tests have no issues.
"""
rancher_cli.login(CATTLE_TEST_URL, ADMIN_TOKEN)
def fin():
rancher_cli.login(CATTLE_TEST_URL,... | a780cccef12163a38444c9476676cdd1f1f62bb1 | 3,634,433 |
def crop_image(image, crop_box):
"""Crop image.
# Arguments
image: Numpy array.
crop_box: List of four ints.
# Returns
Numpy array.
"""
cropped_image = image[crop_box[0]:crop_box[2], crop_box[1]:crop_box[3], :]
return cropped_image | 03ddb9927b82ddfe3ab3a36ec3329b5a980fe209 | 3,634,434 |
import warnings
def reorder(names, faname):
"""Format the string of author names and return a string.
Adapated from one of the `customization` functions in
`bibtexparser`.
INPUT:
names -- string of names to be formatted. The names from BibTeX are
formatted in the style "Last, First M... | 4012add188a3497b582078d7e7e05eeafc95252f | 3,634,435 |
def smoter(
## main arguments / inputs
data, ## training set (pandas dataframe)
y, ## response variable y by name (string)
k = 5, ## num of neighs for over-sampling (pos int)
pert = 0.02, ## perturbation / noise percenta... | 2e1e37896ddff3df619ba1f752662da472d1052c | 3,634,436 |
def _compute_descriptive_stats(lst: list):
"""Basic descriptive statistics and a (parametric) seven-number summary.
Calculates descriptive statistics for a list of numerical values, including
count, min, max, mean, and a parametric seven-number-summary. This summary
includes values for the lower quarti... | a5fb4cc19cec08a584fe9c9f89fe28e8ffc30148 | 3,634,437 |
def prepareNewHTTPDConfig(inputDict, currentHttpdConf):
"""Check if needed start end tags are available.
If not consistent or was modified, file will append new config between tags"""
start, end = -1, -1
# Get the start and the end. In the automatic preparation it will 3 lines defined:
# # PROXYR... | bc525e12fe27a196ab0fd335b1e7780e3325c982 | 3,634,438 |
def array_xy_offsets(test_geo, test_xy):
"""Return upper left array coordinates of test_xy in test_geo
Args:
test_geo (): GDAL Geotransform used to calcululate the offset
test_xy (): x/y coordinates in the same projection as test_geo
passed as a list or tuple
Returns:
x... | 5fa67b7df833459f3fc59951a056316f249acc69 | 3,634,439 |
import torch
def log_density_normal(x, mean=0, var=1, average=False, reduce_dim=None):
"""
:param x:
:param mean:
:param var:
:param average:
:param reduce_dim:
:return:
"""
if isinstance(var, Number):
var = torch.tensor(var).float()
if x.is_cuda:
var ... | f8d4f4950265a05c37dece80d5c78d3b1dd20006 | 3,634,440 |
def get_group_policies(group_names):
"""
returns groups attached policies
"""
# TODO optimize algorithm
group_list = group_names.split(" ")
all_group_policies = ""
for group in group_list:
group_policies_response = iam.list_attached_group_policies(GroupName=group)
group_polic... | c875fd38b71ae6a65faa48063f9f42ea936007d6 | 3,634,441 |
def _sort2D(signal):
"""Revert the operation of _sort.
Args:
signal an instance of numpy.ndarray of one dimention
Returns:
An instance of numpy.ndarray
"""
to = signal.shape[1]
for i in range(1, to // 2 + 1, 1):
temp = signal[:, i].copy()
signal[:, i:to - 1] = ... | 566b2bbfcee7741cdb01451d6b0250c0fe21b4b5 | 3,634,442 |
def get_organizations_by_types(types, allowed_keys=None):
"""Get organization by list of types."""
session = get_session()
items = (
session.query(models.Organization)
.filter(models.Organization.type.in_(types))
.order_by(models.Organization.created_at.desc()).all())
return _to_... | bb15491d3e00cf483994654b19b727d3b1a44c6d | 3,634,443 |
def hiscale(trange=['2003-01-01', '2003-01-02'],
datatype='lmde_m1',
suffix='',
get_support_data=False,
varformat=None,
downloadonly=False,
notplot=False,
no_update=False,
time_clip=False):
"""
This function loads data from the HI-SCALE experim... | 80d75df6b6d60998007e6d98c87a7c6c7c227524 | 3,634,444 |
def order_stats(X):
"""Compute order statistics on sample `X`.
Follows convention that order statistic 1 is minimum and statistic n is maximum. Therefore, array elements ``0``
and ``n+1`` are ``-inf`` and ``+inf``.
Parameters
----------
X : :class:`numpy:numpy.ndarray` of shape (n,)
Da... | 37ea2d05f894fb9d8caed8bec6bc8cada267a58e | 3,634,445 |
def get_npr(treedata, idx):
"""
Returns number of progenitors of a given idx
"""
ind = np.where(treedata['id'] == idx)[0]
return treedata['nprog'][ind][0] | a331211ee87c5f8a3584d3096240079373a39a60 | 3,634,446 |
import argparse
def parse_args():
"""Parse arguments from the command line."""
parser = argparse.ArgumentParser("Generate trace files.")
parser.add_argument('--save-dir', type=str, required=True,
help="direcotry to save the model.")
# parser.add_argument('--trace-file', type=st... | 2980d61fdf5ecdfd8196ceb24479be0265d3b1e7 | 3,634,447 |
def dir_xtrack_to_geo(xtrack_dir, ground_heading):
"""
Convert image direction relative to antenna to geographical direction
Parameters
----------
xtrack_dir: geographical direction in degrees north
ground_heading: azimuth at position, in degrees north
Returns
-------
np.float64
... | bec1aa1897970b40951aeefa777ef0ab37abff07 | 3,634,448 |
def log(lvl, msg, *args, **kwargs):
""" Logs a message with integer level lvl """
return get_outer_logger().log(lvl, msg, *args, **kwargs) | f917817560e55594859517f5068eb9f1d53127b9 | 3,634,449 |
import torch
def train(n_epochs, loaders, model, optimizer, criterion, use_cuda, save_path, scheduler, patience=9):
"""returns trained model"""
early_stopping = EarlyStopping(save_path=save_path, patience=patience, )
# initialize tracker for minimum validation loss
valid_loss_min = np.Inf
fo... | d35a055edd56c64b704c2354d13f454fa1ba1dae | 3,634,450 |
def micro_jy_to_luminosity(mjy, msun, d):
"""Convert an SED in µJy to log solar luminosities.
Parameters
----------
mjy : ndarray
Flux in microjankies.
msun : float
Absolute magnitude of the Sun. 4.74 is the bolometric absolute
magnitude of the Sun.
d : ndarray
D... | d120c80d245c32a27be6c4134b946d2b60fe469f | 3,634,451 |
import re
def _MakeRE(regex_str):
"""Return a regular expression object, expanding our shorthand as needed."""
return re.compile(regex_str.format(**SHORTHAND)) | fd9080d17cbfdf8291fe02734aee8a119be73864 | 3,634,452 |
import random
def generate_rand_num(n):
"""
Create n 3-digits random numbers
:param n:
:return:
"""
nums = []
for i in range(n):
r = random.randint(100, 999)
nums.append(r)
return nums | 8e6ef674479767ce45b73807ee90c2d3adaf65ce | 3,634,453 |
def preprocess_for_eval(image_bytes,
image_size=IMAGE_SIZE,
resize_method=tf.image.ResizeMethod.BILINEAR):
"""Preprocesses the given image for evaluation.
Args:
image_bytes: `Tensor` representing an image binary of arbitrary size.
image_size: image size.
... | 47f8cbe607546f202961afc3e6ca7b048ecf7771 | 3,634,454 |
def _time_to_seconds_nanos(t):
"""
Convert a time.time()-style timestamp to a tuple containing
seconds and nanoseconds.
"""
seconds = int(t)
nanos = int((t - seconds) * constants.SECONDS_TO_NANOS)
return (seconds, nanos) | 1e6822ba4f0e9cc82c30fbcafd18c895c3e30c19 | 3,634,455 |
import struct
def _extract_impl(ctx, name = "", image = None, commands = None, docker_run_flags = None, extract_file = "", output_file = "", script_file = ""):
"""Implementation for the container_run_and_extract rule.
This rule runs a set of commands in a given image, waits for the commands
to finish, an... | e23fe9f45d81d95a7f72cb680da3ee79f676d97c | 3,634,456 |
def nlopt_newuoa(
criterion_and_derivative,
x,
lower_bounds,
upper_bounds,
*,
convergence_relative_params_tolerance=CONVERGENCE_RELATIVE_PARAMS_TOLERANCE,
convergence_absolute_params_tolerance=CONVERGENCE_ABSOLUTE_PARAMS_TOLERANCE,
convergence_relative_criterion_tolerance=CONVERGENCE_REL... | 64c8a997378190665be35fa412360247fc97af12 | 3,634,457 |
import os
def ExistsOnPath(cmd):
"""Returns whether the given executable exists on PATH."""
paths = os.getenv('PATH').split(os.pathsep)
return any(os.path.exists(os.path.join(d, cmd)) for d in paths) | b7c2915566e6ebf9d4cfb75731866f55367f1be1 | 3,634,458 |
def mean_velocity_error(predicted, target):
"""
Mean per-joint velocity error (i.e. mean Euclidean distance of the 1st derivative)
"""
assert predicted.shape == target.shape
velocity_predicted = np.diff(predicted, axis=0)
velocity_target = np.diff(target, axis=0)
return np.mean(np.linalg.nor... | f139dd2bcfa2c59da9b6a1198c90f8b70646f0b5 | 3,634,459 |
import zlib
def getObjectFormat(repo, sha):
"""Returns the object format of the object represented by hash"""
"""NOTE: hash has to be a full sha"""
path = repo_file(repo, "objects", sha[0:2], sha[2:])
with open(path, "rb") as f:
raw = zlib.decompress(f.read())
# computing the starting... | e65eccccfbf95316d72bc40632ecfe3d1f58eabe | 3,634,460 |
def v(a, b, th, nu, dimh, k):
"""Function used in **analytic_solution_slope()**
:param a:
:type a:
:param b:
:type b:
:param th:
:type th:
:param nu:
:type nu:
:param dimh:
:type dimh:
:param k:
:type k:
:return:
:rtype:
"""
# real, b
# real,... | a10dc41e40a014b0923c1d98c114158a3986263e | 3,634,461 |
def image_filenames(image_numbers):
"""List of image file names with directory
image_numbers: list or array of 1-based indices
"""
return [filename(i) for i in image_numbers] | 2c74bc943ce98ed10f8ddc36540826b49db522c4 | 3,634,462 |
import asyncio
def _load_from_mongo(mongo_uri: str):
"""
Load API Test information from a MongoDB.
Collection used to store API Test information will be named: **apitest**
>>> load_from_mongo("mongodb://127.0.0.1:27017")
<type 'APITest'>
>>> _load_from_mongo("mongodb://user:pass@mongo.examp... | ab32356029a293739eaa366d0f88af40c03db05a | 3,634,463 |
from datetime import datetime
def string_as_datetime(time_str):
"""Expects timestamps inline with '2017-06-05T22:45:24.423+0000'"""
# split the utc offset part
naive_time_str, offset_str = time_str[:-5], time_str[-5:]
# parse the naive date/time part
naive_dt = datetime.strptime(naive_time_str, '%... | 18b9b3b4afc0ae3454e056935ad1489f96b0f821 | 3,634,464 |
def __find_regexp_in_pdf(extra_data, patterns, forbidden_patterns=None, accept_even_if_not_found=False):
"""
Finds all matches for given patterns with surrounding characters in all filetypes.
Fails only if there are no matches at all or there is a match for a forbidden pattern.
:param patterns: iterable... | e29dbc92171be2a8de59ae9c4f84fbfe5893938f | 3,634,465 |
def truncated_normal(mean, std, num_samples, min, max):
"""
Return samples with normal distribution inside the given region
"""
return np.random.multivariate_normal(mean=mean, cov=std, size=num_samples * 2) % (max - min) + min | 6cc9a543e016ed28ee46dd79c85004df36abf398 | 3,634,466 |
def post_required(func):
"""Decorator that returns an error unless request.method == 'POST'."""
def post_wrapper(request, *args, **kwds):
if request.method != 'POST':
return HttpResponse('This requires a POST request.', status=405)
return func(request, *args, **kwds)
return post_wrapper | 5c6a4bff7c6605be79e78c9f2924766e55289348 | 3,634,467 |
def get_serial():
"""
Gets a globally unique serial number for each music change.
"""
global serial
serial += 1
return (unique, serial) | 0ea73476b746d22871e0b596d037ff9823f16c71 | 3,634,468 |
def model(load, shape, checkpoint=None):
"""Return a model from file or to train on."""
if load and checkpoint: return load_model(checkpoint)
conv_layers, dense_layers = [32, 32, 64, 128], [1024, 512]
model = Sequential()
model.add(Convolution2D(32, 3, 3, activation='elu', input_shape=shape))
... | 749f0660b87c93e29cfda21f7c595b66313a93b3 | 3,634,469 |
def cross_kerr_interaction(kappa, mode1, mode2, in_modes, D, pure=True, batched=False):
"""returns cross-Kerr unitary matrix on specified input modes"""
matrix = cross_kerr_interaction_matrix(kappa, D, batched)
output = two_mode_gate(matrix, mode1, mode2, in_modes, pure, batched)
return output | 8d32816782eaa987b1adfb9973f2518214e2ee65 | 3,634,470 |
def edgelength(G, node_wise=False, edge_wise=False, summary="mean"):
"""
This function calculates the physical distance between pairs of nodes. The default behaviour is to
return a dictionary of edges.
nodeWise: if True, then returns a dictionary of the sum of distance of all edges for each node
... | e500c70b400f69e31747439524c5b492d13546f3 | 3,634,471 |
def matern52(params, x1, x2, warp_func=None):
"""Matern 5/2 kernel: Eq.(4.17) of GPML book.
Args:
params: parameters for the kernel.
x1: a d-diemnsional vector that represent a single datapoint.
x2: a d-diemnsional vector that represent a single datapoint that can be the
same as or different from... | 7cbba9b84dd1e78d2ed6f7a9cc41feac2d4e597a | 3,634,472 |
def isint(i):
"""Returns if input is of integer type."""
return isinstance(i, (int, np.int8, np.int16, np.int32, np.int64)) | f9418b5869f2f15159322af24b7b787a1712b3f2 | 3,634,473 |
def decode_reponse(response):
"""Return utf-8 string."""
return response.data.decode("utf-8", "ignore") | 3c2c91f08c44db4705feaea525c9c58837fa6d6c | 3,634,474 |
def add_sheet_user(session, *, cls, discord_user, start_row, sheet_src=None):
"""
Add a fort sheet user to system based on a Member.
Kwargs:
cls: The class of the sheet user like FortUser.
duser: The DiscordUser object of the requesting user.
start_row: Starting row if none inserted... | df4d9f9325769bf5f80557a33c7aac5c5bd0eab6 | 3,634,475 |
def clean_uncertain(value, keep=False):
"""
Handle uncertain values in the data.
Process any value containing a '[?]' string.
:param value: the value or list of values to process
:param keep: whether to keep the clean value or discard it
"""
was_list = isinstance(value, list)
values = ... | 982be717dec2c3872198fefcc632d86af0281bc9 | 3,634,476 |
def traceback_file_lines(trace_text=None):
""" this returns a list of lines that start with file in the given traceback
usage:
traceback_steps(traceback.format_exc())
"""
# split the text into traceback steps
return [i for i in trace_text.splitlines() if i.startswith(' File "') and ... | 939fd7e978612d891f38825898f575bc8d9b38af | 3,634,477 |
def load(year, gp, session):
"""session can be 'Qualifying' or 'Race'
mainly to port on upper level libraries
"""
day = 'qualifying' if session == 'Qualifying' else 'results'
sel = 'QualifyingResults' if session == 'Qualifying' else 'Results'
return _parse_ergast(fetch_day(year, gp, day))[0][sel... | 45d36124b16fd3f4108e6a9e01423d8df432f081 | 3,634,478 |
def pad_extents(extents: Extents, pad: float = 0.05) -> Extents:
"""Pad an Extents by a factor
Parameters:
extents: bounding extents to pad
pad: padding distance
Returns:
padded bounding extents
"""
padx = (extents.maxx - extents.minx)*0.05
pady = (extents.maxy - exten... | d5ed2b353c704fbbcb9d23e2454e9a449dcb6261 | 3,634,479 |
from typing import Set
def make_VR_model():
""" This function constructs and returns a pyomo model for the vehicle routing problem this repo is focuses on solving """
model= AbstractModel()
# model sets:
model.P = Set () # set of pick ups
model.D = Set () # set of drop offs
model.R = Set ()... | dc95d0f814ca3e9796e946e66b8b54568812ec2b | 3,634,480 |
from typing import Union
def get_image(
difficulty: Union[gd.DemonDifficulty, gd.LevelDifficulty],
is_featured: bool = False,
is_epic: bool = False,
) -> str:
"""Generate name of an image based on difficulty and parameters."""
parts = difficulty.name.lower().split("_")
if is_epic:
par... | f34f59437bfe0e97ae166f8e5ee3be2737073a0b | 3,634,481 |
import json
def jsonpify(func):
"""
Like jsonify but wraps result in a JSONP callback if a 'callback'
query param is supplied.
"""
def inner(*args, **kwargs):
data = func(*args, **kwargs)
callback = request.args.get('callback')
if callback:
response = app.make_r... | 818eb424b6f61bc7fa7f068323789c6bff1ea7c1 | 3,634,482 |
def ordered(obj):
""" Sort JSON blob by keys """
if isinstance(obj, dict):
return sorted((k, ordered(v)) for k, v in list(obj.items()))
if isinstance(obj, list):
return sorted(ordered(x) for x in obj)
else:
return obj | dba08ec9ece30cfd01d3fcdde4b32e9e42086079 | 3,634,483 |
import copy
def apply_perturbation(X, y, perturbations_info):
"""Application of the perturbations."""
perturb = perturbations_info[3](X, None, perturbations_info[1],
perturbations_info[2])
X_p, y_p = perturb.apply2features(copy.copy(X)).squeeze(2), copy.copy(y)
ret... | 2a7ba4e0286fe81f494f2e2d752532d24e895be4 | 3,634,484 |
def iris_sji_color_table(measurement, aialike=False):
"""
Return the standard color table for IRIS SJI files.
"""
# base vectors for IRIS SJI color tables
c0 = np.arange(0, 256)
c1 = (np.sqrt(c0) * np.sqrt(255)).astype(np.uint8)
c2 = (c0**2 / 255.).astype(np.uint8)
c3 = ((c1 + c2 / 2.) *... | c00dd6fc5572dfd4563079040fab48ec5d439215 | 3,634,485 |
def clipToCollection(image, featureCollection, keepFeatureProperties=True):
""" Clip an image using each feature of a collection and return an
ImageCollection with one image per feature """
def overFC(feat):
geom = feat.geometry()
clipped = image.clip(geom)
if keepFeatureProperties:
... | c42610e2164e389db17a353ca15a22d21a9cd614 | 3,634,486 |
def bbox_filter(image, bboxes, labels):
"""
Maginot Line
"""
h, w, _ = image.shape
x1 = np.maximum(bboxes[..., 0], 0.)
y1 = np.maximum(bboxes[..., 1], 0.)
x2 = np.minimum(bboxes[..., 2], w - 1e-8)
y2 = np.minimum(bboxes[..., 3], h - 1e-8)
int_w = np.maximum(x2 - x1, 0)
int_h =... | 38c8a1997e233ff1484c321559b9b7b21e0ff283 | 3,634,487 |
import json
def sign_transaction(source_address, keys, redeem_script, unsigned_hex, input_txs):
"""
Creates a signed transaction
output => dictionary {"hex": transaction <string>, "complete": <boolean>}
source_address: <string> input_txs will be filtered for utxos to this source address
keys: Lis... | 775fbccd906cbba598eb07d2b8b1f233c32c3954 | 3,634,488 |
import numpy
def CalculateBasakCIC1(mol):
"""
Obtain the complementary information content with order 1 proposed
by Basak.
"""
Hmol = Chem.AddHs(mol)
nAtoms = Hmol.GetNumAtoms()
IC = CalculateBasakIC1(mol)
if nAtoms <= 1:
BasakCIC = 0.0
else:
BasakCIC = numpy.log2(n... | ca5b2e5bea750ce029147fcea61321faa8e98629 | 3,634,489 |
from typing import Any
async def mock_nonpriviledged_user(db: Any, username: str) -> dict:
"""Create a mock user object."""
return { # noqa: S106
"id": ID,
"username": "nonprivileged@example.com",
"password": "password",
"role": "nonprivileged",
} | 23af36146a116373584930eadae9dd0633da1100 | 3,634,490 |
def idea_create(request):
"""
Endpoint to create ideas
---
POST:
serializer: ideas.serializers.IdeaCreationSerializer
response_serializer: ideas.serializers.IdeaSerializer
"""
if request.method == 'POST':
serializer = IdeaCreationSerializer(data=request.data)
if s... | d780854a33c123c33ee3e8179f5a8056bea4716c | 3,634,491 |
def blocks_to_pem(blobs, marker):
"""Convert binary blobs to a string of concatenated PEM-formatted blocks.
Args:
blobs: an iterable of binary blobs
marker: the marker to use, e.g., CERTIFICATE
Returns:
the PEM string.
"""
return PemWriter.blocks_to_pem_string(blobs, marker... | 498d63aa16990c4046f5fbd25aea17fbff72d7c3 | 3,634,492 |
def scatterList(z):
"""
scatterList reshapes the solution vector z of the N-vortex ODE for easy 2d plotting.
"""
k = int(len(z)/2)
return [z[2*j] for j in range(k)], [z[2*j+1] for j in range(k)] | 422bf448ae999f56e92fdc81d05700189122ad0e | 3,634,493 |
from pathlib import Path
def discover_workflow(path: Path) -> Workflow:
"""
Find a instance of virtool_workflow.Workflow in the
python module located at the given path.
:param path: The :class:`pathlib.Path` to the python file
containing the module.
:returns: The first instance o... | 95b67497b61f3ecf715ce677d7b2986d0817830b | 3,634,494 |
from typing import List
from typing import Mapping
from typing import Optional
def swagger_endpoint_data_to_df(
data: List[Mapping],
headers: Optional[List[str]] = None
) -> pd.DataFrame:
"""Load results from cBioPortal API endpoints to pandas DataFrame.
Parameters
----------
data : L... | 6c4e4c657131b8cc54f3827033e077edc7bb57b1 | 3,634,495 |
def compare():
"""
This path takes two inputs in multiform/data
Name of paramaters:
image1: First image
image2 : Second image
"""
if request.method == 'POST':
if 'image1' not in request.files or 'image2' not in request.files:
return make_response(jsonify("Msg: Upload an i... | e4b6625608051804222074f5972b10ee864659d8 | 3,634,496 |
def provides_facts():
"""
Returns a dictionary keyed on the facts provided by this module. The value
of each key is the doc string describing the fact.
"""
return {
"switch_style": "A string which indicates the Ethernet "
"switching syntax style supported by the device. "
"Po... | d41f97df8a24b67d929017fc6c20596a70ba18cd | 3,634,497 |
def _continuum_emission(energy_edges_keV, temperature_K, abundances):
"""
Calculates emission-measure-normalized X-ray continuum spectrum at the source.
Output must be multiplied by emission measure and divided by 4*pi*observer_distance**2
to get physical values.
Which continuum mechanisms are incl... | a9d66263f62acd58edc09f3f1b7f0a40ba5b099d | 3,634,498 |
import pdb
import math
def solve(system, total_integration_time, dt, save_frequency=100, debug=False):
"""Simulate the time evolution of all variables within the system.
Collect all information about the system, create differential
equations from this information and integrate them (numercially)
int... | 9ab30eab078832e856ecd6686476eb0966c3e706 | 3,634,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.