content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def archived_attendance_overview():
"""
Show archived attendance view
"""
this_year = 2019
last_year = 2018
attendance = CommitteeMeetingAttendance.annual_attendance_trends(
period='historical')
# index by year and cte id
years = {
year: {
cte_id: list(cte_gro... | 6d895a63e9b248b135385fd316112e4b749792a3 | 26,811 |
def _get_medical_image_blob(roidb):
""" Builds an input blob from the medical image in the roidb
"""
num_images = len(roidb)
processed_ims = []
pre_ims = []
post_ims = []
abdo_masks = []
for i in range(num_images):
im = raw_reader(roidb[i]["image"], cfg.MET_TYPE, [roidb[i]["heigh... | 9b09d53fbf08ff785eeaadacf3733b8b5bb995b4 | 26,813 |
def is_weak(key: object) -> bool:
"""
Check whether key is weak or not.
Key is weak if it is a basic key - not an action and not a modifier.
"""
return not is_action(key) and not is_mod(key) | 9493afd199fad665e97ae18da973c8a15671bfbb | 26,814 |
def mock_cei_get_trades(mocker: MockerFixture) -> MockerFixture:
"""Fixture for mocking report_reader.get_trades."""
return mocker.patch("irpf_investidor.report_reader.get_trades") | fcceb00df6443a30544b92d001983c7bb243650a | 26,815 |
def _normalize(op1, op2, prec = 0):
"""Normalizes op1, op2 to have the same exp and length of coefficient.
Done during addition.
"""
if op1.exp < op2.exp:
tmp = op2
other = op1
else:
tmp = op1
other = op2
# Let exp = min(tmp.exp - 1, tmp.adjusted() - precision -... | f0ed5a47e6fa466a8fb7aacf837c42f092ff031e | 26,817 |
def change_tags(project_id):
"""Change the list of tags on a project."""
project = Project.query.get_or_404(project_id)
if project.lifetime_stage not in (LifetimeStage.ongoing, LifetimeStage.finalizing):
abort(400, {'message': 'Tags can only be modified in ongoing and finalizing stages.'})
if ... | 0f723eb4816066f8f3a4353b1261c207c2754100 | 26,818 |
from typing import List
from typing import Dict
from typing import Any
import six
from typing import Tuple
from re import T
from typing import Union
def sort_db_results(results: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Deterministically sort DB results.
Args:
results: List[Dict], results fro... | 27a8a206ee08810cf7391a1d4d6e0cf68d06fe14 | 26,819 |
def classify_one(models, cooccurence_csv):
"""
Args:
cooccurence_csv (str): the CSV file path for the co-occurrence feautres
Output:
dx (int): the class for diagnosis
dx_name (str): the name for diagnosis class
"""
# Get the features from the CSV file
cooc_featur... | 6761a01ab832df15f88ee9032e4b1423a2d235cd | 26,820 |
import math
def discretize_q(q, tol=None, lat_range=(-math.pi / 2, math.pi / 2), points=None):
"""
simulate feature database by giving closest lat & roll with given tolerance
and set lon to zero as feature detectors are rotation invariant (in opengl coords)
"""
if tol is not None and points is no... | a72653753d48e53bcebab94088828e9cecf19f34 | 26,821 |
from typing import Union
import scipy
def generate_testdata(
pars: dataclass,
ntrials: int = 1,
baseclass: Union[object, None] = None,
func: Union[object, None] = None,
exp_test_set: bool=True,
):
"""
meanrate is in Hz(events/second)
maxt is in seconds - duration of trace
... | 2c2fdd81608ca1df1564e7b6a7121c164d06e8d9 | 26,823 |
def has_param(param):
"""
Generate function, which will check `param` is in html element.
This function can be used as parameter for .find() method in HTMLElement.
"""
def has_param_closure(element):
"""
Look for `param` in `element`.
"""
if element.params.get(param,... | 6800725c378714b5161772f0a2f9ef89ae278400 | 26,824 |
import torch
def neg_log_likeDUN(output, target, sigma, cat):
"""
function to compute expected loss across different network depths
inputs:
- preds_list, list of predictions for different depths
- targets, single set of targets
- noise, aleatoric noise (length 12)
- cat, variational catego... | 8c2bcd9833e9a309270087331b67223b5e4ce74e | 26,825 |
def shoot(C, D, b, maxiter=1000, abs_tol=1e-7):
"""Return random equality set of P that projects on a projection facet.
Returns randomly selected equality set E_0 of P such
that the projection of the equality set is a facet of the projection.
@param C: Matrix defining the polytope Cx+Dy <= b
@para... | 1cd85fbd4752ff859553d7ef907ee85b20a99210 | 26,826 |
def bwdist(
img,
method=cv2.DIST_L2,
dist_mask=cv2.DIST_MASK_5,
label_type=cv2.DIST_LABEL_CCOMP,
ravel=True,
):
"""Mimics Matlab's bwdist function, similar to OpenCV's distanceTransform()
but with different output.
https://www.mathworks.com/help/images/ref/bwdist.html
Available met... | 9889e731dab572846936f7cc79b88cb794cd9852 | 26,827 |
def calculate_cumulative_conf(areaP90: float=1., areaP10: float=10., pdP90: float=10., pdP10: float=24):
"""Calculate cumulative confidence level for expected development size in MW
Args:
areaP90 (float): pessimistic area in sqkm
areaP10 (float): optimistic area in sqkm
pdP90 (float): p... | 9231e1d7942ad8c0e36e606c3a7ddd25439016fb | 26,828 |
def get_all_keys(data):
"""Get all keys from json data file"""
all_keys = set(data[0].keys())
for row in data:
all_keys = set.union(all_keys, set(row.keys()))
return list(all_keys) | 5532af993f87bf4e00c7bec13eb971e0114e736c | 26,830 |
def submitmq(request):
"""Message queue submit page"""
context = {
"type": "mq",
"choices": FRUIT_CHOICES,
}
if request.method == 'POST': # If the form has been submitted...
p = None
try:
# save preference
p = Preference()
p.nam... | 2b84e7f8ee9a118d0989024dcd58f26d52f30351 | 26,831 |
def plot_projections(img: np.ndarray, spacing: int = 5, zoom: float = None) -> np.ndarray:
"""
Plot three maximum intensity projections of the given image side-by-side.
Parameters
----------
img : np.ndarray
Input 3D image.
spacing : int
Number of pixels to separate the projecti... | cc68f75bb10b249107b90ef6f8d664ff09aee4f2 | 26,832 |
def _ngl_write_atom(
num,
species,
x,
y,
z,
group=None,
num2=None,
occupancy=1.0,
temperature_factor=0.0,
):
"""
Writes a PDB-formatted line to represent an atom.
Args:
num (int): Atomic index.
species (str): Elemental species.
x, y, z (float): Ca... | 92a5d62f3c4f6d927aa5a6010b217344d0d241d3 | 26,833 |
def get_insert_components(options):
""" Takes a list of 2-tuple in the form (option, value) and returns a
triplet (colnames, placeholders, values) that permits making a database
query as follows: c.execute('INSERT INTO Table ({colnames}) VALUES
{placeholders}', values). """
col_names = ','.join(opt[0] for opt in o... | 3e1deecd39b0e519124278f47713d5b3a1571815 | 26,834 |
from typing import List
def send_recording_to_gist(table: str, results: List['FormattedResult'], assignment: str):
"""Publish a table/result pair to a private gist"""
# the "-" at the front is so that github sees it first and names the gist
# after the homework
table_filename = '-stograde report {} t... | 41cd2dc428018893659a0aaa5c67b50e37375dc8 | 26,835 |
def append_composite_importance(composite_terms, ebm, X, composite_name=None, global_exp=None, global_exp_name=None, contributions=None):
"""Computes the importance of the composite_terms and appends it to a global explanation.
In case a global explanation is provided, the composite importance will be appended... | 12c8eeb6ad9dd49c96163ed349236fbc8cdf8ed5 | 26,836 |
import abc
def apply_pair(main, other, *, fn):
"""`Apply` optimized for use with paired structured containers."""
# special sequence types must precede generic `Sequence` check
if isinstance(main, (str, bytes)):
return fn(main, other)
# delegate other types to the function (int, float, etc.)
... | c547182fd33fe97136fccba635fa61d96ec73447 | 26,837 |
import requests
import json
def get_info(connector, host, key, datasetid):
"""Get basic dataset information from UUID.
Keyword arguments:
connector -- connector information, used to get missing parameters and send status updates
host -- the clowder host, including http and port, should end with a /
... | 982e3b9304b3c2ca04348efb794b8b8d34b86b89 | 26,838 |
from typing import Union
from typing import Tuple
from typing import List
def solve_network(
NWN: nx.Graph,
source_node: Union[Tuple, List[Tuple]],
drain_node: Union[Tuple, List[Tuple]],
input: float,
type: str = "voltage",
solver: str = "spsolve",
**kwargs
) -> np.ndarray:
"""
... | c5678fe12cc9abdd9404694c513155e7a85f0713 | 26,839 |
def network_allocations_get_for_share_server(context, share_server_id,
session=None):
"""Get network allocation for share server."""
return IMPL.network_allocations_get_for_share_server(context,
share_server_id... | 7fd30c9249ed167ecf17b2902879de992a023db9 | 26,841 |
def round_corner(radius, fill):
"""Draw a round corner"""
corner = Image.new('L', (radius, radius), 0) # (0, 0, 0, 0))
draw = ImageDraw.Draw(corner)
draw.pieslice((0, 0, radius * 2, radius * 2), 180, 270, fill=fill)
return corner | b5f781123ed0dd45dcf61b5d130a9c38c4d3d38f | 26,842 |
def hindcasts(hcsts, obsvs=None, hists=None, shade=False, ax=None, figsize=(15, 4)):
"""
Plot sets of hindcasts. Where multiple variables are provided, it is
assumed that all inputs contain the same variables.
Parameters
----------
hcsts : dict
Dictionary of hindcasts to plot with the f... | da483ad5f39ca200eb6191cf10e77e3dc2b589c2 | 26,843 |
def _create_integration_test_executable(
orig_target_name,
target_suffix,
executable):
"""Create _integration_test_executable rule and return its names.
Args:
orig_target_name: The name given to the sut_component or the
integration_test.
target_suffix: A suffix to append to the orig_targe... | 761a0c586784ce37c3cd22feafb755d42908bca1 | 26,845 |
import torch
def pgd(model, inp, label,
epsilon=0.3,
step_size=0.01,
num_steps=40,
random_start=True,
pixel_range=(-0.5, 0.5)):
"""Short summary.
Parameters
----------
model : nn.Module
Model to attack
inp : tensor
Input to perturb adversari... | 3c59fdf7f4f9d6941a1622c9dc9a9a378c5120c9 | 26,846 |
def enumerate_trials(perievents):
"""
adds an index to perievents_2D that counts the number of trials per session and event
starting with 1, removes FrameCounter index
:param perievents: perievents df, non-column based format
:return: perievents df with additional index Trial
"""
# unstack i... | d469a823b6af60d305dc37b1ce42176f16b21f8d | 26,847 |
import torch
def add_dims_right(tensor, ndims, right_indent=0):
""" Add empty dimensions to the right of tensor shape
"""
assert right_indent >= 0
for i in range(ndims):
tensor = torch.unsqueeze(tensor, -1-right_indent)
return tensor | 7d4c1b47eb659f0bcfc9dbcf7f7b04c1ccbafb80 | 26,848 |
def ciClim( imData, sigma = 2.5 ):
"""
Confidence interval color limits, for images. Most useful for highly spikey data.
"""
meanData = np.mean( imData )
stdData = np.std( imData )
return np.array( [meanData - sigma*stdData, meanData + sigma*stdData] ) | 64debb8fea07c60da0d9af825482959312ef09d5 | 26,849 |
def get_submodel_name(history = 60, lag = 365, num_neighbors = 20, margin_in_days = None, metric = "cos"):
"""Returns submodel name for a given setting of model parameters
"""
submodel_name = '{}-autoknn-hist{}-nbrs{}-margin{}-lag{}'.format(metric,
... | 69fa276a86c39f342ffceba72408ab6970dd0a41 | 26,850 |
def create_db_scoped_session(connection_string=None):
"""Create scoped session."""
# we use NullPool, so that SQLAlchemy doesn't pool local connections
# and only really uses connections while writing results
return scoped_session(
sessionmaker(bind=create_engine(
connection_string ... | da0583601147dbebb97c25d945f05fdb19859709 | 26,851 |
import torch
def sens_reduce_precise(x: torch.Tensor, sens_maps: torch.Tensor) -> torch.Tensor:
"""
Combine num_coils individual coil images into a single image using estimates of the sensitivity maps.
Then replace the magnitude with the RSS estimate to reduce inaccuracies caused by the sensitivity ma... | 5d40c20dc9dd276a734378602f8ce7a42f402087 | 26,852 |
from typing import Callable
def dict_to_object(item, callback: Callable = None):
"""This function convert a Python Dict into a Python object:
>>> data = {"name": "John Smith", "hometown": {"name": "New York", "id": 123}}type >>> c = json_to_object(data)
type>> c
<class 'automatic'>
>>> c.name
... | 6a44ccdf53e54609cac2954f60e080a148daa1ed | 26,853 |
def show_vm(vm_id):
"""
Executes the onevm show command and returns the xml output.
:param int vm_id: vm id number
:return: XML output from onevm show command
"""
return _get_subp_out(["onevm", "show", "-x", str(vm_id)]) | 962b98bb061b5e647c2f11e2447b7b838994d3d4 | 26,854 |
def isragged(arr):
"""Test if an array is ragged (i.e. unequal-length records).
Parameters
----------
arr : array
Returns
-------
ragged : bool
Returns True of not all entries in arr are of same length
(i.e. arr is indeed ragged). False otherwise.
"""
ragged ... | 1fdc0c23be00a8b7535d7a85df05e5d1b323c298 | 26,855 |
def compress_public_key(public_key):
"""Compresses a given uncompressed public key.
:param public_key: the key to compress, as bytes
:return: the compressed key, as bytes
"""
if public_key[0] != 0x04 or len(public_key) != 65:
raise ValueError('invalid uncompressed public key')
# We take... | 8ff7c609a216e29b9cc31584e3cd824f7ab2879d | 26,856 |
import re
def sphinx_doc_parser(doc: str) -> DocParserRetType:
"""A doc parser handling Sphinx-style and epydoc-style docstrings
Args:
doc: The function doc string
Returns:
The parsed doc string and parsed parameter list
"""
main_doc, param_docs = plain_doc_parser(doc)
par... | 1179149b7215838a7cfaa720b1ba6262170031c1 | 26,857 |
def bilinear_interpolate(X, x, y):
"""
Estimates of the pixel values at the coordinates (x, y) in `X` via bilinear
interpolation.
Notes
-----
Assumes the current entries in X reflect equally-spaced
samples from a 2D integer grid.
Modified from https://bit.ly/2NMb1Dr
Parameters
... | 76692e28fe68e6af5266de8672ee0b32754297c3 | 26,858 |
import time
def do_prediction(intbl, pbms, gene_names,
filteropt="p-value", filterval=0.0001, spec_ecutoff=0.4, nonspec_ecutoff=0.35):
"""
intbl: preprocessed table
filteropt: p-value or z-score
filterval: # TFs for opt z-score and p-val cutoff for p-value
"""
# intbl: #rowi... | 70bcd1ed8ffdaf1b97d64ab2afdb1ad48f4a2047 | 26,859 |
def fetch_res(n, k, dim, ampl_noise, type_mat, scaled, norm_laplacian, n_avrg,
save_res_dir, embedding_method):
"""
Get the results from a given experiment when they were saved to a file,
in order to use them for plotting in plot_from_res, or not to redo the same
computation twice in run_s... | ce8cac77d36b5c6bd2920426e054899681318508 | 26,860 |
def load_gramar_from_SYGUS_spec(spec):
"""Creates Grammar from the given SYGUS grammar specification (http://sygus.seas.upenn.edu/files/SyGuS-IF.pdf, last access 3.08.2016).
:param spec: SYGUS grammar specification.
:return: New grammar object.
"""
grammar = Grammar()
spec = spec.replace('(', ... | b909fdb2df0fd005a6ddc1c3069e1ba7659619c2 | 26,861 |
def im_entropy(im):
"""
Calculate entropy of one single image
:param im: a greyscale image in numpy format
:return: entropy of the image
"""
h, w = im.shape
hist = np.histogram(im.reshape(-1), bins=256)[0]
probs = hist / (h * w)
probs = probs[probs > 0]
ent = np.sum(-probs * np.... | aeaddd3c087e2f621ce0b35c108d6d1de630d477 | 26,862 |
def forward(layers, x):
"""
function for performing forward propagation in all the layers
Parameters:
layers : list
x : numpy array
Returns:
list : (contains output of all layers in the form of numpy arrays)
"""
conv = layers[0]
pool = layers[1]
de... | 2e7ae3c8ab513ca5f138c77a868783dc942063ee | 26,863 |
def gen_word_vec_matrix(doc, nrows=100, stop_min=4, return_df=False):
"""
"""
# filter stop words and non-alpha tokens
vecs = [token.vector for token in doc if token.is_alpha and
((not token.is_stop) or (token.is_stop and len(token)>stop_min))]
vec_df = pd.DataFrame(vecs)
#... | 98ddf6efc3ddadda8d72151a2d63860355aa6769 | 26,864 |
def __same_axes(x_axis, y_axis, xlim, ylim):
"""Check if two axes are the same, used to determine squared plots"""
axes_same_and_not_none = (x_axis == y_axis) and (x_axis is not None)
axes_same_lim = xlim == ylim
return axes_same_and_not_none and axes_same_lim | ce7538ffa17e15df0fc055809103bf69af88e7aa | 26,865 |
import csv
def create_column_dicts(path_to_input):
"""Creates dictionaries: {column_index, column_name} and
{column_name, column_index}"""
cols = {}
with open(path_to_input, newline="") as csvfile:
inputreader = csv.reader(csvfile, delimiter=",")
row = next(inputreader)
for i, ... | 13bf2e3c99fea9b1d2580b7bfc34e445af8b7e98 | 26,866 |
from typing import Type
from typing import Any
def autocommit(session_cls: Type[Any], do_commit_at_outermost: bool = True) -> Any:
"""
自动提交装饰器
:param session_cls: Sqlalchemy Session Class, 且该类可以被inject获取到
:param do_commit_at_outermost: 上下文结束后是否提交
:return:
"""
def decorator(func: FunctionT... | f974ba9d28353ba7cf6f676d08b6b6bcbb751d0e | 26,867 |
from operator import add
def multiply(multiplicand, multiplier):
"""Multiplies the multiplicand by the multiplier
This function multiplies the multiplicand by the multiplier only
when they are either integers or floats
Args:
multiplicand(int/float): The quantity that is to be multiplied
... | ad5da56004fd6ad6df327b892ea7cff2c09e9ac6 | 26,868 |
from typing import Optional
from typing import Container
def rolling_enveloped_dashboard(
channel_df_dict: dict, desired_num_points: int = 250, num_rows: Optional[int] = None,
num_cols: Optional[int] = 3, width_for_subplot_row: int = 400, height_for_subplot_row: int = 400,
subplot_colors: Optional[Contain... | bd26531b9f941e340c03ce519f977d55f860d345 | 26,869 |
def compare_clusterers(clusterer_1, clusterer_2, ground_truth, reduction,
figsize=(15, 5), **kwargs):
"""Utility function for comparing two clustering approaches on a problem
for which we have a ground truth.
Args:
- clusterer_1: a dictionary where key is the name of ... | 2406894a354255e48d5e8777b54eed2e50391a25 | 26,870 |
def generate_and_write_ed25519_keypair(password, filepath=None):
"""Generates ed25519 key pair and writes custom JSON-formatted keys to disk.
The private key is encrypted using AES-256 in CTR mode, with the passed
password strengthened in PBKDF2-HMAC-SHA256.
NOTE: The custom key format includes 'ed25519' as s... | 3c9249d6e72ce442562b9dcb1af8cea59111d369 | 26,871 |
def scale_bicubic(data, scale=(1., 1., 1.)):
"""
returns a interpolated, scaled version of data
the output shape is scaled too.
Parameters
----------
data: ndarray
3d input array
scale: float, tuple
scaling factor along each axis (x,y,z)
interpolation: str
eith... | 95b400b5cd05fb8e476bf5f5936641bca159015f | 26,872 |
def test_calc_functions_multiple_arguments():
"""Tests parse/eval handling functions with multiple arguments correctly"""
def h1(x): return x
def h2(x, y): return x * y
def h3(x, y, z): return x * y * z
assert evaluator("h(2)", {}, {"h": h1}, {})[0] == 2.0
assert evaluator("h(2, 3)", {}, {"h"... | cce31c7386e954389a4d59402d881f602f16373a | 26,873 |
import string
def get_sentiment(text, word_map):
"""
Identifies the overall sentiment of the text by taking the average
of each word.
Note: Words not found in the word_map dict are give zero value.
"""
# remove all punctuation
text = text.translate(str.maketrans("", "", string.punctuatio... | ee9e57c999539c0126e5c0d38711a617e82dab10 | 26,874 |
def point_line_seg_distance(p1: tuple, p2: tuple, p: tuple, extend_line: bool = False):
"""
Find shortest distance between a line segment (p1, p2) and a given point p.
"""
assert isinstance(p1, tuple) and len(p1) == 2
assert isinstance(p2, tuple) and len(p2) == 2
assert isinstance(p, tuple) and ... | 47c669bb5fc3db9d97cf2ac03179b2fc700ad0a5 | 26,875 |
def Tanh_Derivative(x):
"""
这是Tanh激活函数的导数计算公式
:param x: 需要进行计算的数据
:return: Tanh激活函数的导数的函数值
"""
f = Tanh(x)
derivative = 1.0-f*f
return derivative | 9142765acc9299ef3b35a16538956dfa3d61efc8 | 26,876 |
async def api_update_donation(
data: CreateDonation, donation_id=None, g: WalletTypeInfo = Depends(get_key_type)
):
"""Update a donation with the data given in the request"""
if donation_id:
donation = await get_donation(donation_id)
if not donation:
raise HTTPException(
... | d60f59d50e2515a8e5402c04b13c51a53855fa80 | 26,877 |
def random_monoalpha_cipher(pool=None):
"""Generate a Monoalphabetic Cipher"""
if pool is None:
pool = letters + digits
original_pool = list(pool)
shuffled_pool = list(pool)
shuffle(shuffled_pool)
return dict(zip(original_pool, shuffled_pool)) | a12976552fc57183e939bd04f2c61cb175d3adec | 26,878 |
from typing import Union
def get_comment(entity: Union[Table, TableProtocol, Column, Constraint]) -> str:
"""Get comment on entity"""
if isinstance(entity, TableProtocol):
return to_table(entity).comment or ""
elif isinstance(entity, Table):
return entity.comment or ""
elif isinstance(... | 4517d43980f596d1a31773a4322805331d871890 | 26,880 |
from typing import List
def merge_neighbor_spans(spans: List[Span], distance) -> List[Span]:
"""Merge neighboring spans in a list of un-overlapped spans:
when the gaps between neighboring spans is not larger than the
specified distance, they are considered as the neighbors.
Args:
spans (List[... | a059228aefefe52c7417d414ed517cb36ee8b753 | 26,881 |
def handle_all_serials(oid, *args):
"""Return dict of oid to serialno from store() and tpc_vote().
Raises an exception if one of the calls raised an exception.
The storage interface got complicated when ZEO was introduced.
Any individual store() call can return None or a sequence of
2-tuples where... | f2ff56d43f40f4bad5a802acbbe7a8fa869831d3 | 26,882 |
def remove_null_fields(data):
"""Remove all keys with 'None' values"""
for k, v in data.items():
if isinstance(v, dict):
remove_null_fields(v)
if isinstance(v, list):
for element in v:
remove_null_fields(element)
if not data[k]:
del dat... | 3dc90d215d899afb2316acb92b5755fd93da204f | 26,883 |
from scipy.ndimage.filters import gaussian_filter1d
from math import log
import numpy
def epsautoconfeval(epsilon, plotTitle):
"""
investigate distance properties for clustering autoconfiguration
plots of k-nearest-neighbor distance histogram and "knee"
See SegmentedMessages#autoconfigureDBSCAN
... | 4c23d8c50dd182c0d045b047e44c2d2484482eec | 26,884 |
def equal_value_solution(par_dict1=params ,par_dict2=params1 , mean=-0.4, variance=0.35,N=1000):
""" This function sets average tax revenue equal under different sets of parameters by changing the base tax rate.
This is done by minizing the squared difference between old and new average revenue using the ba... | 8a6d2b15c2b6b751647f62a3d0172cde45f23f94 | 26,885 |
def dist_l2(v, w):
"""
Euclidean (L2) distance between
two vectors.
"""
s = 0
for i in range(len(v)):
s = s + (v[i] - w[i]) ** 2
s = np.sqrt(s)
return s | c65dced806a0e121263f3a4e26e88bd88e43fa43 | 26,886 |
def convert_single_example_dual(ex_index, example, max_seq_length, tokenizer,
label_list):
"""Converts a single `InputExample` into one or more `DualInputFeatures`.
Args:
ex_index: index of the example
example: InputExample
max_seq_length: maximal sequence length of quer... | 4c89637846ad9b79db1450bd1af4bfa38f80e08c | 26,887 |
def find_recipes(rounds):
"""
Calculate the last ten recipes in the sequence.
:param rounds: the number of rounds
:return: a list of the last 10 recipes in the sequence
>>> find_recipes(5)
[0, 1, 2, 4, 5, 1, 5, 8, 9, 1]
>>> find_recipes(18)
[9, 2, 5, 1, 0, 7, 1, 0, 8, 5]
>>> find_re... | 281cd92094cf9c4be608de5a57075f7f38a531d0 | 26,888 |
def query_abs_over_wiki(abstract):
"""
query from es with the document is wiki_entity
"""
return {
"track_total_hits": "true",
"version": "true",
"size": 1000,
"sort": [{
"_score": {
"order": "desc"
}
}],
"_source": ... | 7e35af5b210cd3485113d7cb5b72f7dd32745d94 | 26,889 |
def mitm_digest_preimage(tshash_params, digest, except_bitstrings=(), max_length=_MITM_DEFAULT_MAX_LENGTH):
""" Performs a meet-in-the-middle attack to find a preimage whose hash arrives at a certain digest. """
# We currently don't discard bits from the state to get a digest
# possible_truncations = ('0b01... | 7e5dc01a0f6f16d9cf064f7ba8070819c0543706 | 26,890 |
import re
def similarityWithResult(Address_1: Address, Address_2: Address):
"""
地址相似度计算
:param Address_1: 地址1, 由 Geocoding.normalizing 方法返回的 Address 类
:param Address_2: 地址2, 由 Geocoding.normalizing 方法返回的 Address 类
:return:
"""
geocoding = jpype.JClass('io.patamon.geocoding.Geocoding')
... | b4bf880eeb5b0666c06ef987d89beeb952ad6e1a | 26,891 |
def validFilename(string):
""" return a valid filename from the input string
stripping characters that are not allowed
"""
out = ''
allowed = _allowedfilenamechars()
for s in string:
if s in allowed:
out += s
return out | 14dd0cb10dd775f61035ec1a85c74f981c5432aa | 26,893 |
def contains_source_code(http_response):
"""
:param http_response: The HTTP response object
:return: A tuple with:
- re.match object if the file_content matches a source code file
- A tuple containing the programming language names
"""
body = http_response.get_body()
... | eadabdf1782e6785b34b7c65853e1cecfc81ab81 | 26,894 |
def wht(at1,at2,ints):
"""
Assign weights for Hessian matrix given 1-2,1-3,1-4 interactions
:param at1: first atom
:param at2: second atom
:param ints: tuples of 1-2,1-3,1-4 interacting pair
:return: 0 for diagonal, assigned weight constant for all other
"""
apair = [at1,at2]
int2, ... | b9e5e01743a6f732c63fbfc71dc264293d890d1b | 26,895 |
def _get_users_with_perms(obj, attach_perms=False, with_group_users=None):
"""
Returns a list of users with their permissions on an object obj.
"""
user_obj_perms = get_user_perms(obj)
if user_obj_perms is None:
return get_users_with_perms(
obj, attach_perms=attach_perms, with_gr... | 79e0f80d28133e2dc1aef69bcf727d572d259d5b | 26,896 |
import base64
def get_file_data(request, oid, version=None, status=None):
"""Get document data"""
document = get_document(request, oid, version, status)
if request.content_type.startswith('text/xml'):
data = Binary(document.data.data)
else:
data = base64.b64encode(document.data.data).d... | 1195671fb7f428e624cccb1f7dc89e92b7ab5d13 | 26,897 |
def batch_get_all_movies():
"""Attempt to get all movies downloaded and serialized. Pickup where
the last attempt left off."""
goal = len(movie_id_df.movie_id)
pickup = check_row_files()
for i in range(5000, goal, 5000):
print(f"Batch serializing the next 5000 movies (to {i}).")
batc... | 0225c89dfa76223d1354df48c5cb441dbb171461 | 26,898 |
def dataset_from_datasource(dsdict, *, datasource_name, dataset_name=None, **dsrc_args):
"""Transformer: Create a Dataset from a DataSource object
This is just a thin wrapper around Dataset.from_datasource in order to
conform to the transformer API
Parameters
----------
dsdict: dict, ignored.
... | 644bb001c874c0e3d4552363b5edb8ecb369ee05 | 26,899 |
def fix_saving_name(name):
"""Neutralizes backslashes in Arch-Vile frame names"""
return name.rstrip('\0').replace('\\', '`') | ba7063766f3397b955a427b4304605fa2add48fb | 26,902 |
def compute_metrics(logits, labels, lengths):
"""Computes metrics and returns them."""
loss = cross_entropy_loss(logits, labels, lengths)
# Computes sequence accuracy, which is the same as the accuracy during
# inference, since teacher forcing is irrelevant when all output are correct.
token_accuracy = jnp.ar... | 2fa08ad9c06e5860f4cb57ca891087b7d67e7806 | 26,905 |
def replace_prelu(input_graph_def: util.GraphDef) -> util.GraphDef:
"""
Replace all Prelu-activations in the graph with supported TF-operations.
Args:
input_graph_def: TF graph definition to examine
Returns:
Updated copy of the input graph with Prelu-nodes replaced by supported
... | 694d84f2661261a320a3d9cee360dd5980bb3a9d | 26,906 |
def tf_parse_filename_classes(filename, normalization='None', normalization_factor=1, augmentation=False):
"""Take batch of filenames and create point cloud and label"""
idx_lookup = {'airplane': 0, 'bathtub': 1, 'bed': 2, 'bench': 3, 'bookshelf': 4,
'bottle': 5, 'bowl': 6, 'car': 7, 'chair':... | 75cc87faa46f25485e2c097c5243f0a44bda1554 | 26,907 |
def next_traj_points(dimension: int, last_point):
"""
:param dimension: dimension of our fake latent trajectory
:param last_point: the last point that was sent to the client as a numpy array
:return: here we are sending 3 points at a time from a noisy Lorenz system
"""
#Euler step size
step... | 6e33833b877cc8bc218d8c0a74357c6b4d8d2a9b | 26,908 |
from six.moves import urllib
def has_internet():
"""
Test if Internet is available.
Failure of connecting to the site "http://www.sagemath.org" within a second
is regarded as internet being not available.
EXAMPLES::
sage: from sage.doctest.external import has_internet
sage: has_... | d9cacc17a315abe85022e9a889d4a1da3c9b6a49 | 26,909 |
def read_warfle_text(path: str) -> str:
"""Returns text from *.warfle files"""
try:
with open(path, "r") as text:
return text.read()
except Exception as e:
raise Exception(e) | ba15fe6a62fbefe492054b0899dcdbff35462154 | 26,910 |
from typing import List
from typing import OrderedDict
def from_mido(midi: MidiFile, duplicate_note_mode: str = "fifo") -> Music:
"""Return a mido MidiFile object as a Music object.
Parameters
----------
midi : :class:`mido.MidiFile`
Mido MidiFile object to convert.
duplicate_note_mode : ... | 795b13dcba41a7c10270e6cd799ef439a0ceb426 | 26,911 |
def iterable_validator(iterable_type, member_type):
# type: (ISINSTANCE, ISINSTANCE) -> Callable[[object, Attribute, Iterable[Any]], None]
"""``attrs`` validator to perform deep type checking of iterables."""
def _validate_iterable(instance, attribute, value):
# type: (object, Attribute, Iterable[A... | 708738c7bc55e4bb4c4fa9ae93cf56ddb038ebda | 26,912 |
def sample_filtering(df, metadata, filter_by):
"""Filter samples based on selected features and values."""
# Get the variable a values specified for sample filtering
filter_col = filter_by[0]
filter_values = filter_by[1].split(sep=',')
# Saving a new metadata file containing only the samples remai... | 437391b946ed61817292c160402b1c6e0b81fa94 | 26,913 |
def user_is_registered_or_more(user_id):
"""Check that user is registered, moderator, or admin."""
user = Users.query.filter_by(UserID=user_id).first()
user_map = UsersAccessMapping.query.filter_by(UserID=user_id).first()
if user is None:
return False
if user_map is None:
return Fals... | a405ee98673ffa87f260519ec8fc9ff88efa2089 | 26,915 |
from typing import Union
from typing import Sequence
from typing import Optional
from typing import Type
def run(
cmds: Union[str, Sequence[Union[str, Sequence[str]]]],
shell: Optional[Union[str, bool]] = None,
mode: Type[Mode] = str,
block: bool = True,
**kwargs
) -> Processes:
"""
Runs s... | 370f4867701fcda0683030749e0a9754bf2b518e | 26,917 |
def _infer_labels(center_e):
"""Create labels based on center extrema."""
# Infer labels
if center_e == 'trough':
labels = ['Trough', 'Peak', 'Inflection']
keys = ['sample_trough', 'sample_next_peak', 'sample_end']
elif center_e == 'peak':
labels = ['Peak', 'Trough', 'Inflection... | 854a6bbe1c45a806d3c6ecd15bee11f3ec9496a4 | 26,918 |
def MXXXtoMYYY(redshift = 0.3,
MXXX = 6E14,
CXXX = 3.0,
wrt = "crit",
new_wrt = "crit",
XXX = 500.0,
YYY = 500.0,
cosmo = cosmo):
"""
It converts the (MXXX,CXXX) in... | f6c7e628ce79785c9d28939e6e3de8fe3ed3878a | 26,919 |
import html
def gldas_to_cycles(
latitude,
longitude,
output_file,
start_date="2000-01-01",
end_date="2017-12-31",
gldas_path="/raw-data/GLDAS",
):
"""Transform GLDAS to Cycles."""
j = Job("gldas_to_cycles")
j.addProfile(Profile(Namespace.CONDOR, key="+SingularityImage", value=html... | 1ce787266d5b232f0b8c76d639328a0dc4384e2f | 26,920 |
def max_pool_2x2(x):
"""max_pool_2x2 downsamples a feature map by 2X."""
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding='VALID') | 45141be3715fd821c8712bc81c644498871d7b8c | 26,921 |
def set_bit_value(val, offs, value):
"""Set bit at offset 'offs' to a specific value in 'val'."""
if value:
return set_bit(val, offs)
else:
return clear_bit(val, offs) | 793165cc53adc140b60521b6fc772efa80b69ebb | 26,923 |
def gradientFunction(theta, X, y):
"""
Compute cost and gradient for logistic regression with regularization
computes the cost of using theta as the parameter for regularized logistic
regression and the gradient of the cost w.r.t. to the parameters.
"""
# Initialize some useful values
# n... | 5ca8c355474c9cab10b2b255b71b943b2b6b0aa1 | 26,924 |
def splice(tree, rep, tag):
"""Splice in a tree into another tree.
Walk ``tree``, replacing the first occurrence of a ``Name(id=tag)`` with
the tree ``rep``.
This is convenient for first building a skeleton with a marker such as
``q[name["_here_"]]``, and then splicing in ``rep`` later. See ``fora... | b42c5300b7ad9d5d04ba0233c94c735686e1300a | 26,925 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.