content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import uuid
from datetime import datetime
def submit_ride_request():
"""
submit a ride request with the following required fields:
- netId (string) - netId of requester
- date (date object) - date of travel
- time (time object) - time of travel
- origin (string) - chosen from d... | 5f7d1d2d98adb3aa336b48032331b5b5fe2114f2 | 19,400 |
def _heatmap(data,
row_ticks=None,
col_ticks=None,
row_labels=None,
col_labels=None,
ax=None,
cbar_kw={},
cbarlabel="",
**kwargs):
"""Create a heatmap from a numpy array and two lists of labels.
(Code from `... | a3b2117c5d42a0882083673e93505cb6ab2a8225 | 19,401 |
def html_colour_to_rgba(html_colour: str) -> ():
"""Convers HTML colout to its RGB values"""
html_colour = html_colour.strip()
if html_colour[0] == '#':
html_colour = html_colour[1:]
return tuple([int(x, 16) for x in (html_colour[:2], html_colour[2:4], html_colour[4:], '0')]) | 461aaf837a4f99acbb167e98be3642799f425671 | 19,402 |
def index(request):
"""Displays form."""
data = {"menu": "index", "max_characters": settings.PASTE["max_characters"]}
if request.method == "POST":
paste = Paste(slug=random_id(Paste))
if request.FILES:
for language_name, any_file in request.FILES.items():
break
... | dece4cc7e0d4d0138be1bb0b333189989cd1244c | 19,403 |
def trafficking_service():
"""Connect to Google's DFA Reporting service with oauth2 using the discovery service."""
return google_service(DDM_TRAFFICKING_SCOPE) | be94a35558178be9ad697edc89d6ca55ca3ca08b | 19,404 |
def deduplicate(s, ch):
"""
From http://stackoverflow.com/q/42216559/610569
s = 'this is an irritating string with random spacing .'
deduplicate(s)
'this is an irritating string with random spacing .'
"""
return ch.join([substring for substring in s.strip().split(ch) if su... | 5b2bb10376143a1597ddfab1711716c802cdf113 | 19,405 |
def optimize(mod):
"""Optimize all the functions in a module.
Modules are the only mutable piece of Relay. We write an
optimization pass over the module which destructively updates each
function while optimizing.
"""
return pass_set(mod) | 8065bf95d802c95fbad985dbaa1a0835ac27d20f | 19,406 |
def sum_series(n):
"""Calculate sum of n+(n-2)+(n-4)..."""
return n if n < 2 else n + sum_series(n - 2) | 317317fc6a7f14a9cbd564266b73ac087b2bdbd2 | 19,407 |
def get_preconditioner():
"""Compute the preconditioner M"""
diags_x = zeros((3, nx))
diags_x[0,:] = 1/hx/hx
diags_x[1,:] = -2/hx/hx
diags_x[2,:] = 1/hx/hx
Lx = spdiags(diags_x, [-1,0,1], nx, nx)
diags_y = zeros((3, ny))
diags_y[0,:] = 1/hy/hy
diags_y[1,:] = -2/hy/hy
diags_y[2,:... | 9992f894b0bc1141a461ddd52f1b38671cd42986 | 19,408 |
def compute_noise_ceiling(y, scoring=roc_auc_score, K=None, soft=True, return_pred=False, doubles_only=False):
""" Computes the noise ceiling for data with repetitions.
Parameters
----------
y : pd.Series
Series with numeric values and index corresponding to stim ID.
K : int
Number ... | e10c02bca26342eff97b1e5e29c96ed2429c429e | 19,409 |
def maskw(m, edge, xray_image, imax, jmax, maxr, roundR, listcounter):
"""
Takes in a bunch of parameters for masking the image
Parameters
----------
Stuff ;
Returns
-------
highper, lowper, totalper, old_files, iMask, StatsA
"""
# old_files=np.zeros((imax,jmax))
# highpe... | f06089859238337113b52e14859d2703a83e34e8 | 19,410 |
def get_all_contained_items(item, stoptest=None):
"""
Recursively retrieve all items contained in another item
:param text_game_maker.game_objects.items.Item item: item to retrieve items\
from
:param stoptest: callback to call on each sub-item to test whether\
recursion should continue.... | d04e5c297dddb70db83637e748281f04b08b6a25 | 19,411 |
import importlib
import os
import sys
def make_from_file(fn : str, robotModel : RobotModel, *args,**kwargs) -> RobotInterfaceBase:
"""Create a RobotInterfaceBase from a Python file or module containing the
``make()`` function.
args and kwargs will be passed to ``make``.
Example::
iface = mak... | 8ae9a1b33a0b9239630a94ff6fd484362323ffa2 | 19,412 |
def page_id_url(context, reverse_id, lang=None):
"""
Show the url of a page with a reverse id in the right language
This is mostly used if you want to have a static link in a template to a page
"""
request = context.get('request', False)
if not request:
return {'content':''}
if lang ... | 7808c8b69b9b028eadfffebff4e16dd34654d869 | 19,413 |
def convert(string):
""" the convert() function takes simple-formatted string and returns a 'lingtree description string' suitable for pasting into the SIL LingTree program directly
the string should contain multiple lines, one line per 'node relationship'. E.G. :
S = NP VP
NP = \L Juan
Juan = \G John
VP =... | 0afd987c9da9579b2a80e7d6a3428533df75ef3e | 19,414 |
def Hij_to_cijkl(H):
"""Convert a Hooke's matrix to the corresponding rigidity tensor
Parameters
----------
H: 6x6 iterable or dict
The Hooke's matrix to be converted. If not already a np.ndarray, an iterable must
be castable to one.
Returns
-------
c: 3x3x3x3 np.ndarray
... | 691c38eabe459c83d69dc8def69b48a9a0f3055e | 19,415 |
from datetime import datetime
import requests
import json
import sys
def get_cymon_feed_size(jwt, feed_id):
"""Determine the number of results a feed will return (max: 1000).
Params:
- jwt: (type: string) JWT token.
- feed_id: (type: string) Cymon feed ID.
Returns:
- total: (type: int) feed ... | 2b5491921e047c94cd384dc74b5f8aa55d89e185 | 19,416 |
def train10():
"""
CIFAR-10 training set creator.
It returns a reader creator, each sample in the reader is image pixels in
[0, 1] and label in [0, 9].
:return: Training reader creator
:rtype: callable
"""
return reader_creator(
paddle.dataset.common.download(CIFAR10_URL, 'cifar'... | fcfabaa575a8cffa511e579b797f738727c75945 | 19,417 |
def _generate_one_direction_LSTM(transformer, X, W, R, B, initial_h, initial_c, P, clip,
act, dtype, hidden_size, batch_size):
"""Generate subgraph for one direction of unrolled LSTM layer
Args:
transformer (_ModelTransformerHelper): helper for model generation
X... | f0093c872a0ae639e5616e29d9666353e19d5748 | 19,418 |
def FindTerms(Filename, NumTerms):
"""Reorders the first NumTerms of the output of Todd program to find omega breakpoints"""
f = open(Filename, 'r')
# Get the value of omega
Omega = int(f.readline().split()[1])
print "Omega =", Omega
# Skip these lines
for i in range(3):
f.readline()
Terms = []
for line i... | 7ec4d6cb4a1fc698cc951e618d375a06eddc54e7 | 19,419 |
def hessian_power(h):
"""
Power in the hessian filter band
Frobenius norm squared
"""
if len(h) == 2:
p = np.abs(h[0])**2 + 2*np.abs(h[1])**2 + np.abs(h[2])**2
elif len(h) == 6:
p = np.abs(h[0])**2 + 2*np.abs(h[1])**2 + 2*np.abs(h[2])**2 + np.abs(h[3])**2 + 2*np.abs(h[4])**2 + np... | 3ea5b77b55d9a22406c34b5ffb9a244f127df476 | 19,420 |
def read_table(source, columns=None, memory_map=True):
"""
Read a pyarrow.Table from Feather format
Parameters
----------
source : str file path, or file-like object
columns : sequence, optional
Only read a specific set of columns. If not provided, all columns are
read.
memo... | bcbdfa9b9bde999a4caca7dae9fa76eea04c6978 | 19,421 |
def save_classnames_in_image_maxcardinality(
rgb_img, label_img, id_to_class_name_map, font_color=(0, 0, 0), save_to_disk: bool = False, save_fpath: str = ""
) -> np.ndarray:
"""
Args:
rgb_img
label_img
id_to_class_name_map: Mapping[int,str]
Returns:
rgb_img
"""
... | 807e4c850226a56cdd41ce5edfec7dc983313e7a | 19,422 |
def yolo2lite_mobilenet_body(inputs, num_anchors, num_classes, alpha=1.0):
"""Create YOLO_V2 Lite MobileNet model CNN body in Keras."""
mobilenet = MobileNet(input_tensor=inputs, weights='imagenet', include_top=False, alpha=alpha)
print('backbone layers number: {}'.format(len(mobilenet.layers)))
# inpu... | 650a2f053db1fb8cee7e054a66bdb1cea7a82724 | 19,423 |
from typing import List
from typing import Tuple
def from_pandas(
X: pd.DataFrame,
max_iter: int = 100,
h_tol: float = 1e-8,
w_threshold: float = 0.0,
tabu_edges: List[Tuple[str, str]] = None,
tabu_parent_nodes: List[str] = None,
tabu_child_nodes: List[str] = None,
) -> StructureModel:
... | 1c7c645b60a23e9fc5dca3f63b8216aa82445ff0 | 19,424 |
def conv_seq_to_sent_symbols(seq, excl_symbols=None, end_symbol='.',
remove_end_symbol=True):
"""
Converts sequences of tokens/ids into a list of sentences (tokens/ids).
:param seq: list of tokens/ids.
:param excl_symbols: tokens/ids which should be excluded from the final
... | a87da4bb5c34882d882832380f3831929ad41415 | 19,425 |
def emphasize_match(seq, line, fmt='__{}__'):
"""
Emphasize the matched portion of string.
"""
indices = substr_ind(seq.lower(), line.lower(), skip_spaces=True)
if indices:
matched = line[indices[0]:indices[1]]
line = line.replace(matched, fmt.format(matched))
return line | c33c3d5cc52fb7b34bf4ae68495f78afcc1a051d | 19,426 |
def param_value(memory, position, mode):
"""Get the value of a param according to its mode"""
if mode == 0: # position mode
return memory[memory[position]]
elif mode == 1: # immediate mode
return memory[position]
else:
raise ValueError("Unknown mode : ", mode) | e02ed7e1baea57af4b08c408b6decadee9c72162 | 19,427 |
def check_array_shape(inp: np.ndarray, dims: tuple, shape_m1: int, msg: str):
"""check if inp shape is allowed
inp: test object
dims: list, list of allowed dims
shape_m1: shape of lowest level, if 'any' allow any shape
msg: str, error msg
"""
if inp.ndim in dims:
if inp.shape[-1] == ... | 2ca900df0ea13e4b41f8bc9c7ff1e727aea27713 | 19,428 |
def Implies(p, q, simplify=True, factor=False):
"""Factory function for Boolean implication expression."""
p = Expression.box(p)
q = Expression.box(q)
expr = ExprImplies(p, q)
if factor:
expr = expr.factor()
elif simplify:
expr = expr.simplify()
return expr | e5b57ccffdb413ad1de46fef65b670dd20bb53c4 | 19,429 |
def r_power(r_amp):
"""Return the fraction of reflected power.
Parameters
----------
r_amp : float
The net reflection amplitude after calculating the transfer
matrix.
Returns
-------
R : numpy array
The model reflectance
"""
return np.abs(r_amp)**2 | 2d7250f2e447c6a85d7ace63cf087733b920444e | 19,430 |
def wrap_get_server(layer_name, func):
""" Wrapper for memcache._get_server, to read remote host on all ops.
This relies on the module internals, and just sends an info event when this
function is called.
"""
@wraps(func) # XXX Not Python2.4-friendly
def wrapper(*f_args, **f_kwargs):
re... | fc8f65480b3be4e8cb04ac1a42e1b969ce5b4ccc | 19,431 |
def shape(batch) -> (int, int):
"""Get count of machine/tasks of a batch"""
return len(batch), len(batch[0]) | 43119e21e5f9034cb4c733f2855254c77a452e9e | 19,432 |
from typing import Union
from typing import List
import requests
from io import StringIO
def uniprot_mappings(query: Union[str, List[str]],
map_from: str = 'ID',
map_to: str = 'PDB_ID',
) -> pd.DataFrame:
"""Map identifiers using the UniProt identifie... | 79fb3b75c2724bee51242dfcbba78a7efdc11667 | 19,433 |
def build_property_filter_spec(client_factory, property_specs, object_specs):
"""Builds the property filter spec.
:param client_factory: factory to get API input specs
:param property_specs: property specs to be collected for filtered objects
:param object_specs: object specs to identify objects to be ... | 43822b966766fe5922b0d9ff45f6e5835ae6500e | 19,434 |
def get_user_name_from_token():
"""Extract user name and groups from ID token
returns:
a tuple of username and groups
"""
curl = _Curl()
token_info = curl.get_token_info()
try:
return token_info['name'], token_info['groups'], token_info['preferred_username']
except Exce... | cd4b4931fdbc646bde0d555d8914cf0fac9fca89 | 19,435 |
def prob17(limit=1000):
"""
If the numbers 1 to 5 are written out in words: one, two, three, four,
five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written out
in words, how many letters would be used?
NOTE: Do n... | 586f60fa4411a5818102a903286aa97095faeffb | 19,436 |
def mask_orbit_start_and_end(time, flux, orbitgap=1, expected_norbits=2,
orbitpadding=6/(24), raise_error=True):
"""
Ignore the times near the edges of orbits.
args:
time, flux
returns:
time, flux: with `orbitpadding` days trimmed out
"""
norbits, gr... | c8da4b3394424acd8ec1b9ccb1af03ba2add2043 | 19,437 |
def to_cnf(expr):
"""
Convert a propositional logical sentence s to conjunctive normal form.
That is, of the form ((A | ~B | ...) & (B | C | ...) & ...)
Examples
========
>>> from sympy.logic.boolalg import to_cnf
>>> from sympy.abc import A, B, D
>>> to_cnf(~(A | B) | D)
And(Or(D,... | b718d26ba3669d88b2d4bc368be48307cd7334bf | 19,438 |
from typing import List
from pathlib import Path
from typing import Optional
def plot_contours_for_all_classes(sample: Sample,
segmentation: np.ndarray,
foreground_class_names: List[str],
result_folder: Path,
... | d3f7b1e246bd2eb19272279f946af4218f2eb65b | 19,439 |
from typing import VT
from typing import List
from typing import Dict
from typing import Set
from typing import FrozenSet
from typing import Tuple
import itertools
def match_gadgets_phasepoly(g: BaseGraph[VT,ET]) -> List[MatchPhasePolyType[VT]]:
"""Finds groups of phase-gadgets that act on the same set of 4 verti... | 740957f18d5ad223d9b4c64f3c61e6f1bc4bea9e | 19,440 |
import re
def get_replaceid(fragment):
"""get replace id for shared content"""
replaceid=re.findall(r":[A-z]+:\s(.+)", fragment)[0]
return replaceid | 25e1a940904d86c5e57d2d36dbd91247c6e08bb3 | 19,441 |
def _tower_fn(is_training, weight_decay, feature, label, data_format,
num_layers, batch_norm_decay, batch_norm_epsilon):
"""Build computation tower (Resnet).
Args:
is_training: true if is training graph.
weight_decay: weight regularization strength, a float.
feature: a Tensor.
... | 8f15447ef605990c5b596afe11e5bcd8f84164b1 | 19,442 |
def DiscRate(t, dur):
"""Discount rates for the outer projection"""
return scen.DiscRate(dur) + DiscRateAdj(t) | 07e6af30738531b349fac62bfbfe9e58ba0bee51 | 19,443 |
def outlierDivergence(dist1, dist2, alpha):
"""Defines difference between how distributions classify outliers.
Choose uniformly from Distribution 1 and Distribution 2, and then choose
an outlier point according to the induced probability distribution. Returns
the probability that said point would be cl... | 4c631f30dd32d35dd8ced7dbcbc0c93b4ee6c89b | 19,444 |
import os
def load_data(root_path, data_path):
"""
:param root_path: root path of data
:param data_path: name of data
:return: datas, labels: arrays which are normalized
label_dict
"""
path = os.path.join(root_path, data_path)
f = open(path, 'r')
label_dict = {}
label... | 4e3a8d69949bc721d6ebf5d85508fd689c659f06 | 19,445 |
def getCP2KBasisFromPlatoOrbitalGauPolyBasisExpansion(gauPolyBasisObjs, angMomVals, eleName, basisNames=None, shareExp=True, nVals=None):
""" Gets a BasisSetCP2K object, with coefficients normalised, from an iter of GauPolyBasis objects in plato format
Args:
gauPolyBasisObjs: (iter plato_pylib GauPolyBasis object... | 1a23922122dd0d32c69e8829d891811ec0ad37b1 | 19,446 |
import math
def longitude_to_utm_epsg(longitude):
"""
Return Proj4 EPSG for a given longitude in degrees
"""
zone = int(math.floor((longitude + 180) / 6) + 1)
epsg = '+init=EPSG:326%02d' % (zone)
return epsg | f17a03514cc9caf99e1307c0382d7b9fa0289330 | 19,447 |
def SupportVectorRegression(X_train, X_test, y_train, y_test, search, save=False):
"""
Support Vector Regression.
Can run a grid search to look for the best parameters (search=True) and
save the model to a file (save=True).
"""
if search:
# parameter values over which we will se... | e51e2aa3a706fb2308b9e693bef67950f4eb8a0b | 19,448 |
def conv_relu_pool(X, conv_params, pool_params):
"""
Initializes weights and biases
and does a 2d conv-relu-pool
"""
# Initialize weights
W = tf.Variable(
tf.truncated_normal(conv_params, stddev=0.1)
)
b = tf.constant(0.1, shape=conv_params['shape'])
conv = tf.nn.conv2d(X, W,... | d3bba15fbba220790eaf2e74cec0595b3d327479 | 19,449 |
def compute_node_depths(tree):
"""Returns a dictionary of node depths for each node with a label."""
res = {}
for leaf in tree.leaf_node_iter():
cnt = 0
for anc in leaf.ancestor_iter():
if anc.label:
cnt += 1
res[leaf.taxon.label] = cnt
return res | a633f77d0fff1f29fe95108f96ccc59817179ddd | 19,450 |
def create_device(hostname, address, username="root", password=""):
"""Create and return a DeviceInfo struct."""
return DeviceInfo(hostname, address, username, password) | af5d722ae1a7f2383bc274340313bfcc61c56c18 | 19,451 |
def max_box(box1, box2):
"""
return the maximum of two bounding boxes
"""
ext = lambda values: min(values) if sum(values) <= 0 else max(values)
return tuple(tuple(ext(offs) for offs in zip(dim[0], dim[1])) for dim in zip(box1, box2)) | 5323e927999e613ac709bca57373e1985c65946b | 19,452 |
def homogenize(a, w=1.0):
"""
Example:
a=[
[a00, a01],
[a10, a11],
[a20, a21]
], w=1
->
result=[
[a00, a01, w],
[a10, a11, w],
[a20, a21, w]
]
"""
return np.hstack([a, np.full((len(a), 1), w,... | dd8dec2d96a6c6aa04d6754ee66c93230b91a309 | 19,453 |
def find_similar_term(term, dictionary):
"""
Returns a list of terms similar to the given one according to the Damerau-Levenshtein distance
https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance
"""
return list(filter(lambda t: textdistance.damerau_levenshtein.distance(t, term) <= 2, di... | a4fca3fbfee5597ae4a333f6e8856fc75aa31a2a | 19,454 |
import hashlib
def calc_sign(string):
"""str/any->str
return MD5.
From: Biligrab, https://github.com/cnbeining/Biligrab
MIT License"""
return str(hashlib.md5(str(string).encode('utf-8')).hexdigest()) | 3052e18991b084b3a220b0f3096d9c065cf4661c | 19,455 |
from typing import Callable
from typing import Optional
from typing import Tuple
from typing import Dict
def compile_circuit(
circuit: cirq.Circuit,
*,
device: cirq.google.xmon_device.XmonDevice,
compiler: Callable[[cirq.Circuit], cirq.Circuit] = None,
routing_algo_name: Option... | f0e64da1aa7b87d1459c8708493ac5ec59b74c33 | 19,456 |
def remove_prefix(utt, prefix):
"""
Check that utt begins with prefix+" ", and then remove.
Inputs:
utt: string
prefix: string
Returns:
new utt: utt with the prefix+" " removed.
"""
try:
assert utt[: len(prefix) + 1] == prefix + " "
except AssertionError as e:
... | fa6717e34c6d72944636f6b319b98574f2b41a69 | 19,457 |
def format_ucx(name, idx):
"""
Formats a name and index as a collider
"""
# one digit of zero padding
idxstr = str(idx).zfill(2)
return "UCX_%s_%s" % (name, idxstr) | c3365bf66bca5fe7ab22bd642ae59dfb618be251 | 19,458 |
def get_connection():
"""
Return a connection to the database and cache it on the `g` object.
Generally speaking, each app context has its own connection to the
database; these are destroyed when the app context goes away (ie, when the
server is done handling that request).
"""
if 'db_conne... | 33d4f75aeead593a0521797ac1df07324d05cb16 | 19,459 |
def first_location_of_minimum(x):
"""
Returns the first location of the minimal value of x. The position is calculated relatively to the length of x.
:param x: the time series to calculate the feature of
:type x: pandas.Series
:return: the value of this feature
:return type: float
"""
x... | 88f7630931215f656bc99d31eea88a4f106a5faa | 19,460 |
def _positive_int(integer_string, strict=False, cutoff=None):
"""
Cast a string to a strictly positive integer.
"""
ret = int(integer_string)
if ret == -1:
return -1
if ret < 0 or (ret == 0 and strict):
raise ValueError()
if cutoff:
return min(ret, cutoff)
return ... | ecb4908fdb5223dc7301f68792c1540154931dfe | 19,461 |
def x1_0_mult(guess, slip):
"""
Compute x1_0 element-wise
:param guess: (np.array) [odds]
:param slip: (np.array) [odds]
:return: np.array
"""
return ((1.0+guess)/(guess*(1.0+slip)))/x0_mult(guess,slip) | 2c00f210c89b2a85ef40fe0adabd89c2034722e3 | 19,462 |
def get_xblock_app_config():
"""
Get whichever of the above AppConfig subclasses is active.
"""
return apps.get_app_config(XBlockAppConfig.label) | 8b937738a0c1c2c1131a37975808d249d0b06899 | 19,463 |
def remove_experiment_requirement(request, object_id, object_type):
"""Removes the requirement from the experiment, expects requirement_id (PK of req object)
to be present in request.POST"""
if request.POST:
assert 'requirement_id' in request.POST
requirement_id = request.POST['requirement_i... | 3cd0b2919bd47038cbc7f3431d552a3864395645 | 19,464 |
from typing import List
def _k_hot_from_label_names(labels: List[str], symbols: List[str]) -> List[int]:
"""Converts text labels into symbol list index as k-hot."""
k_hot = [0] * len(symbols)
for label in labels:
try:
k_hot[symbols.index(label)] = 1
except IndexError:
raise ValueError(
... | e074b55e9dae2f8aec6beb14d863f7356035705d | 19,465 |
import logging
import resource
def upload(training_dir, algorithm_id=None, writeup=None, api_key=None, ignore_open_monitors=False):
"""Upload the results of training (as automatically recorded by your
env's monitor) to OpenAI Gym.
Args:
training_dir (Optional[str]): A directory containing the res... | fbb07310bffb82b0831b08334014a33831a8714d | 19,466 |
from typing import Tuple
from typing import List
def partition_analysis(analysis: str) -> Tuple[List[FSTTag], FSTLemma, List[FSTTag]]:
"""
:return: the tags before the lemma, the lemma itself, the tags after the lemma
:raise ValueError: when the analysis is not parsable.
>>> partition_analysis('PV/e+... | e071bc5a9d624ef42ea55bb1a4ce5e612715a06c | 19,467 |
def dummy_dictionary(
dummy_tokens=3,
additional_token_list=None,
dictionary_cls=pytorch_translate_dictionary.Dictionary,
):
"""First adds the amount of dummy_tokens that you specify, then
finally the additional_token_list, which is a list of string token values"""
d = dictionary_cls()
for i... | 870456e86ddf4f98643387945f9823c0bd7cd532 | 19,468 |
def lies_in_epsilon(x: Num, c: Num, e: Num) -> bool:
"""
Функция проверки значения x на принадлежность отрезку выда [c - e, c + e].
:param x: значение
:param c: значение попадание в epsilon-окрестность которого необходимо проверить
:param e: epsilon-окрестность вокруг значения c
:return: True - ... | d7e2b4dec95859d1c5992a64d689eab4ec543001 | 19,469 |
def decimal_to_digits(decimal, min_digits=None):
"""
Return the number of digits to the first nonzero decimal.
Parameters
-----------
decimal: float
min_digits: int, minimum number of digits to return
Returns
-----------
digits: int, number of digits to the first nonzero decima... | 773cc534208fd08b66f86f8bf4fb465b9ac0a15d | 19,470 |
def lcs(a, b):
"""
Compute the length of the longest common subsequence between two sequences.
Time complexity: O(len(a) * len(b))
Space complexity: O(min(len(a), len(b)))
"""
# This is an adaptation of the standard LCS dynamic programming algorithm
# tweaked for lower memory consumption.
... | 0201e9efade98aece854e05d0910192251e5f63c | 19,471 |
def paginate_years(year):
"""Return a list of years for pagination"""
START_YEAR = 2020 # first year that budgets were submitted using this system
y = int(year)
return (START_YEAR, False, y-1, y, y+1, False, settings.CURRENT_YEAR) | 37ed9fdd6e1af69a3e404e64f6d42634ea6a0d2e | 19,472 |
def wait_for_service_tasks_state(
service_name,
expected_task_count,
expected_task_states,
timeout_sec=120
):
""" Returns once the service has at least N tasks in one of the specified state(s)
:param service_name: the service name
:type service_name: str
:par... | a19ed21a7996dcd08148727c8120596dc6bdac18 | 19,473 |
def eval_add(lst):
"""Evaluate an addition expression. For addition rules, the parser will return
[number, [[op, number], [op, number], ...]]
To evaluate that, we start with the first element of the list as result value,
and then we iterate over the pairs that make up the rest of the list, adding
or subtracti... | 5d6972ccc7a0857da224e30d579b159e89fb8dce | 19,474 |
import subprocess
def run_cmd(cmdStr):
""" 用shell运行命令,并检查命令返回值。
仔细检查cmdStr,以避免可能存在的安全问题。
"""
cmdProc = subprocess.Popen(
cmdStr,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
stdout, stderr = cmdProc.communicate()
# check command return
... | d86542e603f0e652a67ecc6c806a0d65421f2519 | 19,475 |
def is_password_valid(plaintextpw: str, storedhash: str) -> bool:
"""
Checks if a plaintext password matches a stored hash.
Uses ``bcrypt``. The stored hash includes its own incorporated salt.
"""
# Upon CamCOPS from MySQL 5.5.34 (Ubuntu) to 5.1.71 (CentOS 6.5), the
# VARCHAR was retrieved as U... | 8c2bc03bd4d0445fd157823b0e0303761d6638ea | 19,476 |
def find_item(item_to_find, items_list):
"""
Returns True if an item is found in the item list.
:param item_to_find: item to be found
:param items_list: list of items to search in
:return boolean
"""
is_found = False
for item in items_list:
if (item[1] == item_to_find[1]) and m... | acf02fbe8b1599105d86ecc6aaa98023901561c0 | 19,477 |
def validate_target_types(target_type):
"""
Target types validation rule.
Property: SecretTargetAttachment.TargetType
"""
VALID_TARGET_TYPES = (
"AWS::RDS::DBInstance",
"AWS::RDS::DBCluster",
"AWS::Redshift::Cluster",
"AWS::DocDB::DBInstance",
"AWS::DocDB::DB... | db33903e36849fb8f97efecb95f1bbfa8150ed6f | 19,478 |
def cprint(*objects, **kwargs):
"""Apply Color formatting to output in terminal.
Same as builtin print function with added 'color' keyword argument.
eg: cprint("data to print", color="red", sep="|")
available colors:
black
red
green
yellow
blue
pink
cyan
white
no-colo... | 42d0f2357da7f84404a888cf717a737d86609aa4 | 19,479 |
from sys import path
import os
def handle_authbuf(tsuite, ssh, res_type):
"""Deals with the transfer of authbuf keys. Returns True if the authbuf key needs
to be pulled after lauching this object
Args:
tsuite: tsuite runtime.
ssh: remote server connection
res_type: slash2 resource type."""
i... | 587356ee9cb02e2c4a59c9e817a651c06841fbe4 | 19,480 |
from typing import List
def clean(tokens: List[str]) -> List[str]:
"""
Returns a list of unique tokens without any stopwords.
Input(s):
1) tokens - List containing all tokens.
Output(s):
1) unique_tokens - List of unique tokens with all stopwords
removed.
"""
... | ccc0fdba6ffd3cf699ac39013631880061812f9f | 19,481 |
def validate_file_submission():
"""Validate the uploaded file, returning the file if so."""
if "sourceFile" not in flask.request.files:
raise util.APIError(400, message="file not provided (must "
"provide as uploadFile).")
# Save to GCloud
uploaded_file ... | f3636851448e26b814196a56fe56061fb9acffcf | 19,482 |
def oauth_redirect(request, consumer_key=None, secret_key=None,
request_token_url=None, access_token_url=None, authorization_url=None,
callback_url=None, parameters=None):
"""
View to handle the OAuth based authentication redirect to the service provider
"""
request.session['next'] = get_login_r... | 7e1491d6643d9610c207a2c92164c9f75526cf95 | 19,483 |
import os
def get_service_url():
"""Return the root URL of this service."""
if 'SERVICE_URL' in os.environ:
return os.environ['SERVICE_URL']
# the default location for each service is /api/<service>
return '/api/{}'.format(get_service_name()) | b844d32b582d588a795e15777ce0cac46f03e152 | 19,484 |
def render_template(content, context):
"""Render templates in content."""
# Fix None issues
if context.last_release_object is not None:
prerelease = context.last_release_object.prerelease
else:
prerelease = False
# Render the template
try:
render = Template(content)
... | e72a574b39888202e11ca51a279ff9306e4c2da3 | 19,485 |
def isJacobianOnS256Curve(x, y, z):
"""
isJacobianOnS256Curve returns boolean if the point (x,y,z) is on the
secp256k1 curve.
Elliptic curve equation for secp256k1 is: y^2 = x^3 + 7
In Jacobian coordinates, Y = y/z^3 and X = x/z^2
Thus:
(y/z^3)^2 = (x/z^2)^3 + 7
y^2/z^6 = x^3/z^6 + 7
y^2 = x^3 + 7*z^6
"""
fv... | 87ecd5d9c42d9a27cd40c49a6034c73a5f784855 | 19,486 |
def decode_base85(encoded_str):
"""Decodes a base85 string.
The input string length must be a multiple of 5, and the resultant
binary length is always a multiple of 4.
"""
if len(encoded_str) % 5 != 0:
raise ValueError('Input string length is not a multiple of 5; ' +
... | 0cae86ac35cce55afdbbb6d48b86af3fb05eaf8f | 19,487 |
def process_doc(doc: PDFDocument):
"""Process PDF Document, return info and metadata.
Some PDF store infomations such as title in field info,
some newer PDF sotre them in field metadata. The
processor read raw XMP data and convert to dictionary.
Parameters
----------
doc : PDFDocument
... | fc8e4df6d00a4afb23a2693a4222b1809e7a8d6c | 19,488 |
def score_lin_reg(est, X, y, sample_weight=None, level=1):
"""
Scores a fitted linear regression model.
Parameters
-----------
est:
The fitted estimator.
X: array-like, shape (n_samples, n_features)
The test X data.
y_true: array-like, shape (n_samples, )
The true ... | 855c93e03dbcd30929e08e3b00670c9ba1755fb8 | 19,489 |
from typing import List
def select_questions(db: Database) -> List[Row]:
"""
Selects a list of 20 questions from the database using a spaced-repetition
algorithm.
The questions are drawn from 3 quizzes in a set ratio: 10 from the first quiz, 7
from the second, and 3 from the third.
The quizz... | b4c624e3fc7c3e1dc9962a77fb2238d97737fa43 | 19,490 |
def process_ona_webhook(instance_data: dict):
"""
Custom Method that takes instance data and creates or Updates
an Instance Then Returns True if Instance was created or updated
"""
instance_obj = process_instance(instance_data)
if instance_obj is None:
return False
return True | dabb1d81cbb91e0484ec66c101d7f1019fe08edc | 19,491 |
import torch
def test_quantized_conv2d_nonfunctional():
"""Basic test of the PyTorch quantized conv2d Node with external quantized
input on Glow."""
def test_f(a):
q = torch.nn.quantized.Quantize(1/16, 0, torch.quint8)
dq = torch.nn.quantized.DeQuantize()
conv = torch.nn.quantized... | 316cf6e8abbea810ec02a3dd94eccbc050e3915d | 19,492 |
import math
def distance(v, w):
"""the distance between two vectors"""
return math.sqrt(squared_distance(v, w)) | 301e98d6c2bb8b5e10ae7efd9fa65abd375d048f | 19,493 |
def createLayerOnSimFrameDepend(job, layer, onjob, onlayer, onframe):
"""Creates a layer on sim frame dependency
@type job: string
@param job: the name of the dependant job
@type layer: string
@param layer: the name of the dependant layer
@type onjob: string
@param onjob: the name of the job... | ad702b12676a493cc65c2252821328c431e6618e | 19,494 |
def QA_SU_save_stock_min_5(file_dir, client=DATABASE):
"""save stock_min5
Arguments:
file_dir {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
Returns:
[type] -- [description]
"""
return tdx_file.QA_save_tdx_to_mongo(... | 85cfeeebf7673cfb6ee6957f29e8a3185ec14da2 | 19,495 |
def get_course_by_name(name):
""" Return a course dict for the given name, or None
{ 'id':id, 'name':name, 'title':title }
"""
ret = run_sql(
"""SELECT course, title, description, owner, active, type,
practice_visibility, assess_visibility
FROM courses
... | 78485e616f42aabe095eaeff687ad9dab94c1dad | 19,496 |
import platform
import socket
import os
def make_nailgun_transport(nailgun_server, nailgun_port=None, cwd=None):
"""
Creates and returns a socket connection to the nailgun server.
"""
transport = None
if nailgun_server.startswith("local:"):
if platform.system() == "Windows":
pi... | 2bf92c174063352175f0b0d22021c6532bc144d8 | 19,497 |
import re
from datetime import datetime
def timedelta(string):
"""
Parse :param string: into :class:`datetime.timedelta`, you can use any
(logical) combination of Nw, Nd, Nh and Nm, e.g. `1h30m` for 1 hour, 30
minutes or `3w` for 3 weeks.
Raises a ValueError if the input is invalid/unparseable.
... | 664dfb9e46017b507d04174da94d6da8a542fb31 | 19,498 |
def englishTextNull(englishInputNull):
"""
This function returns true if input is empty
"""
if englishInputNull == '':
return True | 2ad18e38f474a164a21bdc790bee05c2a8e06e89 | 19,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.