content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def fib_iterative(n: int) -> int:
""" Find the n-th fibonacci number by iteration using Dynamic Programming"""
curr: int = 1
prev: int = 1
for i in range(2, n):
prev, curr = curr, curr + prev
return curr | 18d407bcd25a32407b42c497d6dee1dadeba421b | 3,597,212 |
import ctypes
def crc16Calc(Data, StartElement, Len):
""" Calculates 2 Byte CRC """
crc16Table = [0x0000,0x1021,0x2042,0x3063,0x4084,0x50a5,0x60c6,0x70e7,\
0x8108,0x9129,0xa14a,0xb16b,0xc18c,0xd1ad,0xe1ce,0xf1ef,\
0x1231,0x0210,0x3273,0x2252,0x52b5,0x4294,0x72f7,0x62d6,\
0x9339,0x8318... | 4fca47d528e441d3a0fb104b7705192163987588 | 3,597,213 |
def adjustSize(imageSize, targetSize):
"""-> the size (x,y) the image must be scaled to in order to fit into the
target size, while keeping the aspect ratio.
"""
sx, sy = imageSize
tx, ty = targetSize
x = tx
y = sy * tx / sx
if y > ty:
y = ty
x = sx * ty / sy
return x... | 32e18fbb34864e630c19d1d689cfb28de28ff503 | 3,597,214 |
def get_log_level():
"""Set global low level log level"""
return _log_level | 0004bee29bbecad372e4a60eaa112b0a25c0c84b | 3,597,215 |
def unique_orderid(df, topn):
"""
Считает количество уникальных заказов для каждого продукта из topn.
:param df: объединенный фрейм
:param topn: число самых популярных продуктов для вывода
:return: массив количества уникальных заказов для каждого продукта из topn
"""
return np.array([df[df[... | ccf719a79ce7a13cdc0a0190c751d23b657115c6 | 3,597,216 |
import operator
def length_hint(a: protocols.SupportsLengthHint, default: int = 0) -> int:
"""
Return an estimated length for the object o. \
First try to return its actual length, then an estimate \
using `a.__length_hint__()`, and finally return the default value.
Example:
>>> length_hi... | 155b98395ffc1de2aa890f3bfd1cc122b0095c8c | 3,597,217 |
def create_file_structure(experiment_path):
""" Creates the folder structure for a new experiment. """
fu.ensure_dir(experiment_path)
return _apply_file_structure(experiment_path, _create_subfolder) | 1c2b63a12b5feeefe450d235d4ffeedd501a3353 | 3,597,218 |
def sha2_256(data: bytes) -> hashes.MessageDigest:
"""
Convenience function to hash a message.
"""
return HashlibHash.hash(hashes.sha2_256(), data) | 8e27080064268632a36894d5b19382eb8e87f242 | 3,597,219 |
def make_mask_image(mask, slc, rotate, alpha):
"""Turn a single slice of a binary mask into an RGBA image."""
m = mask.get_fdata()
mask_as_rgba = np.zeros([m.shape[0], m.shape[1], 4], dtype=np.uint8)
mask_as_rgba[m[:, :, slc] > 0, 0] = 255
mask_as_rgba[m[:, :, slc] > 0, 3] = int(255 * alpha)
if ... | fad9d7697e43ad1827d6c38d6b8aec3801039169 | 3,597,220 |
from mir_eval.segment import tree
def process(in_path, boundaries_id, labels_id=None, ds_name="*",
annot_beats=False, framesync=False, feature="hpcp", hier=False,
save=False, n_jobs=4, annotator_id=0, config=None, plot=False):
"""Main process.
Parameters
----------
in_path : str
Path to the dataset root ... | d4782a1052ca087f7c42b8f321ee13c642d1a9cf | 3,597,221 |
def vcoord(filename):
"""compute the vertical coordinate in space and time for a given file"""
na=np.newaxis
a = mygis.read_nc(filename,"lev").data[na,:,na,na]
b = mygis.read_nc(filename,"b").data[na,:,na,na]
orog= mygis.read_nc(filename,"orog").data
z= a+b*orog
return z | b25ee6a9b8a493df62ccb5a9a285aec4d64ad2ec | 3,597,222 |
from typing import get_args
def _build_lambada_dataset():
"""Build lambada dataset."""
args = get_args()
tokenizer = get_tokenizer()
assert len(args.valid_data) == 1
val_dataset = _LambadaDataset(args.valid_data[0], tokenizer.eod, tokenizer,
args.seq_length, args... | f9d777cc6dcec6e273cd71ac853e0b9b3a60b32a | 3,597,223 |
def get_task_type_by_name(task_type_name, client=default):
"""
Args:
task_type_name (str): Name of claimed task type.
Returns:
dict: Task type object for given name.
"""
return raw.fetch_first(
"task-types", {"name": task_type_name}, client=client
) | 097aa0ad70f81275f0af47762ecf930b7c98b7dd | 3,597,224 |
import re
def AutoscalersForMigs(migs, autoscalers):
"""Finds Autoscalers with target amongst given IGMs.
Args:
migs: List of triples (IGM name, scope type, location reference).
autoscalers: A list of Autoscalers to search among.
Returns:
A list of all Autoscalers with target on mig_names list.
"... | 52f809794395ba6ed31b94bed36dc9f4de8ce919 | 3,597,225 |
from typing import Tuple
import base64
import binascii
async def _basic_authentication(
encoded: bytes, idp: IdentityProvider
) -> Tuple[User, Claims]:
"""Authentication using Basic scheme.
"""
try:
decoded = base64.b64decode(encoded)
except binascii.Error:
raise web.HTTPUnauthoriz... | cb43844ae3d557e2ef53d128f8e6922babb5d3f2 | 3,597,226 |
def activation_std(X, threshold):
"""
The standard deviation of the durations of actived durations
"""
if type(X) == pd.DataFrame:
X = X.values
thres_X = X >= threshold
cumsum_X = np.cumsum(thres_X, axis=0)
thres_X_num = thres_X.astype(np.float64)
rise_marker_X = np.diff(
... | a54af0e3be759144555075adf75abc971e7416e6 | 3,597,227 |
def normalize_mode(mode):
"""
Return a mode value, normalized to a string and containing a leading zero
if it does not have one.
Allow "keep" as a valid mode (used by file state/module to preserve mode
from the Salt fileserver in file states).
"""
if mode is None:
return None
if... | 66d58de58eb9f0e77e2fa75253cfeef3ee1abe2c | 3,597,228 |
def genotype_call_with_read_pair(concordant, discordant, std_depth):
"""
Genotype call based on total depth of concordant and discordant reads a la
Hormozdiari et al. 2010 (Genome Research).
"""
#homozygous_deletion_threshold = std_depth
homozygous_deletion_threshold = 5
if concordant < hom... | 971bc1e98de51b2af02c79efb3bc7492c4290c92 | 3,597,229 |
def n_days(D, M, Y, system="old"):
"""
January 1, 1 = day 0
"""
if system == "old":
leap = Y % 4 == 0
output = 0
output += 365 * (Y - 1) + (Y - 1) // 4
output += n_days_accum[M - 1] + 1 if (leap and M > 2) else n_days_accum[M - 1]
output += D - 1
return ou... | e770869d047742f3d1b08a67bf7ef423661bf301 | 3,597,230 |
import math
def relu_density_logit(x, reduce_dims):
"""logit(density(x)).
Useful for histograms.
Args:
x: a Tensor, typilcally the output of tf.relu
reduce_dims: a list of dimensions
Returns:
a Tensor
"""
frac = tf.reduce_mean(tf.to_float(x > 0.0), reduce_dims)
scaled = tf.log(frac + math... | d54c89e1b0a79eb65b9e6fb4517bd1f913ff186c | 3,597,231 |
import math
def spherical_index_lm(k):
""" returns the degree l and the order m from the mode k """
l = int(math.floor(math.sqrt(k)))
return l, k - l*(l + 1) | de00ebda16ad2480b32a5d827351bb43ec858e42 | 3,597,232 |
def filter_mesos_slaves_by_blacklist(slaves, blacklist: DeployBlacklist, whitelist: DeployWhitelist):
"""Takes an input list of slaves and filters them based on the given blacklist.
The blacklist is in the form of:
[["location_type", "location]]
Where the list inside is something like ["region", "... | cd1766866d7c8f6ffef6ca1b6cc8919039712862 | 3,597,233 |
async def dep_access_token(authorization: str = Header(None)) -> str:
"""Parse and return an access token provided in the authorisation header."""
access_token = parse_access_token(authorization)
if not access_token:
raise UnauthorizedException(log=False)
return access_token | 874cbc6d264724edc4e4be39d9dc34870b4a4be0 | 3,597,234 |
def announcement() -> models.Announcement:
"""Announcement factory for creating announcements.
Returns:
(Announcement): Announcement object
"""
return AnnouncementFactory() | 8c68203a2bfaac2ee1cc8047293c41a2f4a5f95b | 3,597,235 |
def fitness(x):
"""
A dummy fitness function. Find a solution with mean 15.
"""
return np.abs(15.0 - np.mean(x)) | 1fa53fa098e5173178e73ebc8ee617f48cc09c7f | 3,597,236 |
def average_gradients(tower_grads):
"""Calculate the average gradient for each shared variable across all towers.
Note that this function provides a synchronization point across all towers.
Args:
tower_grads: List of lists of (gradient, variable) tuples. The outer list
is over individual gra... | 0773da13a9afe1e3b263ddbbe32343846eb3761c | 3,597,237 |
def exercise_submit_row(context):
"""
Displays the row of buttons for delete and save.
"""
opts = context["opts"]
change = context["change"]
is_popup = context["is_popup"]
save_as = context["save_as"]
has_copy_permission = False
original = context["original"]
user = context["use... | 7d2c017092458efab65576c1392ba4dfffaadec9 | 3,597,238 |
import base64
import six
def xor_cipher_encrypt_base64(text, key):
"""Encrypts the UTF-8 encoded representation of the text using an
XOR cipher using the key. The key can be a byte array generated
using xor_cipher_genkey() or an appropiate string of the correct
type and composition, in which case if w... | ddc4cfeea879137ec3a56784501ca6e75d3d31f4 | 3,597,239 |
from typing import List
from typing import Tuple
def tag(words: List[str], corpus: str) -> List[Tuple[str, str]]:
"""
รับค่าเป็น ''list'' คืนค่าเป็น ''list'' เช่น [('คำ', 'ชนิดคำ'), ('คำ', 'ชนิดคำ'), ...]
"""
if not words:
return []
if corpus == "orchid":
i = 0
words = tag... | d34c5f2fe44256f03025dbee33f64b9330b0a399 | 3,597,240 |
def EVBMF(tensor, sigma2=None, H=None):
"""
Implementation of the analytical solution to Empirical Variational Bayes
Matrix Factorization.
This function can be used to calculate the analytical solution to empirical
VBMF. This is based on the paper and MatLab code by Nakajima et al.:
"Global ana... | fe4445acdc96d82f7381b6cf826c79d57f7e8304 | 3,597,241 |
def _ddx(t, x, ivp):
"""If Jacobian is available:
x''(t) = J_f(x(t)) @ f(x(t))
Else it just returns zero.
"""
try:
jac = ivp.jacobian(t, x)
except NotImplementedError:
jac = np.zeros((len(x), len(x)))
evl = ivp.rhs(t, x)
if np.isscalar(evl) is True:
evl = np.arra... | dfb9f10b4ce8661ea35823d8e984d1d55bd93da4 | 3,597,242 |
import ipaddress
def _get_available_ip_in_ip_ranges(ip_ranges: list, used_ips: set):
"""Get an available ip from the passed in ip ranges.
:param list ip_ranges: list of dictionaries, each containing a start and
end ip address
:param set used_ips: set of used ips.
:return: available ip. Empt... | 395aeca853d82ef11126faaff5023869d45a4bbe | 3,597,243 |
def is_date(string, fuzzy=False):
"""
Return whether the string can be interpreted as a date.
:param string: str, string to check for date
:param fuzzy: bool, ignore unknown tokens in string if True
"""
try:
parse(string, fuzzy=fuzzy)
return True
except ValueError:
r... | 7175ba67c0d9198d0407d45355519e249c3a6b6b | 3,597,244 |
from typing import Tuple
def process_node_to_actinia_process_chain(node: Node) -> Tuple[list, list]:
"""This function calls the openEO process node to actinia process chain
converter process based on the node process_id.
It will gather the actinia process chain and the output identifier of the
proces... | cefaad83e87d1221d32594ea8b44614b0557ae3a | 3,597,245 |
def dialogflow_error_response(message, error):
"""Return a response saying the error message."""
dialogflow_response = DialogflowResponse(message['result']['parameters'])
dialogflow_response.add_speech(error)
return dialogflow_response.as_dict() | 759739b6d2a902f28db390b1fb54fcc94b63a7a7 | 3,597,246 |
import torch
def hamming_distance(input1, input2):
"""Computes hamming distance.
Args:
input1 (torch.Tensor): 2-D feature matrix. {0, 1}.
input2 (torch.Tensor): 2-D feature matrix. {0, 1}.
Returns:
torch.Tensor: distance matrix.
"""
input1 = input1.to(torch.int)
input... | 7287c0f322b4632f04486430990b9fd819bddc98 | 3,597,247 |
from datetime import datetime
def parse_k8s_timestamp(timestamp: str) -> datetime.datetime:
"""Get date/time in UTC from k8s timestamp"""
fmt = "%Y-%m-%dT%H:%M:%SZ"
naive = datetime.datetime.strptime(timestamp, fmt)
return naive.replace(tzinfo=datetime.timezone.utc) | bb70bd35adeb253d0eb670915c299ddaa0dd77fc | 3,597,249 |
import numpy
from typing import List
def decircularize(obj, readtable):
"""Return a structure that is similar to OBJ, but where each circularity
has been replaced by appropriate SharpsignEquals and SharpsignSharpsign
instances.
"""
# Phase 1: Scan the data and number all circular objects.
table = {}
... | 5567375f36f4f475e28d9cd878b7ab8da11087ee | 3,597,250 |
def main():
"""instantiate and launch the application"""
shell = Shell()
last_result = shell.loop()
return last_result.exit_code | 1d6b2cd6f649f48c5008d144c015fdf9453f3a0f | 3,597,251 |
import collections
def count_corpus(tokens):
"""统计词元的频率。"""
# 这里的 `tokens` 是 1D 列表或 2D 列表
if len(tokens) == 0 or isinstance(tokens[0], list):
# 将词元列表展平成使用词元填充的一个列表
tokens = [token for line in tokens for token in line]
return collections.Counter(tokens) | 058c4735526043dc38bb98113c53b1601e4fb5e7 | 3,597,252 |
import urllib
def convertHPURL(files):
"""
convert file to NZMATH homepage address.
"""
return urllib.parse.urlunsplit( ('http', HPpla, HPdoc + files, '', '') ) | 00c896e9423b859fe709ca14639c83dd4b673d45 | 3,597,254 |
def get_generic_fields():
"""Return a list of all GenericForeignKeys in all models."""
generic_fields = []
for model in apps.get_models():
for field_name, field in model.__dict__.items():
if isinstance(field, GenericForeignKey):
generic_fields.append(field)
return gen... | 6a35cc649fb4e31367f21a97119264bdb5d8f644 | 3,597,255 |
def get_blocks(fname):
"""Get blocks of the diff that can be independently filtered."""
with open(fname, 'r') as fh:
lines = iter(fh.readlines())
parts = []
line = next(lines)
while True:
if line.startswith('diff --git'):
block = [line]
... | 902d897b85794711184cb50bd8a308bd980620d6 | 3,597,256 |
def Standardization(img):
""" normalize image input """
img = img.astype(np.float32)
var = np.var(img, axis=(0, 1), keepdims=True)
mean = np.mean(img, axis=(0, 1), keepdims=True)
return (img - mean) / (np.sqrt(var) + EPSILON) | dac0ccfeabb6875103aa9b2d8ccf1bb0c4428461 | 3,597,257 |
from unittest.mock import patch
def bagxml(monkeypatch):
"""
Test fixture that patches the following functions.
open()
bagatom.getBagTags()
bagatom.getOxum()
"""
m = mock_open(read_data=BAGIT_CONTENTS)
monkeypatch.setattr('codalib.bagatom.getBagTags', lambda x: {})
mo... | 4251616cef1c26e62adf7616249c96896b6586a3 | 3,597,258 |
def get_phase_average(x, period_ind=None,
time=None, freq=None, nbins=100,
axis=-1, return_std=True, use_masked_array=True):
"""
Returns phase average of a ND array (generalization of get_average_data_from_periodic_data)
... Assume x is a periodic data, and you ar... | bc4f2a9c1f6920f251255dca88ceed9be98252a7 | 3,597,259 |
def get_outcomes(context, context_id, group_id):
""" return a list of outcomes
calls get_outcome() for full outcome, as get_outcome_links() returns outcome links with abbreviated outcomes """
links = get_outcome_links(context, context_id, group_id)
return [get_outcome(link['outcome']['id']) for link... | d51d671942b256feaf2ff9ba9a71a325dda1a44c | 3,597,261 |
from typing import Callable
from typing import Any
from typing import List
def parallel_map(fn: Callable[[Any], Any], inputs: List[Any], num_thread: int):
"""Applies a function to a list of inputs in parallel.
Uses a Threading pool to process inputs in parallel.
Args:
fn: A `Callable` function t... | df09382f88903dc976af64cd0ce9d4e8fd63ee01 | 3,597,262 |
def t3ModelKdV(alpha,F_modes,G_modes,k,epsilon,u_full,uu,uuStar,uk3,A,AStar,B,BStar,C,CStar,DStar):
"""Computes third order ROM term in KdV
*see paper / symbolic notebook for expression*
Computed in real space to avoid loops and then converted back
to Fourier space.
Parameters
---... | da38a0bcdd3c0feee328d061e238810d3dabb881 | 3,597,263 |
from functools import reduce
import operator
import io
def __indent__(rows, hasHeader=False, hasUnits=False, headerChar='-', delim=' | ', justify='left',
separateRows=False, prefix='', postfix='', wrapfunc=lambda x: x):
"""Indents a table by column.
INPUTS:
rows [sequence or sequences o... | 1fe2403a3b5881b9ad9a7760d33263eb8ff45aa0 | 3,597,264 |
def from_camel_case(name):
"""Convert camel case to snake case.
Function and variable names are usually written in camel case in C++ and
in snake case in Python.
"""
new_name = str(name)
i = 0
while i < len(new_name):
if new_name[i].isupper() and i > 0:
new_name = new_na... | c6e7184598252a6db1bcaee5d5375969c5c9bd39 | 3,597,265 |
import json
def msg_post_kafka(msg,
topic,
is_json=True,
host='localhost:9092',
key=None,
close=True
):
"""
Function to send msg to kafka under the topic
:param msg: message to be send
:p... | 2bcb9d863a483adb63d2ce4d841a90b8f576d7e1 | 3,597,267 |
def multi_bracket_validation(string):
"""Check for balanced brackets."""
open_bracket = Stack()
for item in string:
if item in ('{', '[', '('):
open_bracket.push(item)
elif item in ('}', ']'):
if chr(ord(item) - 2) != open_bracket.pop():
return False
... | 32bffc9669a91af0cd65b788dc304d6675699a64 | 3,597,268 |
import json
def binlog_list(request):
"""
获取binlog列表
:param request:
:return:
"""
instance_name = request.POST.get('instance_name')
try:
instance = Instance.objects.get(instance_name=instance_name)
except Instance.DoesNotExist:
result = {'status': 1, 'msg': '实例不存在', 'da... | 9b37abfbaa8d0bef237df904d6a14aa0383f5199 | 3,597,269 |
def get_jacobian_imu(x):
"""Imu measurement jacobian"""
H = np.zeros((2, 5))
H[0, 2] = x[4]
H[0, 4] = x[2]
H[1, 4] = 1
return H | d977b8ff3d4e36938c900e25e6356772b7a56d03 | 3,597,270 |
def FilterComputers(item):
""" filters an ASSET CONTROL generated csv list for computer-like items """
return not FilterInven(item) | ca6183ce27f54fd6f9e96bb3ebaf8d37d6b01241 | 3,597,271 |
from typing import Optional
def end_of_input(parse_state: ParseState) -> Optional[Parsing]:
"""Match the end of text, return a value of None."""
if len(parse_state.text) == parse_state.pos:
return Parsing(None, parse_state)
return None | 6d8d977de8261a2eb0a95b592271dc84267a1332 | 3,597,273 |
def molecule2stateTuples(molecule):
"""
Receives a molecule structure, returns a tuple detailing the state of the contained states
"""
tupleList = []
for component in molecule.components:
componentDefinition = [component.name]
componentDefinition.append(1 if len(component.bonds) > 0 ... | 2cc19579e640c5099201e1d3da43ad56641f29d0 | 3,597,274 |
def create_user_json_from_screen_names(twitter_api, screen_names):
"""Gets the User json objects from Twitter for the given screen_names"""
user_json = []
start = 0
length = len(screen_names)
end = length if length < USER_LIMIT else USER_LIMIT
while start < length:
user_json += twitter_a... | 5e3c2533ba305deb679248775df218a6493b9c9b | 3,597,276 |
import time
def time_to_micros(time_str: str) -> int:
"""Converts an ISO-8601 formatted time to microseconds from midnight"""
t = time.fromisoformat(time_str)
return (((t.hour * 60 + t.minute) * 60) + t.second) * 1_000_000 + t.microsecond | 28fe94bdb0cf69d01d2e4f549ca72e25b815fd21 | 3,597,277 |
import pickle
import torch
def any_broadcast(data, root_rank):
"""broadcast arbitrary data from root_rank to all nodes."""
enc = pickle.dumps(data)
max_size = hvd.allgather(torch.tensor([len(enc)]).cuda()).max().item()
buffer_, enc_byte = _encode(enc, max_size, use_max_size=True)
hvd.broadcast_(... | dc978b0eefa0132bc044365fd67aa71c407485ba | 3,597,278 |
import torch
import math
def gaussian_tc(mu, logsigma, dset_size=1, eps=1e-9):
"""Compute the TC term KL(q(z) || prod_i q(z_i)) using minibatch-weighted sampling.
Reduces to 1/M sum_i^M log(sum_j^M q(z^(i) | x_j)) - log(NM) where z^(i) ~ q(z|x_i)
Arguments:
mu (torch.Tensor): Mean. Expec... | e5f84dcd232be40ab8bf0b0f5bc8b3262070ee4f | 3,597,279 |
def update_release(id, **kwargs):
"""
Update an existing ProductRelease with new information
"""
to_update = utils.checked_api_call(releases_api, 'get_specific', id=id).content
for key, value in iteritems(kwargs):
if value is not None:
setattr(to_update, key, value)
response... | 5a606239152a24a9ff7286e6016b2df24026c37c | 3,597,281 |
def is_v2_component(op: _container_op.ContainerOp) -> bool:
"""Determines whether a component is a KFP v2 component."""
if not isinstance(op, _container_op.ContainerOp):
return False
component_spec = op._metadata
return (component_spec and component_spec.metadata and
component_spec... | 1e0b06072eea6ae25e2b7019887fa0bfd878ed3e | 3,597,282 |
def PatternListToStr(pattern):
"""Return a pattern string for the given list of integers.
PatternListToStr([5,3,1]) -> '531'
"""
return ''.join([chr(p) for p in pattern]) | d42f06204f3b4c6fa3badb45d5755614554b3f9b | 3,597,284 |
def crf_kernel_config(defn):
"""Creates a default kernel configuration for sampling the dish assignment
using the "Posterior sampling in the Chinese restaurant franchise" Gibbs
sampler from Teh et al (2005)
Parameters
----------
defn : LDA model definition
"""
return ['crf'] | f5d874d62c9c858115cc32dc6ee193c13a7b0eb7 | 3,597,285 |
from operator import inv
def to_weierstrass(pt, curve):
"""Given a point P and an Montgomery Curve it is on, computes the equivalent point and curve
in weierstrass form.
Note: Multiple calls for same curve with different P will produce different output curves.
This is due to y-coordinates being omitt... | 6c7cf4684aa99db8e445627321577488d94b01eb | 3,597,286 |
import copy
def exact_to_2nd_order_model_layer_avg(model, layer_to_avg=3):
"""Convert LeNet model training on exact augmented objective to model
training on 2nd order approximation, but approximation is done at different
layers.
"""
model_2nd = copy.deepcopy(model)
model_2nd.approx = True
... | becf33033b93bac6d3e78e4f35881222ae554d75 | 3,597,287 |
def read_city_data(path):
""" Maps the neighborhoods of the city from the provided data
so each entry contains a map between the neighborhood and the
polygon delimiting it """
raw_cities = read_json(path)
cities = {}
for n in raw_cities['features']:
coords = np.array([c for c in n['geome... | 081cb7fadd4fd81b54a1b44a6cb3a495f4ad420d | 3,597,288 |
import re
def search_by_regex(nodes: list, option: int, regex: str) -> list:
"""
Return all :param regex matched values from :param nodes at :param option index.
:param nodes: list of nodes.
:param option: Index in the nodes list(check constants at the start of this file).
:param regex: Pattern t... | 3a045c324dd333157a6de036ed7affd11a91b6a0 | 3,597,289 |
def get_channel_information(channel_handle: c_void_p) -> ChannelInformation:
"""DMD Reader API Get channel information"""
channel_information = DmdChannelInformation()
error_code = _DMDReader_GetChannelInformation(channel_handle, byref(channel_information))
_check_error(error_code)
return ChannelInf... | 1846ddd7354e5049d5e3473e0c6a19a95154cf45 | 3,597,290 |
def get_retention_policy(interval, retention_policies):
"""Get appropriate retention policy for interval provided
:param interval: Interval of query in seconds
:type interval: int
:param retention_policies: Retention policy configuration
:type retention_policies: dict(max time range of interval
... | dc1e2358d715cadbcd5275240203fe20a50c1cc9 | 3,597,291 |
def media_list(request, source):
"""Implements a generic list view function.
Given a SQLAlchemy query result and the request that triggered this
view render, this function will return the appropriate view context
dictionary for a list page.
The view takes one GET parameter, 'page', which defaults ... | e8f91446dc441f4231f6bf93c0a429e47d8d681b | 3,597,292 |
def get_structure_mask(image_id, structure_id, margin=None):
"""Load or generate a structure mask array
mask file is guaranteed to exist since it is always created in structure_insert()
** No margin is ever saved into the mask file. It needs to be added every time if requested
"""
imagedoc = get_do... | 0b08a388bab6737c2b57087f5afc0a2dd450c6b8 | 3,597,293 |
def is_boolean(value):
"""
Check if the value represents a boolean.
>>> vtor.check('boolean', 0)
0
>>> vtor.check('boolean', False)
0
>>> vtor.check('boolean', '0')
0
>>> vtor.check('boolean', 'off')
0
>>> vtor.check('boolean', 'false')
0
>>> vtor.check('boolean'... | b7294b20bbe5b577868f1efed8665f6a6c9dbe92 | 3,597,294 |
def set_part_base_plane(part):
"""returns an alinged plane at (U.5,V.5) of a planar surface"""
x = True
if x == True:#rs.IsPlaneSurface(part):
normalizedParameter = (.5,.5)
frameParameter = rs.SurfaceParameter(part,normalizedParameter)
frame = rs.SurfaceFrame(part,frameParameter)
... | 5ea8a2c69338a424000521d644329ec1bc68d4c8 | 3,597,295 |
def analysis_get_headerdata(analysis):
"""Obtains the headerdata from an OpticStudio analysis.
Parameters
----------
analysis: Any
An OpticStudio Analysis.
Returns
-------
list
The headerdata.
"""
return list(analysis.Results.HeaderData.Lines) | b84f11e1503d3181edecb8ab1c4cae7fd535d0be | 3,597,296 |
def create_bowtie(qgene,sgene,slope,qpad,spad):
"""returns bowtie"""
EXP = EXPON
if abs(abs(qgene[1] - qgene[0]) - abs(sgene[1] - sgene[0])) > 3000:
EXP = 0.94
rngx = qgene[1] - qgene[0]
rngy = abs(sgene[1] - sgene[0])
center = sum(qgene)/2., sum(sgene)/2.
intercept = center[1]... | 4b275abd3f2ade52b3bbeb526fc3b132d9b6c0b5 | 3,597,297 |
def get_content(viewmodel: ViewModelGetEntries) -> str:
"""出力文字列の取得."""
content = f'{viewmodel.name}産駒の出走予定\n'
if viewmodel.entries:
for date, group in groupby(viewmodel.entries, lambda x: x.date):
content += f'\n{date.strftime("%m/%d")}\n'
for race, group2 in groupby(group,... | 165b3403ee462c37b7c0e5b1120c21341de2b062 | 3,597,298 |
from datetime import datetime
def get_users_settings(user_ids):
"""Gets domain objects representing the settings for the given user ids."""
user_settings_models = user_models.UserSettingsModel.get_multi(user_ids)
result = []
for ind, model in enumerate(user_settings_models):
if user_ids[ind] =... | 10fd5cea0800cfdd6d0a8d6a26f60ffe6e2fdb2e | 3,597,299 |
def build_invalid_data_managers_folder( trans, folder_id, data_managers, error_messages=None, label=None ):
"""Return a folder hierarchy containing invalid Data Managers."""
if data_managers or error_messages:
if label is None:
label = "Invalid Data Managers"
data_manager_id = 0
... | f5b1b09f49a70fc252656ffd9e0164845b3c839a | 3,597,300 |
import warnings
def extract_cube_at_time(cubes, time, time_extract):
"""
Extract a single cube at a given time from a cubelist.
Args:
cubes (iris.cube.CubeList):
CubeList of a given diagnostic over several times.
time (datetime.datetime object):
Time at which forec... | 24f6019f8a01a8d4b9c8f66c18c94eaee4f3077e | 3,597,301 |
def param_split_sentences():
"""Parametrize `test_split_sentences`"""
names = 'samp'
vals = get_samples(['sentence_short', 'sentence_list', ] + SAMPLES)
ids = get_sample_ids(['sentence_short', 'sentence_list', ] + SAMPLES)
return parametrize(names, vals, ids) | 55481de6c26520138fd4103f08cd485395857d23 | 3,597,302 |
from typing import Dict
from typing import List
def _outer_comma_and_pipe_indices(s: str) -> Dict[str, List[int]]:
"""Return any indices of ',' and '|' that are outside of braces."""
indices = {OR: [], COMMA: []}
brace_dict = {OPEN_BRACKET: 1, CLOSE_BRACKET: -1}
brace_count = 0
for i, char in enu... | c1378cc48e10680a8db4fb810ff5fca30ec374a9 | 3,597,303 |
import string
def generate_passwd():
"""[summary]
The function randomly generates a password.
[description]
This function generates randomly a password from ascii letters and digits. The length of password is limitted from PASSWD_MIN_LEN to PASSWD_MAX_LEN
Returns:
[type: String] -- [description: a generated ... | d82ef0c21ca54095cd2b61952ca69c2d5f139eaa | 3,597,304 |
def url_check(url):
"""
Expects a string as argument.
Retruns True , if URL is valid else False.
For detailed docs look into urlparse.
"""
min_attr = ('scheme' , 'netloc')
try:
result = urlparse(url)
if all([result.scheme, result.netloc]):
return True
else:
return False
except:
return False | b19eb9c401477f36096e24c3385d29df62a829e8 | 3,597,306 |
def _phi(r, order=2, epsilon=0.0000000001):
"""Coordinate-wise nonlinearity used to define the order of the
interpolation.
See https://en.wikipedia.org/wiki/Polyharmonic_spline for the definition.
Args:
r: input op
order: interpolation order
Returns:
... | a96c0cc372af0618b4fe6e3f87f5b3da96400fed | 3,597,307 |
def ProcessToken(sentence):
"""
Tokenize, remove stopwords, and get lemma of a given sentence.
Input:
sentence -- a string.
Output:
cleaned tokens.
"""
en_stop = set(nltk.corpus.stopwords.words("english"))
tokens = Tokenize(sentence)
clean_tokens = []
for token in tokens:
... | 1160850444a6958b2388103da29923ab7559fbbc | 3,597,308 |
def wc_accelerated_gradient_strongly_convex(mu, L, n, verbose=1):
"""
Consider the convex minimization problem
.. math:: f_\\star \\triangleq \\min_x f(x),
where :math:`f` is :math:`L`-smooth and :math:`\\mu`-strongly convex.
This code computes a worst-case guarantee for an **accelerated gradient... | 06e737eca2c9105c0ed2cb5ac1a72065bf9ba525 | 3,597,309 |
from typing import Callable
from typing import Union
from typing import Tuple
from typing import Any
from typing import cast
def staged(
func: Decoratee,
) -> Callable[..., Union[Tuple[Any, Completion], Intermediate]]:
"""Transform a two stage computation into a result and a completion function."""
def s... | 84d8270180a67a11f83a956e0040716acfa81628 | 3,597,310 |
import numpy
def pixels3d (surface):
"""pygame.numpyarray.pixels3d (Surface): return array
reference pixels into a 3d array
Create a new 3D array that directly references the pixel values in a
Surface. Any changes to the array will affect the pixels in the
Surface. This is a fast operation since... | 2bfd880b6438bfe31a665d83b875957634ec0525 | 3,597,311 |
def _estimator(fdist, bins):
"""
Default estimator function using WB.
"""
# can't be an instance method of NgramModel as they
# can't be pickled either.
res=WittenBellProbDist(fdist,fdist.B()+1)
res.check()
return res | 22ece7fbf831ae7c22d991f3817f4ca6c0046326 | 3,597,312 |
import re
def FindChromeUprevCandidate(stable_ebuilds, chrome_rev, sticky_branch):
"""Finds the Chrome uprev candidate for the given chrome_rev.
Using the pre-flight logic, this means the stable ebuild you are uprevving
from. The difference here is that the version could be different and in
that case we wan... | 70c29d2c2df3dfacecb2d2669d2b4a4cb9e6feef | 3,597,313 |
import json
def aws_iot_core_get_all_certificates(detail=False):
"""
returns all the certificates registered in the aws-iot-core
"""
# Return parameters
certificateArns = []
certificateIds = []
# Create client
iot_client = boto3.client('iot', IOT_CORE_REGION)
# Parameter used to... | d5d9dc4e18f82586e695a94003317f0aedf4a543 | 3,597,315 |
def choose_best_title(url, titles):
"""given several title results, ordered by their likelihood
to be good titles, select the best working title.
"""
default = {
'text': get_netloc(url).from_ok( ),
'font-size': -1
}
non_empty = [title for title in titles + [default] if len(title['text']) > 0]
retu... | b935ce6c675fbab35849bd4dac9998282750b906 | 3,597,316 |
import torch
def probe_inference(model: torch.nn.Module, inp: torch.tensor, device: torch.device = None,
forward_indices: [int] = None) -> ProbeSummary:
"""
Probes the inference of a given model.
:param model: The model to probe.
:param inp: The model input to use.
:param devic... | ba93b178372879b0264a689cae0d445e3cbfcea1 | 3,597,317 |
from typing import Union
def db_span(
self, span: Union[Span, None], query: str, span_tag={}, db_type="SQL"
) -> Span:
"""
Span for database
"""
statement = query.strip()
spance_idx = statement.find(" ")
if query in TRANS_TAGS:
operation = query
else:
if spance_idx == -... | 365547a56ea23a55ba6104cc1743cfe05255fc3b | 3,597,318 |
def border_filtering(feature_arr, input_arr, flipax=[]):
"""
Dilate the potential iceberg features and remove those that have
more than 50% of their border pixels on a no-data boundary.
This function is modified from JessicaS11/iceberg_delin/icebergdelineation.py
Parameters
----------
... | 8e1ed49cbe7071a3588db66db42ab54b7551afe1 | 3,597,319 |
def kw2re(x):
"""Convert a list of keywords to a regex."""
return r'(%s)' % '|'.join(sorted(list(set(x)))) | 13127d8b0c6d1772ebd4be58aca0f9e3f160544a | 3,597,320 |
def about():
"""View: About Page"""
return render_template("pages/about.html") | 678a7ca994dc9af7a732401ee427e757a232ebce | 3,597,321 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.