content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import time
def get_dist():
"""
Measures the distance of the obstacle from the rover.
Uses a time.sleep call to try to prevent issues with pin writing and
reading. (See official gopigo library)
Returns error strings in the cases of measurements of -1 and 0, as -1
indicates and error, and 0 s... | a615d9938b117821d39b9acdce507f0171583c03 | 12,919 |
from typing import Callable
def map_filter(filter_function: Callable) -> Callable:
"""
returns a version of a function that automatically maps itself across all
elements of a collection
"""
def mapped_filter(arrays, *args, **kwargs):
return [filter_function(array, *args, **kwargs) for arr... | a5f9f97d1a0d4acdaa39b9fb72a73b95a81553bb | 12,920 |
from typing import Literal
def compare_models(
champion_model: lightgbm.Booster,
challenger_model: lightgbm.Booster,
valid_df: pd.DataFrame,
comparison_metric: Literal["any", "all", "f1_score", "auc"] = "any"
) -> bool:
"""
A function to compare the performance of the Champion ... | 8f5f522375a4c274c3c80fcbfddad2e8cf450328 | 12,921 |
def check_additional_args(parsedArgs, op, continueWithWarning=False):
"""
Parse additional arguments (rotation, etc.) and validate
:param additionalArgs: user input list of additional parameters e.g. [rotation, 60...]
:param op: operation object (use software_loader.getOperation('operationname')
:re... | ab289271fe4a61ec77ed2b522687dd4df7cbd35c | 12,922 |
import re
def clean_text(text, language):
"""
text: a string
returns: modified initial string (deletes/modifies punctuation and symbols.)
"""
replace_by_blank_symbols = re.compile('\#|\u00bb|\u00a0|\u00d7|\u00a3|\u00eb|\u00fb|\u00fb|\u00f4|\u00c7|\u00ab|\u00a0\ude4c|\udf99|\udfc1|... | eaf22844fcd3528c20b34f16c276042810a672f5 | 12,923 |
def parameters():
"""
Dictionary of parameters defining geophysical acquisition systems
"""
return {
"AeroTEM (2007)": {
"type": "time",
"flag": "Zoff",
"channel_start_index": 1,
"channels": {
"[1]": 58.1e-6,
"[2]": ... | 5ae2626c2c8a5445457169f3f2866bf8233ee7f3 | 12,924 |
import binascii
def generate_ngrams_and_hashit(tokens, n=3):
"""The function generates and hashes ngrams
which gets from the tokens sequence.
@param tokens - list of tokens
@param n - count of elements in sequences
"""
return [binascii.crc32(bytearray(tokens[i:i + n]))
for i in r... | eb627add56f51a533c773e0dfea029bfcdb808ee | 12,925 |
from typing import List
def generate_fingerprints(args: Namespace, logger: Logger = None) -> List[List[float]]:
"""
Generate the fingerprints.
:param logger:
:param args: Arguments.
:return: A list of lists of target fingerprints.
"""
# import pdb; pdb.set_trace()
checkpoint_path = ar... | aac2b9f342306be7dc79a029c8433dd5f2147d0e | 12,926 |
def transform_xlogx(mat):
"""
Args:
mat(np.array): A two-dimensional array
Returns:
np.array: Let UsV^† be the SVD of mat. Returns
Uf(s)V^†, where f(x) = -2xlogx
"""
U, s, Vd = np.linalg.svd(mat, full_matrices=False)
return (U * (-2.0*s * np.log(s))) @ Vd | f4cf18a8ae9f7a298ffd6b6400a33a9cad5fabbd | 12,927 |
from datetime import datetime
def get_clip_name_from_unix_time(source_guid, current_clip_start_time):
"""
"""
# convert unix time to
readable_datetime = datetime.fromtimestamp(int(current_clip_start_time)).strftime('%Y_%m_%d_%H_%M_%S')
clipname = source_guid + "_" + readable_datetime
return... | 0a212a76a69507ae3020c1e05ec354a927ad3dae | 12,929 |
def extract_pc_in_box3d(pc, box3d):
"""Extract point cloud in box3d.
Args:
pc (np.ndarray): [N, 3] Point cloud.
box3d (np.ndarray): [8,3] 3d box.
Returns:
np.ndarray: Selected point cloud.
np.ndarray: Indices of selected point cloud.
"""
box3d_roi_inds = in_hull(pc[... | 2d9cb9089631e357ed8ec5ee454203d5eaec1c1d | 12,930 |
import typing
def get_list_as_str(list_to_convert: typing.List[str]) -> str:
"""Convert list into comma separated string, with each element enclosed in single quotes"""
return ", ".join(["'{}'".format(list_item) for list_item in list_to_convert]) | 6b565c3d63d9887f05d5369511b8453c406f7b72 | 12,931 |
def normalize_sides(sides):
"""
Description: Squares the sides of the rectangles and averages the points
so that they fit together
Input:
- sides - Six vertex sets representing the sides of a drawing
Returns:
- norm_sides - Squared and fit sides list
"""
sides_list = []
# Average side vertices and make... | 855fcc45d14db2eede9fd7ec2fa6bf2f6854950d | 12,932 |
def GetFieldInfo(column: Schema.Column,
force_nested_types: bool = False,
nested_prefix: str = 'Nested_') -> FieldInfo:
"""Returns the corresponding information for provided column.
Args:
column: the column for which to generate the dataclass FieldInfo.
force_n... | e788ef090bb8fd8150f2effe42d2db4e8c3fdde6 | 12,933 |
def get_session():
"""
Get the current session.
:return: the session
:raises OutsideUnitOfWorkError: if this method is called from outside a UOW
"""
global Session
if Session is None or not Session.registry.has():
raise OutsideUnitOfWorkError
return Session() | 8a1bfb7afff2cc1a843eaa01e59eabea5e083339 | 12,934 |
import functools
import torch
def create_sgd_optimizers_fn(datasets, model, learning_rate, momentum=0.9, weight_decay=0, nesterov=False, scheduler_fn=None, per_step_scheduler_fn=None):
"""
Create a Stochastic gradient descent optimizer for each of the dataset with optional scheduler
Args:
... | 6d76d5dfc0f633a324d7ee9fe347f1bc68bf0492 | 12,935 |
def equalize(img):
"""
Equalize the histogram of input PIL image.
Args:
img (PIL image): Image to be equalized
Returns:
img (PIL image), Equalized image.
"""
if not is_pil(img):
raise TypeError('img should be PIL image. Got {}'.format(type(img)))
return ImageOps.... | d31d3590ba7927518475053911bdb4251381815d | 12,936 |
def ratingRange(app):
""" Get the rating range of an app. """
rating = 'Unknown'
r = app['rating']
if r >= 0 and r <= 1:
rating = '0-1'
elif r > 1 and r <= 2:
rating = '1-2'
elif r > 2 and r <= 3:
rating = '2-3'
elif r > 3 and r <= 4:
rating = '3-4'
elif r > 4 and r <= 5:
rating = '4-5'
return rating | 69056c367a87e331cd3b606423540250b20f6485 | 12,938 |
def immediate_sister(graph, node1, node2):
"""
is node2 an immediate sister of node1?
"""
return (node2 in sister_nodes(graph, node1) and is_following(graph, node1, node2)) | cb1cdc13e8aceb88e72781a547c9ef1eb2079cb0 | 12,939 |
def get_topic_link(text: str) -> str:
"""
Generate a topic link.
A markdown link, text split with dash.
Args:
text {str} The text value to parse
Returns:
{str} The parsed text
"""
return f"{text.lower().replace(' ', '-')}" | 445afc9358f98323934e0e2788ed52658c7040cb | 12,940 |
def load_data(datapath):
"""Loads data from CSV data file.
Args:
datapath: Location of the training file
Returns:
summary dataframe containing RFM data for btyd models
actuals_df containing additional data columns for calculating error
"""
# Does not used the summary_data_from_transaction_data fr... | d7efe25303fa7839a9842d7b04bcdb1f749a4830 | 12,941 |
def rms(a, axis=None):
"""
Calculates the RMS of an array.
Args:
a (ndarray). A sequence of numbers to apply the RMS to.
axis (int). The axis along which to compute. If not given or None,
the RMS for the whole array is computed.
Returns:
ndarray: The RMS of the arra... | 1b4a2989f8dd06956ae87a2991ef75ca0c6037fc | 12,942 |
def event_message(iden, event):
"""Return an event message."""
return {
'id': iden,
'type': TYPE_EVENT,
'event': event.as_dict(),
} | 3b30f3f697d0615a55b3b494f73d01c8df5dcb0e | 12,944 |
def logout():
"""Logout."""
logout_user()
flash(lazy_gettext("You are logged out."), "info")
return redirect(url_for("public.home")) | 2e65faed65671e881594a9a3c990bc6151417575 | 12,945 |
import json
def predicate_to_str(predicate: dict) -> str:
"""
谓词转文本
:param predicate: 谓词数据
:return: 文本
"""
result = ""
if "block" in predicate:
result += "检查方块\n\n"
block = predicate["block"]
if "nbt" in block:
result += f"检查nbt:\n``` json\n{try_pretty_j... | 799f3fe66fe5ca78635c9d9b3f3a33a11ee63912 | 12,946 |
from typing import Optional
async def get_postcode(postcode_like: PostCodeLike) -> Optional[Postcode]:
"""
Gets the postcode object for a given postcode string.
Acts as a middleware between us and the API, caching results.
:param postcode_like: The either a string postcode or PostCode object.
:ret... | c0123b52dca8892c2f399892bee8f6ee2d5ada60 | 12,948 |
def get_ebv(path, specs=range(10)):
"""Lookup the EBV value for all targets from the CFRAME fibermap.
Return the median of all non-zero values.
"""
ebvs = []
for (CFRAME,), camera, spec in iterspecs(path, 'cframe', specs=specs, cameras='b'):
ebvs.append(CFRAME['FIBERMAP'].read(columns=['EBV'... | f27fc781109eed9e4e8102c88396f33a735742e9 | 12,950 |
def create_pipeline(pipeline_name: Text, pipeline_root: Text, data_root: Text,
beam_pipeline_args: Text) -> pipeline.Pipeline:
"""Custom component demo pipeline."""
examples = external_input(data_root)
# Brings data into the pipeline or otherwise joins/converts training data.
example_gen =... | 7804df79d4e1ac969df5ef5a2399d841b52d4683 | 12,952 |
def toggleAction(*args, **kwargs):
"""A decorator which identifies a class method as a toggle action. """
return ActionFactory(ToggleAction, *args, **kwargs) | c9bc47a1f62ccac95ace344a4def7bd81064793e | 12,953 |
def getHistograph(dataset = {}, variable = ""):
"""
Calculates a histogram-like summary on a variable in a dataset
and returns a dictionary. The keys in the dictionary are unique items
for the selected variable. The values of each dictionary key, is the number
of times the unique item occured i... | e07c0d1b3e9ba8507402189057b186ee0f8dee3c | 12,954 |
def _get_client_by_settings(
client_cls, # type: Type[BaseClient]
bk_app_code=None, # type: Optional[str]
bk_app_secret=None, # type: Optional[str]
accept_language=None, # type: Optional[str]
**kwargs
):
"""Returns a client according to the django settings"""
client = client_cls(**kwargs... | efbb42d7795f7e0939d33f2427470e202d6580c9 | 12,955 |
from controllers import sites
import jinja2
def create_and_configure_jinja_environment(
dirs, autoescape=True, handler=None, default_locale='en_US'):
"""Sets up an environment and gets jinja template."""
# Defer to avoid circular import.
locale = None
app_context = sites.get_course_for_current_r... | 88d285cd436b5af0848c2ca1e45caa3e28a8e074 | 12,956 |
import numpy
def bootstrap_cost(target_values, class_probability_matrix, cost_function,
num_replicates):
"""Bootstraps cost for one set of examples.
E = number of examples
K = number of classes
B = number of bootstrap replicates
:param target_values: length-E numpy array of ta... | ba76e9b9614407a4c0d49c16e3b9ab9f0974a820 | 12,957 |
def jdeblend_bob(src_fm, bobbed):
"""
Stronger version of jdeblend() that uses a bobbed clip to deblend.
Parameters:
clip src_fm: Source after field matching, must have field=3 and low cthresh.
clip src: Bobbed source.
Example:
src =
from havsfunc impo... | d5e79710d7346a2376656ccfaf9c43a70fa8bc36 | 12,958 |
import optparse
def ParseArgs():
"""Parse the command line options, returning an options object."""
usage = 'Usage: %prog [options] LIST|GET|LATEST'
option_parser = optparse.OptionParser(usage)
AddCommandLineOptions(option_parser)
log_helper.AddCommandLineOptions(option_parser)
options, args = option_pars... | cfef602975011d4b04e7797a9e1426293f0d0b7b | 12,959 |
import io
def generate_table_definition(schema_and_table, column_info,
primary_key=None, foreign_keys=None,
diststyle=None, distkey=None, sortkey=None):
"""Return a CREATE TABLE statement as a string."""
if not column_info:
raise Exception('N... | 383cdc8ed13fbaa45adadec26f31ad0f5ac52fbc | 12,960 |
def gradient_descent_update(x, gradx, learning_rate):
"""
Performs a gradient descent update.
"""
# Return the new value for x
return x - learning_rate * gradx | db5ec512883352f473990eca124c8ad302ec3564 | 12,961 |
def nth_permutation(n, size=0):
"""nth permutation of 0..size-1
where n is from 0 to size! - 1
"""
lehmer = int_to_lehmer(n, size)
return lehmer_to_permutation(lehmer) | b79bb639cbf23296879562fa718218beee86f378 | 12,962 |
def signin(request):
"""
Method for log in of the user
"""
if request.user.is_authenticated:
return_var = render(request, '/')
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=us... | aadab619cca9d71e3f255f910af7b8d1dd59b8f4 | 12,963 |
def compare_features(f1, f2):
"""Comparison method for feature sorting."""
def get_prefix(feature):
if feature.startswith('e1-'): return 'e1'
if feature.startswith('e2-'): return 'e2'
if feature.startswith('e-'): return 'e'
if feature.startswith('t-'): return 't'
return '... | 2b93e2c6b6a9993d13964d726efe855d57f72448 | 12,964 |
def localized_index(lang):
"""
Example view demonstrating rendering a simple HTML page.
"""
context = make_context()
context['lang'] = lang
context['content'] = context['COPY']['content-%s' % lang]
context['form'] = context['COPY']['form-%s' % lang]
context['share'] = context['COPY']['sh... | 7d6878f30270c735a2d97353b813cdf632043b92 | 12,965 |
def build_output_unit_vqa(q_encoding, m_last, num_choices, apply_dropout,
scope='output_unit', reuse=None):
"""
Apply a 2-layer fully-connected network to predict answers. Apply dropout
if specified.
Input:
q_encoding: [N, d], tf.float32
m_last: [N, d], tf.floa... | 2fc8d0c9246cbb3350af9d20a85964c9f3967618 | 12,966 |
def coding_problem_16(length):
"""
You run a sneaker website and want to record the last N order ids in a log. Implement a data structure to
accomplish this, with the following API:
record(order_id): adds the order_id to the log
get_last(i): gets the ith last element from the log. i is guar... | 5c1b3e6be920ce826f7c8e8b0fc8fd27cd398079 | 12,967 |
def _check_dimensions(n_grobs, nrow = None, ncol = None):
"""
Internal function to provide non-Null nrow and ncol numbers
given a n_number of images and potentially some information about the
desired nrow/ncols.
Arguments:
----------
n_grobs: int, number of images to be organized
nrow: ... | 20531024ecabc4b4b7b5ce1d8a20774cf2b568ac | 12,968 |
import re
def year_parse(s: str) -> int:
"""Parses a year from a string."""
regex = r"((?:19|20)\d{2})(?:$|[-/]\d{2}[-/]\d{2})"
try:
year = int(re.findall(regex, str(s))[0])
except IndexError:
year = None
return year | f52449aefcba52106fe8c7c03355c237a94775e1 | 12,969 |
import random
def sampleDistribution(d):
"""
Expects d to be a list of tuples
The first element should be the probability
If the tuples are of length 2 then it returns the second element
Otherwise it returns the suffix tuple
"""
# {{{
z = float(sum(t[0] for t in d))
if z == 0.0:
... | 4e47b3dead1e9cc42bf152e6854cbd7cdb255438 | 12,970 |
def logout():
"""
`/register` endpoint
Logs out a user and redirects to the index page.
"""
logout_user()
flash("You are logged out.", "info")
return redirect(url_for("main.index")) | 7054a11253b02522178c528197071c1ae9c3ae81 | 12,971 |
import requests
def players_season_totals(season_end_year, playoffs=False, skip_totals=False,
output_type=None, output_file_path=None, output_write_option=None, json_options=None):
"""
scrape the "Totals" stats of all players from a single year
Args:
season_end_year (int): year in which the... | ea0fa62e9b7ec644404d7968f2b11b14781b4c37 | 12,972 |
import random
def array_shuffle(x,axis = 0, random_state = 2020):
"""
对多维度数组,在任意轴打乱顺序
:param x: ndarray
:param axis: 打乱的轴
:return:打乱后的数组
"""
new_index = list(range(x.shape[axis]))
random.seed(random_state)
random.shuffle(new_index)
x_new = np.transpose(x, ([axis]+[i for i in li... | df6ff3e9fd1d94ff6a6e633451a88815b16f1e83 | 12,973 |
import time
def get_recent_activity_rows(chase_driver):
"""Return the 25 most recent CC transactions, plus any pending
transactions.
Returns:
A list of lists containing the columns of the Chase transaction list.
"""
_goto_link(chase_driver, "See activity")
time.sleep(10)
rows = c... | 2ac3d6de1cac0e28d2dd9a9d170cef7f1facf007 | 12,975 |
def loglikelihood(x, mean, var, pi):
"""
式(9.28)
"""
lkh = []
for mean_k, var_k, pi_k in zip(mean, var, pi):
lkh.append(pi_k * gaussian_pdf(x, mean_k, var_k))
return np.sum(np.log(np.sum(lkh, 0))) | d2355334b305f1bf2084efea3baee78daf06cc35 | 12,976 |
def calc_E_ST_GJ(E_star_ST):
"""基準一次エネルギー消費量(GJ/年)の計算 (2)
Args:
E_star_ST(float): 基準一次エネルギー消費量(J/年)
Returns:
float: 基準一次エネルギー消費量(GJ/年)
"""
# 小数点以下一位未満の端数があるときはこれを切り上げる
return ceil(E_star_ST / 100) / 10 | 06d7ade15d91c205bd9662dd41d218d8b7867a2f | 12,977 |
def next_line(grd_file):
"""
next_line
Function returns the next line in the file
that is not a blank line, unless the line is
'', which is a typical EOF marker.
"""
done = False
while not done:
line = grd_file.readline()
if line == '':
return line, False
elif line.strip():
return line, True | 337f188930a03142bae59cdb378b09f1ac5e2ecb | 12,978 |
def get_proto(proto):
"""
Returns a protocol number (in the /etc/protocols sense, e.g. 6 for
TCP) for the given input value. For the protocols that have
PROTO_xxx constants defined, this can be provided textually and
case-insensitively, otherwise the provided value gets converted to
an integer a... | a3632e0731e4227020eb75d5ea27d211e27e188a | 12,980 |
def f5_update_policy_cookie_command(client: Client, policy_md5: str, cookie_id: str,
cookie_name: str,
perform_staging: bool, parameter_type: str,
enforcement_type: str,
attack... | 633015c3dc3c478e17975ea540a6e6ab46b710e1 | 12,981 |
def ping():
"""
Determine if the container is working and healthy. In this sample container, we declare
it healthy if we can load the model successfully.
:return:
"""
health = False
try:
health = model is not None # You can insert a health check here
except:
pass
... | 96cc202cf4cf25dd6fb91ae29cac66667ed13d27 | 12,982 |
from .coo import COO
def random(
shape,
density=0.01,
random_state=None,
data_rvs=None,
format='coo'
):
""" Generate a random sparse multidimensional array
Parameters
----------
shape: Tuple[int]
Shape of the array
density: float, optional
D... | f62ba3afc168bf39734897291d094d43bd1ee7f1 | 12,983 |
from pathlib import Path
import hashlib
def file_md5_is_valid(fasta_file: Path, checksum: str) -> bool:
"""
Checks if the FASTA file matches the MD5 checksum argument.
Returns True if it matches and False otherwise.
:param fasta_file: Path object for the FASTA file.
:param checksum: MD5 checksum... | ec400afbe29d940d0638a581da7f2ee001b9e985 | 12,984 |
def combine_to_int(values):
"""Combine several byte values to an integer"""
multibyte_value = 0
for byte_id, byte in enumerate(values):
multibyte_value += 2**(4 * byte_id) * byte
return multibyte_value | 58ff7cbee356cdcbe5b26e973de16c5b1cc40afc | 12,985 |
import torch
def loss_fn(x, results, is_valtest=False, **kwargs):
"""
Loss weight (MCAE):
- sni: snippet reconstruction loss
- seg: segment reconstruction loss
- cont: smooth regularization
- reg: sparsity regularization
- con: constrastive loss
- cls: auxilliary classification loss <n... | ef5953c3350952a1083aabaa8f656834a32ae17c | 12,986 |
def _as_uint32(x: int) -> QVariant:
"""Convert the given int to an uint32 for DBus."""
variant = QVariant(x)
successful = variant.convert(QVariant.UInt)
assert successful
return variant | 08de1fccf4625485fab82c2569932ffd3e006541 | 12,987 |
def svcs_tang_u(Xcp,Ycp,Zcp,gamma_t,R,m,Xcyl,Ycyl,Zcyl,ntheta=180, Ground=False):
"""
Computes the velocity field for nCyl*nr cylinders, extending along z:
nCyl: number of main cylinders
nr : number of concentric cylinders within a main cylinder
INPUTS:
Xcp,Ycp,Zcp: cartesian coo... | f5ee6309a01c493f930086a92db44c93cb33cbba | 12,988 |
def np_to_o3d_images(images):
"""Convert numpy image list to open3d image list
Parameters
----------
images : list[numpy.ndarray]
Returns
o3d_images : list[open3d.open3d.geometry.Image]
-------
"""
o3d_images = []
for image in images:
image = np_to_o3d_image(image)
... | 419f59c47cba9c22595c8d16ca0d35f105ec4882 | 12,989 |
def compute_mse(y_true, y_pred):
"""ignore zero terms prior to comparing the mse"""
mask = np.nonzero(y_true)
mse = mean_squared_error(y_true[mask], y_pred[mask])
return mse | 3c594c4105f99d8088665b4c0a7345807a667e55 | 12,990 |
def image2d(math_engine, batch_len, batch_width, height, width, channels, dtype="float32"):
"""Creates a blob with two-dimensional multi-channel images.
:param neoml.MathEngine.MathEngine math_engine: the math engine that works with this blob.
:param batch_len: the **BatchLength** dimension of the new blo... | d816388f619ac1e09e2bfc705ddab75a490ec023 | 12,991 |
def error_response(error, message):
"""
returns error response
"""
data = {
"status": "error",
"error": error,
"message": message
}
return data | f3e52ea42cb48378f08ecb65f58d2291960e6488 | 12,992 |
import tqdm
def graph_to_text(
graph: MultiDiGraph, quoting: bool = True, verbose: bool = True
) -> str:
"""Turns a graph into
its text representation.
Parameters
----------
graph : MultiDiGraph
Graph to text.
quoting : bool
If true, quotes will be added.
verbose : b... | a3ccf008f1ebcc62cfe1c8e6620923c665de8768 | 12,993 |
def test_has_valid_dir_structure():
"""Check if the specified dir structure is valid"""
def recurse_contents(contents):
if contents is None:
return None
else:
for key, value in contents.items():
assert(isinstance(key, str))
if value is None:
return None
... | f2dc8dcb38dc5873dea8500391a1733f9f8a18d1 | 12,994 |
def getFBA(fba):
"""AC factory.
reads a fileobject and creates a dictionary for easy insertation
into a postgresdatabase. Uses Ohlbergs routines to read the files (ACfile)
"""
word = fba.getSpectrumHead()
while word is not None:
stw = fba.stw
mech = fba.Type(word)
datadic... | e5c5f52fe831938400eec5ae15c043ecbf8cf7d1 | 12,995 |
def logtimestamp():
"""
returns a formatted datetime object with the curren year, DOY, and UT
"""
return DT.datetime.utcnow().strftime("%Y-%j-%H:%M:%S") | 71b204c473d8e6a4868d966877dd61909252e891 | 12,996 |
def get_most_common_non_ascii_char(file_path: str) -> str:
"""Return first most common non ascii char"""
with open(file_path, encoding="raw_unicode_escape") as f:
non_ascii = {}
for line in f:
for char in line:
if not char.isascii():
if char in non... | 5280b637206964d6b386478ddbaeb6ad69f92c8c | 12,997 |
def compute_noise_from_target_epsilon(
target_epsilon,
target_delta,
epochs,
batch_size,
dataset_size,
alphas=None,
approx_ratio=0.01,
):
"""
Takes a target epsilon (eps) and some hyperparameters.
Returns a noise scale that gives an epsilon in [0.99 eps, eps].
The approximati... | 60bddeaca8e772fa15582fe87516f4e5c5284b75 | 12,998 |
def cart2pol(x, y):
"""
author : Dr. Schaeffer
"""
rho = np.sqrt(x**2 + y**2)
phi = np.arctan2(y, x)
return(rho, phi) | 490e839b9a7c7e369643c27df3bbf4a6cd6779ba | 12,999 |
def requires_site(site):
"""Skip test based on where it is being run"""
skip_it = bool(site != SITE)
return pytest.mark.skipif(skip_it,
reason='SITE is not %s.' % site) | b436e6390828af2ffdca6e972b5a55fccafed64b | 13,000 |
def iou(bbox_1, bbox_2):
"""Computes intersection over union between two bounding boxes.
Parameters
----------
bbox_1 : np.ndarray
First bounding box, of the form (x_min, y_min, x_max, y_max).
bbox_2 : np.ndarray
Second bounding box, of the form (x_min, y_min, x_max, y_max).
Re... | c076290d386a2c6740f7cd6aaee18a42f9c850ce | 13,002 |
def GetIntensityArray(videofile, threshold, scale_percent):
"""Finds pixel coordinates within a videofile (.tif, .mp4) for pixels
that are above a brightness threshold, then accumulates the
brightness event intensities for each coordinate,
outputting it as a 2-D array in the same size as the video frame... | 720b50da3eb04698c62b2afa67ca3cd7b4f3661d | 13,003 |
def _check_data(handler, data):
"""Check the data."""
if 'latitude' not in data or 'longitude' not in data:
handler.write_text("Latitude and longitude not specified.",
HTTP_UNPROCESSABLE_ENTITY)
_LOGGER.error("Latitude and longitude not specified.")
return Fals... | 829681db92b0b7a6368ca143b6c656b46c972430 | 13,004 |
import requests
from bs4 import BeautifulSoup
def get_soup(page_url):
""" Returns BeautifulSoup object of the url provided """
try:
req = requests.get(page_url)
except Exception:
print('Failed to establish a connection with the website')
return
if req.status_code == 404:
... | d837e3b6aa6184285857428b2c796172379f3a1f | 13,005 |
def foreign_key_constraint_sql(table):
"""Return the SQL to add foreign key constraints to a given table"""
sql = ''
fk_names = list(table.foreign_keys.keys())
for fk_name in sorted(fk_names):
foreign_key = table.foreign_keys[fk_name]
sql += "FOREIGN KEY({fn}) REFERENCES {tn}({kc}), ".fo... | 0883050d2b9d302ab9099ef27abd400e4d4fe69e | 13,006 |
from typing import Optional
def expandDimConst(term: AST.PPTerm,
ntId: int) -> Optional[AST.PPTerm]:
"""
Expand dimension constant to integer constants (Required for fold zeros)
"""
nt = ASTUtils.getNthNT(term, ntId)
if type(nt.sort) != AST.PPDimConst:
return None
s... | b048d8ed0ec743a88c17a1f120a57d5e548e7d69 | 13,007 |
from scipy.optimize import minimize_scalar
def _fit_amplitude_scipy(counts, background, model, optimizer='Brent'):
"""
Fit amplitude using scipy.optimize.
Parameters
----------
counts : `~numpy.ndarray`
Slice of count map.
background : `~numpy.ndarray`
Slice of background map.... | 51faafd7a81ff70196075bacac6b36db6b7e09f8 | 13,008 |
from pathlib import Path
def get_world_paths() -> list:
"""
Returns a list of paths to the worlds on the server.
"""
server_dir = Path(__file__).resolve().parents[1]
world_paths = []
for p in server_dir.iterdir():
if p.is_dir and (p / "level.dat").is_file():
world_paths.app... | bf1c23c6a1c928dc66470db2e11b49ad2fc9e5d9 | 13,010 |
def derivative_p(α_L, α_G, ρ_G, v_L, v_G): # (1)
"""
Calculates pressure spatial derivative to be pluged into the expression for
pressure at the next spatial step (see first equation of the model). It
returns the value of pressure spatial derivative at the current time step
and, hence, t... | e2aa8a4967b121b798058aa963b0685080b7eb8b | 13,011 |
def fit_sigmoid(colors, a=0.05):
"""Fits a sigmoid to raw contact temperature readings from the ContactPose dataset. This function is copied from that repo"""
idx = colors > 0
ci = colors[idx]
x1 = min(ci) # Find two points
y1 = a
x2 = max(ci)
y2 = 1-a
lna = np.log((1 - y1) / y1)
... | 2024e32cd454cb27cf3d0fef9f270a22abba5ea0 | 13,012 |
def deprecated(func):
"""Decorator for reporting deprecated function calls
Use this decorator sparingly, because we'll be charged if we make too many Rollbar notifications
"""
@wraps(func)
def wrapped(*args, **kwargs):
# try to get a request, may not always succeed
request = get_cur... | d01f53acd584faa3c3b15771c76a00210ffbeb83 | 13,013 |
def stellar_mags_scatter_cube_pair(file_pair, min_relative_flux=0.5, save=False):
"""Return the scatter in stellar colours within a star datacube pair."""
hdulist_pair = [pf.open(path, 'update') for path in file_pair]
flux = np.vstack(
[hdulist[0].data for hdulist in hdulist_pair])
noise = np.sq... | b1f823a9ab33f7deadb1651aaa728690b0a08cf6 | 13,016 |
import hmac
import hashlib
def is_valid_webhook_request(webhook_token: str, request_body: str, webhook_signature_header: str) -> bool:
"""This method verifies that requests to your Webhook URL are genuine and from Buycoins.
Args:
webhook_token: your webhook token
request_body: the body of the... | 1ce1ef0a9e1386ebbea7773d8cd9d40df2544792 | 13,018 |
import torch
def logsigsoftmax(logits):
"""
Computes sigsoftmax from the paper - https://arxiv.org/pdf/1805.10829.pdf
"""
max_values = torch.max(logits, 1, keepdim=True)[0]
exp_logits_sigmoided = torch.exp(logits - max_values) * torch.sigmoid(logits)
sum_exp_logits_sigmoided = exp_logits_sigmo... | d7f6c2ef4279d511ff81fc30cfa1db5875c5ea4a | 13,019 |
def multi(dispatch_fn):
"""Initialise function as a multimethod"""
def _inner(*args, **kwargs):
return _inner.__multi__.get(
dispatch_fn(*args, **kwargs),
_inner.__multi_default__
)(*args, **kwargs)
_inner.__multi__ = {}
_inner.__multi_default__ = lambda *args, *... | 29023826b3e67ccc39a458fc90bd817cd725c35f | 13,020 |
def choose_key(somemap, default=0, prompt="choose", input=input, error=default_error,
lines=LINES, columns=COLUMNS):
"""Select a key from a mapping.
Returns the key selected.
"""
keytype = type(print_menu_map(somemap, lines=lines, columns=columns))
while 1:
try:
us... | d3c2438c85afae48980f772a06a7e622866197c5 | 13,021 |
from typing import Tuple
def predicted_orders(
daily_order_summary: pd.DataFrame, order_forecast_model: Tuple[float, float]
) -> pd.DataFrame:
"""Predicted orders for the next 30 days based on the fit paramters"""
a, b = order_forecast_model
start_date = daily_order_summary.order_date.max()
future... | 48f79b1076c32f93bdf148d1b986c6892cd3a8af | 13,023 |
import torch
import tqdm
def eval_loop(model, ldr, device):
"""Runs the evaluation loop on the input data `ldr`.
Args:
model (torch.nn.Module): model to be evaluated
ldr (torch.utils.data.DataLoader): evaluation data loader
device (torch.device): device inference will be run on
... | ca96192b1cd104ea3c86b5c5234ab5bf708613c8 | 13,025 |
def get_total_frts():
"""
Get total number of FRTs for a single state.
Arguments:
Returns:
{JSON} -- Returns headers of the columns and data in list
"""
query = """
SELECT
place.state AS state
, COUNT(DISTINCT frt.id) AS state_total
FROM
... | 0f054ef795f09ea01b28c139fd353bf237ed10a4 | 13,026 |
def newton_sqrt(n: float, a: float) -> float:
"""Approximate sqrt(n) starting from a, using the Newton-Raphson method."""
r = within(0.00001, repeat_f(next_sqrt_approx(n), a))
return next(r) | 4d7186bd55e4f4d4511078bcb0fff4959a182a3b | 13,027 |
def prismatic(xyz, rpy, axis, qi):
"""Returns the dual quaternion for a prismatic joint.
"""
# Joint origin rotation from RPY ZYX convention
roll, pitch, yaw = rpy[0], rpy[1], rpy[2]
# Origin rotation from RPY ZYX convention
cr = cs.cos(roll/2.0)
sr = cs.sin(roll/2.0)
cp = cs.cos(pitch/2... | 898db39d01a7b26daf2657c69c42af12bd8fef60 | 13,028 |
def markov_chain(bot_id, previous_posts):
"""
Caches are triplets of consecutive words from the source
Beginning=True means the triplet was the beinning of a messaeg
Starts with a random choice from the beginning caches
Then makes random choices from the all_caches set, constructing a markov chain
... | 652690d61c97de420e88f53cfd05c5d59e9229af | 13,029 |
def _assign_data_radial(root, sweep="sweep_1"):
"""Assign from CfRadial1 data structure.
Parameters
----------
root : xarray.Dataset
Dataset of CfRadial1 file
sweep : str, optional
Sweep name to extract, default to first sweep. If None, all sweeps are
extracted into a list.
... | 7734917c8b4aced4812896e3269981c984241202 | 13,031 |
def get_memory_usage():
"""This method returns the percentage of total memory used in this machine"""
stats = get_memstats()
mfree = float(stats['buffers']+stats['cached']+stats['free'])
return 1-(mfree/stats['total']) | 27bcf8866b6b57253acf6a282265949dcfd3af61 | 13,032 |
def gamma0(R, reg=1e-13, symmetrize=True):
"""Integrals over the edges of a triangle called gamma_0 (line charge potentials).
**NOTE: MAY NOT BE VERY PRECISE FOR POINTS DIRECTLY AT TRIANGLE
EDGES.**
Parameters
----------
R : (N, 3, 3) array of points (Neval, Nverts, xyz)
Returns
-----... | c3ed9c624a5f14922d3c76a3eb2ae2f616f82cac | 13,033 |
def is_even(x):
""" True if obj is even. """
return (x % 2) == 0 | f19563063515eb4d39b8b607cf68f6f188af409e | 13,034 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.