content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def process_2d_sawtooth(data, period, samplerate, resolution, width, verbose=0, start_zero=True, fig=None):
""" Extract a 2D image from a double sawtooth signal
Args:
data (numpy array): measured trace
period (float): period of the full signal
samplerate (float): sample rate of the acqu... | f7b212d54637e04294cda336e154910eb718b3e5 | 26,800 |
def lower_threshold_projection(projection, thresh=1e3):
"""
An ugly but effective work around to get a higher-resolution curvature
of the great-circle paths. This is useful when plotting the great-circle
paths in a relatively small region.
Parameters
----------
projection : class
... | 165c657f1ec875f23df21ef412135e27e9e443c6 | 26,801 |
def post_benchmark(name, kwargs=None):
"""
Postprocess benchmark
"""
if kwargs is None:
kwargs = {}
post = benchmarks[name].post
return post(**kwargs) | 900f60435ae31e8ec09312f23ab9f98a723d22af | 26,802 |
def tag_view_pagination_counts(request,hc,urls,tag_with_items):
"""
retrieve the pagination counts for a tag
"""
hc.browser.get(urls['https_authority'])
try:
po = hc.catalog.load_pageobject('TagsPage')
po.goto_page()
po.search_for_content([tag_with_items])
po = hc.... | 7130ffdbb2b8f90fadf1a159d15726012511ddee | 26,803 |
def arts_docserver_role(name, rawtext, text, lineno, inliner, options=None,
content=None):
"""Create a link to ARTS docserver.
Parameters:
name (str): The role name used in the document.
rawtext (str): The entire markup snippet, with role.
text (str): The text ma... | 8f20cc4adb9f7fa17514116fe984562d9f0174f3 | 26,804 |
def arima_model(splits, arima_order, graph=False):
"""
Evaluate an ARIMA model for a given order (p,d,q) and also forecast the next one time step.
Split data in train and test. Train the model using t = (1, ..., t) and predict next time step (t+1).
Then add (t+1) value from test dataset to history and f... | 07ca1349e5ebe02793fbf798cbd4e5ce20128a74 | 26,805 |
import ctypes
def srfscc(srfstr, bodyid):
"""
Translate a surface string, together with a body ID code, to the
corresponding surface ID code. The input surface string may
contain a name or an integer ID code.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/srfscc_c.html
:... | 9f32b6929c2fd5d482db5f79f4b00f1fe41b114b | 26,806 |
import json
import requests
def pr_comment(
message: str,
repo: str = None,
issue: int = None,
token=None,
server=None,
gitlab=False,
):
"""push comment message to Git system PR/issue
:param message: test message
:param repo: repo name (org/repo)
:param issue: pull-req... | 7115ec59fca36459a15e07906ce5c58b305bcfdc | 26,807 |
import subprocess
import sys
def check_output(command, catch_errors=True):
"""Execute a command and return the output as a stripped string. """
try:
return subprocess.check_output(
command, shell=True,
stderr=subprocess.STDOUT).decode('utf-8').strip()
except subprocess.CalledProcessError as sube... | b12b37fabc205636a5d9e7fc67f0808c8337fcf2 | 26,808 |
def list_kickstart_profiles(name):
"""
returns the list of profile name matching the name of kickstart file
e.g. http://host:port/cm/v1/cobbler/kickstarts/default.ks/profile
"""
cp = CobblerProvision()
method = request.method
if method == "GET":
# MUST know how to get user token,... | 05b734bd6142ef6260a18cd4961c32f26c71b068 | 26,809 |
from typing import Sequence
def windowed_run_count_1d(arr: Sequence[bool], window: int) -> int:
"""Return the number of consecutive true values in array for runs at least as long as given duration.
Parameters
----------
arr : Sequence[bool]
Input array (bool).
window : int
Minimum dur... | ff7b18380cd77ad046fc5d5aa678e7393c72d495 | 26,810 |
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 |
import platform
import subprocess
def start_daemon(args: list) -> int:
"""Starts daemon process.
Arguments:
args: Arguments for `subprocess.Popen` (first item must be the daemon filename)
Returns:
PID for started daemon, or None if start failed.
Note:
Gracefull shutdown on W... | b21fb344b3173c5d3f49d1dcd4f7b0890290df35 | 26,812 |
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 pql_breakpoint(state: State):
"""Creates a Python breakpoint.
For a Preql breakpoint, use debug() instead
"""
breakpoint()
return objects.null | a826c75ddb7a665d85f379a90b0e17b2ce2fc572 | 26,816 |
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 |
import sys
def constant_time_compare(val1, val2):
"""
Returns True if the two strings are equal, False otherwise.
The time taken is independent of the number of characters that match.
"""
if len(val1) != len(val2):
return False
result = 0
if sys.version_info >= (3, 0, 0): # bytes... | c2b8c8d4a8b5c5f1b6b106211eeabe9b51a30fbe | 26,822 |
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_admins_timeseries_chart_data():
"""
Return admins timeseries data to frontend
:return: dict
"""
chart_data = {}
try:
pipe = [
{'$match': {VAX_AREA_KEY: {'$ne': 'ITA'}}},
{'$sort': {VAX_DATE_KEY: 1}}
]
cursor = vax_admins_summary_coll.aggreg... | 0b06612e6be332797f0c7b715810e3ddd61e0c62 | 26,829 |
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 d2s_func(va, vb, ka, wa, wb, pa):
"""
Create a function that requires only frequency as an argurment, and used to
calculate intensities across array of frequencies in the DNMR
spectrum for two uncoupled spin-half nuclei.
The idea is to calculate expressions
that are independant of frequency... | c3af0fc4d07a8b35b0147c18a15d968d2680b7bb | 26,840 |
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 Main(block_index):
"""
:param block_index:
:return:
"""
header = GetHeader(block_index)
print("got block!")
ts = header.Timestamp
print("got timestamp")
block = GetBlock(block_index)
txlist = block.Transactions
# @TODO this does not work
# for tx in block.Transa... | be63ad2741c2d9d4de56739916924a927cf238bd | 26,844 |
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 |
def mrf_slice_example(slice):
"""convert mrf slice data to tensorflow
Args:
slice: Dict. Contains keys:
immrf/data, immrf/path,
tmap/data, tmap/path,
mask/data, mask/path
Returns: TODO
"""
immrf = slice["immrf/data"]
tmap = slice["tmap/d... | 9c8995cd8a68793e505e525da144dabccaba5ff7 | 26,879 |
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 longitudinal_summary(ds, lat_dim='lat', lon_dim='lon', lon_res=5):
"""Compute longitudinal (bin) statistics, averaging over latitude."""
# Check lat_dim and lon_dim
# Check lon_res < 180
# TODO: lon between -180 and 180 , lat between -90 and 90
aggregating_dims = list(ds[lon_dim].dims)
bi... | 7b2c6abf8eaf399587c58aea5783c474542602ec | 26,892 |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.