content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def derive_sender_1pu(epk, sender_sk, recip_pk, alg, apu, apv, keydatalen):
"""Generate two shared secrets (ze, zs)."""
ze = derive_shared_secret(epk, recip_pk)
zs = derive_shared_secret(sender_sk, recip_pk)
key = derive_1pu(ze, zs, alg, apu, apv, keydatalen)
return key | ed2015f683ecdba93288c9a40a9dce35c3d99c37 | 3,648,700 |
def collapse(board_u):
"""
takes a row/column of the board
and collapses it to the left
"""
i = 1
limit = 0
while i < 4:
if board_u[i]==0:
i += 1
continue
up_index = i-1
curr_index = i
while up_index>=0 and board_u[up_index]==0:
... | a79a3c7b83355f95face09e0ab21ab0b15a81053 | 3,648,701 |
import re
def find_match_in_file(search_term, file_location):
"""
This function is used to query a file
search_term = Term to find
file_location = Location of file to query.
"""
try:
with open(file_location) as line:
for search in line:
result = re.match(... | d78776069c8f2b4da5f09bf0ce3e675e215ee584 | 3,648,702 |
def get_cost_function(cost_function_name: str):
"""
Given the name of a cost function, retrieve the corresponding function and its partial derivative wrt Y_circ
:param cost_function_name: the name of the cost function
:return: the corresponding cost function and its partial derivative wrt Y_circ
"""... | 4f6664d91878e482f1996faa9141c201e2d260d3 | 3,648,703 |
def create_C1(data_set):
"""
Create frequent candidate 1-itemset C1 by scaning data set.
Args:
data_set: A list of transactions. Each transaction contains several items.
Returns:
C1: A set which contains all frequent candidate 1-itemsets
"""
C1 = set()
for t in data_set:
... | 9f3deb61c6c3b982976c61c4247102431794daa8 | 3,648,704 |
def timezone(name):
"""
Loads a Timezone instance by name.
:param name: The name of the timezone.
:type name: str or int
:rtype: Timezone
"""
return Timezone.load(name) | c0d0250a30581c4414eb4bb293331127011ae2a3 | 3,648,705 |
def complexDivision(a, b):
"""
复数除法
:param a: 负数a
:param b: 负数b
:return: 返回除法结果
"""
res = np.zeros(a.shape, a.dtype)
divisor = 1. / (b[:, :, 0] ** 2 + b[:, :, 1] ** 2)
res[:, :, 0] = (a[:, :, 0] * b[:, :, 0] + a[:, :, 1] * b[:, :, 1]) * divisor
res[:, :, 1] = (a[:, :, 1] * b[:, ... | b3758021f466d8b56af06698c83077875ff7fdb5 | 3,648,706 |
def dynamics_RK4(OdeFun, tspan, x, u, v):
"""
# RK4 integrator for a time-invariant dynamical system under a control, u,
and disturbance, v.
# See https://lpsa.swarthmore.edu/NumInt/NumIntFourth.html
This impl adopted from unstable-zeros's learning CBFs example for two airplanes
https://githu... | cda0b30b9973e299be4c14e11660d6f2fd9bc0e9 | 3,648,707 |
def random_decay(num_actions=None, decay_type='polynomial_decay', start_decay_at=0,
stop_decay_at=1e9, decay_rate=0., staircase=False, decay_steps=10000,
min_exploration_rate=0):
"""Builds a random decaying exploration.
Decay a random value based on number of states and the de... | 6cdcaac8e6fbdf609ed09dd686cebad0935017aa | 3,648,708 |
def not_found_handler(not_found):
"""Basic not found request handler."""
return render_template('except.html',
http_excep=not_found,
message='Not resource found at this URL.',
http_code=404,
http_error="N... | 35e147ea123eba7df7e517279aaf3e0790656d95 | 3,648,709 |
def remove_minor_regions(labeled_img, biggest_reg_lab):
"""
Set all the minor regions to background and the biggest to 1.
Returns:
A numpy array with the new segmentation.
"""
f = np.vectorize(lambda x: 1 if x == biggest_reg_lab else 0)
return f(labeled_img) | 86f015d4bca9dab570fd8ea8684f466d86803b54 | 3,648,710 |
from bs4 import BeautifulSoup
import re
import json
def get_right(html):
"""
获取公共解析部分(右边页面,用户详细资料部分)
"""
soup = BeautifulSoup(html, "html.parser")
scripts = soup.find_all('script')
pattern = re.compile(r'FM.view\((.*)\)')
cont = ''
# 这里先确定右边的标识,企业用户可能会有两个r_id
rids = []
for scri... | c76ae4a70904145f34b6fe1a3c2d8d5ef563f342 | 3,648,711 |
def marginal_ln_likelihood_worker(task):
"""
Compute the marginal log-likelihood, i.e. the likelihood integrated over
the linear parameters. This is meant to be ``map``ped using a processing
pool` within the functions below and is not supposed to be in the
public API.
Parameters
----------
... | fd46ef000994c981889fbb440d8ffeacdf0a8b41 | 3,648,712 |
def from_matvec(matrix, vector=None):
""" Combine a matrix and vector into an homogeneous affine
Combine a rotation / scaling / shearing matrix and translation vector into
a transform in homogeneous coordinates.
Parameters
----------
matrix : array-like
An NxM array representing the th... | 82aaf8fd72f076baa731163b335b5afd873f6f8c | 3,648,713 |
import argparse
def create_parser():
"""
Creates the argparse parser with all the arguments.
"""
parser = argparse.ArgumentParser(
description='Management CLI for Enodebd',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# Add subcommands
subparsers = parser.add_subpar... | dab0b5e1631225bd76a53d97c2b526984d4a661a | 3,648,714 |
def read_file(fp, limit=DEFAULT_FILE_READ_SIZE):
"""
Return output of fp.read() limited to `limit` bytes of output from the end of file.
"""
fp.seek(0, 2) # Go to EOF
total = fp.tell()
if total > limit:
fp.seek(total - limit)
else:
fp.seek(0)
return fp.read() | 97fe4bc2b465cdcc562c931c6ffae68ceb616715 | 3,648,715 |
def sample_quaternions(shape=None):
"""
Effective Sampling and Distance Metrics for 3D Rigid Body Path Planning, James J. Kuffner (2004)
https://ri.cmu.edu/pub_files/pub4/kuffner_james_2004_1/kuffner_james_2004_1.pdf
"""
s = np.random.random(shape)
sigma1 = np.sqrt(1 - s)
sigma2 = np.sqrt(s)... | b7484c857cea09ade1e15b46ffa102bdeb16aa34 | 3,648,716 |
def _select_free_device(existing):
"""
Given a list of allocated devices, return an available device name.
According to
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/device_naming.html
all AWS Linux instances have ``/dev/sd[a-z]`` available. However:
- ``sda`` is reserved for the root de... | 93860df03c9df75c11f31c3017106fbed58bb48e | 3,648,717 |
def create_target_delivery_request(get_offers_opts):
"""Converts dict representation of get_offers options to TargetDeliveryRequest object"""
return TargetDeliveryRequest(request=create_delivery_request(get_offers_opts.get("request")),
target_cookie=get_offers_opts.get("targetCo... | cf470d56b32d6fd5eaeee3b549333425607dedbd | 3,648,718 |
def wintype_to_cdata(wintype):
"""
Returns the underlying CFFI cdata object or ffi.NULL if wintype is None.
Used internally in API wrappers to "convert" pywincffi's Python types to
the required CFFI cdata objects when calling CFFI functions. Example:
>>> from pywincffi.core import dist
>>> from... | e85123a0dc790c9b53f7afb4199c45d573e14310 | 3,648,719 |
import os
def GenerateOutput(target_list, target_dicts, data, params):
"""
Generates all the output files for the specified targets.
"""
options = params['options']
if options.generator_output:
def output_path(filename):
return filename.replace(params['cwd'], options.generator_output)
else:
... | 9090dde872f00b466e41e352c1bed37593716fce | 3,648,720 |
import json
def rating_feedback_view(incident: Incident, channel_id: str):
"""Builds all blocks required to rate and provide feedback about an incident."""
modal_template = {
"type": "modal",
"title": {"type": "plain_text", "text": "Incident Feedback"},
"blocks": [
{
... | 5698c87cc7530decbff083130c0150085ff7871c | 3,648,721 |
def _GetTargetOS():
"""Returns the target os specified in args.gn file.
Returns an empty string is target_os is not specified.
"""
build_args = _GetBuildArgs()
return build_args['target_os'] if 'target_os' in build_args else '' | 930c56d18d55d12728f7aac594096f0697c03bb4 | 3,648,722 |
def generalise_sent_pos(s):
"""
generalise sentence pattern by POS tags only
:param s:
:return:
"""
rets = []
for token in s['sent']:
e = token.idx + len(token.text)
is_matched = False
for ann in s['anns']:
if token.idx >= ann['s'] and e <= ann['e']:
... | 03092bd253f13739d918438839ff4234f5ef80af | 3,648,723 |
def add_batting_metrics(df):
"""
Adds the following columns to a given DataFrame:
PA
1B
OBP
BA
SLG
OPS
ISO
PA/HR
K
BB
BABIP
wOBA
wRAA
wRC
Args:
df (DataFrame): the DataFrame t... | 50a424696a1db32966b8b240823e326248f092aa | 3,648,724 |
def line_break(text, line_len=79, indent=1):
"""
Split some text into an array of lines.
Enter: text: the text to split.
line_len: the maximum length of a line.
indent: how much to indent all but the first line.
Exit: lines: an array of lines.
"""
lines = [text.rstrip()]
... | 34b866109689796a4d428e7d3a68a34f7152250f | 3,648,725 |
from nipype.pipeline import engine as pe
from nibabies.workflows.anatomical.preproc import init_anat_average_wf
from nibabies.workflows.anatomical.registration import init_coregistration_wf
from nibabies.workflows.anatomical.brain_extraction import (
init_infant_brain_extraction_wf,
)
from nibabies.workflow... | 71bc9d3d0d11ebd93f608a66e115110272b23c67 | 3,648,726 |
def visualize_spectrum(y):
"""Effect that maps the Mel filterbank frequencies onto the LED strip"""
global _prev_spectrum
y = np.copy(interpolate(y, config.N_PIXELS // 2))
common_mode.update(y)
diff = y - _prev_spectrum
_prev_spectrum = np.copy(y)
# Color channel mappings
r = r_filt.upda... | ca20151f268f5124d7cf909a64ff1c668740a858 | 3,648,727 |
def testDuplicateContours(glyph):
"""
Contours shouldn't be duplicated on each other.
"""
contours = {}
for index, contour in enumerate(glyph):
contour = contour.copy()
contour.autoStartSegment()
pen = DigestPointPen()
contour.drawPoints(pen)
digest = pen.getD... | ed3f5499dfbf36192f025a0551b252bd2623216f | 3,648,728 |
import re
def expand_strength(row):
"""Extracts information from Strength column and cleans remaining strengths.
Gets Additional Info and Final Volume Quantity columns from Strength.
Reformats any malformed strengths and removes commas from within numbers.
"""
strengths = row['Strength']
# s... | e6520fa26a4f8a75954db4e957a4ed7f3e52f8a2 | 3,648,729 |
def dem_autoload(geometries, demType, vrt=None, buffer=None, username=None, password=None,
product='dem', nodata=None, hide_nodata=False):
"""
obtain all relevant DEM tiles for selected geometries
Parameters
----------
geometries: list[spatialist.vector.Vector]
a list of :c... | 8b95d2ae3a518cd8181c21d138f7754146e9acd1 | 3,648,730 |
import string
import random
def randomString(stringLength=6):
"""Generate a random string of fixed length """
letters = string.ascii_uppercase
return ''.join(random.choice(letters) for i in range(stringLength)) | 8652f4039d7b3ea024001e965e81d4b742b6c2e8 | 3,648,731 |
def create_new_record(account,userName,password):
"""
Function that creates new records for a given user account
"""
new_record = Records(account,userName,password)
return new_record | 7e87347dbb1526168cdb7ebee1268a67381682e0 | 3,648,732 |
def is_bow(vec):
"""
Checks if a vector is in the sparse Gensim BoW format
"""
return matutils.isbow(vec) | 0e180f1cd0319a366492c692b73459302407a9da | 3,648,733 |
import asyncio
def timeout(seconds, loop=None):
"""
Returns a channel that closes itself after `seconds`.
:param seconds: time before the channel is closed
:param loop: you can optionally specify the loop on which the returned channel is intended to be used.
:return: the timeout channel
"""
... | c2cc8c362123a5dd9c8b867a78b23cb32c0f4330 | 3,648,734 |
def analyse_df(df, options):
"""
Analyses a dataframe, creating a metadata object
based on the passed options. Metadata objects can be
used to apply dataset preparations across multiple platforms.
"""
_validate_options(options)
metadata = _create_metadata(options)
for proc i... | 8ccefe92dabca1da71b32bc941ab320f04e1b437 | 3,648,735 |
def base_route():
"""
Base route to any page. Currently, aboutme.
"""
return redirect(url_for("pages.links")) | e01efc921ac2d55c8de3f8b2b20fa68b10f0d834 | 3,648,736 |
def blend_normal(source, source_mask, target):
"""Blend source on top of target image using weighted alpha blending.
Args:
source (np.ndarray): Array of shape (H, W, C) which contains the source
image (dtype np.uint8).
source_mask (np.ndarray): Array of shape (H, W) which contains the
source fo... | af6b4206eafc019aa2075772541cb6cb195f2ad1 | 3,648,737 |
def load_dataset(name):
"""
Load a dataset.
"""
try:
func = loaders[name]
except KeyError:
print(f"Dataset '{name}' is not in available list: {list_datasets()}")
else:
return func() | fd57b34625590a8c0680c6b46d35980245ec6e5c | 3,648,738 |
import tokenize
def split_symbols_implicit_precedence(tokens, local_dict, global_dict): # pragma: no cover
"""Replace the sympy builtin split_symbols with a version respecting implicit multiplcation.
By replacing this we can better cope with expressions like 1/xyz being
equivalent to 1/(x*y*z) rat... | a26adc14eec622b04e454b0a426ee37ac26e9bef | 3,648,739 |
def altsumma(f, k, p):
"""Return the sum of f(i) from i=k, k+1, ... till p(i) holds true or 0.
This is an implementation of the Summation formula from Kahan,
see Theorem 8 in Goldberg, David 'What Every Computer Scientist
Should Know About Floating-Point Arithmetic', ACM Computer Survey,
Vol. 23, No... | 952e77fcedfbe01658342126d95b79175c082976 | 3,648,740 |
from re import T
import functools
from datetime import datetime
from typing import cast
def action_logging(f: T) -> T:
"""
Decorates function to execute function at the same time submitting action_logging
but in CLI context. It will call action logger callbacks twice,
one for pre-execution and the oth... | 4a524549b6c3c19928e70be460482061b71d2197 | 3,648,741 |
def decode_public_id(str_id):
"""
make numeric ID from 4-letter ID
Args:
str_id (str): ID consisting of a number and 3 alphabets
Return:
num_id (int): numeric ID
"""
def alpha2num(c):
return encoder.find(c)
def num2num(c):
return 5 if c ==... | 8425ffe2d0fd7161507734a3b452d48d78e97246 | 3,648,742 |
def get_sentence_idcs_in_split(datasplit: DataFrame, split_id: int):
"""Given a dataset split is (1 for train, 2 for test, 3 for dev), returns the set of corresponding sentence
indices in sentences_df."""
return set(datasplit[datasplit["splitset_label"] == split_id]["sentence_index"]) | b10d05dec6c70fae6a31eb017afe4d110a6bc23a | 3,648,743 |
def valid_scope_list():
"""List all the oscilloscope types."""
s = "\nValid types are:\n"
s += ", ".join(DS1000C_scopes) + "\n"
s += ", ".join(DS1000E_scopes) + "\n"
s += ", ".join(DS1000Z_scopes) + "\n"
s += ", ".join(DS4000_scopes) + "\n"
s += ", ".join(DS6000_scopes) + "\n"
return s | 2d6dfb7ae6ea5c62ebe674fa1018202aa5f9f0ac | 3,648,744 |
import tempfile
import logging
import os
import zipfile
def process_input_file(remote_file):
"""Process the input file.
If its a GCS file we download it to a temporary local file. We do this
because Keras text preprocessing doesn't work with GCS.
If its a zip file we unpack it.
Args:
remote_file: The... | 6126d50a02c2e30191955bc51333c52ae47de9b4 | 3,648,745 |
def load():
"""Returns an instance of the plugin"""
return SyslogOutOutputPlugin | 072c827e96e85b04e1109a1788e92502729de09d | 3,648,746 |
def word_sorter(x):
"""
Function to sort the word frequency pairs after frequency
Lowest frequency collocates first - highest frerquency collocates last
"""
# getting length of list of word/frequency pairs
lst = len(x)
# sort by frequency
for i in range(0, lst):
for j i... | 571570bb03d6473b9c6839aa6fdc0b1ba8efbe3c | 3,648,747 |
def le_assinatura():
"""[A funcao le os valores dos tracos linguisticos do modelo e devolve uma assinatura a ser comparada com os textos fornecidos]
Returns:
[list] -- [description]
"""
print("Bem-vindo ao detector automático de COH-PIAH.")
print("Informe a assinatura típica de um aluno in... | b6a0bacb02f3f878a88a6681d87d11408c292fe2 | 3,648,748 |
def category_task_delete(request, structure_slug, category_slug,
task_id, structure):
"""
Deletes task from a category
:type structure_slug: String
:type category_slug: String
:type task_id: String
:type structure: OrganizationalStructure (from @is_manager)
:param ... | 3329c2342f6b115ab33df334df27a26ab8f3fc79 | 3,648,749 |
def lnposterior_selection(lnprobability, sig_fact=3., quantile=75, quantile_walker=50, verbose=1):
"""Return selected walker based on the acceptance fraction.
:param np.array lnprobability: Values of the lnprobability taken by each walker at each iteration
:param float sig_fact: acceptance fraction below q... | 4c489ee8b3edaca5baad033101236e4165f37041 | 3,648,750 |
def space_check(board, position):
"""Returns boolean value whether the cell is free or not."""
return board[position] not in PLAYERS_MARKS | d335a2dd441e7b761e6f9680905e993b12b3e8f7 | 3,648,751 |
import logging
def find_repo_root_by_path(path):
"""Given a path to an item in a git repository, find the root of the repository."""
repo = git.Repo(path, search_parent_directories=True)
repo_path = repo.git.rev_parse("--show-toplevel")
logging.debug("Repository: {}".format(repo_path))
return repo... | 85b6c7d15293057fe6734d83891f1e025f98eb69 | 3,648,752 |
import functools
def validate_params(serializer_cls):
"""利用Serializer对请求参数进行校验"""
def decorator(func):
@functools.wraps(func)
def wrapper(request: Request):
data = request.query_params if request.method == "GET" else request.data
serializer = serializer_cls(data=data)
... | c2573c131a01ede9862efac3bf3b280b2f426214 | 3,648,753 |
from typing import Optional
import gc
def get_pairs_observations(kdata: kapture.Kapture,
kdata_query: Optional[kapture.Kapture],
keypoints_type: str,
max_number_of_threads: Optional[int],
iou: bool,
... | cb9b04c88d2dec30c1d782be602c8ab615ddb65f | 3,648,754 |
def col2im_conv(col, input, layer, h_out, w_out):
"""Convert image to columns
Args:
col: shape = (k*k, c, h_out*w_out)
input: a dictionary contains input data and shape information
layer: one cnn layer, defined in testLeNet.py
h_out: output height
w_out: output width
Returns:
im: shape =... | 408b1ea43eac3c25cc32909a4f32e8380e2ff0d4 | 3,648,755 |
import os
def parse_arguments(argv):
""" Parse command line arguments """
parser = create_parser()
args = parser.parse_args(argv)
if args.n is None and not args.tch:
parser.error('-n is required')
if args.m is None and args.grnm:
parser.error('-m is required')
if args.d is Non... | d64d4995f643a82022e75192b3acc133d1d6f295 | 3,648,756 |
import argparse
def parse_args() -> argparse.Namespace:
"""
Creates the parser for train arguments
Returns:
The parser
"""
parse = argparse.ArgumentParser()
parse.add_argument('--local_rank', dest='local_rank', type=int, default=0)
parse.add_argument('--port', dest='port', type=i... | 70370de42d6e80f108399776c119724c3417a125 | 3,648,757 |
def fix_missing_period(line):
"""Adds a period to a line that is missing a period"""
if line == "":
return line
if line[-1] in END_TOKENS:
return line
return line + " ." | c886384b634ed9e88e37c539b541c3037029c056 | 3,648,758 |
async def main() -> int:
"""main async portion of command-line runner. returns status code 0-255"""
try:
await tome.database.connect()
return await migrations.main(
whither=args.whither, conn=tome.database.connection(), dry_run=args.dry_run
)
except KeyboardInterrupt:
... | d72a0e30aac405cc87a39bda8d31e53119162c0f | 3,648,759 |
def getTaskStatus( task_id ) :
"""Get tuple of Instance status and corresponding status string.
'task_id' is the DB record ID."""
_inst = Instance.objects.get( id = task_id )
return ( _inst.status , STATUS2TEXT[_inst.status] ) | 48fc342d16bd6d9f1f1b912f1fef00a4ae9ed932 | 3,648,760 |
def fit_affine_matrix(p1, p2):
""" Fit affine matrix such that p2 * H = p1
Hint:
You can use np.linalg.lstsq function to solve the problem.
Args:
p1: an array of shape (M, P)
p2: an array of shape (M, P)
Return:
H: a matrix of shape (P, P) that transform p2 to p1.
... | 302d7a30bfe11f343016de7f42708b71b6df3f3b | 3,648,761 |
def cnn_lstm_nd(pfac,
max_features=NUM_WORDS,
maxlen=SEQUENCE_LENGTH,
lstm_cell_size=CNNLSTM_CELL_SIZE,
embedding_size=EMBEDDING_SIZE):
"""CNN-LSTM model, modified from Keras example."""
# From github.com/keras-team/keras/blob/master/examples/imdb_cnn_... | cf5573dc6b9f02549cb40505d0d224c90ddccf90 | 3,648,762 |
def updateUserPassword(userName, newPassword):
""" update the user password """
cursor = conn('open')
if cursor:
try:
cursor.execute("UPDATE user SET u_Pass= %s where u_name= %s ",
(generate_password_hash(newPassword), userName))
conn("commit")
conn('close')
except Exception as e:
return Fa... | 9aac85b6393e60121b3ec4aad943b87613173298 | 3,648,763 |
def mit_b1(**kwargs):
"""
Constructs a mit_b1 model.
Arguments:
"""
model = MixVisionTransformer(embed_dims=64, num_layers=[2, 2, 2, 2], num_heads=[1, 2, 5, 8], **kwargs)
return model | a38e4d09646a29f0648379ba02a42bb079da9917 | 3,648,764 |
def GenerateConfig(_):
"""Returns empty string."""
return '' | ed42eb1c320ca1df25603a53d4abf4a1b14215f3 | 3,648,765 |
def calc_procrustes(points1, points2, return_tform=False):
""" Align the predicted entity in some optimality sense with the ground truth.
Does NOT align scale
https://github.com/shreyashampali/ho3d/blob/master/eval.py """
t1 = points1.mean(0) # Find centroid
t2 = points2.mean(0)
points1_t = ... | 01f3957624a764f3d6853a402a9d0d9c8b933766 | 3,648,766 |
from pathlib import Path
import torch
def read_image_pillow(input_filename: Path) -> torch.Tensor:
"""
Read an image file with pillow and return a torch.Tensor.
:param input_filename: Source image file path.
:return: torch.Tensor of shape (C, H, W).
"""
pil_image = Image.open(input_filename)
... | dec3cdfddaec4e6f50a6c5fc1ba384d217c0637b | 3,648,767 |
def compute_solar_angle(balloon_state: balloon.BalloonState) -> float:
"""Computes the solar angle relative to the balloon's position.
Args:
balloon_state: current state of the balloon.
Returns:
Solar angle at the balloon's position.
"""
el_degree, _, _ = solar.solar_calculator(
balloon_state.... | f11f91b282ee4897e444591d8eb14377c8001fa9 | 3,648,768 |
from typing import Optional
from typing import Tuple
from typing import List
def parse_links(source_file: str, root_url: Optional[str]=None) -> Tuple[List[Link], str]:
"""parse a list of URLs with their metadata from an
RSS feed, bookmarks export, or text file
"""
check_url_parsing_invariants()
... | d13207d1415b02d9f39b15d6b1f2435b8304500b | 3,648,769 |
from typing import Iterable
from typing import Any
from typing import cast
def executemany(c: CursorType, sql: str, args: Iterable[Iterable[Any]]) -> OtherResult:
"""
Call c.executemany, with the given sqlstatement and argumens, and return c.
The mysql-type-plugin for mysql will special type this functio... | 25f93840189a99e2c90bf5d63cd49558f497e38f | 3,648,770 |
import os
def get_default_directory():
"""Return the default directory in a string
.. note:: Not tested on unix!
Returns:
(str): Default directory:
Windows: %AppData%/deharm
Unix: '~' expanded
"""
if kivy.utils.platform == 'win':
# In case this is running... | 2d2d204466c63866ec1183be180283f82ff19427 | 3,648,771 |
import click
import struct
def validate_host():
"""Ensure that the script is being run on a supported platform."""
supported_opsys = ["darwin", "linux"]
supported_machine = ["amd64"]
opsys, machine = get_platform()
if opsys not in supported_opsys:
click.secho(
f"this applicat... | e0346ebd8d80062a2be7666d1d89d40803dd069f | 3,648,772 |
def EAD_asset(x,RPs,curves,positions):
"""
Calculates the expected annual damage for one road segment (i.e. a row of the DataFrame containing the results)
based on the damage per return period and the flood protection level.
WARNING: THIS FUNCTION PROBABLY REALLY SLOWS DOWN THE OVERALL POST-PR... | f2cae0626ff55f81277314d9f45dadcba480c7fd | 3,648,773 |
def procrustes_alignment(data, reference=None, n_iter=10, tol=1e-5,
return_reference=False, verbose=False):
"""Iterative alignment using generalized procrustes analysis.
Parameters
----------
data : list of ndarrays, shape = (n_samples, n_feat)
List of datasets to alig... | 1452c124d88cf00f9c0d45bf7ba0e1db449657d3 | 3,648,774 |
def get_paramsets(args, nuisance_paramset):
"""Make the paramsets for generating the Asmimov MC sample and also running
the MCMC.
"""
asimov_paramset = []
llh_paramset = []
gf_nuisance = [x for x in nuisance_paramset.from_tag(ParamTag.NUISANCE)]
llh_paramset.extend(
[x for x in nui... | d49d2d757a041f1087508810239eac21260ac4b7 | 3,648,775 |
def indgen(*shape):
"""
Create a (multi-dimensional) range of integer values.
Notes
-----
**porting to python**
If ``shape`` is of one dimension only, you can use ``np.arange(n)``.
IDL accepts floats as dimension parameters, but applies ``int()`` before
using them. While ``np.arange()... | 68f703ae0c7863bd8ed3866755d50df97d1c9de9 | 3,648,776 |
def post_search(request):
"""
Crear funcion de busqueda de posts llamando el form SearchForm
Cuando el formulario es emitido,mandas el formulario usando el metodo GET
atraves del POST. Cuando el formulario es emiido se instancia con los datos enviados por GET
y verifica que los datos sean validos, s... | 0e2880cc619ccd1e7f7d151015aa5084e0f8c978 | 3,648,777 |
def get_bins(values):
"""
Automatically compute the number of bins for discrete variables.
Parameters
----------
values = numpy array
values
Returns
-------
array with the bins
Notes
-----
Computes the width of the bins by taking the maximun of the Sturges and the ... | 638c07fe6263391ff42d7a96b2d482c4b6dd7c9a | 3,648,778 |
def destination_name(data):
""" Fonction qui permet de récupérer le nom du terminus en fonction de data passé en paramètre
Nom fonction : destination_name
Paramètre : data, un flux xml
Return : un string qui a comme valeur le libellé de la destination final"""
tree = ET.ElementTree(ET.f... | ee5065523e1ae26104687a97ef0bd41e70670ef2 | 3,648,779 |
def prim_NumToTensor(mapper, graph, node):
""" 构造转为Tensor的PaddleLayer。
TorchScript示例:
%other.2 : Tensor = prim::NumToTensor(%1736)
参数含义:
%other.2 (Tensor): 输出。
%1736 (-): 输入。
"""
scope_name = mapper.normalize_scope_name(node)
output_name = mapper._get_outputs_name(no... | 0fd8881513dc4ee95e7c187b790e8d95d5996ec7 | 3,648,780 |
def import_taskdict(modname):
"""Import user module and return its name and TASKDICT"""
try:
mod = import_module(modname)
except (ImportError, ModuleNotFoundError):
LOGGER.critical('Module %s not found. '
'Check it is along PYTHONPATH', modname)
raise
try:... | b351389ab92650a5dcc317953e6fe500b324a09d | 3,648,781 |
def nlp_stem(string):
"""
Generates a list of the stem for each word in the original string and returns the joined list of stems as a single string.
"""
ps = nltk.porter.PorterStemmer()
stems = [ps.stem(word) for word in string.split()]
return " ".join(stems) | a0e44b709eb8b53500f9208634b059ff50660710 | 3,648,782 |
def _CreateHostConfigEntityFromHostInventory(lab_name, host):
"""Creates HostConfig from HostInventory.
Args:
lab_name: the lab name.
host: the ansible inventory Host object.
Returns:
the HostConfig entity.
"""
return datastore_entities.HostConfig(
id=host.name,
lab_name=lab_name,
... | e3de12526f380baa5b6e0cfd7b0cb6ce14236633 | 3,648,783 |
import PIL
import time
def visualize_object_detection_custom(
image, post_processed, config, prev_state, start_time, duration):
"""Draw object detection result boxes to image.
Args:
image (np.ndarray): A inference input RGB image to be draw.
post_processed (np.ndarray): A one batch ou... | 7a325b782ea0dba6bc573d27661545804d68614b | 3,648,784 |
def all_files(directory="..\\raw_data\\"):
""" Return flat list of all csv files in the given directory.
Args:
directory [string] full path to directory with csv files.
Default project layout is used if it is not provided
Returns:
Flat list of csv files as absolute names.
"""
... | 179e40756b02c7a25f01fb4e0b8b863326256a3a | 3,648,785 |
def connected_user(**params):
"""Returns the connected user."""
if g.context.person:
return g.context.person == request.view_args.get('person_id') | 713f52c8aa090cf8756d49279df72f4f470b4b5c | 3,648,786 |
def remove_plugin(plugin, directory=None):
"""Removes the specified plugin."""
repo = require_repo(directory)
plugins = get_value(repo, 'plugins', expect_type=dict)
if plugin not in plugins:
return False
del plugins[plugin]
set_value(repo, 'plugins', plugins)
return True | d631d0906411782e681cb2deb76cc1e347f856e4 | 3,648,787 |
def command_arg(name, value_type=None, help=''): # noqa; pylint: disable=redefined-builtin
"""
Decorator wrapping functions to add command line arguments to the sub command to be invoked
:param name: Name of the argument
:param value_type: Type of the argument
:param help: Help string for the argu... | 6d8490e5afaa3345ff9af7d905c67f4bc53e4325 | 3,648,788 |
def ioc_arg_parser(*, desc, default_prefix, argv=None, macros=None,
supported_async_libs=None):
"""
A reusable ArgumentParser for basic example IOCs.
Parameters
----------
description : string
Human-friendly description of what that IOC does
default_prefix : string
... | 7b4638afdc04284d5e69bfb48d476a557bc8bcd3 | 3,648,789 |
def count_model_param_and_flops(model):
"""
Return the number of params and the number of flops of (only) 2DConvolutional Layers and Dense Layers for both the model.
:return:
"""
param_by_layer = dict()
flop_by_layer = dict()
nb_param_model, nb_flop_model = 0, 0
for layer in model.lay... | 5fff62167db1d369eb02aae07ef7a23bbd5d7a16 | 3,648,790 |
def plate_from_dataframe(
dataframe, wellname_field="wellname", num_wells="infer", data=None
):
"""Create a plate from a Pandas dataframe where each row contains the
name of a well and data on the well.
it is assumed that the dataframe's index is given by the well names.
This function is used e.g.... | c45b2996303471d4d5e3fe945786af6819e72a83 | 3,648,791 |
import OpenSSL
def catch_conn_reset(f):
"""
A decorator to handle connection reset errors even ones from pyOpenSSL
until https://github.com/edsu/twarc/issues/72 is resolved
It also handles ChunkedEncodingError which has been observed in the wild.
"""
try:
ConnectionError = OpenSSL.SSL.... | a5b3b7d78a03b81b0eb768e816f5bf3d95ea50cc | 3,648,792 |
def prepared(name):
"""Prepare the given volume.
Args:
name (str): Volume name
Returns:
dict: state return value
"""
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
# Idempotence.
if __salt__['metalk8s_volumes.is_prepared'](name):
ret['result'] =... | 443ea25a3bd5797744f2f095b54d40172c57f5ee | 3,648,793 |
def if_statement(env, node):
"""
'If' statement def for AST.
interpret - runtime function for Evaluator (true of false statement depending on condition).
"""
condition_value = node.condition.interpret(env)
if condition_value:
node.true_stmt.interpret(env)
else:
if node.altern... | 96522698c42d7649d3951f5fd2ffe3bbd992c985 | 3,648,794 |
def volCyl(radius:float, height: float) -> float:
"""Finds volume of a cylinder"""
volume: float = pi * radius * radius * height
return volume | 2d4320bb0a2d802e4308d22593e8c2f1d797ad87 | 3,648,795 |
from s3 import S3DateFilter, \
from s3db.req import req_status_opts
def req_filter_widgets():
"""
Filter widgets for requests
@returns: list of filter widgets
"""
T = current.T
S3LocationFilter, \
S3OptionsFilter, \
S3TextFilter, ... | 13720abfd491609e2d6ac9e4ab702ef744041b61 | 3,648,796 |
from typing import List
def is_minimally_connected(graph: List[List[int]], num_vertices: int) -> bool:
"""
1. Has no cycle.
2. All nodes are connected
"""
visited = set()
has_cycle = is_cyclic(graph, 0, -1, visited)
if has_cycle or len(visited) < num_vertices:
# if num_vertices >... | 8b836f34b6e0c3c5f5651f8c31a4448a8af09d13 | 3,648,797 |
def to_keep(path):
"""
:param path:
:return: True if heigh and width >= 512
"""
img = Image.open(path)
h, w = img.size
return h >= 512 and w >= 512 | 0a24fe38f52c6441fc9955e2e4890962b7c35fb6 | 3,648,798 |
from typing import Hashable
from typing import Callable
def __register(key, *additional_keys, default_handler_info, registry=None, registering_for_name="", overwrite=False):
"""
Internal decorator to register the non-default handlers for multimethod
registry and key_fn_name are keyword arguments with defa... | 769184841dd2eb87813533bb19bde0bf747ac26f | 3,648,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.