content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def keysInter(x):
"""Keys interpolation function
"""
y = np.zeros(x.shape)
abs_x = np.abs(x)
idx1 = np.bitwise_and(abs_x >= 0, abs_x < 1)
idx2 = np.bitwise_and(abs_x >= 1, abs_x <= 2)
y[idx1] = 1.5 * abs_x[idx1] ** 3 - 2.5 * abs_x[idx1] ** 2 + 1
y[idx2] = -0.5 * abs_x[idx2] ** 3 + 2.5 * ... | c43d33be8e3e56a94c0afd86aa0dc75447895c23 | 53,092 |
def rotate_landmarks(landmarks, eye_center, angle, row):
""" rotate landmarks to fit the aligned face
:param landmarks: dict of landmarks for facial parts as keys and tuple of coordinates as values
:param eye_center: tuple of coordinates for eye center
:param angle: degrees of rotation
:param row: r... | 3185adc07df68afb08f3938f0bfc03ed2db25a98 | 53,093 |
def _lookup(name, func, multi, converters):
"""Look up a Webware field/cookie/value/session value. Return
'(realName, value)' where 'realName' is like 'name' but with any
conversion suffix strips off. Applies numeric conversion and
single vs multi values according to the comments in the source.
""... | 0001df664ecfe0c0dbad2ba9240637dd774d6496 | 53,094 |
def generate_random_unit_vector():
"""
Generates a random unit vector.
:return: 3-elem np array with magnitude 1
"""
vec = np.random.normal(size=3)
mag = np.linalg.norm(vec)
if mag <= 1e-5:
return generate_random_unit_vector()
else:
return vec / mag | 8d9438d3fef67e412b561956a69394bf71826025 | 53,095 |
def read_chunk(addr):
"""Read a chunk's metadata."""
# In GLIBC versions <= 2.24 the `mchunk_[prev_]size` field was named `[prev_]size`.
# To support both versions, change the new names to the old ones here so that
# the rest of the code can deal with uniform names.
renames = {
"mchunk_size"... | 4b85387a620aa0deadde11d76d3de4173e3a3877 | 53,096 |
def dense_brightness_weight(image, sigma_X = 4, sigma_I = 10, r = 5):
"""
Calculate bright_weight(connection) for image
Args:
image: ndarray [B,H,W,C].
sigma_X: sigma for metric of distance.
sigma_I: sigma for metric of intensity.
r: radius of circle that only the neighb... | 6a2d2fc04385a8c03a2e62d18adbc86d5cfe49c0 | 53,098 |
def to_dict_of_lists(G,nodelist=None):
"""Return adjacency representation of graph as a dictionary of lists.
Parameters
----------
G : graph
A NetworkX graph
nodelist : list
Use only nodes specified in nodelist
Notes
-----
Completely ignores edge data for MultiGr... | 682250ea22fc93a23ee7ad65b3d1ecc742eb0f12 | 53,099 |
def calc_VFA_T1(S1, S2, fa1, fa2, TR):
"""Equation to calculate T1 from two T1w UTE GRE 'magnitude' images with different flip angles"""
T1 = -1.0 * TR / np.log((S1/np.sin(fa1) - S2/np.sin(fa2)) / (S1/np.tan(fa1) - S2/np.tan(fa2)))
return T1 | 3471ffde7c5d6056583cdb2b4c65537e79171d7f | 53,100 |
def is_type_name(type_name):
"""Does not handle keywords.
"""
return type_name[0].isupper() | fd8f4e7cdc0bac7f00bc41ecaa87533103907db5 | 53,101 |
def gauss_int(x, mu, sigma, A=1):
"""
integral of a gaussian from 0 to x, w/ args: mu, sigma, area, const.
"""
return A/2 * (1 + erf((x - mu)/sigma/np.sqrt(2))) | eaf6309c892629767941aa91fc6b1f484bcba9f8 | 53,103 |
def pad_data(matrix):
"""
pad data to fit mini-batch training
:param matrix:
:return:
"""
padded_index = matrix.shape[1]
data, data_len = [], []
for i in range(matrix.shape[0]):
seq = matrix.getrow(i).indices
data.append(seq)
data_len.append(len(seq))
longest... | 5d6ca42bebe7d258519d290566af5e2c93f31c9a | 53,104 |
def predict(m, fn):
"""
Args:
m: the trained model
fn: the full path to a file in the same format as the test set
Returns:
list: a list of 0s and 1s, corresponding to the lines in the specified file.
"""
vectorize = TFIDF(VECTOR_SIZE)
ds = preprocess(fn, train=False)
... | 8234b121e807414204c3444790cc1ae7bbff1768 | 53,105 |
def generate_query_string_missing_row(tablename_left, tablename_right,
l_column_name, r_column_name,
primary_keys, columns_list,
type_cast_dict):
"""
This method will produce a query to detect row... | 11d0bdb26ae8f453a74c1930929c5397f812a987 | 53,106 |
def test_project_gnb_data_tfidf(db, test_profile, tmpdir, settings):
"""This fixture only creates the test project without any data."""
proj = create_project("test_project", test_profile, classifier="gnb")
test_data = read_test_data_backend(file="./core/data/test_files/test_no_labels.csv")
add_data(proj... | e683dd47cd1bea00b6eb0ac63265ff6c75a46a6e | 53,107 |
def enc_state2(request):
"""The encoded state from compute_enc_state with another set of
parameters."""
return compute_enc_state(request) | 09b951be827ed862628fb1de32e54571625b5da0 | 53,108 |
def pi_modulus(recon_pattern,
diffracted_pattern,
offset_v=1e-12):
"""
Transfer sample from real space to q space.
Use constraint based on diffraction pattern from experiments.
Parameters
----------
recon_pattern : array
reconstructed pattern in real space
... | c99cba3d536a60e13b7911fa0c5af7197cbf6fd8 | 53,109 |
import numpy
def grazing_effect_on_aboveground_production(tgprod, fracrc, flgrem, grzeff):
"""Adjust aboveground production with the impact of grazing.
Removal of biomass by herbivores directly impacts potential
aboveground production according to the amount of biomass removed
and the parameter grzef... | d50e71a283cf605705f9449a9150626fafd57b3d | 53,110 |
def slow_conv(A, w, delays):
""" A simple implementation of convolution to compare against fast_conv """
#A is a NxM matrix, N is number of samples, M is dimensionality
Mw,D = w.shape
N,M = A.shape
assert Mw == M
y = np.zeros([N])
for k in range(N):
x = np.zeros([M, D])
fo... | fd1781b6b0af553ed374b9d675a43b6ab5fa4821 | 53,111 |
def process(data, action):
"""Выполняет верхнюю операцию в стаке и возвращаем результат в стэк"""
if not action.function:
return True
# Если для операции не хватает аргументов или значение не подходит - выдаём ошибку
try:
# Берём нужное кол-во аргументов для операции
if action.a... | 84bce6a3d942e1db308b3fe4848da9044cc856d4 | 53,112 |
from datetime import datetime
def get_last_day_of_month(t: datetime) -> int:
"""
Returns day number of the last day of the month
:param t: datetime
:return: int
"""
tn = t + timedelta(days=32)
tn = datetime(year=tn.year, month=tn.month, day=1)
tt = tn - timedelta(hours=1)
return tt... | 7bdb7fdd343fb2f1cf2d87d29dd87340588cd996 | 53,113 |
def get_Z_mats(V_mats):
"""
transform into conic matrix Z
Z = (V.T).dot(V)
Returns:
Z_mats (ndarray): Z is a conic representation of an ellipse
"""
Vt_mats = np.array(list(map(np.transpose, V_mats)))
Z_mats = Vt_mats @ V_mats
return Z_mats | 03602aef3f5a8127ebe941b19bfc03b97f62c4ee | 53,114 |
def wrap_message(messageText, width=79):
"""Word-wrap the message
:param str messageText: The text to alter.
:param int width: The column-number which to wrap at.
:returns: The wrapped text.
:rtype: str
.. Note: Originally a stand-alone script in
``Presentation/Tofu/MailingListManager/lscripts``."""
... | a430d4d0beaa190d3fd73ed1e07921f5b7cdfcff | 53,116 |
def client_id_from_id_token(id_token):
"""
Extracts the client id from a JSON Web Token (JWT).
Returns a string or None.
"""
payload = JWT().unpack(id_token).payload()
aud = payload.get('aud', None)
if aud is None:
return None
if isinstance(aud, list):
return aud[0]
r... | ce9952bc71aeaa9aa34b227484d0417ea069ff47 | 53,117 |
def route_agent(identifier):
"""Provide data from the DataPoint table for a specific Agent.
Args:
identifier: GraphQL identifier for the agent
Returns:
None
"""
# Initialize key variables
rows = []
screen = uri.graphql_filter(request)
# Get data from API server
po... | 8bd25fffbea4d6c6ddfcc97a2cbc3b8e535b4c8f | 53,118 |
def _convert_decoration_content_item(raw_data):
"""
Convert some raw data (usually a `dict`) to one of the registered
table content classes. Given that string is a valid table content
`str` values are returned unchanged.
"""
if _is_preprocessed_data(type(raw_data)):
return raw_data
e... | 786a6ec385af62fdb4f062b0e27885bf4ea4fef9 | 53,119 |
import inspect
def get_custom_kwargs(clazz, **kwargs):
"""
Filters kwargs based on the signature of the 'clazz'
:param clazz: Clean class or clean function to check the signature of
:param kwargs: optional arguments provided by the user
:return: filtered dictionary of kwargs
:raises ValueErro... | f6ab1127c0902e5e9fde22dafc42c55615e652a5 | 53,120 |
def get_key_in_nested_dict(nested_dict, target_key):
"""
Traverses the passed dict to find and return the value of target_key in the dict.
:param nested_dict: dictionary to search in
:param target_key: key you are looking for
:return: values of key
"""
for key in nested_dict:
if key ... | f0e677cc02ccbab7a4e3c09ba8bf1694c52b1818 | 53,122 |
def get_type(entry: DirEntry) -> EntryType:
"""
Gets the type of directory entry held by this file.
May not function properly with non-POSIX file permission attributes.
Args:
entry (os.DirEntry): The directory entry object returned by os.scandir()
Returns:
EntryType: The type of d... | ef8d0539707fe73f9443a3f613ac1414c4580df1 | 53,123 |
import yaml
def read_configfile(configfile):
"""
Function to read the configfile.
Returns a hash.
"""
with open(configfile, 'r') as stream:
try:
confighash = yaml.safe_load(stream)
except yaml.YAMLError as exc:
error( exc )
return confighash | 7b4de0b7a477072a9abfbcb9c26337b7f69fbacd | 53,124 |
def fpm(st1, st2, dt=0.01, fmin=1., fmax=10., nf=100, w0=6, norm='global',
st2_isref=True):
"""
Frequency-dependent Phase Misfit
.. seealso:: [Kristekova2009]_, Table 1. and 2.
:param st1: signal 1 of two signals to compare, type numpy.ndarray with
shape (number of components, number o... | 0198e46da5c896a4c801332be76c88a9202b21d2 | 53,125 |
def graph_edges_to_gdf(graph: nx.Graph) -> gpd.GeoDataFrame:
"""Create and fill a GeoDataFrame (geopandas) from edges of a networkX graph. The ``'geometry'`` attribute is used
for shapes.
Parameters
----------
graph : nx.Graph
Graph to parse
Returns
-------
gpd.GeoDataFrame
... | 63486616ae4fffb9c326a5356c39fd4114fe4c1e | 53,126 |
def get_least_viewed_episode(episodes):
"""Identifies and returns episode with the lowest recorded viewership. Ignores episodes with
no viewship value. Ignores ties. Delegates to the function < has_viewer_data > the task of
determing if the episode includes viewership "episode_us_viewers_mm" data.
Para... | 6dc7f0000922472335b8f2e7384939378093e2e4 | 53,127 |
from typing import List
def find_max_subarray_sum_brute(nums: List[Nums], k: int) -> Nums:
"""Given a list of numbers, find the maximum subarray sum of size k
Args:
nums: List[Nums]
k: int
Returns:
Nums
Raises:
ValueError if k < 0 or k > length of nums or nums is emp... | f1cb8499ad0f3edcdd4c74da456311d187ca955d | 53,130 |
def create_simple_posting_with_cost_or_price(entry, account,
number, currency,
price_number=None, price_currency=None,
cost_number=None, cost_currency=None, costspec=None,
... | 9886da19216adf375c635950a6a6600b72a60b22 | 53,131 |
def rmr_rcv_msg(vctx, ptr_mbuf):
"""
Refer to the rmr C documentation for rmr_rcv_msg
extern rmr_mbuf_t* rmr_rcv_msg(void* vctx, rmr_mbuf_t* old_msg)
"""
return _rmr_rcv_msg(vctx, ptr_mbuf) | bea930c9a09ca443d631f17fcc009d86531d742e | 53,132 |
import torch
def lse( v_ij ):
"""[lse(v_ij)]_i = log sum_j exp(v_ij), with numerical accuracy."""
V_i = torch.max(v_ij, 1)[0].view(-1,1)
return V_i + (v_ij - V_i).exp().sum(1).log().view(-1,1) | cc0dc0f6a602eacdc90b1a1264f8c29d620602d9 | 53,133 |
def get_instruments_filekinds(observatory, filepaths):
"""Given a list of filepaths return the mapping of instruments and
filekinds covered by the files.
"""
itmapping = defaultdict(set)
for filepath in filepaths:
instrument, filekind = get_file_properties(observatory, filepath)
itma... | 926c6068b028ae367d2c99b5b0a658a30607cfd3 | 53,134 |
from typing import Optional
def all_reduce_max(
inp: Tensor, group: Optional[Group] = WORLD, device: Optional[str] = None,
) -> Tensor:
"""
Create all_reduce_max operator for collective communication.
:param inp: input tensor.
:param group: communication group.
:param device: execution device... | 2cc3de17294089966a40e5704c75904ebbda528a | 53,135 |
def app(request):
"""
Displays default view for the app
:param request: HTTP Request
"""
request.session.flush()
results, search_query, message = [], None, None
if request.method == 'POST':
search_form = SearchForm(request.POST)
if search_form.is_valid():
query =... | 75a43fad12881e67c8fe5982d26b9746cb06f46c | 53,136 |
def has_roles(user):
"""Whether or not the user has any roles set in the system"""
return RoleAssignment.objects.filter(user=user).count() > 0 | fec784fd520fd0e9af4ac2f97c8714e58f88d627 | 53,137 |
def get_output(interpreter, score_threshold):
""" Returns list of detected objects.
Args:
interpreter: Interpreter object.
score_threshold: score threshold.
Returns: bounding_box, class_id, score
"""
# Get all output details.
boxes = get_output_tensor(interpreter, 0)
class_id... | 3936d625cffcca9b6d9df0e39dbf0d5b15266b35 | 53,138 |
def Weld(thisMesh, angleToleranceRadians, multiple=False):
"""
Makes sure that faces sharing an edge and having a difference of normal greater
than or equal to angleToleranceRadians share vertexes along that edge, vertex normals
are averaged.
Args:
angleToleranceRadians (double): Angle at w... | b6e5a460c4c44b3ee4cd499f6159ce322dfb5978 | 53,140 |
import logging
def _get_all_classes(**kwargs):
"""
Perform a GET call to get a dictionary containing all traffic classes
:param kwargs:
keyword s: requests.session object with loaded cookie jar
keyword url: URL in main() function
:return: List of all traffic classes in the table
"... | ffaf33603e5528d5e957dbdd893d8cda62bd946b | 53,141 |
def find_by_username(username):
"""
function that finds user by username
"""
return Users.find_by_username(username) | f8e043e9d41b66289d00be40060ba2322b74fdd2 | 53,142 |
def create_cobra_model_from_patric_model(model_id, id_type='modelseed', validate=False):
""" Create a COBRA model from a PATRIC model.
Parameters
----------
model_id : str
ID of model
id_type : {'modelseed', 'bigg'}
Type of IDs ('modelseed' for _c or 'bigg' for '[c])
validate : ... | e41c8565cea69199a84130f4b1cc2e385b5d1b56 | 53,143 |
def regionDailyTimeSeries(C, region):
""""
Returns a summed time series the length of axis 0 for C subet by the passed
region name
"""
minLat, maxLat, minLon, maxLon, resolution = cnm.getRegionBounds(region)
C_PNW, ynew, xnew = cnm.mask2dims(C, longitude, latitude, 0, minLon, maxLon, minLat, maxLat)
C_PNW_daily... | 47a065988462e8eb0c3a06b7d91f6638d1e9ed43 | 53,144 |
def oauth2(roles=None, required=True, throw_exception=True):
"""Decorate a Flask route to connect with BDC-Auth Provider.
You can specify user roles required to access a resource.
Make sure to set the following variables to the app:
- ``BDC_AUTH_CLIENT_ID``: Application Client Id
- ``BDC_AUTH_CLI... | 4b2469c9ea8b30987206138f559365bf142d229d | 53,145 |
def atSendCmdGetTradingDaysCondition(market, begin_day, end_day):
""" 获取交易日日期
:param market: 市场代号
:param begin_day: 交易日起始时间
:param end_day: 交易日结束时间
:return: list 指定范围内的交易日
"""
func_name = 'atSendCmdGetTradingDaysCondition'
atserial.ATraderGetTradingDaysByCondition_send(market, begin_... | 9c3e583277a6a8f96176391095dd1a6858c1c07d | 53,146 |
def offset(string: str, row: int, column: int, start_line_index: int = 0) -> int:
"""get offset from string at row column position
Return:
offset: int
"""
if not string:
raise ValueError("unable get offset from empty string")
if start_line_index:
row -= start_index
li... | c9187da599ef5b9d99fb46cc2a6edd07c155df68 | 53,147 |
from typing import Callable
from typing import Tuple
def train_val_split(
dataset: Dataset,
batch_size: int,
val_split: float,
shuffle: bool = True,
num_workers: int = 4,
collate_fn: Callable = None,
pin_memory: bool = True,
drop_last: bool = False,
timeout: float = 0,
worker_i... | d260e87bf3286e074ea611e38088360daf5d1ad9 | 53,148 |
def _format_label(duration, start_time, end_time):
"""
Formats a time block label.
:param duration: Duration.
:param start_time: Start time.
:param end_time: End time.
:return: Formatted string with duration, start, and end time.
"""
return 'Asleep {} ({} to {})'.format(
... | fab7865bb908d16aba69b07d2cb5c009e5ad3905 | 53,149 |
def get_categories(category_path, parent_category, exclude_str, save_cats_path, verbose):
"""
Process the categories file to get a list of all sub-categories of the specified parent
:param category_path: Path to categories json file
:param parent_category: Parent category
:param exclude_str: Comma s... | c77d35c32dab02f97ea6d8d2a71bae52c5fb2d39 | 53,150 |
def get_cold_plasma_coefficients(nu, B, n_e, theta, T):
"""Get radiative transfer coefficients appropriate for a cold plasma.
(Seeing as this module is called "synchrotron" this code may not quite
belong here, but...)
*nu*
Observing frequency, in Hz [note: all inputs are broadcast as vectors]
... | dd3d24fc68d4df58d4863e130b4301fe1750a68b | 53,151 |
def update_license(data):
"""Add license information to the template
Args:
data (Dict): Data to be updated in the template
Returns:
str: Updated license
"""
authors = [
"{:s} ({:s})".format(name, DATA["authors"][name])
for name in DATA["authors"].keys()
]
ma... | 6692da1665f6a10709ab2e3e15e4fe3f3fbb5e66 | 53,152 |
def halfSpaceFromRaDec(ra, dec, radius):
"""
Take an RA, Dec and radius of a circular field of view and return
a HalfSpace
Parameters
----------
ra in degrees
dec in degrees
radius in degrees
Returns
-------
HalfSpace corresponding to the circular field of view
"""
... | c68d9cc5042b2257a33c4484ec5b51b307dec72e | 53,154 |
def unique(data):
"""
in python 3: TypeError: '<' not supported between instances of 'int' and 'str'
need to keep the same Type of member in List
"""
data.sort()
l = len(data) - 1
i = 0
while i < l:
if (data[i] == data[i + 1]):
del data[i]
i -= 1
... | 5102a0d868741f9dca745e11972987ce74e78b8a | 53,155 |
from typing import List
from typing import AnyStr
def add_returning(query: QueryBuilder, fields: List[AnyStr]) -> AnyStr:
"""Build the string query to add final RETURNING statement.
:param query: Current query builder instance
:param fields: Fields to be returned
"""
if fields is None:
r... | cd426dbc777ad8f1038c7988d5f990ff987c537d | 53,156 |
def PtknsToStr(path_tokens):
"""
There are three ways to store paths:
As a single string: '/Protein/Phe/Ca' <- the format entered by the user
As a list of tokens ['Protein', 'Phe', 'Ca'] <- split into tokens
As a list of nodes in a tree (pointers to nodes in a tree hierarchy)
This functio... | 8dd64e6213f8a49f5b20619261a4b3d8daa8d95d | 53,157 |
def drawb(shape, col=None, mod=pyxel):
"""
Like draw, but renders only the outline of a shape.
Args:
shape: A Pymunk shape, body or space
mod: mod namespace that transforms the scene.
col (int): A color index
"""
try:
method = shape.drawb
except AttributeError:
... | 1833669c8e6297b852e072a930ff850c6ad03d05 | 53,158 |
def strings(binary):
"""
Runs and returns the results of the command strings on a binary file
:params str binary: the path to the binary
:return: the raw result of the strings command
"""
return execute("strings {}".format(binary)) | fb510340ba127f21d9340a9ffb610576ad0f04e1 | 53,159 |
import re
def _make_abbreviation(key, tag_name, attrs, is_empty=False):
"""
Make abbreviation from string
@param key: Abbreviation key
@type key: str
@param tag_name: Expanded element's tag name
@type tag_name: str
@param attrs: Expanded element's attributes
@type attrs: str
@param is_empty: Is expanded elem... | 5a5d1f84a4e7ed65db569ca7009c6062e3123bac | 53,160 |
import ast
from typing import List
from typing import Any
def parse_internal_function(
code: ast.FunctionDef, sig: FunctionSignature, context: Context
) -> LLLnode:
"""
Parse a internal function (FuncDef), and produce full function body.
:param sig: the FuntionSignature
:param code: ast of functi... | 88af4de83ea8c74780a195fdc699cd92425acc62 | 53,161 |
def traverse_grid(start_cell, direction, num_steps):
"""
Helper function that iterates over the cells
in a grid in a linear direction and returns
a list of their indices.
"""
indices = list()
for step in range(num_steps):
row = start_cell[0] + step * direction[0]
col = start_... | 0ce6f91759c36a63b103ebff2cddd8dd50ca837b | 53,162 |
def __format_size(file_size):
"""
Format file size information depending on the amount of bytes.
"""
file_size = int(file_size)
list_units = ["B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]
list_index = 0
while file_size > 1000:
file_size = float(file_size) / 1000
l... | d893e09281fce75cb5d0ea011cca623767ae6cbb | 53,164 |
import unittest
def testsuite():
"""
Return a PyUnit testsuite for the epytext module.
"""
tests = unittest.TestSuite()
parse_tests = unittest.makeSuite(ParseTestCase, 'test')
tests = unittest.TestSuite( (tests, parse_tests) )
return tests | 4d322baf4de89f44e884639b49440a67b372cff2 | 53,165 |
def parse_wiggle_header(header):
"""
:param header:
:return:
"""
_, chrom, start, step = header.strip().split()
foo, chrom = chrom.split('=')
assert foo == 'chrom', 'Unexpected wiggle header: {}'.format(header)
bar, start = start.split('=')
assert bar == 'start', 'Unexpected wiggle h... | 87525a16b849fca7f78b786c220c7861de085b82 | 53,166 |
def minEditDistance(s1, s2):
"""Compute minimum edit distance converting s1 -> s2 with operations."""
len1 = len(s1)
len2 = len(s2)
# Create two-dimensional structure such that m[i][j] = 0
# for i in 0 .. len1 and for j in 0 .. len2
m = [None] * (len1 + 1)
op = [None] * (len1 + 1)
for i... | 2bff64290098327c94d9e5dcf0c76f5336cb747d | 53,167 |
import struct
import typing
def pack_format(flat: FlatFmt) -> bytes:
"""pack collection of indexes into a tagged byte format."""
max_idx = max(flat, key=lambda idx: idx or 0)
if max_idx > 0xFFFF:
format_str = '>L'
elif max_idx > 0xFF:
format_str = '>H'
else:
format_str = '>... | 1ebf371908b3ae4ca067a04b1346e3edb74aa86e | 53,168 |
def get_or_404(*args, **kwargs):
"""Returns a model instance fetched by key or raises a 404 Not Found error.
Example:
from tipfy import RequestHandler
from tipfy.appengine.db import get_or_404
from mymodels import Contact
class EditContactHandler(RequestHandler):
de... | 6490cf6802c6a76515b2c096e84f9e599cd01e26 | 53,169 |
def sisnr_objf(x: th.Tensor,
s: th.Tensor,
eps: float = EPSILON,
zero_mean: bool = True,
non_nagetive: bool = False) -> th.Tensor:
"""
Computer SiSNR
Args:
x (Tensor): separated signal, N x S
s (Tensor): reference signal, N x S
... | 46973f012dce9e190418307941f2b12a4fa9ce58 | 53,170 |
def _path_in_ignore_dirs(source_path: str, ignore_dirs: list) -> bool:
"""Checks if the source path is to be ignored using a case sensitive match
Arguments:
source_path: the path to check
ignore_dirs: the list of directories to ignore
Return:
Returns True if the path is to be ignored... | 5d392392e735bdbc1e60cca9414fca8a1eb3ec0c | 53,171 |
def load_drivers(conf):
"""Imports all the driver files corresponding to this agent.
Returns: Dictionary of driver objects with a specified service type and
vendor name
"""
ld = load_driver.ConfiguratorUtils(conf)
drivers = ld.load_drivers(const.SERVICE_TYPE)
for service_type, driver_nam... | b6898a416e131918880e1a50b12e185efa516dd9 | 53,172 |
def absolute_difference_error(output, target, is_mean=False, name="absolute_difference_error_loss"):
"""Return the TensorFlow expression of absolute difference error (L1) of two batch of data.
Parameters
----------
output : Tensor
2D, 3D or 4D tensor i.e. [batch_size, n_feature], [batch_size, h... | 86ed3212ad265575a2381a38ae9568a3ed94e1b1 | 53,173 |
def maximum_knapsack(items, limit):
"""
Berechnet die Lösung für Maximum Knapsack über Dynamic Programming
(ähnlich wie Subset Sum)
"""
# Erstelle Tabelle
table = [[None for j in range(len(items) + 1)] for i in range(limit + 1)]
# Fülle erste Zeile mit 0 (da der Wert im Knapsack mit 0 Gegenständen imme... | 4866516378abeb3d0b7e294376d7127cd392d947 | 53,174 |
def gpio_read(gpio_pin: int) -> bool:
"""Return an input or output pin state."""
return (GPIO.input(gpio_pin) == GPIO.HIGH) | ae37aacbaf72d22ed59819458c4adb410741bd19 | 53,175 |
import base64
def auth0_url_encode(byte_data):
"""
Safe encoding handles + and /, and also replace = with nothing
:param byte_data:
:return:
"""
return base64.urlsafe_b64encode(byte_data).decode('utf-8').replace('=', '') | 3a80301d59e7f5ac8bf6ae3e2cd4599fd4848ae5 | 53,176 |
def replace_jax_simple_full_softmax_vars_to_tf(
jax_initial_vars: NestedMap) -> NestedMap:
"""Replaces JAX Simple Full Softmax vars to TF compatible vars.
Args:
jax_initial_vars: JAX ConvBNAct layer vars.
Returns:
tf_initial_vars which is TF compatible with ConvBNAct.
"""
tf_initial_vars = jax_i... | afeb44aae1f76742f568b76870ee0e8fdecbdfbc | 53,177 |
def _fmt(x, pos):
"""
Used for nice formatting of powers of 10 when plotting logarithmic
"""
a, b = '{:.2e}'.format(x).split('e')
b = int(b)
if abs(float(a) - 1) < 0.01:
return r'$10^{{{}}}$'.format(b)
else:
return r'${} \times 10^{{{}}}$'.format(a, b) | f8c8a77800266797efb69468848d8a80c8930558 | 53,178 |
def quint4(scale, zero_point):
"""
Consturct a quantized unsigned int4 data type with ``scale`` (float) and
``zero_point`` (uint8). The real value represented by a quint4 data type is
float_val = scale * (uint4_val - zero_point)
"""
return get_quantized_dtype("quint4", scale, zero_point) | f5568c1bcd1b90d8de66ad246bc4cd185f49d394 | 53,180 |
def word_averaging(wv, words):
"""Calculate average word vectors.
Args:
wv: The keyed vectors instance to use to get word vectors as :class:`gensim.models.keyedvectors.WordEmbeddingsKeyedVectors`.
words: The words to transform into vectors as :class:`list` of :class:`str`.
Returns:
... | abe38c7eed1d695606b5f8975f666243da4c5c19 | 53,181 |
from typing import Optional
from typing import List
from typing import Union
from typing import Tuple
def create_full_X_test_2d(
X_ranges: MatrixLike2d,
x_indices: Optional[List[int]] = [0, 1],
fixed_values: Optional[Union[ArrayLike1d, float]] = None,
fixed_values_real: Optional[Union[ArrayLike1d, fl... | d054ef7c7a206c0c21c0f1879ea602ee87d0aa22 | 53,182 |
def create_win_salt_restart_task():
"""
Create a task in Windows task scheduler to enable restarting the salt-minion
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
salt '*' service.create_win_salt_restart_task()
"""
# Updated ... | a2a3e5878602743f928aa119f256d108d2e7e695 | 53,183 |
def prepare_mol(filename, header, add_hydrogens=True):
"""
"""
atoms = []
coordinates = []
with open(filename, 'r') as f:
molfmt = f.read()
mol = Chem.MolFromMolBlock(molfmt)
# get formal charge
charge = Chem.GetFormalCharge(mol)
# Get coordinates
conf = mol.GetCo... | 0ec0ae59a424c4d0a286f695182c3ef2589dc3de | 53,184 |
def build_put_async_relative_retry400_request(
**kwargs # type: Any
):
# type: (...) -> HttpRequest
"""Long running put request, service returns a 200 with ProvisioningState=’Creating’. Poll the
endpoint indicated in the Azure-AsyncOperation header for operation status.
See https://aka.ms/azsdk/py... | c855b67cd63a4dfcd89a86fff950999d78044c94 | 53,186 |
import requests
def open_recipe_file(file, recipes_path=None, github_repo='bioconda/bioconda-recipes'):
"""
Open a file at a particular location and return contents as string
"""
if recipes_path:
return open(f'{recipes_path}/{file}').read()
else: # if no clone of the repo is available loc... | ce5fc3c054bc937203966459e9981a5befdae40b | 53,187 |
def confidence_interval(data, column_name, confidence_level):
"""
get a 95% confidence interval from a bootstrap dataframe column
Parameters
----------
data : pandas dataframe
the bootstrap dataframe generated by :py:func:`.bootstrapLE`
column_name : string
the statistic that y... | 69668a88030c0a2d6d90dbc1b834cbab76d0ec17 | 53,189 |
def dist_to_freq(dist: float, bw: float, ts: float) -> float:
"""
"""
return int(2 * dist * bw / (299792458 * ts)) | 5e232569e25e663ca6b13a7acdd0c5f1b2afd5aa | 53,190 |
def batch_files(pool_size, limit):
""" Create batches of files to process by a multiprocessing Pool """
batch_size = limit // pool_size
filenames = []
for i in range(pool_size):
batch = []
for j in range(i * batch_size, (i + 1) * batch_size):
filename = 'numbers/numbers_%d... | 8272e2d58f582edb5737d4b18833f7123907d451 | 53,191 |
def implements(numpy_function):
"""Register an __array_function__ implementation"""
def decorator(func):
QUANTITY_FUNCTIONS[numpy_function] = func
return func
return decorator | 24622b6f509d6659dfb12bd0f04d77675afb15c7 | 53,192 |
def merge_imd_with_other_set(imd_df, other_df):
"""Merge IMD data with other data based on postcode.
Parameters
----------
imd_df : pandas.DataFrame
Deprivation data
other_df : pandas.DataFrame
Other data
Return
----------
merged_df : pandas.DataFrame
Two datas... | 053ddd59ccb223c638d7bd093c06fb4c402df631 | 53,193 |
def encode_note_mat_to_atr_mat(nmat,
length=None,
tgt_pad_length=None,
eo=0,
ep=0,
estimate_ep=False,
w=0):
"""
Convert note m... | d3abbbb656ca9896d9f0f85787ea301030990f7d | 53,194 |
from mkt.webapps.models import Webapp
def get_iarc_app_title(app):
"""Delocalized app name."""
with no_translation(app.default_locale):
delocalized_app = Webapp.with_deleted.get(pk=app.pk)
return unicode(delocalized_app.name) | 27d0f5e0fa63ef4caacdeb0eb6e914cae798d757 | 53,196 |
def box_ball_location_on_collision(
ball_loc, box_loc, box_rot_matrix, box_corner=HITBOX, box_offset=HITBOX_OFFSET, ball_radius=92
):
"""Closest box location for there to be a collision with the ball"""
ball_local_loc = (ball_loc - box_loc).dot(box_rot_matrix)
hit_local_loc = box_local_collision_locatio... | 20eaa6445e097928a6802c20ddd427b135b21f18 | 53,197 |
def list_missing_data_cols(df, back_color="red"):
"""
This function reports statistics on missing data in the datasets.
"""
lst_cols_missing = list(df.columns[df.isnull().any()])
lst_cols_miss_data = [(col, df[col].isnull().sum()) for col in lst_cols_missing]
lst_cols_miss_data = sorted(lst_cols... | edd455872152c6ed419159664e098762f77c0753 | 53,198 |
def plot_secant_method():
"""Illustrates the Secant Method.
The Secant Method replaces the derivative in Newton’s method with an estimate.
The code for this function is taken from the Python CompEcon toolbox by
Randall Romero-Aguilar [RA20]_ and has been slightly altered to fit the
style of these ... | c33389d61c3f13e9c97e2e9c7c4b832ef2927d81 | 53,199 |
def compute_wu_bound_strong(lipschitz_constant, gamma, n_samples, batch_size, verbose=True):
"""
compute the bound in the strongly convex case
basically copied from
https://github.com/tensorflow/privacy/blob/1ce8cd4032b06e8afa475747a105cfcb01c52ebe/tensorflow_privacy/privacy/bolt_on/optimizers.py
""... | 120650fe3ac2460f592f784f734d678a423ce4eb | 53,200 |
async def init_wiki():
"""
Async-creates the wiki object and sets its .soup to actual JSON.
return: gbfwiki.wiki wiki
"""
wiki = Wiki()
await wiki._init()
return wiki | d0313a5c70266d291d89b188b95ea1ff866a315d | 53,201 |
def pig_latin(wrd):
"""Returns the Pig Latin version of a word.
For words that begin with a consonant, take the consonant/consonant cluster
and move it to the end of the word, adding the suffix 'ay' to the end of the word.
For words that begin with a vowel, leave the word as is and add the
suffix ... | 2eba5f4aaff1391e60f4097e526539d5b486c9bd | 53,204 |
from typing import List
from typing import Optional
def select_config(
configs: List[cconfig.Config],
index: Optional[int],
start_from_index: Optional[int],
) -> List[cconfig.Config]:
"""
Select configs to run based on the command line parameters.
:param configs: list of configs
:param in... | 5cb5f2f44867aa2d5c662fb13b4e19e2fe737da7 | 53,205 |
def parse_units(units_str):
"""
Extract and parse the units
Extract the bounds over which the expression is assumed to apply.
Parameters
----------
units_str
Returns
-------
Examples
--------
>>> parse_units('Widgets/Month [-10,10,1]')
('Widgets/Month', (-10,10,1))
... | 18f35a06aedfc9d026cfa70a1217b0b5b0420ca5 | 53,206 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.