content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _GenerateJSONForTestResults(options, log_processor):
"""Generates or updates a JSON file from the gtest results XML and upload the
file to the archive server.
The archived JSON file will be placed at:
www-dir/DEST_DIR/buildname/testname/results.json
on the archive server. NOTE: This will be deprecated.... | c3883a92fd11686862d6dd576205e894872b85d1 | 3,634,364 |
def unrank(n, rk):
"""Return the permutation of rank rk in Sn."""
P = [0] * n
# Store (j+1)! for calculation.
fac = 1
for j in xrange(n-1):
fac *= (j+1)
d = (rk % (fac * (j+2))) / fac
rk -= d * fac
P[n-j-2] = d
for i in xrange(n-j-1,n):
if P[i] ... | e9da99b2341fc03ab67346f463b60d084b8802df | 3,634,365 |
def _compute_influence_kernel(iter, dqd, iter_scale,
radius,learning_rate):
"""Compute the neighborhood kernel for some iteration.
Parameters
----------
iter : int
The iteration for which to compute the kernel.
dqd : array (nrows x ncolumns)
This is one... | fc353b48b11dd85ccbdd280e43cd17da8f7a6f3d | 3,634,366 |
from typing import Union
from typing import Dict
def get_as_dict(x: Union[Dict, Sentence]) -> Dict:
"""Return an object as a dictionary of its attributes."""
if isinstance(x, dict):
return x
else:
try:
return x._asdict()
except AttributeError:
return x.__dic... | 9d85131564324c021a3ff7f2a068e5a0e80dc59e | 3,634,367 |
def get_user_sector_name(db_id):
"""
Get the user defined sector for the given database id string.
Raise an exception if not found.
"""
found, sector = user_sector_finder("id", int(db_id))
if found:
return make_sector_description(sector[0], True)
else:
raise NotFoundExcepti... | 2ee958e8d151f0ffc3e44d5ded405c660baed014 | 3,634,368 |
from pathlib import Path
def delete_author_by_id(
author_id: int = Path(...,
title="The Id of the author to be deleted", ge=0),
sql: Session = Depends(db_session),
current_user: UsersBase = Depends(get_current_active_user)
):
"""delete a specific author"""
... | 78e0c57dbcc7c76d60cfbbc28a7abfeca728d712 | 3,634,369 |
import random
def assign_judges_to_track(track, judges):
"""
Assign judges to projects in a single, specified track with all the projects they will be looking at
:param str track: name of the track we want judges for
:param list judges: a list of the judges allocated for this track
:return: a dictionary with th... | 981e52d3d8079835f39fe8f8510174bb351d3682 | 3,634,370 |
def get_current_user(current_user):
"""
User route to get current user
Parameters
----------
Registered/Admin access
Returns
-------
User Data
"""
sql_query = "SELECT * FROM diyup.users WHERE email_address=%s"
cur = mysql.connection.cursor()
cur.execute(sql_query, (cur... | 98c42555a5153ed06516e528b210a6163e2559e0 | 3,634,371 |
import json
def incident_exists(name, message, status):
"""
Check if an incident with these attributes already exists
"""
incidents = cachet.Incidents(endpoint=ENDPOINT)
all_incidents = json.loads(incidents.get())
for incident in all_incidents['data']:
if name == incident['name'] and \... | d087b9917a233625a731d6a41389ae9532a6f68d | 3,634,372 |
def compute_down(expr):
""" Compute the expression on the entire inputs
inputs match up to leaves of the expression
"""
return expr | 71677a16093d82a28c1d153c9385b33c01b4dd24 | 3,634,373 |
def NEV_to_HLA(survey, NEV, cov=True):
"""
Transform from NEV to HLA coordinate system.
Params:
survey: (n,3) array of floats
The [md, inc, azi] survey listing array.
NEV: (d,3) or (3,3,d) array of floats
The NEV coordinates or covariance matrices.
cov: boolean
... | 984e6f400d1415b0fde087ad913c4cff05ef6b0c | 3,634,374 |
def create_read_model_cmd() -> list:
"""Create TaiSEIA device model request protocol data."""
return SAInfoRequestPacket.create(
sa_info_type=SARegisterServiceIDEnum.READ_MODEL
).to_pdu() | 11efc850a056facd25279336eda7ce8868a248f4 | 3,634,375 |
def generate_mandatory_attributes(diagnostic_cubes, model_id_attr=None):
"""
Function to generate mandatory attributes for new diagnostics that are
generated using several different model diagnostics as input to the
calculation. If all input diagnostics have the same attribute use this,
otherwise s... | c8abbf1a9fd42dfafbd7e1bd957dee8f6bef1a00 | 3,634,376 |
def _convert_to_slices(indices, max_nslice_frac=0.1):
"""
Convert list of indices to a list of slices.
Parameters
----------
indices : list
A 1D list of integers for array indexing.
max_nslice_frac : float
A float from 0 -- 1. If the number of slices
needed to represent ... | acf0bb5800b7fe5c96836a973b090f748a02875a | 3,634,377 |
def log2(x, dtype=None):
"""
Base-2 logarithm of `x`.
Note:
Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
not supported.
Args:
x (Tensor): Input tensor.
dtype (:class:`mindspore.dtype`, optional): Default: :class:`None`. Over... | 8c99294cc5efb6c31447428cd930bb01641298a8 | 3,634,378 |
async def init_app():
"""
Инициализируем приложение
:return:
"""
app = web.Application()
try:
app.db = await asyncpg.pool.create_pool(get_config())
except asyncpg.exceptions.InvalidCatalogNameError:
raise Exception('DSN сконфигурирован неверно '
'и... | 73caac054abe8b356e8e167d3cc815c6254e8dd3 | 3,634,379 |
def pad_array(
x: np.ndarray, to_multiple: int = None, to_size: int = None, axis: int = 0
):
"""Pads an array either to a multiple of `to_multiple` or to the
exact length `to_size` along `axis`.
Parameters
----------
x: np.ndarray
The array to pad.
to_multiple: int, optional
... | 9a8116fac37b794fe7f2e6e216c722e1f8261068 | 3,634,380 |
from typing import Sequence
def ihfft2(x, s=None, axes=(-2, -1), norm="backward", name=None):
"""
Compute the two dimensional inverse FFT of a real spectrum.
This is really `ihfftn` with different defaults.
For more details see `ihfftn`.
Args:
x(Tensor): Input tensor
s(Sequence[i... | 2814a48a449affdc8c057dda6d75cd17e09acdc0 | 3,634,382 |
def pp_ajaximg(context, nodelist, *args, **kwargs):
"""
Modifies the request session data to prep it for AJAX requests to the Ajax image uploader.
"""
context.push()
namespace = get_namespace(context)
request = kwargs.get('request', None)
obj = kwargs.get('object', None)
if obj is not N... | ffc9f3fd2d945614582885bb19ba60575bd4a03d | 3,634,383 |
def bgr2rgb(x, dim=-3):
"""Reverses the channel dimension. See :func:`channel_flip`"""
return channel_flip(x, dim) | dc943e7e814f7d2b0cd4f83ec4cb9bf10aad6924 | 3,634,384 |
def get_all_predictions():
"""
Function for getting the predictions of models on the mnist test dataset.
:return: a dictionary with predictions of all models.
"""
all_results = {}
model_paths = ["ffnn_models", "dropout_models"]
sizes = [1000, 2500, 7000, 19000, 50000]
pred, correct = Non... | 246606cac76b58e98e5a7130a4a0631ddcb69508 | 3,634,385 |
def moving_avg(timeseries, days=7, dropna=False, win_type=None, params=None):
"""Takes a centred moving average of a time series over a window with user-defined width and shape. Note: when taking a N-day centred moving average, the first and last N//2 days won't return a value and are effectively lost, BUT they are... | d7d6cd61d61d341beb3c37f7abe307c65ebe72a2 | 3,634,386 |
def get_defined_lvls(inp_str):
""" gets a list which specifies what levels have been defined
"""
levels_def_pattern = ('level' + one_or_more(SPACE) + capturing(one_or_more(NONSPACE)))
defined_levels = all_captures(levels_def_pattern, inp_str)
return defined_levels | 624766b6e3b5f17a721e9deacf316bc6793a64f7 | 3,634,387 |
from typing import Tuple
def requests_per_process(process_count: int, conf) -> Tuple[int, int]:
"""Divides how many requests each forked process will make."""
return (
int(conf.concurrency / process_count),
int(conf.requests / process_count),
) | 00af7a63471201c3fffcfb610f74a745ca326b68 | 3,634,388 |
def load_into_bamfile(meshdata, subfiles, model):
"""Uses pycollada and panda3d to load meshdata and subfiles and
write out to a bam file on disk"""
if os.path.isfile(model.bam_file):
print 'returning cached bam file'
return model.bam_file
mesh = load_mesh(meshdata, subfiles)
model... | 0ba3e498f400bdf8ebfbcbf6075a749634c13ff3 | 3,634,389 |
def gettree(number, count=3):
"""
Сформировать дерево каталогов
"""
result = []
newline = str(number)
while len(newline) % count:
newline = '0' + newline
for i in range(0, len(newline)//count):
result.append(newline[i*count:i*count+count])
return result | 55fcec36ef3a50a949ed4f2d12103374fcfd13b0 | 3,634,390 |
def to_unserialized_json(obj):
"""
Convert a wire encodeable object into structured Python objects that
are JSON serializable.
:param obj: An object that can be passed to ``wire_encode``.
:return: Python object that can be JSON serialized.
"""
return _cached_dfs_serialize(obj) | 9d173afca84f5af3617420be1ba04e5ecb3e4242 | 3,634,391 |
def get_negatives(all_contexts, vocab, counter, K):
"""返回负采样中的噪声词."""
# 索引为1、2、...(索引0是词表中排除的未知标记)
sampling_weights = [
counter[vocab.to_tokens(i)]**0.75 for i in range(1, len(vocab))
]
all_negatives, generator = [], RandomGenerator(sampling_weights)
for contexts in all_contexts:
... | 471dcd8afac5cc02507a32bd150229e6b34bcf8a | 3,634,393 |
def edmonds(V, E, root):
"""Recursive application of Edmonds' algorithm according
to Wikipedia's description [0].
[0] https://en.wikipedia.org/wiki/Edmonds'_algorithm#Description
:param V: set of vertices
:type V: [int, ...]
:param E: a set of edges
:type E: [(int... | 3a4ec311e3e167dc3634a3d87dca0628d7c78938 | 3,634,395 |
import pymultinest
def run_multinest(loglikelihood, prior, dumper, nDims, nlive, root, ndump,
eff, seed=-1):
"""Run MultiNest.
See https://arxiv.org/abs/0809.3437 for more detail
Parameters
----------
loglikelihood: :obj:`callable`
probability function taking a single p... | f388c52ebe8d3a27914d7b7966167e608db274dd | 3,634,396 |
def tema(close, timeperiod=30):
"""Triple Exponential Moving Average 三重指数移动平均线
The triple exponential moving average was designed to smooth
price fluctuations, thereby making it easier to identify trends
without the lag associated with traditional moving averages (MA).
It does this by taking multip... | 74f8b5b465caa3de4417db2afa36375125761153 | 3,634,397 |
import re
def load_single_model(save_path_stem, load_results_df=True):
"""load in the model, loss df, and model df found at the save_path_stem
we also send the model to the appropriate device
"""
try:
if load_results_df:
results_df = pd.read_csv(save_path_stem + '_results_df.csv')... | c42b55e98cf663ea5db778b289a66229f9fc244b | 3,634,398 |
def gray2jet(img):
"""[0,1] grayscale to [0.255] RGB"""
jet = plt.get_cmap("jet")
return np.uint8(255.0 * jet(img)[:, :, 0:3]) | 7ea522cc5361e24d67bcde6760a178ff83a6deb4 | 3,634,399 |
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 |
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 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 |
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 _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 |
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 |
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 |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.