content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import re
def to_numpy(t):
"""
return numpy datetime64 scalar corresponding to the given comma time string
>>> import numpy as np
>>> from comma.csv.time import to_numpy
>>> to_numpy('20150102T123456') == np.datetime64('2015-01-02T12:34:56.000000', 'us')
True
>>> to_numpy('20150102T123456... | 9f859a64378231572f66916893f39ce3a0e6d772 | 59,900 |
def _migrate_db_sync(engine, abs_path, version=None, init_version=0):
"""Upgrade or downgrade a database.
Function runs the upgrade() or downgrade() functions in change scripts.
:param engine: SQLAlchemy engine instance for a given database
:param abs_path: Absolute path to migrate repository.
:pa... | 1d2eb159354c9a026abc805b2706dd4252619776 | 59,901 |
def run_diag(parameter: "CoreParameter") -> "CoreParameter":
"""Runs the aerosol aeronet diagnostic.
:param parameter: Parameters for the run
:type parameter: CoreParameter
:raises ValueError: Invalid run type
:return: Parameters for the run
:rtype: CoreParameter
"""
variables = paramet... | 69836d585a7f1c53c48923aba48482a32083b5ff | 59,902 |
import io
import re
def parse_msa_file(infile):
"""Read sequences from a multiple sequence alignment (MSA) file.
Parameters
----------
infile : str
file path to input MSA file in A3M format (like FASTA format, but
lowercase letters will be dropped)
Returns
-------
skbio T... | bcb4bd5ad22a79d31e18c0470830ab72b5106aaf | 59,903 |
def cadastro(request):
"""Cadastra um novo usuário no sistema"""
if request.method == 'POST':
nome = request.POST['nome']
email = request.POST['email']
senha = request.POST['password']
senha2 = request.POST['password2']
if campo_vazio(nome):
messages.error(req... | 7c8e2c049d6f70a1f3ae9b850f6737757915f697 | 59,904 |
def parser_summaries(gold_corpus, annotated_corpus):
"""Computes parser evaluation summaries for gold and annotated sentences."""
pos, uas, las = calculate_parse_metrics(gold_corpus, annotated_corpus)
return {'POS': pos, 'LAS': las, 'UAS': uas, 'eval_metric': las} | beddd90bfb940434f60f7099ceca3fd5d20f4b85 | 59,905 |
import json
def json_files_serializer(objs, status=None):
"""JSON Files Serializer.
:parma objs: A list of:class:`invenio_files_rest.models.ObjectVersion`
instances.
:param status: A HTTP Status. (Default: ``None``)
:returns: A Flask response with JSON data.
:rtype: :py:class:`flask.Respo... | 830ddc8c8c9b55a75ee0abb4f3b7a4398fd46f76 | 59,906 |
import requests
def update_nic(name, index, type):
"""Updates a network adapter in the VM"""
nic = get_nic(name, int(index))
# Set default values
if type is None:
print("[DEBUG] Inheriting type key")
type = nic['type']
if mac_addr is None:
print("[DEBUG] Inheriting mac_ad... | 5abd0a66ecaaa4c0b27ffd15693f70328b7733ee | 59,907 |
def TensorBoardConfig(argument_parser):
"""
Set CLI arguments
:param argument_parser: argument parser
:type argument_parser: ```ArgumentParser```
:returns: argument_parser
:rtype: ```ArgumentParser```
"""
argument_parser.description = """Enable visualizations for TensorBoard.
TensorBo... | 22abff24eb0d0ca64d32db7a8de57623d51a3c00 | 59,908 |
import os
import glob
from datetime import datetime
import shutil
def process_documents():
"""Processes emails (html), pdf, docx, xlsx, and txt files for DrQA use
This function maintains a list of previously processed files and their
last modification timestamps. If any change is detected, the files are
... | f5f80e0ab87e7f09b93634b5b3935977e730aa94 | 59,909 |
def delta_prob(variants, tx, clf1, clf2, model='cterm', is_sum=True):
"""Calculate the difference between a position specific
model and a "bag of words" model"""
# fetch c-terminal sequence
term_seq, vars_considered = utils.process_var_seq(variants, model=model, is_sum=is_sum)
# return None if no v... | d4f7e222286c4fd262ebcc26a74b1f4724742722 | 59,910 |
import builtins
import functools
def install_import_hook():
"""Installs __import__ hook."""
saved_import = builtins.__import__
@functools.wraps(saved_import)
def import_hook(name, *args, **kwargs):
if name == 'end':
process_import()
end
return saved_import(name, *ar... | b78799448becd79ab1a1001a07b1eb4445da5780 | 59,911 |
def draw_square_support(data, h, c1, c2, t, r):
"""
"Support", "Cuboid"
:param (h, c1, c2): position
:param (r, t): shape
"""
data[cut(16 + h):cut(16 + h + t), cut(16 + c1 - r):cut(16 + c1 + r), cut(16 + c2 - r):cut(16 + c2 + r)] = 1
step = np.asarray([7, h, c1, c2, t, r])
return data, s... | 094b4d722e0d5afa2642d10eac72399e60ebf577 | 59,912 |
def read_or_skip(file):
"""This function is to supress imageio exception if file doesn't exist"""
try:
img = skimage.io.imread(img_folder + file)
img = skimage.transform.resize(img, (img_width, img_height), mode='reflect')
return img[:,:,:img_channels]
except:
#print('Skippin... | cbcae49d0fa18dc441f1e154d6a4034ca4883b61 | 59,913 |
def read_zero_mode(zero_mode, L1, L2):
"""Read the \alpha_i, \beta_j parameters from the 2D zero mode Operator.
"""
if isinstance(zero_mode, qy.Operator):
alphas = np.zeros((L1,L2))
betas = np.zeros((L1,L2))
for (coeff, os) in zero_mode:
if len(os.orbital_operators... | be01b3f27c61341f7bc213f4eba98b8d41435af7 | 59,914 |
def worm_like_chain_1p(x, L_0, L_p=50e-9, T=298):
"""
An improved worm-like chain model.
Petrosyan, R. "Improved approximations for some polymer extension
models". Rehol Acta. 2016. doi:10.1007/s00397-016-0977-9
Parameters
----------
x : float
Extension (m)
L_0 : float
... | 38ce0482241870d215751228505d59bbc3c49f28 | 59,915 |
def label_mapper(raw_labels, new_labels):
"""Map some raw labels into new labels.
When dealing with GEO DataSets it is very common that each GSM sample has
a different phenotye (e.g. 'Brain - 001', 'Brain - 002', ...). This
function maps these raw labels into new homogeneous labels.
Parameters
... | 67aaa329374169f61414032b0949344437d16022 | 59,916 |
import time
import logging
def detect_scenes(cap, scene_manager, start_frame = 0, end_frame = 0, duration_frames = 0):
"""Performs scene detection based on passed video and scene detectors.
Args:
cap: An open cv2.VideoCapture object that is assumed to be at the
first frame. Frames are r... | 59a0ef88df005309cfa3a8cb9037d1fde2d9d85e | 59,917 |
def pad_1d_tensor(inputs):
"""
Pad 1d tensor to fixed size.
"""
max_len = hp.character_max_length
padded = np.pad(inputs, (0, max_len - inputs.shape[0]))
return padded | 728d8c8d1558c16489c4571bfa1d372b6e8cb409 | 59,918 |
def get_apispec(app):
""" Формируем объект APISpec.
:param app: объект Flask приложения
"""
spec = APISpec(
title="ustMock",
version="1.0.0",
openapi_version="3.0.3",
info={'description': "ustMock api based from marshmallow models"},
plugins=[FlaskPlugin(), DocPlu... | 800e87b001fd880ca3b9b17cba24d18488ec88c6 | 59,919 |
from typing import MutableSequence
def lookup_func(arg, ctx):
"""
Runs an ansible lookup plugin. Usage:
.. code-block:: YAML
lookup:
lookupFunctionName: 'arg' or ['arg1', 'arg2']
kw1: value
kw2: value
"""
arg = map_value(arg, ctx)
assert_form(arg, test=arg... | 75db3924e9cfebae28b0b18c9db8699edf5e4435 | 59,920 |
def text2entity(text):
"""Convert HTML/XML special chars to entity references
"""
return ESCAPE.get(text, text) | ded63af8e8e5d1d097c67301ca4433382fef3c73 | 59,921 |
from pathlib import Path
from typing import Dict
def register(
manager: TaskManager,
project: str,
cwd: Path,
substitutions: Dict[str, str],
) -> bool:
"""Register static-analysis tasks to the manager."""
manager.register(Phony("python-sa"), ["python-lint-mypy"])
# Register a target so t... | 6b326ecfc1713045f934e006670d8a0d3f52f463 | 59,922 |
def transform_all(calendar, listings, reviews, save_results=False):
""" Transforms all the columns. """
calendar, listings, reviews = transform_prices(calendar, listings, reviews)
calendar, listings, reviews = transform_booleans(calendar, listings,
review... | b9e337a970570b47b2e543285ca673bd26bb4481 | 59,923 |
from typing import Optional
def validate_self_discharge(self_discharge: Optional[float]) -> Optional[float]:
"""
Validates the self discharge of an object.
Self discharge is always optional.
:param self_discharge: The self discharge of the object.
:return: The validated self discharge.
"""
... | 4d1d6c3ddb6530fc6fc6e03809a4320b0b50033f | 59,924 |
import re
def parse_pw_text_output(data, xml_data={}, structure_data={}, input_dict={}, parser_opts={}):
"""
Parses the text output of QE-PWscf.
:param data: a string, the file as read by read()
:param xml_data: the dictionary with the keys read from xml.
:param structure_data: dictionary, coming... | adcfadf363c1cd18bc80457e9b6d7ce237e0068a | 59,925 |
import collections
def shrink_nd(a, trim_spec, assume_sorted=False):
"""Perform multidimensional shrink.
Args:
a: ndarray
The grid to shrink.
trim_spec: sequence of tuples
Iterates over tuples (bins, low, high, axis)
assume_sorted: bool, optional
If... | 895c547371ec37df6bc73e9fc8df4003b583c3e4 | 59,926 |
import base64
def hash_b64(s):
"""
hash the string using sha256 and produce a base64 output
removes the trailing "="
"""
hasher = SHA256.new(s.encode('utf-8'))
result = base64.b64encode(hasher.digest())[:-1].decode('ascii')
return result | 81770cc9a5ac7fdbd29fa1e6d10d9a580aec0196 | 59,927 |
import os
def get_logging_config():
"""
Returns logging configuration file path
:return: str
"""
create_logger_directory()
return os.path.normpath(os.path.join(os.path.dirname(__file__), '__logging__.ini')) | fc8a4d588f022d151d0d8ae879352774e89ca136 | 59,928 |
def all_builtins():
"""Helper function to return an iterator over all builtin plugins."""
return (p for p in plugin.plugins.itervalues() if p.builtin) | ead7e176af58bc38772b5b5bfc4dc8b25082ca5b | 59,929 |
def parse_type_arg(type_arg_string):
"""Parse typed individual argument strings
This is the base function to parse an individual argument
string with type information. It identifies the type and calls
the appropriate parsing function from the parsing function dict.
Args:
type_arg_string(st... | 401f181a21d2745ded0db2f2e8f417e6186fe6e8 | 59,930 |
def load_davis_bias(file_path, verbose=False):
"""Load DAVIS bias.
TODO: to investigate bias differences between 240C and 346.
# Arguments
file_path : `str`<br/>`
the absolute path to the JSON string.
# Returns
bias_obj: `dict`<br/>
A dictionary that contains v... | e5429daa72ef042955c3e3fbee3ec083f77b1432 | 59,931 |
import pickle
import base64
def unbp(data):
"""Un-(Base64-Pickle)."""
return pickle.loads(base64.b64decode(data)) | d1338e2d877ac84c78cd67e2b5b425c173011331 | 59,932 |
from stalker_pyramid.views.client import query_client
from typing import Type
def create_project(request):
"""called when adding a new Project
"""
logged_in_user = get_logged_in_user(request)
came_from = request.params.get('came_from', '/')
logger.debug('create_project create_project create_pro... | 5007ba96a1f4968fb7bd3e085a56a51b08b2e42d | 59,933 |
def check_in_field(pos, field_config):
"""
Return flag to indicate whether the object is in the field
"""
k1 = field_config['borderline'][0]
k2 = field_config['borderline'][1]
b = field_config['borderline'][2]
flag = k1 * pos[0] + k2 * pos[1] + b > 0
return flag | 1a0020bf9a0a6baad6cb465092864899bba7324a | 59,934 |
from operator import inv
from re import I
def xrecover(y):
""" Return y given x such that (x,y) is on the curve """
xx = (y * y - 1) * inv(d * y * y + 1)
x = expmod(xx, (q + 3) / 8, q)
if (x * x - xx) % q != 0:
x = (x * I) % q
if x % 2 != 0:
x = q - x
return x | 909367253a6f990aa9866a42a88a25bb1d482a02 | 59,935 |
def ocs_iso_to_mjd(iso_string=''):
"""
:param iso_string: input ISO-8660 date
:return: string representation of date_string as MJD
"""
if not isinstance(iso_string, str) or iso_string == '':
return ''
else:
return '{0:23.17f}'.format(Time(str(iso_string)).mjd) | e08492f29b149ad15b120f805e60d2977a5bc358 | 59,936 |
def random_vec(n, type="stdnorm"):
"""
input:
n : vector size
output:
random vector that follows rademacher distribution & std normal distribution
example:
"randmacher" : [1,1,-1,1,-1,-1,-1,1,-1,1]
"""
if type == "stdnorm":
return np.random.standard_normal(n)
... | 42048fac4d61bdab1512b02fa862a10c417d6aad | 59,937 |
def add_hard_linked_production_volumes(data):
"""Add information to target datasets about subtracted production volume.
Production volumes from hard (activity) links are subtracted from the total production volume of transforming or market activities. The amount to subtract is added to a new field in the produ... | 2e34304acda4b764dcd377603b1617ed78daf87b | 59,938 |
import os
def main(data_path, augmentation = False, callbacks = None, rescale = 0, batch_size = 32, target_size = (128, 128),
display_images = True, learning_rate = 0.001, input_shape = (128, 128, 3), num_classes = 5, blocks = 4,
metrics = None, normalization = 'layer_normalization', epochs = 50):... | 29f45323264d20c4db1e756747955225195bd6a7 | 59,939 |
import os
def list_of_images(JPGPATH):
"""
Arg: JPGPATH
Return: listOf_images for cropper() function.
Kinda got helped from.
https://mkyong.com/python/python-how-to-list-all-files-in-a-directory/
"""
listOF_imgs = []
# r=root, d=directories, f = files
for r, d, f in os.walk(JPGPA... | 78ab62c0c3bc8a690ad7b5fa84de47aca6e775bb | 59,940 |
def location_get(table_name):
"""
Gets data from table.
Args:
table_name: Name of table in DB.
Returns: All data in table |table_name|.
"""
db = get_db()
select_stmt = "SELECT * FROM " + table_name
cur = db.execute(select_stmt)
result = {"result": cur.fetchall()}
p... | aa55184f2854408148d7d784c3d1adbffd51496e | 59,941 |
import inspect
import ray
def create_backend_worker(func_or_class):
"""Creates a worker class wrapping the provided function or class."""
if inspect.isfunction(func_or_class):
is_function = True
elif inspect.isclass(func_or_class):
is_function = False
else:
assert False, "func... | 47fe7fac5ad154b0a567cf82205492e085c24535 | 59,942 |
def local_structure_tensor(img: np.ndarray,
si: float = 0.8,
so: float = 1.6,
slope_method: str = 'eigen',
grad_method: str = None,
f: float = 1) -> [np.ndarray, np.ndarray, np.ndarray]... | 6553fe2fe15c046226ea67d15247a457b945fc30 | 59,943 |
def v1_find_users_by_name(request: WSGIRequest) -> JsonResponse:
"""
Find users by a string their name contains.
Return the found users in JSON formatted as a select2 result.
"""
name_contains = request.GET.get('name_contains')
if name_contains is None or len(name_contains) < 2:
# Nothin... | 7c1cff476684b2fd61c8826482d177d1d187503d | 59,944 |
def inline_callback():
"""Filters callback_query done in messages posted through inline query.
Assumes update_type is callback_query.
:return: True or False
"""
if context.update.type is not UpdateType.callback_query:
return False
if context.update.callback_query.inline_message_id is ... | 3e07b8549a626800510ca9a1b7fbddcda7183e2f | 59,945 |
import argparse
def setup_argparse():
"""Setup arg parse for cli."""
parser = argparse.ArgumentParser()
parser.set_defaults(action="config", func=cli_handle_config)
parser.add_argument(
"key",
choices=[
"%s.%s" % (section, key)
for section, key, _, _ in hdtop.c... | 2dfd2fd23574aa9b581b36885d2e9cf615a21e31 | 59,946 |
def clearBlinkCache():
"""
clearBlinkCache() -> None
Clear the Blink cache for all devices.
"""
return None | d518a45b96fc7193a6a28952aee2500b0bb470b1 | 59,947 |
def compute_I_ux(model, t1=None, t2=None):
"""Compute the :math:`I_{ux}` integral.
Args:
model (:class:`.gpcm.GPCM`): Model.
t1 (tensor, optional): First time input. Defaults to zero.
t2 (tensor, optional): Second time input. Defaults to zero.
Returns:
tensor: Value of :mat... | 558a9ef603cec235dd39db5021ce8c5970e37b1a | 59,948 |
def read_facade(facade, facades, create, typemap, data, objects,
sequence_names,
fks,
resources):
""" Parse the resource `r` as a facade.
"""
# TODO: Generate better error messages, if keys which are assumed to be
# present, e.g. because they are used as f... | f96881472730e916028b00f9f4a5e25ecd6d832d | 59,949 |
async def translations(
query: str,
src: LANGUAGE_CODE,
dst: LANGUAGE_CODE,
response: Response,
guess_direction: bool = False,
):
"""
Translate the query between src and dst language.
The response contains the list of lemma objects matching the query in the source
language. Each of ... | 28d464beba4082f22cc1ba13eacc1b5c19b775c3 | 59,950 |
import random
def blur_cifar(ds): # TODO1 do multiprocessing
"""
Applies gaussian blurring with random stdev in [0, 3].
The saved dataset was created with seed = 42.
:param ds (np.array): Loaded dataset
:return: blurred (np.array): Blurred dataset
"""
print('Blurring CIFAR-10')
resu... | 25d530dcf6cd1f1e172fd3bc7a8c383c2e89f07a | 59,951 |
import requests
def md_to_rst(from_file):
"""
将markdown格式转换为rst格式
@param from_file: {str} markdown文件的路径
@param to_file: {str} rst文件的路径
"""
response = requests.post(
url='http://c.docverter.com/convert',
data={'to': 'rst', 'from': 'markdown'},
files={'input_files[]': ope... | 5001a37634b08857747f58de1f7591c34a5d4fa2 | 59,952 |
def parse_charge(charge_str):
"""
Parses a SMILES charge specification.
Parameters
----------
charge_str : str
The charge specification to parse.
Returns
-------
int
The charge.
"""
if not charge_str:
return 0
signs = {'-': -1, '+': 1}
sign = signs... | 0b605a00dd12903c834c83a27d7e42078acdb456 | 59,953 |
def accuracy(y_true, y_score):
"""Compute accuracy using one-hot representaitons."""
if isinstance(y_true, list) and isinstance(y_score, list):
# Online scenario
if y_true[0].ndim == 2 and y_score[0].ndim == 2:
# Flatten to single (very long prediction)
y_true = np.concat... | dcb49e25a019638e6f3a5bf7bb0e7dfc87f49ed0 | 59,954 |
def compute_pairwise_diffs_and_scores(mean_traces):
"""Computes pairwise differences and their confidence scores between key
bytes.
This function correlates mean text traces to pick the most likely
differences.
Args:
mean_traces: A (16, 256, NUM_SAMPLES) array of mean text traces.
Ret... | 0fcb25da0c4ccb4ab0fb7fe0c5345f47f855bfc6 | 59,955 |
import torch
def sample_boxes(mean, var, num_samples, eps=1e-4, angular_dim=6):
"""
Sample boxes from distributions
Args:
mean [torch.Tensor(..., D)]: Bounding box parameter means
var [torch.Tensor(..., D)]: Bounding box parameter variances
num_samples [int]: Number of samples (M)
... | c41a3ba8afa100811735091c45f2fb1eef1b7235 | 59,956 |
def flag_abuse_for_comment(request, course_id, comment_id):
"""
given a course and comment id, flag comment for abuse
ajax only
"""
course_key = CourseKey.from_string(course_id)
user = cc.User.from_django_user(request.user)
comment = cc.Comment.find(comment_id)
comment.flagAbuse(user, co... | bd135c4248c784b14a5fd560d753441af8a9ed80 | 59,957 |
from typing import Dict
def _get_all_aliases(sql, example: NLToSQLExample) -> Dict[str, DatabaseTable]:
"""Returns a dictionary of aliases for the tables."""
root = sql
while True:
if root.parent is None:
break
root = root.parent
aliases = {}
for item in _iterate_sql(r... | 5d5196e1191109bdbceb6f38fbbf8749fd15c062 | 59,958 |
import math
def filter_green_channel(img,
green_thresh=200,
avoid_overmask=True,
overmask_thresh=90,
dtype="bool"):
"""
Create a mask to filter out pixels with a green channel value greater than a particular th... | 57f81d904b5482995737429955561f72d5ce8e51 | 59,959 |
def user_can_delete_model_nodegroups(user, resource):
"""
returns a list of graphs of which a user can edit resource instances
Arguments:
user -- the user to check
resource -- an instance of a model
"""
return user_has_resource_model_permissions(user, ["models.delete_nodegroup"], resource... | 1a4cb4e6d1185387a63a8b3ade725f18a9231576 | 59,960 |
def l_min(s, m):
""" Minimum allowed value of l for a given s, m.
The formula is l_min = max(\|m\|,\|s\|).
Parameters
----------
s: int
Spin-weight of interest
m: int
Magnetic quantum number
Returns
-------
int
l_min
"""
return max(abs(s), abs(m)) | 9eec996df3b8e026c8b58649fddbbbcc05c38372 | 59,961 |
import attr
def query_and(draw, stattrs=st.lists(st.sampled_from(_supported_attr_types()),
min_size=1, unique=True)):
"""
Generate a AttrAnd query.
"""
attr_types = draw(stattrs)
query_attrs = list(map(draw, map(st.from_type, attr_types)))
assume(not(len(qu... | 57e8f522f4e3b6b579d55012189896546911cf74 | 59,962 |
def discrete_sample(p, n_samples=1):
"""
Samples from a discrete distribution.
:param p: a distribution with N elements
:param n_samples: number of samples
:return: vector of samples
"""
# check distribution
#assert isdistribution(p), 'Probabilities must be non-negative and sum to one.'... | 1dccafc919a85a58efcd481275be129ebe0362ae | 59,963 |
def my_get_matrix(opt):
"""Return which distance matrix to use
Parameters:
opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions
Returns which distance matrix to use
Ca/Cb/... -- distance matrix function
"""
if opt.matrix == 'Ca':
retu... | f6ea4e4e0c0850efa5a63da245f398d4f88b4af1 | 59,964 |
def load_cifar(labels='cifar10', channels_last=False, flatten=False, dtype=None,
normalize=False):
"""
Load the CIFAR dataset.
Args:
labels ({"cifar10", "cifar100"}): Specify the labels to load.
channels_last (bool): If True, will place the channels in the last
di... | ccf93d9ede78578949c9a8fb221304e34d4be1e9 | 59,965 |
def to_mp3(
audio_content: bytes,
sample_rate: str,
src_sample_rate: str = "22050",
src_fmt: str = "s16le",
) -> bytes:
"""Convert audio to MP3 (using ffmpeg)
Args:
audio_content Any audio content (with headers) that the available ffmpeg binary
can decode
sampl... | 2049b4f733ae2d6f53b23d3c7898fedc98e804c7 | 59,966 |
import torch
def indices_to_dense_vector(indices,
size,
indices_value=1.,
default_value=0,
dtype=np.float32):
"""Creates dense vector with indices set to specific value and rest to zeros.
This func... | ce3de9751b8d97a0ced2760bad9b2bef52484d2f | 59,967 |
def lastrow_calc_player_velocities(team, smoothing=True, filter_='Savitzky-Golay', window=7, polyorder=1, maxspeed = 12):
""" calc_player_velocities( tracking_data )
Calculate player velocities in x & y direciton, and total player speed at each timestamp of the tracking data
Parameters
-------... | d4ff6a7594d9a9f79ddfb2643ac5ec3b51f7a30e | 59,968 |
from django_wireguard.models import WireguardPeer
def purge_private_keys() -> int:
"""Purge all Private Key from database.
:return: Removed keys count.
"""
peers = WireguardPeer.objects.filter(private_key__isnull=False)
if peers.exists():
peers.update(private_key=None)
return peers.... | 9ab704de807a4057d7afb0c3353a4033fa173957 | 59,969 |
from typing import Any
from typing import Union
def _strat_commutes_from_commutes(left_val: Any,
right_val: Any,
*,
atol: Union[int, float] = 1e-8
) -> Union[bool, NotImplementedType,... | 040cc5060b653c68ce63141b2d971349458a591b | 59,970 |
def request_elevations(locations):
"""Request elevations for a list of (lat,lon) coordinates.
Args:
locations: list of (lat,lon)
Returns:
a list of elevation responses in the deserialized Elevation API response
format in order of input locations
"""
elevations_response = GMAPS.elevation(locations... | 98ccf44cfb96a9136eb6ff40fe3853e598da5fbd | 59,971 |
def get_rand_token(bits=256):
"""Generate a random number of specified length and return its hex string.
Default is to generate 256 bits = 32 bytes, resulting in a 64 characters
token to be generated (since a byte needs 2 hex chars).
"""
return hex(getrandbits(bits))[2:-1] | fe5afd3edb7ba0d69f589904964f3b6255bbe4fc | 59,972 |
def synch_parallel_process(proc1, proc2):
"""
Return the step function of process proc1||proc2.
:param proc1: a process
:param proc2: a process
:return: synchronous parallel composition of proc1 and proc2
"""
return lambda pdef, d: synch_parallel_combine(proc1(pdef, d), proc2(pdef, d)) | 32475548423ed2ccc93a29d00ed2b40ead3a51cd | 59,973 |
import time
def native_sort_implementation(array):
"""Implement native python sort method."""
begin = time.time()
nat_sortedarray = sorted(array.getData())
end = time.time()
time_native = end - begin
print('Native sort', f'{time_native =}')
return nat_sortedarray | 7b964644fdb2b11e8c50303ac0c7f4d4d76d6842 | 59,974 |
def haversine(lat1: float, long1: float, lat2: float, long2: float) -> float:
"""Determines the distance between two coordinates.
We take r as the average radius of the Earth: 6378 km.
>>> import math
>>> bahen = (43.65983570963418, -79.39694225927128)
>>> margad = (43.668387110900944, -79.39244320... | 402b3786ee47ae5b6c54d857685b783e28b7cbe2 | 59,975 |
from pathlib import Path
from typing import List
def add_paths(df: pd.DataFrame, feature_dir: Path, label_dir: Path) -> pd.DataFrame:
"""
Given dataframe with a column for chip_id, returns a dataframe with a column
added indicating the path to each band's TIF image as "{band}_path", eg "B02_path".
A c... | ce5c71e9b02f5f45819a60aac850bcd4d1d81778 | 59,976 |
def _figure_layout(
layout,
width,
height,
labels,
xaxis,
yaxis,
sign,
orientation,
zero_vals
):
""" Sets up figure and axis layouts, and adds leaf labels. """
if len(labels) > 0:
if orientation in ["left", "right"]:
axis_key_labels = yaxis
else:
... | a231a88eb911ba2b60fd329f71aa98c734a20519 | 59,977 |
def threshold_means(df, thresh_name, thresholds, comp_df=None, error_fac=1.0,
use_percents=True):
"""Computes the means (and standard deviations) along a set of threshold
values. This is handy for doing the Threshold v.s. Robustness plots
when in comparison to DREA.
Args:
... | 99f7855f457a2aec71a1454ac08fb656745f84d1 | 59,978 |
def softmax_loss_naive(W, X, y, reg):
"""
Softmax loss function, naive implementation (with loops)
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples.
Inputs:
- W: A numpy array of shape (D, C) containing weights.
- X: A numpy array of shape (N, D) containing a min... | 28b4a2d7db781b218aaeeb2c899e5d02f7705554 | 59,979 |
import pickle
def unpack_apply_message(bufs, g=None, copy=True):
"""unpack f,args,kwargs from buffers packed by pack_apply_message()
Returns: original f,args,kwargs"""
bufs = list(bufs) # allow us to pop
assert len(bufs) >= 2, "not enough buffers!"
pf = buffer_to_bytes_py2(bufs.pop(0))
f = unc... | 77004594532a06c2fabe806663db68d77b8528e6 | 59,980 |
def find_ram_base(u_boot_console):
"""Find the running U-Boot's RAM location.
Probe the running U-Boot to determine the address of the first bank
of RAM. This is useful for tests that test reading/writing RAM, or
load/save files that aren't associated with some standard address
typically represente... | ae550229a493ac88819cecfcc983a5ee84c995b3 | 59,981 |
def my_name():
"""
The pmap axis of this processor.
Returns:
i: The axis.
"""
return jax.lax.axis_index(axis_name=AXIS_NAME) | cd813f2abf3fe47952af51f61919f2d6e0ea2bb0 | 59,982 |
import urllib
import re
def _get_query_params(args):
"""
creates dictionary of search params for displaying on
search result page
:param args: request.args
:return: dictionary with all params of query
"""
result_dict = {}
for key in args:
if key == 'provinz' and args['provinz']... | 80ac3542a0b5e2a1f52e9d183cc6307d302781c4 | 59,983 |
def vecHomography(H: np.ndarray, p: int, q: int):
"""
Input:
H -- 3x3 homography matrix
p -- first column index
q -- second column index
Output:
v -- 1x6 vector containing components of H based on the
indices p and q which represent columns of the homography H
... | 1c1c5a1fd2b187bef7a5347bf90eede2b6990069 | 59,984 |
from typing import Iterable
from typing import List
def sort_terms(naf: KafNafParser, terms: Iterable[Cterm]) -> List[Cterm]:
"""Sort terms by natural order (sent, offset)"""
def get_offset(term: Cterm):
tokens = [naf.get_token(tid) for tid in naf.get_dict_tokens_for_termid(term.get_id())]
tok... | e41806e5fd3619d83dbd9eeacad5899e8e687e29 | 59,985 |
import os
import pickle
def load_pkl_files(dsm_prefix):
"""
Load the space from either a single pkl file or numerous files
:param dsm_prefix:
:param dsm:
:return:
"""
# Check whether there is a single pickle file for the Space object
if os.path.isfile(dsm_prefix + '.pkl'):
retu... | b52eebb1ea0cbf4f2dce1650d05be55f238bf0cd | 59,986 |
import urllib
import yaml
import requests
def _fetch_global_config(config_url, github_release_url, gh_token, file_name):
"""
Fetch the index_runner_spec configuration file from the Github release
using either the direct URL to the file or by querying the repo's release
info using the GITHUB API.
"... | d5321fd255a6a3e748dff423161ffd6751d31ee9 | 59,987 |
import os
def encode_mpeg1(ipattern,
ofile,
input_frame_rate,
output_frame_rate):
"""
Creates a mpeg1 video file using ffmpeg.
"""
enc_bin = ffmpeg_bin()
if not enc_bin is None:
mpeg1_ofps = 24
if not output_frame_rate is None:
... | a317e6359c099b6224743e252976d76a8d2302fd | 59,988 |
def batch_jdbc(conf: BlockConfig) -> DataFrame:
"""Batch save data with jdbc driver.
:param str Mode: the mode to write with such as append or overwrite
:param str Driver: the driver
:param str ConnUrl: the connection url
:param str Table: table to write to
:param str User: username to database... | 1ac129ca5e26ee021b4ec3684bc684e27f4190a8 | 59,989 |
import logging
def get_chunks(lines):
"""
Get a list of the chunks from an xmd file
"""
logger = logging.getLogger("eggsmark.{}".format(
__name__,
))
chunks = []
chunks_info = []
line_n = 0
while line_n < len(lines):
try:
chunk, chunk_info = _get_next_ch... | 28c5fc04a1d2263f31b40e42e33051d6a891551a | 59,990 |
def remove_parents(network, name, **kwargs):
"""
removes all parents of the given node name, replacing the root node with
itself
"""
def inner(root_node):
if network.is_built:
graph = network.graph
else:
graph = treeano.core.graph.TreeanoGraph(root_node)
... | f2600cebdc9a5c4d6b2e0d41a73fd78e1b6c9fc9 | 59,991 |
def fetch_messages(chatkit_access_data, room_id, initial_id=None, limit=20, direction="newer"):
"""
direction in ['newer', 'older']
"""
endpoint_parts = ["rooms", room_id, "messages"]
query_parameters = {}
if(initial_id is not None):
query_parameters['initial_id'] = initial_id
if(... | 9fe484ef236e81699a4f176e960c2a09f8496b2e | 59,992 |
async def test_thread_override_step_and_step(mocker):
"""
Throw an error if we try to send on an emoji step
"""
global third_step
third_step = False
class FirstLogic(BaseStep):
name = "first"
async def send(self, message, user_id):
return message, {"example": 0}
... | 28b293e7d20befd8387912eb76e4dd43c0e27761 | 59,993 |
from typing import Dict
import json
def validate_file(file: str, schema: str, fuzz: bool=False,
backend: Backend=None, output: Dict=None) -> bool:
"""validate a spaceTx formatted file with a given schema.
Accepts local filepaths or files hosted at http links.
Parameters
----------
... | 9a19c0047f976d87113a0bb6a298e5f121563fea | 59,994 |
from typing import Iterable
from typing import Any
from functools import reduce
def concat(*it: Iterable[Any]) -> Any:
"""
Concatenation of iterable objects
Args:
it: Iterable object
Examples:
>>> fpsm.concat([1, 2, 3], [4, 5, 6])
[1, 2, 3, 4, 5, 6]
"""
return reduce(... | e2b9d1604630198486fa0649d62784078547031a | 59,995 |
import math
def to_4326(coord_size: int, point: mi.Point) -> mi.Point:
"""Convert a point in maps.me-mercator CS to WGS-84 (EPSG:4326)."""
merc_bounds = (-180.0, -180.0, 180.0, 180.0) # Xmin, Ymin, Xmax, Ymax
x = point.x * (merc_bounds[2] - merc_bounds[0]) / coord_size + merc_bounds[0]
y = point.y * ... | 82762aeddfe1ae292453e198d316ff2efe357b0b | 59,996 |
def plot(domain, solution=None, solution_exact=None, **kwargs):
"""Plots a solution (and optionally a reference solution) onto the given
DiscreteDomain instance.
**kwargs are the same as the ones in the DiscreteDomain's visualize() method.
Parameters
----------
domain : DiscreteDomain
... | 003f55c54a19145e847b3baf97266f301b09ddaf | 59,997 |
import os
def load_sample_pheno_data(pheno_id, sample_id, obj_direction, ENSEMBLE_DIR, scale=True, ic_rank=True):
""" Load data given phenotype, MNC sample, MNC optimization direction
ic_rank is a useless parameter that I can't get rid of due to being too deep bro :(
"""
if ic_rank==True:
... | ed8dba88ab4e2adccd53f4c1795e1209abaa3187 | 59,998 |
import platform
import functools
def Linux(func=None):
"""
is Linux expression and decorator
Args:
func:
Returns:
"""
if func is None:
return platform.system() == "Linux"
@functools.wraps(func)
def wrapper(*args, **kwargs):
if platform.system() == "Linux":
... | 22d8668edd639c94c8a96b5c8ea62af7d4e09fae | 59,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.