content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def load_shapefile():
"""
load Local Authorities Upper Tier shape file data.
Do some merging and postprocessing to match COVID19 data as best as possible.
Example usage of data:
shp.lad19nm[shp.lad19nm == 'Wirral']
"""
# Load shape file data
shapefile = 'DATA/shapefile3/Counties_and_Unit... | 969b80649840219bee2408513ac5f6ee845670d3 | 3,601,961 |
def _fn(request: Request) -> bool:
"""For testing purposes."""
return True | e2838f7ba88f7556a3ca786801d10ddab2d52b79 | 3,601,962 |
def _query_parser():
"""
Construct a parser for the subset of SQL that is applicable to the export API
"""
whitespace = parsy.regex(r"\s*")
lower = lambda x: x.lower()
string = lambda x: parsy.string(x, lower)
def lexeme(value):
"""A string or parser surrounded by whitespace"""
... | fc04ed9eb9bb5dc0ae55d2d5504ce83f52f74956 | 3,601,963 |
def get_flat_params(parameter_groups):
"""
:param parameter_groups:
:return: List of parameters pulled out of parameter groups
"""
parameter_list = []
for parameter_group in parameter_groups:
parameter_list += parameter_group['params']
return parameter_list | ef11030018341635594d07f56a23dd9aa3c1244e | 3,601,964 |
def game_over(state):
"""
Return whether the game is over and if it is, indicate the winner, and other
information if needed
:param state: the state to evaluate
:return: a tuple of [game_is_over, winner, metadata]
"""
for victory_condition in victory:
if __is_victory(state.player1_st... | a2845e72476275b7c0680eae647d17bfd0fab852 | 3,601,965 |
def l_roots(n, mu=False):
"""Gauss-Laguerre quadrature
Computes the sample points and weights for Gauss-Laguerre quadrature.
The sample points are the roots of the `n`th degree Laguerre polynomial,
:math:`L_n(x)`. These sample points and weights correctly integrate
polynomials of degree :math:`2*n... | f71efc3a4a62b412b2b04470f777260cfbbabc20 | 3,601,966 |
def format_job_status(job):
"""
Convert job status dictionary into the format that cliff need for display.
:param job: type dic
:return: formatted result used for display
"""
start = job['begin_time']
end = job['end_time']
success, start = utc_to_local_time(start)
success, end = utc_... | d99aacb62de00887dafc00e8f7ea772d3b01a799 | 3,601,967 |
def read_name_hash(read_name):
"""Takes a read name from an input bam and shortens & obfuscates it"""
return str(abs(hash(read_name)) % 10**9) | bc1e048925f0a0e710481656f0b90e4c290c2341 | 3,601,968 |
def _get_updated_parsed(job_item):
"""
:param job_item:
:return:
"""
return job_item.published.timetuple() | a1377d3adcbae990727abed8ecdabfb9fb2d610b | 3,601,970 |
def top_split(dog, race):
""" Retorna o melhor split do galgo """
history = History.objects.filter(dog=dog, race__track__track_id=race.track.track_id, distance=race.distance,
grade__in=filter_grade(race.grade), split__gt=0).values_list('split', flat=True)
if history:
... | 1c3a91011251bf0cee066169067848376439b2e9 | 3,601,971 |
def prompt_bet(min_bet, max_bet):
""" Prompt for an integer bet amount until one within bounds is given. """
print()
print('How much do you want to bet?')
user_bet = prompt_number(
min_bet, max_bet, 'Please input a bet within range 5-500.'
)
return user_bet | 891805678c1da475d878c0cf60add0e64f0184c4 | 3,601,972 |
def parse_performance_criterion(config, shared, logger):
"""Parse the CLI argument that determines the performance criterion to be
met for a run to continue.
Function parses argument ``--during_acc_criterion``.
Args:
config (argparse.Namespace): Command-line arguments.
shared (argparse... | c19a70f85fee4c3d50d92b20a84000227fbbad08 | 3,601,974 |
def pressure_from_altitude(y):
"""
Calculate standard atmospheric pressure based on an altitude in m. The
basic formula can be found many places. For instance, Munson, Young, and
Okiishi, 'Fundamentals of Fluid Mechanics', p. 51.
Enter: y: altitude in m.
Exit: p: pressure in N/m/m.
"""
... | b8f7d42b28d3448ac1a0f62079a0ae4ed672f9e9 | 3,601,975 |
import torch
def classification_error(
probabilities, targets, length=None, allowed_len_diff=3, reduction="mean"
):
"""Computes the classification error at frame or batch level.
Arguments
---------
probabilities : torch.Tensor
The posterior probabilities of shape
[batch, prob] or ... | af02f61b253466ab256a5eb76967c9916a6bfc9d | 3,601,976 |
def tf_ensure_flat(x, ndims=2):
"""
Makes sure a tensor is flattened ONLY IF NEEDED, i.e. it has more dimensions than required ones.
:param x: A tensor to be flattenned
:param ndims: The number of dimensions to be left in the output tensor.
:return: The flatened tensor, or the original, if it is fin... | 18d8a37b070cdfb26d650c0498325a887c185163 | 3,601,979 |
def validate_crc16(data):
"""
Validate that the CRC of the contents of buffer is the residual OK value.
The input is a bytestring.
"""
return crc16(data) == _CRC_OK_RESIDUAL | 004247797a3337a3426dec2c3b6b48cda90404e0 | 3,601,980 |
from datetime import datetime
def get_ahead_one_hour(datetime_str):
"""
获得提前一小时的时间字符串和时间戳
:return:
"""
datetime_obj = datetime.datetime.strptime(datetime_str, '%Y-%m-%d %H:%M:%S')
datetime_obj_one_hour_ahead = datetime_obj + datetime.timedelta(hours=-1)
return datetime_obj_one_hour_ahead.s... | 12f334da38d36df927a3f26a08ca20a5183cb615 | 3,601,981 |
def fitting_tsne(X, n_comp, perp, metric='euclidean'):
"""Fit t-SNE"""
tsne = TSNE(n_components=n_comp, perplexity=perp, metric=metric)
X_tsne = tsne.fit_transform(X)
return X_tsne | 8ac465db99c48972d408ddfa32148a96258741cc | 3,601,982 |
def is_box_outside_rect(poly, rect):
"""
poly 是否在rect外, true 为outside
"""
poly = np.array(poly)
xl, yt, xr, yd = rect
if len(poly.shape) == 2:
if poly[:, 0].max() <= xl or poly[:, 0].min() >= xr:
return True
if poly[:, 1].max() <= yt or poly[:, 1].min() >= yd:
... | 11549b9cdf70871ded24cbf67b69de8edd3e57ae | 3,601,984 |
import urllib
def collect_request_attributes(scope):
"""Collects HTTP request attributes from the ASGI scope and returns a
dictionary to be used as span creation attributes."""
server_host, port, http_url = get_host_port_url_tuple(scope)
query_string = scope.get("query_string")
if query_string and... | 546c079779bfb5895e28f21f575ad91017289e85 | 3,601,985 |
def spatial_atleast3d(string_input):
"""
This function parses a 3-element tuple from a string input.
The input will be padded with ones, if the length is less than 3.
"""
output_tuple = int_array(string_input)
if len(output_tuple) < 3:
# will pad the array with single dimensions
... | 0d276d4c7eff5c642319f73eb889842fda3eb4d3 | 3,601,986 |
def email_validation_reset(request):
"""
Resend the validation email
"""
if request.user.is_authenticated():
try:
resend = EmailValidation.objects.get(user=request.user).resend()
response = "done"
except EmailValidation.DoesNotExist:
response = "faile... | a3734fe7a1a7a3a1c029064c2ac6f839742f1a3c | 3,601,987 |
from typing import List
from typing import Dict
from typing import Any
def generate_tmap_config(
filename: str, layer_data: List[FullLayerData], internal_shapes: bool = False
) -> Dict[str, Any]:
"""Generates a dict containing the tissumaps cfg of the napari layers to be saved.
Parameters
----------
... | 3681ccd954c2a6870224233ecca47dbd9bd63778 | 3,601,989 |
def spacetime_integrated_kernel_3(a: float, b: float, c: float, d: float,
h: float, k: float) -> float:
""" Returns kernel integrated in time over [a,b] x [c, d], and in space
over [0,h] x [0,k]
"""
assert a < b and c < d and h > 0
f_bd = fint_3(b, d, h, k)
f_bc... | fc234f6c12a1b6133b17c38057fe334e360621ab | 3,601,990 |
import array
def hybrid(x, llim=None, ulim=None, period=None, return_all=False):
"""
Return hybrid statistic and corresponding periods for signal x
Arguments:
- return_all: whether to return the hybrid, ipdft, autocorr
statistics as a numpy array, or just the hybrid statistic
... | 04b6f83d74579af379a68c8af6e0affe236049c6 | 3,601,991 |
def read_pedigree(pedigree_file=None, keepInverse=True):
"""
Reading the pedigree file and dumping it in a ordered dictionary.
Generates a dictionary with individual: [parent1, parent2]
"""
if not pedigree_file:
pedigree_file = PEDIGREE_FILE
pedigree = None
with open(pedigree_file, '... | 458dd8afc6924920890f15292e91d4ded4011dbc | 3,601,992 |
import pandas as pd
def _lsa_events_converter(events_file):
"""Make a model where each trial has its own regressor using least squares
all (LSA)
Parameters
----------
events_file : str
File that contains all events from the bold run
Yields
------
events : DataFrame
A ... | 4cc216bdf01f67dbefbd31005f0398cd217aa8a5 | 3,601,993 |
import torch
from typing import OrderedDict
def load_model(filepath = '../data/checkpoint.pth'):
"""
Function loads the model from checkpoint.
INPUT:
filepath - path for the saved model
OUTPUT:
model - loaded pytorch model
"""
print("Loading model from {} \n".format(filepath... | 6bce5b826d4802a1ea0592a5a4446b9e0fb6ad6c | 3,601,994 |
from typing import Union
from typing import List
def model_outputs(model: Union[str, ModelProto]) -> List:
"""
Get the output from an ONNX model
:param model: the loaded model or a file path to the ONNX model
to get the model outputs for
:return: the output from the model
"""
model = ... | b3fc7928ad8f0f5f121f8411ccb077bcbecb35bc | 3,601,995 |
def get_acc(preds, labels, threshold=0.5):
"""Gets the accuracy score of the predictions
Parameters
----------
preds : array_like
Class predictions for each sample
labels : array_like
Binary class labels of each sample
threshold : float
The decision threshold
Return... | 635d4dd4aa3a51825013b3adb8ecf15647fc8503 | 3,601,996 |
def is_untranslated_paragraph(service_name: str, line: str, source_lang: object) -> bool:
"""
Call the language detect function of each translate API
:rtype: bool
"""
if service_name == const.TRANSLATION_SERVICE_GOOGLE_V2:
return is_detected(line, source_lang)
else:
end_words = i... | c8cd20fbf22d1d20bd78a1616ad6a904b6c495ec | 3,601,997 |
from typing import Union
from datetime import datetime
from typing import Optional
from typing import Callable
from typing import Dict
from typing import Any
def daily_partitioned_config(
start_date: Union[datetime, str],
timezone: Optional[str] = None,
fmt: Optional[str] = None,
) -> Callable[[Callable[[... | 68730dd7f9243e1aff88d8f37b3e4b8a75dd3de7 | 3,601,999 |
def get_pixel_dist(pixel, red, green, blue):
"""
Returns the color distance between pixel and mean RGB value
Input:
pixel (Pixel): pixel with RGB values to be compared
red (int): average red value across all images
green (int): average green value across all images
blue (int... | f86466a13cd028380d3c8bf8aee4b877a1284c59 | 3,602,000 |
async def filter_repositories(
client, headers, account_id, date_from, date_to, exclude_inactive, repos, timezone,
):
"""Filter repositories according to the provided filter paramaters."""
url = "https://api.athenian.co/v1/filter/repositories"
params = {
"account": int(account_id),
"date... | 1d53a6ab36007b90adf3f1bf583b422994cfaf6f | 3,602,001 |
def latest_posts(count=10):
"""
A way to get latest posts from inside a template
"""
return Post.objects.all()[:count] | f0eef0b303b665de4297dc5c6583e56b68798017 | 3,602,003 |
def DispersionBulge(**kwargs):
"""
Create a model of a dispersion-dominated bulge.
This will create a dispersion-dominated bulge model from the stored
parameters specified in kwargs. The bulge model is described in detail
in the online documentation and uses and limitations to this model are
di... | 72cb6899a664904ecd90ec9b3d88864e3b6c1baa | 3,602,004 |
def powerlaw_cl(p, x):
"""
p are parameters of the model
"""
norm_corr = x * (x + 1.) /2./np.pi *1.e12
res = np.zeros(len(x))
res[x!=0.] = powerlaw_dl(p, x[x!=0.]) / norm_corr[x!=0.]
return res | c3a87774f9c23228b4fbfd9ad479639090058b63 | 3,602,005 |
def get_dataset_location(bq):
"""Parse payload for dataset location"""
# Default BQ location to EU, as that's where we prefer our datasets
location = "EU"
# ... but the payload knows best
if "location" in bq:
location = bq["location"]
return location | 071a5258a72b3a3a248c6e44b99b7ccc2890d3f5 | 3,602,006 |
def show_window(window, **kwargs):
"""Create a Qt window in Python, or interactively in IPython with Qt GUI
event loop integration:
# in ~/.ipython/ipython_config.py
c.TerminalIPythonApp.gui = 'qt'
c.TerminalIPythonApp.pylab = 'qt'
See also:
http://ipython.org/ipyth... | 49407e3b1e0f3aa1911f9c2f5bf9ebfc82cf912e | 3,602,007 |
import google
def create_google_blueprint():
"""
Google use default config variables
GOOGLE_OAUTH_CLIENT_ID and GOOGLE_OAUTH_CLIENT_SECRET
https://developers.google.com/identity/protocols/oauth2/scopes#google-sign-in
https://flask-dance.readthedocs.io/en/latest/providers.html#module-flask_dance.co... | 440da490014f3955f68e10b67e19cb8a1d669190 | 3,602,008 |
def state(c:Config)->State:
""" State constructor """
return (c,Program()) | b6482deb2d1a1d2955b00ba9900fa9ea9292c1b9 | 3,602,009 |
def analyze(x: np.ndarray, param: np.ndarray = [1, 1], m: int = 8):
"""预测第1到第m-1经络的结果,也就是C1-Cm-1,暂时先无视C0
流程:filter滤波原始数据 -> findTroughs找谷底索引 -> compute根据谷底索引对每单个周期计算平均幅值等统计量
-> selectRatio根据测试者参数选择标准幅值比例 -> match根据标准幅值比例进行拟合
-> 对比拟合后的数据幅值比例和标准幅值比例
参数:
x:数据
... | e495d6e1699ae5543b227c94780e99bbf1dde7b3 | 3,602,010 |
def get_fws_and_tasks(workflow, fw_name_constraint=None, task_name_constraint=None):
"""
Helper method: given a workflow, returns back the fw_ids and task_ids that match name
constraints. Used in developing multiple powerups.
Args:
workflow (Workflow): Workflow
fw_name_constraint (str):... | 28f4f2cdcc58b942ee3e0631c21bf2a3a052db35 | 3,602,011 |
def undistort_image(config, image, cam_name):
"""copied from https://www.a2d2.audi/a2d2/en/tutorial.html"""
if cam_name in ['front_left', 'front_center',
'front_right', 'side_left',
'side_right', 'rear_center']:
# get parameters from config file
intr_mat_u... | 04f181164415f76251dbc640cba68e2707315e13 | 3,602,012 |
def get_fields_limit(request):
"""
returns possible all fields.
'limit=5000' will limit the number of
field for enumerations to the 5000 first.
"""
try:
limit = int(request.matchdict['limit'])
except Exception as e:
us.JSONResponse(errors = ["limit must be a valid integer"])
... | abfcf6d7c17a4f2c9b19e5929fb9d43e5edda7c6 | 3,602,013 |
def _get_tags(ws_info):
"""Get the tags relevant to search from the ws_info metadata"""
metadata = ws_info[-1]
if metadata.get('searchtags'):
if isinstance(metadata['searchtags'], list):
return metadata['searchtags']
else:
return [metadata['searchtags']]
else:
... | f6922f92913446284545aa73cb2b8cd7139749e8 | 3,602,014 |
def benchmark_prices(all_prices, benchmark_path='../docs/benchmarks.csv'):
"""
Function to create a column with benchmark close price
"""
# Create list of benchmark symbols
benchmarks = pd.read_csv('../docs/benchmarks.csv')
benchmarks = benchmarks[['symbol', 'description']]
benchmarks_list =... | a38e7c7e13dfcc3dada9568118bc099ab5d18854 | 3,602,017 |
def parse_hexblob(blob: str) -> bytes:
"""
Binary conversions from hexstring are handled by bytes(hstr2bin()).
:param blob:
:return:
"""
return bytes(hstr2bin(blob)) | 9113ff240bb2f896f18448c11fc04ee8dd226a73 | 3,602,018 |
def regex_select(env=None, app=None, request=None):
"""
Selects a set of regex rewrite params for the current request
"""
if app:
THREAD_LOCAL.routes = params_apps.get(app, params)
elif env and params.routes_app:
if routers:
map_url_in(request, env, app=True)
else... | 095f4f0755ae78161262254ea2444f2cddd91832 | 3,602,019 |
def load_pandas():
"""
Load the strikes data and return a Dataset class instance.
Returns
-------
Dataset
See DATASET_PROPOSAL.txt for more information.
"""
data = _get_data()
return du.process_pandas(data, endog_idx=0) | d42b28d9eaf50a0ddc093635fc979876d91a635f | 3,602,021 |
def mockingjay_100hr(refresh=False, *args, **kwargs):
"""
The mockingjay base model on 100hr
refresh (bool): whether to download ckpt/config again if existed
"""
return mockingjay_logMelBase_T_AdamW_b32_200k_100hr(refresh=refresh, *args, **kwargs) | 0f912523a5b794d1ffe75d59c8d32a442d8c6a7e | 3,602,022 |
import logging
def show_metadata_probe(pad, info, user_data):
"""Buffer probe to show metadata in a buffer"""
gst_buffer = info.get_buffer()
if gst_buffer:
logging.info("show_metadata_probe: %20s:%-8s: pts=%23s, dts=%23s, duration=%23s, size=%8d" % (
pad.get_parent_element().name,
... | d64b1dc89f0a9a50a7d576100ca4a2b060ce7e04 | 3,602,023 |
def read_structure_annotation(fn_ann, fn_ann_color='', Fs=1, remove_digits=False, index=False):
"""Read and convert structure annotation and colors
Notebook: C4/C4S1_MusicStructureGeneral.ipynb
Args:
fn_ann: path and filename for structure annotions
fn_ann_color: filename used to identify ... | 100c41e33d497cf028492c2d69ddf5b701deff07 | 3,602,024 |
import json
def getCoordinates():
"""Get geometry data from JavaScript and proccess it
"""
# get the data send by JavaScript
jsdata = request.form['boundingbox']
# check if retrieved data is from viweport button or from draw button
if "type" in json.loads(jsdata).keys():
jsonData = js... | e5d027bac8824ff81acd3ddce7fa49af77a8d42a | 3,602,025 |
def _str_bool(v):
"""convert a string rep of yes or true to a boolean True, all else to False"""
if (type(v) is str and v.lower() in ['yes', 'true']) or \
(type(v) is bool and bool(v)):
return True
return False | ba4663c402b94b00edb4b1a97a4ba4ed755caf85 | 3,602,027 |
import json
import base64
def json_safe(string, content_type='application/octet-stream'):
"""Returns JSON-safe version of `string`.
If `string` is a Unicode string or a valid UTF-8, it is returned unmodified,
as it can safely be encoded to JSON string.
If `string` contains raw/binary data, it is Bas... | c47c3faf0aeb95902f4a72732c8fb861950c2af0 | 3,602,029 |
def show_main(path=MAIN_CF):
"""
Return a dict of active config values. This does not include comments,
spacing or order. Bear in mind that order is functionally important in the
main.cf file, since keys can be referred to as variables. This means that
the data returned from this function should not... | a70b7800fd406a98acf93294ea902cb583cf6cec | 3,602,030 |
def get_fixed_params():
""" Parameters that currently cannot be searched during HPO """
fixed_params = {'batch_size': 512, # The size of example chunks to predict on.
'n_cont_embeddings': 0, # How many continuous feature embeddings to use.
'norm_class_name': 'LayerNorm', ... | 186e786f96f2a81c88423fdcd27bf28aef97b511 | 3,602,031 |
def _checkpoint_is_greater(a, b):
# type: (Checkpoint, Checkpoint) -> bool
"""Ensure elements of checkpoint 'a' are all greater than or equal to those in
checkpoint 'b'."""
return a.checkpoint >= b.checkpoint and a.checkpoint_time >= b.checkpoint_time | dca9c83e1cf8d2e22e6d763fd02b526bcbaed414 | 3,602,032 |
def to_env_dict(config):
"""Convert configuration object to a flat dictionary."""
entries = {}
if config.has_value():
return {config.__to_env_var__(): config.node['value']}
if config.has_default():
return {config.__to_env_var__(): config.node['default']}
for k in config.node:
... | 4c46f365e7b53d79d25dea7d062f9d985d30877d | 3,602,033 |
def ensure_pil(im):
"""Lazily force image type to PIL.Image
"""
return np2pil(im) if is_np(im) else im | 0e1a58e6e320819044444af71d355dfda639a670 | 3,602,034 |
import base64
import json
def encode_base64_json(data):
"""
Encode dict-like data into a base64 encoded JSON string.
This can be used to get dict-like data into HTTP headers / envvar.
"""
return base64.b64encode(bytes(json.dumps(data), 'utf-8')) | 08b9d8568a59717173adf00658aad03bddb8df14 | 3,602,036 |
def conjugate_row(row, K):
"""
Returns the conjugate of a row element-wise
Examples
========
>>> from sympy.matrices.densetools import conjugate_row
>>> from sympy import ZZ
>>> a = [ZZ(3), ZZ(2), ZZ(6)]
>>> conjugate_row(a, ZZ)
[3, 2, 6]
"""
result = []
for r in row:
... | c4c5ccb03513c32e3bc9866ef6c3a370e70d01d6 | 3,602,037 |
def load_small_dataset(dataset_dir='./dataset/', batch_size=2, split=('train', 'validation')):
"""加载coco2017子数据集.
Args:
dataset_dir: str, default='./dataset/',
请提前下载coco2017子数据集, 并建立对应路径保存.
[coco2017子数据集](https://github.com/srihari-humbarwadi/datasets/releases/download/v0.1.0/da... | a1e6298fec9154efff70b1b5f116cb7e5f254d38 | 3,602,038 |
import re
def linux_ver_normalize(vstr):
"""Normalize a Linux compiler version number.
Intel changed from "80" to "9.0" in 2005, so we assume if the number
is greater than 60 it's an old-style number and otherwise new-style.
Always returns an old-style float like 80 or 90 for compatibility with Window... | fe59ec6bf45a3a93213aa4a9317f0b1e4a12494c | 3,602,041 |
import numpy
def gain_cal_bs_lin(vis_pol_src):
"""
Apply stefcal to XX and YY visibilities
Parameters
----------
vis_pol_obs : (2, 2, N, N) array
Observsered (measured) polarized visibilities
Returns
-------
g_bs_lin : (2, N) array
Gain solutions for X and Y chann... | 229a79c27e63917c6ece5240cc243f776eed7db1 | 3,602,043 |
def _get_fischer_burmeister_scalar(a, b):
"""Get the value of the Fischer-Burmeister function for two scalar inputs.
This method was suggested by Bob Vanderbei. Since the Fischer-Burmeister
is symmetric, the order of the scalar inputs does not matter.
Args:
a (float): First input.
b (f... | 4f43169b73c9160ada64ff216fa0a25fdda75cca | 3,602,044 |
def test_phone_login_or_register():
"""
用户验证码登录或注册
:return:
"""
res = ResMsg()
obj = request.get_json(force=True)
phone = obj.get('account', None)
code = obj.get('code', None)
if phone is None or code is None:
res.update(code=ResponseCode.InvalidParameter)
return res... | 492ce0e90fe0dbd0b3bcba6616a55eef78909953 | 3,602,046 |
import torch
def random_mask_tokens(args, inputs, tokenizer):
""" Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original. """
if len(inputs.shape) == 1:
inputs = inputs.unsqueeze(0)
labels = inputs.clone()
input_mask = (~inputs.eq(0)).to(torch.fl... | 5522b3aeedad605eb2645a3c8938315ff59b0b7c | 3,602,047 |
def manage_alerts():
"""Manage alerts page."""
alerts = Alert.query.filter(Alert.user_id == current_user.id).all()
form = ManageAlertForm(request.form, alerts)
if request.method == 'POST':
if request.form['submit'] == 'Delete' and form.alert_id.validate(form):
current_alert = None
... | 627617cee3e52f1e801fa81e4b24372426682b2b | 3,602,048 |
def stagnant_operator(
tj=None,
tpulse=10,
tspan=None,
j_el=-1,
L=100e-6,
A=0.196e-4,
q0=1.5e15 / Chem.NA,
p_m=1e5,
mol="H2",
p_gas=0,
normalize=False,
D=None,
kH=None,
n_el=None,
Temp=None,
unit="pmol/s",
flux_direction="out",
verbose=True,
ax... | c28b546288fb52309249e4ea113b3594801f5811 | 3,602,049 |
def default_sv1_sciencemask():
"""Returns default mask of bits for science targets in SV1 survey.
"""
sciencemask = 0
sciencemask |= sv1_mask["LRG"].mask
sciencemask |= sv1_mask["ELG"].mask
sciencemask |= sv1_mask["QSO"].mask
sciencemask |= sv1_mask["BGS_ANY"].mask
sciencemask |= sv1_mas... | 36ae9641b4df0d9877c6ae5310ebe610d352c727 | 3,602,050 |
def EventStart(builder):
"""This method is deprecated. Please switch to Start."""
return Start(builder) | 7a56b1dddd41223435bb51bea1b6fef5e6d027de | 3,602,051 |
import requests
def post(*args, **kwargs):
"""A wrapper for requests.POST method"""
response = requests.post(*args, **kwargs)
if response.status_code == 200:
return response
raise APIError(API_ERROR_MESSAGE.format('POST', response.status_code)) | a07c3999bc2940103a4f3233b074ee4d019faade | 3,602,052 |
def ispyschema(schema):
""" Is object PySchema instance?
Returns true for PySchema Record *classes*
i.e. NOT when schema is a *Record* instance
>>> class FooRecord(Record):
... pass
>>> ispyschema(FooRecord)
True
>>> ispyschema(FooRecord())
False
"""
return isinstance(s... | 1c482e50b6cd531da42e1eee94b7364cda3a7b9e | 3,602,053 |
def video_to_laplace_pyramid_seq(vid, max_layer):
""" Creates a list containing Laplacian pyramids of all video frames. """
pyramid_seq = list()
for frame in vid:
pyramid = build_gauss_pyramid(frame, max_layer=max_layer)
pyramid = build_laplace_pyramid(pyramid)
pyramid_seq.append(py... | bb5d036375814930990e4c0702d790e900708efc | 3,602,054 |
def expand_stereo(ich):
""" Obtain all possible stereoisomers compatible with an InChI string.
:param ich: InChI string
:type ich: str
:rtype: list[str]
"""
gra = graph(ich)
sgrs = automol.graph.stereomers(gra)
ste_ichs = [automol.graph.stereo_inchi(sgr) for sgr in sgrs]
... | 9954e86c44e10eb1b32610942b32cfb67710e4c1 | 3,602,055 |
import math
def edgeweight_properties(graph, weight_label="weight"):
"""
Calculates properties of edge weights.
Parameters
----------
graph: nx.Graph
Graph to calculate the properties from
weight_label:
Returns
-------
max_weight: number
Maximum weights of an edg... | a22857d844c2235859c004bfac897b3b5c80feee | 3,602,056 |
def timedelta_to_seconds(td):
"""
Converts a timedelta to total seconds.
(This is built-in in Python 2.7)
"""
# we ignore microseconds for this
if not td:
return None
return td.seconds + td.days * 24 * 3600 | ef4ebd88581d8a2a1f64b9f940afbe22da8f55bc | 3,602,058 |
def get_matching(files: dict,
var_order: str,
out_var: dict = None,
**kwargs):
""" Get filenames that have defined variable values
This gets all filenames that match a set of variable values. Variables must
be one of :attr:`VARIABLES`, and the inputs must ... | b3f5532d2bafdd06771ae26c6b640a5699143bc0 | 3,602,059 |
import torch
def _safe_mean(losses, num_present):
"""Computes a safe mean of the losses.
Args:
losses: `Tensor` whose elements contain individual loss measurements.
num_present: The number of measurable elements in `losses`.
Returns:
A scalar representing the mean of `losses`. If `num_present`... | 4174dead8e2fc582633589713e076871a0631de1 | 3,602,060 |
import json
def get_property_value(dcid, prop):
"""Returns the property values for a given node dcid and property label."""
response = dc.fetch_data('/node/property-values', {
'dcids': [dcid],
'property': prop,
},
compress=False,
po... | 9901f5217b9eac8bb042c02136c9f7aa57954e3d | 3,602,061 |
import json
def trip_to_geojson(feed, trip_id, *, include_stops=False):
"""
Return a GeoJSON representation of the given trip, optionally with
its stops.
Parameters
----------
feed : Feed
trip_id : string
ID of trip in ``feed.trips``
include_stops : boolean
Returns
--... | 899981c4945229e5938eae86b88eb91b3ea9b070 | 3,602,062 |
def balance_loss(x, y, y_pred, criterion):
"""
Args:
x: model input
y: labels
y_pred: predictions
criterion: loss function
Returns: balanced loss, torch.tensor
"""
_, _, _, _, _, speaker_ids, emotion_ids = x
batch_size = speaker_ids.shape[0]
loss_balanced = ... | 28ad887934ff60283bde3200b4017374ac6b2bfa | 3,602,063 |
import torch
def custom_op(inputs, name, domain, domain_version, example_outputs):
"""Applies a custom operation, implemented within PopART, to the inputs.
:param tuple inputs: A tuple of input tensors, for example, (x, y).
:param str name: unique name of the PopART custom
:param str domain: domain f... | 02eef53237890a6d6c76b10957b88845fe8f4ce0 | 3,602,064 |
def OutputTypeHandler(cursor, name, defaultType, size, precision, scale):
"""
Unicode output handler for oracle connections
Source: http://www.oracle.com/technetwork/articles/dsl/tuininga-cx-oracle-084866.html
"""
if defaultType in (cx_Oracle.STRING, cx_Oracle.FIXED_CHAR):
return cursor.var(... | 8d8788d141d974da8a19cffa7ed08e0eb3376f0e | 3,602,065 |
def _feet_to_alt_units(alt_units: str) -> float:
"""helper method"""
if alt_units == 'm':
factor = 0.3048
elif alt_units == 'ft':
factor = 1.
else:
raise RuntimeError(f'alt_units={alt_units} is not valid; use [ft, m]')
return factor | 95d5208741fdff275211b9c33a901dedaa65186e | 3,602,066 |
def encrypt_aes_cbc(text, key, iv):
"""
encrypt_aes_cbc
"""
aes = AES.new(key.encode("utf-8"), AES.MODE_CBC, iv.encode("utf-8"))
encrypt_text = aes.encrypt(pad(text.encode("utf-8"), AES.block_size, style="pkcs7"))
return encrypt_text.hex() | b5d85930afd0c92c5b7a3f5e07bfb866a92e4bfd | 3,602,067 |
def condition_adjoint( physical_adjoint ):
"""
application: apply pre-conditioning to PhysicalAdjointData, get vector gradient
input: PhysicalAdjointData
output: UnknownData
notes: this function must apply the prior error covariance
"""
return phys_to_unk( physical_adjoint, True ) | 616fdce0399b83bb484d52d9e0213d707a2ca368 | 3,602,069 |
import re
def ParseTraceDump(msg):
"""Parse a full backtrace. Returns a list of strings split by the location lines (File ..., line ..., in ...).
These lines are included in the output.
"""
return re.split(kTraceCodeLine, msg) | 6a9067327fc5e245f18d601bec2706eef77f39a3 | 3,602,070 |
def get_proper_state(job, state):
"""
Return a proper job state to send to server.
This function should only return 'starting', 'running', 'finished', 'holding' or 'failed'.
If the internal job.serverstate is not yet set, it means it is the first server update, ie 'starting' should be
sent.
:pa... | ba54c1f4eee99055e73099bc381ccbb69da4b183 | 3,602,071 |
def solve(task: str) -> str:
"""Find Knot Hash of the given input."""
rope = Rope()
lengths = process_data(task) + [17, 31, 73, 47, 23]
for _ in range(64):
for length in lengths:
rope.reverse(length)
rope.move(length)
sparse_hash = rope.nodes
dense_hash = compress... | 5e9399639512eea078ac7ee1bd9e6fa567369ea3 | 3,602,072 |
def get_first_import(node, context, name, base, level):
"""return the node where [base.]<name> is imported or None if not found
"""
fullname = '%s.%s' % (base, name) if base else name
first = None
found = False
for first in context.body:
if first is node:
continue
if... | 52b278d0eadf6337743d2395d4a829c9f5c318c2 | 3,602,073 |
def are_collinear(p1, p2, p3, tolerance=0.5):
"""return True if 3 points are collinear.
tolerance value will decide whether lines are collinear; may need
to adjust it based on the XY tolerance value used for feature class"""
x1, y1 = p1[0], p1[1]
x2, y2 = p2[0], p2[1]
x3, y3 = p3[0], p3[1]
r... | 337065b80e1cc1810be263bccd9c8ae66c258ed3 | 3,602,074 |
def transformResults(threadCounts, values, function):
"""Apply the function to all of the measurements"""
res = {}
for bm in list(values.keys()):
res[bm] = []
for (nThreads, v) in zip(threadCounts, values[bm]):
res[bm].append(None if v == None else function(v, nThreads))
retu... | 1fe7944479b045bebd403eeb888fe0c00b012291 | 3,602,075 |
import math
def coriolis_freq(lat):
"""Compute coriolis frequency.
https://en.wikipedia.org/wiki/Earth%27s_rotation#Angular_speed
omega = 7.2921150 ± 0.0000001×10−5 radians per second
:param theta: Latitude in degrees.
"""
omega = 7.2921150e-5
theta = math.radians(lat)
f = 2 * omega... | a5f40ef6b3862746905ab8e3cd4e77f1fdc1d484 | 3,602,076 |
def history_ping_stats(filename, parse_samples, verbose=False):
"""Fetch, parse, and compute the packet loss stats.
Args:
filename (str): Filename from which to read JSON data, or "-" to read
from standard input.
parse_samples (int): Number of samples to process, or -1 to parse all
... | bb717176ce99413be37b5844a7b33a8671b64711 | 3,602,077 |
def _find_cut_ranges(spark_context, tsuid, criteria, md_list, chunk_size=75000):
"""
Find the start and end dates in reference tsuid to be used later for cutting other TS depending on criteria.
Return example with 3 ranges found:
[
[ start_date_of_1st_range, end_date_of_1st_range],
[ star... | bc96d3c02b68715b4b8a0b750aa053a8ed9e301d | 3,602,078 |
def concat_channels(l_inputs, data_format='NHWC', scope=None):
"""Concat a list of tensors on the channel axis.
Args:
inputs: List Tensors;
data_format: NHWC or NCHW.
"""
with tf.name_scope(scope, 'concat_channels', l_inputs):
if data_format == 'NHWC':
net = tf.concat(l_... | 2a80a58ba261afc3a38527b9d5e5b8a2e730a066 | 3,602,079 |
def _msearch_success(response):
"""Return true if all requests in a multi search request succeeded
Parameters
----------
response : requests.models.Response
Returns
-------
bool
"""
parsed = response.json()
if 'responses' not in parsed:
return False
for result in pa... | acdac4408464120fdeb7f20a06f07aac6ca3809f | 3,602,080 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.