content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def estimate_perfomance_plan(sims, ntra, stateinit, destination, plan=list(), plot=False, verbose=True):
"""
Estimates the performances of two plans and compares them on two scenarios.
:param list() sims: List of :class:`simulatorTLKT.Simulator`
:param int ntra: Number of trajectories used to estimate ... | 274ebadafa7f7637e27a0f25a013171a0955d4ce | 22,300 |
def xls_dslx_ir_impl(ctx, src, dep_src_list):
"""The implementation of the 'xls_dslx_ir' rule.
Converts a DSLX source file to an IR file.
Args:
ctx: The current rule's context object.
src: The source file.
dep_src_list: A list of source file dependencies.
Returns:
DslxModuleIn... | 119112184086ccb469157eae1b17e1a0f38b57ef | 22,301 |
def split_data(images, labels):
"""
Split data into training (80%), validation (10%), and testing (10%)
datasets
Returns (images_train, images_validate, images_test, labels_train,
labels_validate, labels_test)
Assumes that num_covid_points <= num_normal_points and num_virus_points
"""
... | 87950ef842781abb8500961a11d997b254bde6af | 22,302 |
import random
def randomlyInfectRegions(network, regions, age_groups, infected):
"""Randomly infect regions to initialize the random simulation
:param network: object representing the network of populations
:type network: A NetworkOfPopulation object
:param regions: The number of regions to expose.
... | 213450bfbdba56a8671943905d6ac888a548c8aa | 22,303 |
def timestamp_to_uint64(timestamp):
"""Convert timestamp to milliseconds since epoch."""
return int(timestamp.timestamp() * 1e3) | 165df202cb5f8cee5792bfa5778114ea3e98fa65 | 22,304 |
def extensible(x):
"""
Enables a function to be extended by some other function.
The function will get an attribute (extensible) which will return True.
The function will also get a function (extendedby) which will return a
list of all the functions that extend it.
"""
extensible_functions.a... | a810e90e386441e8b223824c77ee452b4f7ff6d5 | 22,305 |
def _validate_user_deploy_steps(task, user_steps, error_prefix=None):
"""Validate the user-specified deploy steps.
:param task: A TaskManager object
:param user_steps: a list of deploy steps. A deploy step is a dictionary
with required keys 'interface', 'step', 'args', and 'priority'::
... | 58cf55b444c533ec96a86ad09b76ca9bc275f7dd | 22,306 |
from operator import gt
def is_period_arraylike(arr):
""" return if we are period arraylike / PeriodIndex """
if isinstance(arr, pd.PeriodIndex):
return True
elif isinstance(arr, (np.ndarray, gt.ABCSeries)):
return arr.dtype == object and lib.infer_dtype(arr) == 'period'
return getattr... | f675f56dbca7ef80dc75bbe454a4f6e11a419c50 | 22,307 |
def reset_password_step_2(token):
"""Processing the second step of changing the password (password change)"""
email = confirm_token_reset_password(token)
if not email:
return redirect(url_for('web_pages.reset_password_step_1'))
form = EditPassword()
if form.validate_on_submit():
pass... | dcec97ba112ff96af4510488f801926190cfe221 | 22,308 |
def FStarTypeRole(typ, rawtext, text, lineno, inliner, options={}, content=[]):
"""An inline role to highlight F* types."""
#pylint: disable=dangerous-default-value, unused-argument
return nodes.literal(typ, rawtext, text, lineno, inliner, options=options, content=content) | 970ed43558e87a4319aed91c33d781fbe6a39d20 | 22,309 |
def matobj2dict(matobj):
"""A recursive function which converts nested mat object
to a nested python dictionaries
Arguments:
matobj {sio.matlab.mio5_params.mat_struct} -- nested mat object
Returns:
dict -- a nested dictionary
"""
ndict = {}
for fieldname in matobj._fieldnam... | 6b8413fd0c4dc9bb4e778944e7a6d4c260b56fa1 | 22,310 |
import io
def download_from_vt(client: vt.Client, file_hash: str) -> bytes:
"""
Download file from VT.
:param vt.Client client: the VT client
:param str file_hash: the file hash
:rtype: bytes
:return: the downloaded data
:raises ValueError: in case of any error
"""
try:
buf... | 055cd636d853d81921034d197bac9ad7a9c206c2 | 22,311 |
import torch
def divide_and_conquer(x, k, mul):
"""
Divide and conquer method for polynomial expansion
x is a 2d tensor of size (n_classes, n_roots)
The objective is to obtain the k first coefficients of the expanded
polynomial
"""
to_merge = []
while x[0].dim() > 1 and x[0].size(0) ... | 64bdf2d50cf7cbf7da814b93521df5cee41623fe | 22,312 |
def calculate_operating_pressure(feed_state_block=None, over_pressure=0.15,
water_recovery=0.5, NaCl_passage=0.01, solver=None):
"""
estimate operating pressure for RO unit model given the following arguments:
feed_state_block: the state block of the RO feed that has t... | 2252910515ad6b6188c06bbf3add2a36b37da1ea | 22,313 |
from bs4 import BeautifulSoup
def parse_pypi_index(text):
"""Parses the text and returns all the packages
Parameters
----------
text : str
the html of the website (https://pypi.org/simple/)
Returns
-------
List[str]
the list of packages
"""
soup = BeautifulSoup(te... | 68d831aab69f3ffdd879ea1fa7ca5f28fc1b1e75 | 22,314 |
import os
def fetch(data_dir, dest="wmt14"):
"""
Fetches most data from the WMT14 shared task.
Creates the `dest` if it doesn't exist.
Args:
data_dir (str): absolute path to the dir where datasets are stored
dest (str): name for dir where WMT14 datasets will be extracted
Returns... | 3bf699362fdb6c80427fe3b6fbd6450601187aca | 22,315 |
def _get_score_measure(func, alphabeta, color, board, alpha, beta, depth, pid):
"""_get_score_measure
"""
measure(pid)
return _get_score(func, alphabeta, color, board, alpha, beta, depth, pid) | e36723d03c2ee686177ea3f8ce34874b250c2058 | 22,316 |
def mousePressed():
"""
Return True if the mouse has been left-clicked since the
last time mousePressed was called, and False otherwise.
"""
global _mousePressed
if _mousePressed:
_mousePressed = False
return True
return False | 37fd34e71ee7e9c4a671a5ba5a4a946a7441c0da | 22,317 |
def variable_on_cpu(name, shape, initializer):
"""
Next we concern ourselves with graph creation.
However, before we do so we
must introduce a utility function ``variable_on_cpu()``
used to create a variable in CPU memory.
"""
# Use the /cpu:0 device for scoped operations
with tf.devic... | 10e724f900d7c7334e81f3380fc4764ca935b284 | 22,318 |
def adaptive_generate_association_rules(patterns, confidence_threshold):
"""
Given a set of frequent itemsets, return a dictof association rules
in the form {(left): (right)}
It has a check with 2048 thus will only retain multimodal rules.
"""
missed = 0
rules = defaultdict(set)
for setn... | 35589916f91aab789a8d31559bcdbaca37bfdcd1 | 22,319 |
import subprocess
def cli():
"""
Rebuild the docker container
:return: Subprocess call result
"""
cmd = "docker-compose down && docker-compose build"
return subprocess.call(cmd, shell=True) | e9d0eec7fbe97efad859ef8da28486075d3daa80 | 22,320 |
from typing import Union
from typing import Collection
def scored_ngrams(
docs: Documents,
n: int = 2,
metric: str = "pmi",
tokenizer: Tokenizer = DEFAULT_TOKENIZER,
preprocessor: CallableOnStr = None,
stopwords: Union[str, Collection[str]] = None,
min_freq: int = 0,
fuse_tuples: bool ... | a77b42eb1361c55cb23a1b168e99d4abb1ef9af1 | 22,321 |
import argparse
def parse_command_line_arguments() -> argparse.Namespace:
"""Specifies the command line parser and returns a
:class:`argparse.Namespace` containing the arguments."""
parser = argparse.ArgumentParser(
description=f"supreme-pancake v{__version__}")
parser.add_argument(
"-... | 707493e5100145142426315f903b70d9cfdc0ea5 | 22,322 |
def imurl(image_url, return_as_array = False , **kwargs):
"""
Read image from url and convert to bytes or ndarray
Paramters
---------
image_url: http / https url of image
return_as_array: Convert image directly to numpy array
default: False
kwargs:
Keyword argu... | c6c93ab7a2b97b522bca2d6673bfd843fdc8bb72 | 22,323 |
def generate_command(config, work_dir, output_analysis_id_dir, errors, warnings):
"""Build the main command line command to run.
Args:
config (GearToolkitContext.config): run-time options from config.json
work_dir (path): scratch directory where non-saved files can be put
output_analysi... | bb24ff62f3c4fa579eedf721708e84bf4cf3920c | 22,324 |
def ip(
context,
api_client,
api_key,
input_file,
output_file,
output_format,
verbose,
ip_address,
):
"""Query GreyNoise for all information on a given IP."""
ip_addresses = get_ip_addresses(context, input_file, ip_address)
results = [api_client.ip(ip_address=ip_address) for ... | b4c52e1bb1abb03679b977d4b15f5e0295c1e0c2 | 22,325 |
def get_layer(neurons, neuron_loc, depth=None, return_closest: bool=False):
"""Obtain the layer of neurons corresponding to layer number or specific depth."""
layers = np.unique(neuron_loc[2, :])
if depth is not None:
if depth in layers:
pass
elif return_closest:
de... | d221d294bbe974554b0180ea9d41394294de41dc | 22,326 |
def _format_unpack_code_level(message,
signal_names,
variable_lines,
helper_kinds):
"""Format one unpack level in a signal tree.
"""
body_lines = []
muxes_lines = []
for signal_name in signal_names:
... | b88362f6fd3cb5ccaf3a3f76472f2002ac9c1518 | 22,327 |
import socket
from sys import stdout
import select
def find_phones():
"""
This function broadcasts on the LAN to the Shexter ports, and looks for a reply from a phone.
:return: (IP, Port) tuple representing the phone the user selects. None if no phone found.
"""
sock_sender = socket.socket(socket.... | 8d449adf26de552087ae303f76caab1f338444e1 | 22,328 |
def fileGDB_schema() -> StructType:
"""Schema for dummy FileGDB."""
return StructType(
[
StructField("id", LongType()),
StructField("category", StringType()),
StructField("geometry", BinaryType()),
]
) | 0ef7ad136d64f19e392bb8a9ff471478094193fe | 22,329 |
def set_atom_stereo_parities(sgr, atm_par_dct):
""" set atom parities
"""
atm_dct = mdict.set_by_key_by_position(atoms(sgr), atm_par_dct,
ATM_STE_PAR_POS)
return _create.from_atoms_and_bonds(atm_dct, bonds(sgr)) | 1e733291ce12e614b538054c2c05fc3892ce3206 | 22,330 |
def clean(expr):
"""
cleans up an expression string
Arguments:
expr: string, expression
"""
expr = expr.replace("^", "**")
return expr | f7c990146094c43d256fe15f9543a0ba90877ee3 | 22,331 |
def atom_stereo_keys(sgr):
""" keys to atom stereo-centers
"""
atm_ste_keys = dict_.keys_by_value(_atom_stereo_parities(sgr),
lambda x: x in [True, False])
return atm_ste_keys | c084c30f4601d18941d98c313d3a74b93153cd80 | 22,332 |
def get_node_rd(graph, k=3):
"""
Get k nodes to defend based on Recalculated Degree (RD) Removal :cite:`holme2002attack`.
:param graph: an undirected NetworkX graph
:param k: number of nodes to defend
:return: a list of nodes to defend
"""
return get_node_rd_attack(graph, k) | dbbf501353133a1cb222f6d2d4f632faa07bad1c | 22,333 |
def get_frog():
"""Returns the interface object to frog NLP. (There should only be one
instance, because it spawns a frog process that consumes a lot of RAM.)
"""
global FROG
if FROG is None:
FROG = frog.Frog(frog.FrogOptions(
tok=True, lemma=True, morph=False, daringmorph=False,... | 5701b2856532241d797eb77d9734fd67ee838312 | 22,334 |
import requests
def fetch(url: str, **kwargs) -> Selector:
"""
Send HTTP request and parse it as a DOM selector.
Args:
url (str): The url of the site.
Returns:
Selector: allows you to select parts of HTML text using CSS or XPath expressions.
"""
kwargs.setdefault('headers', D... | f5bbe41f3b7bc83d0092d0b2165681df096413d1 | 22,335 |
import math
def growth(x, a, b):
""" Growth model. a is the value at t=0. b is the so-called R number.
Doesnt work. FIX IT """
return np.power(a * 0.5, (x / (4 * (math.log(0.5) / math.log(b))))) | 6276fd00f270ef72f52ed7493f431dd0e3b34326 | 22,336 |
from datetime import datetime
import pytz
def __to_localdatetime(val):
"""Convert val into a local datetime for tz Europe/Amsterdam."""
try:
# "timestamp": "2019-02-03T19:20:00",
dt = datetime.strptime(val, __DATE_FORMAT)
dt = pytz.timezone(__TIMEZONE).localize(dt)
return dt
... | e2eea5da625a3514b6872e5604336d5dfb6f0ccb | 22,337 |
import warnings
def imgMinMaxScaler(img, scale_range):
"""
:param img: image to be rescaled
:param scale_range: (tuple) (min, max) of the desired rescaling
"""
warnings.filterwarnings("ignore")
img = img.astype("float64")
img_std = (img - np.min(img)) / (np.max(img) - np.min(img))
img_... | f55795167f6a284ea81609413edc73c1336a2a5e | 22,338 |
def conditional_vff(Xnew, inducing_variable, kernel, f, *,
full_cov=False, full_output_cov=False, q_sqrt=None, white=False):
"""
- Xnew are the points of the data or minibatch, size N x D (tf.array, 2d)
- feat is an instance of features.InducingFeature that provides `Kuu` and `Kuf` met... | ad4f2b69f4ea0cfb59247cf9d360514dc180774e | 22,339 |
def xor(text, key):
"""Returns the given string XORed with given key."""
while len(key) < len(text): key += key
key = key[:len(text)]
return "".join(chr(ord(a) ^ ord(b)) for (a, b) in zip(text, key)) | 3cae903ef4751b2f39e0e5e28d448b8d079ce249 | 22,340 |
from pathlib import Path
def get_emojis_voc_counts(path):
"""
Generate a value count of words for every emoji present in the csv files
found in the child directories of "path"
Args:
path (str): parent path of the csv files
Return:
em2vocab [dict of dict]: a dict associating each ... | b4525be35e191c84a9ea0d781d510f348724ff42 | 22,341 |
from unittest.mock import Mock
from unittest.mock import patch
import asyncio
async def test_camera_snapshot_connection_closed(driver):
"""Test camera snapshot when the other side closes the connection."""
loop = MagicMock()
transport = MagicMock()
transport.is_closing = Mock(return_value=True)
co... | 636f22f167d07699d7e591f74ae92ecde8f460c4 | 22,342 |
import numpy
from re import T
def _as_scalar(res, dtype=None):
"""Return None or a TensorVariable whose type is in T.float_scalar_types"""
if dtype is None:
dtype = config.floatX
if numpy.all(res.type.broadcastable):
while res.owner and isinstance(res.owner.op, T.DimShuffle):
r... | c5a8b6041a6eb160cec23f6957c9d9cc9147d4f7 | 22,343 |
import datasets
import torch
def partition_dataset():
""" Partitioning MNIST """
dataset = datasets.MNIST(
'./data',
train=True,
download=True,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307, ), (0.3081, ))
]))... | 6922ae2cc80655d93eeee23d31f1224f172de1cc | 22,344 |
def add_size_to_nus(demo_graph, pop, time_left):
"""
adds either nu, or [nu0, growth_rate], where nu0 is the size at the beginning of the epoch
use time_left to set nu0 to the size at the beginning of the epoch
"""
if 'nu' in demo_graph.nodes[pop]:
return demo_graph.nodes[pop]['nu']
else... | 6e655b157389ca8672433b26baa1f2362f5dde34 | 22,345 |
def _rand_lognormals(logs, sigma):
"""Mock-point"""
return np.random.lognormal(mean=logs, sigma=sigma, size=logs.shape) | 8fbf51e548293ff6c4dee8f385af69ecaaf34cde | 22,346 |
def add_start_end_qualifiers(statement, startVal, endVal):
"""Add start/end qualifiers to a statement if non-None, or return None.
@param statement: The statement to decorate
@type statement: WD.Statement
@param startVal: An ISO date string for the starting point
@type startVal: str, unicode, or No... | 9a87feff53aca00ce257a5d0b967621461a5d15a | 22,347 |
def _CheckFilter(text):
"""CHecks if a string could be a filter.
@rtype: bool
"""
return bool(frozenset(text) & FILTER_DETECTION_CHARS) | 0d0dfed55df78ea6f49e4f615e9f7fe5758f9bc1 | 22,348 |
def listProxyServers():
"""return a list of proxy servers as a list of lists.
E.g. [['nodename','proxyname'], ['nodename','proxyname']].
Typical usage:
for (nodename,proxyname) in listProxyServers():
callSomething(nodename,proxyname)
"""
return listServersOfType("PROXY_SERVER") | 0e2ae4a874fa0ca030a04e694c7eacefde4f45f6 | 22,349 |
def api_version(func):
"""
API版本验证装饰器
:param func:
:return:
"""
@wraps(func)
def wrapper(*args, **kwargs):
# 验证api版本
verify_result = verify_version(kwargs.get('version'))
if not verify_result:
raise ApiVersionException() #抛出异常,返回结果状态码400, message:api versi... | 2e73bc7899a4052004246c1e3392001507469c86 | 22,350 |
from typing import List
from typing import Union
def is_prefix(a: List[Union[int, str]], b: List[Union[int, str]]):
"""Check if `a` is a prefix of `b`."""
if len(a) >= len(b):
return False
for i in range(len(a)):
if a[i] != b[i]:
return False
return True | 4b0605af536aa5fa188cfca0cee62588fe41bf5d | 22,351 |
import glob
def shm_data_find(ifo, ldr_type, start, stride, directory='.', verbose=False):
"""a routine to automate discovery of frames within /dev/shm
"""
end = start+stride
frames = []
for frame in sorted(glob.glob(shm_glob_tmp%(directory, ifo, ifo, ldr_type))):
s, d = utils.extract_st... | f4aba39ba77edf5d22cdaa0da16f888c26999512 | 22,352 |
def backward_inference(protocol, subsys_x, t_x, subsys_y, t_y, silent=True):
"""
Forward inference answers the question:
Given a measurement result of 'subsys_y' at the end of the protocol,
what can I say about the result an Agent would have received had she done
a measurement of 'subsys_x' before t... | 22e73ff5c4b90b535e9387cf71829bf88745a95d | 22,353 |
def rainfall_interception_hbv(Rainfall, PotEvaporation, Cmax, InterceptionStorage):
"""
Returns:
TF, Interception, IntEvap,InterceptionStorage
"""
Interception = pcr.min(
Rainfall, Cmax - InterceptionStorage
) #: Interception in mm/timestep
InterceptionStorage = (
Intercept... | 0e95a1088a36d25d0d1210384a56945d0b032fda | 22,354 |
from rspn.learning.structure_learning import get_next_operation, learn_structure
def learn_mspn(
data,
ds_context,
cols="rdc",
rows="kmeans",
min_instances_slice=200,
threshold=0.3,
max_sampling_threshold_cols=10000,
max_sampling_threshold_rows=100000,
... | 6ac8117b4d448c89fe148c4c97828da4a09dc471 | 22,355 |
import os
def _sanitize_filename(dfile, no_symlink=True):
"""Check and sanitize 'dfile' for use as a target file.
"""
dirname, basename = os.path.split(dfile)
dirname = os.path.abspath(dirname)
dfile = os.path.join(dirname, basename)
if no_symlink:
if os.path.islink(dfile):
... | f612bc587209ee21411fd5d132b2bf9285767f77 | 22,356 |
def generate_image_anim(img, interval=200, save_path=None):
"""
Given CT img, return an animation across axial slice
img: [D,H,W] or [D,H,W,3]
interval: interval between each slice, default 200
save_path: path to save the animation if not None, default None
return: matplotlib.animation.Animatio... | 90ebd9d0e21b58f75a2eca8623ac7a9d12b4a820 | 22,357 |
import sys
import os
import subprocess
import json
def get_routes(config, prefix=None, group_by=None):
"""Executes the helper script that extracts the routes out of the
pyramid app."""
python = sys.executable
script = os.path.join(os.path.dirname(__file__), "extract.py")
config = os.path.expanduse... | b71d896f7b3fc23848899efc332d2e9008ff1f9c | 22,358 |
def square_root(s):
""" Function to compute square roots using the Babylonian method
"""
x = s/2
while True:
temp = x
x = (1/2) * ( x + (s/x) )
if temp == x:
return x
# Como la convergencia se alcanza rápidamente, llega un momento en que el error
# e... | 9af22ce073bcb8d131736efba6133a92d9d7dc74 | 22,359 |
def quisort(uslist, lo=None, hi=None):
"""Sort in-place an unsorted list or slice of a list
lo and hi correspond to the start and stop indices for the list slice"""
if hi is None:
hi = len(uslist) - 1
if lo is None:
lo = 0
def partition(uslist, lo, hi):
"""Compare and swap... | a33adbe819ec1c60149e6d9a50ab78555f6021d5 | 22,360 |
def is_generator(f):
"""Return True if a function is a generator."""
isgen = (f.__code__.co_flags & CO_GENERATOR) != 0
return isgen | 239d0854e27a16d9e99102ff9c698086119b8e35 | 22,361 |
import torch
def reward(sample_solution, use_cuda=True, name='reward'):
"""
Args:
sample_solution seq_len of [batch_size]
"""
'''
if 'TSP' in name:
batch_size = sample_solution[0].size(0)
n = len(sample_solution)
tour_len = Variable(torch.zeros([batch_size]))
... | fed916437085d15b2c9c6a04486e43251c3b0422 | 22,362 |
def addRegionEntry(Id: int, parentId: int, name: str, RegionType: RegionType, alias=''):
"""
添加自定义地址信息
:param Id: 地址的ID
:param parentId: 地址的父ID, 必须存在
:param name: 地址的名称
:param RegionType: 地址类型,RegionType,
:param alias: 地址的别名, default=''
:return:
"""
geocoding = jpype.JClass('io.... | ba6c78842f847939f1a44b859156d15738adca58 | 22,363 |
def check_movement(pagination):
"""Check for ability to navigate backward or forward between pages."""
pagination_movements = pagination.find_element_by_xpath(
'.//div[@class="search_pagination_right"]'
).find_elements_by_class_name("pagebtn")
# Check for ability to move back
try:
mo... | 37bb55ae4509f8bdc98d3bf52bbef4a4a1e5d600 | 22,364 |
def glint_correct_image(imarr, glintarr, nir_band=7):
"""
Apply the sunglint removal algorithm from section III of Lyzenga et al.
2006 to a multispectral image array.
Parameters
----------
imarr : numpy array (RxCxBands shape)
The multispectral image array. See `OpticalRS.RasterDS` for ... | 2982883b37fa2452b12311c62f4d0c404f1718f9 | 22,365 |
def get_named_game(id):
"""Get specific game from GB API."""
query_uri = f"{GB_GAME_URL}{id}?format=json&api_key={API_KEY}"
return query_for_goty(query_uri, expect_list=False, always_return_something=False) | 4b4c7efeecace2d07b5ce7052cfa550d233a61bb | 22,366 |
from datetime import datetime
import pytz
def isoweek_datetime(year, week, timezone='UTC', naive=False):
"""
Returns a datetime matching the starting point of a specified ISO week
in the specified timezone (default UTC). Returns a naive datetime in
UTC if requested (default False).
>>> isoweek_da... | d109d8ca0443b6454c7ab58a9482d5c52ec90799 | 22,367 |
def returned(n):
"""Generate a random walk and return True if the walker has returned to
the origin after taking `n` steps.
"""
## `takei` yield lazily so we can short-circuit and avoid computing the rest of the walk
for pos in randwalk() >> drop(1) >> takei(xrange(n-1)):
if pos == Origin:
return True
return... | 6c501a58c6d2abe9d9fa76736fabf75f3f78dbd9 | 22,368 |
def get_ego_as_agent(frame: np.ndarray) -> np.ndarray:
"""Get a valid agent with information from the AV. Ford Fusion extent is used.
:param frame: The frame from which the Ego states are extracted
:return: An agent numpy array of the Ego states
"""
ego_agent = np.zeros(1, dtype=AGENT_DTYPE)
eg... | 249ca88c8aa01c7f06c6acf2d8427ca158926603 | 22,369 |
import json
def load_users(dir="private/users"):
"""load_users will load up all of the user json files in the dir."""
files = get_files_in_dir(dir)
dict = {}
for filename in files:
user = {}
filepath = join(dir, filename)
with open(filepath) as file:
try:
... | e9181ff8f34a6c351f874649ec328d14b4ba2784 | 22,370 |
def _scale_annots_dict(annot, new_sz, ann_im_sz):
"""Scale annotations to the new_sz, provided the original ann_im_sz.
:param annot: bounding box in dict format
:param new_sz: new size of image (after linear transforms like resize)
:param ann_im_sz: original size of image for which the bounding boxes we... | 44a0f9bf0b1a9befbaea95fd6b6fd5d9440178a4 | 22,371 |
from typing import Any
from typing import Tuple
from typing import List
import inspect
def get_handlers_in_instance(inst: Any) -> Tuple[List[Handler], List[Handler]]:
"""Get all handlers from the members of an instance.
Args:
inst: Instance to get handlers from.
Returns:
2-tuple containi... | c4f268d06fba208ce2a40bac3700b2c43d394051 | 22,372 |
def django_op_to_flag(op):
"""
Converts a django admin operation string to the matching
grainy permission flag
Arguments:
- op <str>
Returns:
- int
"""
return DJANGO_OP_TO_FLAG.get(op, 0) | 6d221271d69db3ed923395b920ee7aba30b50bab | 22,373 |
def rgb2gray(images):
"""将RGB图像转为灰度图"""
# Y' = 0.299 R + 0.587 G + 0.114 B
# https://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
return np.dot(images[..., :3], [0.299, 0.587, 0.114]) | f011345d43f49e1b7d625a4d379a72ec684cab00 | 22,374 |
import os
def wav2vec2_local(ckpt, *args, **kwargs):
"""
The model from local ckpt
ckpt (str): PATH
"""
assert os.path.isfile(ckpt)
return _UpstreamExpert(ckpt, *args, **kwargs) | a6e63598deccb99edfe798871e026fed7995381d | 22,375 |
def mIou(y_true, y_pred, n_classes):
"""
Mean Intersect over Union metric.
Computes the one versus all IoU for each class and returns the average.
Classes that do not appear in the provided set are not counted in the average.
Args:
y_true (1D-array): True labels
y_pred (1D-array): Pr... | aebb9a367f45172b999ddda8eb024371f3e0df3d | 22,376 |
import operator
def drop_last(iterable, n=1):
"""Drops the last item of iterable"""
t1, t2 = tee(iterable)
return map(operator.itemgetter(0), zip(t1, islice(t2, n, None))) | edef599cc1697cd4d8f1e1df2d479e123945aa41 | 22,377 |
def density(height: float) -> float:
"""
Returns the air density in slug/ft^3 based on altitude
Equations from https://www.grc.nasa.gov/www/k-12/rocket/atmos.html
:param height: Altitude in feet
:return: Density in slugs/ft^3
"""
if height < 36152.0:
temp = 59 - 0.00356 * height
... | ec85f9384035808084a024eb5a374ecfe7a64a2f | 22,378 |
import logging
import os
def parse(opts):
"""
Entry point for XML Schema parsing into an OME Model.
"""
# The following two statements are required to "prime" the generateDS
# code and ensure we have reasonable namespace support.
filenames = opts.args
namespace = opts.namespace
schema... | 04e36d09693a0065e3284d43a517a9de977dab39 | 22,379 |
def has_paired_before() -> bool:
"""Simple check for whether a device has previously been paired.
This does not verify that the pairing information is valid or up to date.
The assumption being - if it's previously paired, then it has previously
connected to the internet.
"""
identity = Identity... | f43ddf1290fcb101f0a0ae3d0fb6eabc368113c2 | 22,380 |
def caller_linkedin(user_input: dict) -> dict:
"""
Call LinkedIn scraping methods to get info about found and potential subjects.
Args:
`user_input`: user input represented as a dictionary.
Returns:
`dict`: the dictionary with information about found or potential subjects.
"""
r... | abb6277e699efa184949faf2b5c6585734be2f53 | 22,381 |
def service_request_eqf(stub_response):
"""
Return a function to be used as the value matching a ServiceRequest in
:class:`EQFDispatcher`.
"""
def resolve_service_request(service_request_intent):
eff = concretize_service_request(
authenticator=object(),
log=object(),
... | f2a052f975ad8c94a58de50c1eb8aaa563522ca1 | 22,382 |
def get_nearest_point_distance(points, wire1, wire2):
"""
>>> get_nearest_point_distance([(0, 0), (158, -12), (146, 46), (155, 4), (155, 11)], [((0, 0), (75, 0)), ((75, 0), (75, -30)), ((75, -30), (158, -30)), ((158, -30), (158, 53)), ((158, 53), (146, 53)), ((146, 53), (146, 4)), ((146, 4), (217, 4)), ((217, 4... | 917ae2370497ec4ea753daed89a2ee82724887fc | 22,383 |
def strip_tokens(tokenized: str) -> str:
"""Replaces all tokens with the token's arguments."""
result = []
pos = 0
match = RX_TOKEN.search(tokenized, pos)
while match:
start, end = match.span()
result.append(tokenized[pos:start])
result.append(match.groupdict()['argument'])
... | b70c58ee45fc24e88269c99067a2f161b2b37e75 | 22,384 |
def circular(P=365, K=0.1, T=0, gamma=0, t=None):
"""
circular() simulates the radial velocity signal of a planet in a
circular orbit around a star.
The algorithm needs improvements.
Parameters:
P = period in days
K = semi-amplitude of the signal
T = velocity at zero phase... | 33d3ea97d21ce1a14b07d02216597fe8977b2400 | 22,385 |
def set(isamAppliance, dsc, check_mode=False, force=False):
"""
Updating the tracing levels
"""
check_value,warnings = _check(isamAppliance, dsc)
if force is True or check_value is False:
if check_mode is True:
return isamAppliance.create_return_object(changed=True, warnings=war... | 1451ace2ed5ef6820e34ebb05d0879e3d5e3917b | 22,386 |
import logging
import json
import tempfile
import os
import zipfile
import requests
def submit_annotations(ann_srv_url, annotations, send_zip=False):
"""
Call the Annotation Storage Service to save annotations.
:param ann_srv_url: URL of the annotation service where the annotations
... | 8b69af6ca4019c84a8d90df7390e763c143810d8 | 22,387 |
from astropy.table import Table
from astropy.time import Time
def parse_logfile(logfile):
"""
Read iotime log entries from logfile
Return Table with columns function duration readwrite filename timestamp datetime
"""
rows = list()
with open(logfile) as fx:
for line in fx:
... | 8fb27648694df32e9035d0d24cae80f9ff9e654a | 22,388 |
def histogram2d(x,y,n=10,range=None,density=False,keep_outliers=False,out=None):
"""2D histogram with uniform bins. Accelerated by numba
x, y: array_like
x and y coordinates of each point. x and y will be flattened
n : scalar or (nx, ny)
number of bins in x and y
range : None or ((xmin,xmax)... | 8faf591e769630540345565ff3a34f33e83f70ce | 22,389 |
import os
import inspect
def createSplash(app):
"""Creates a splash screen object to show while the Window is loading.
Return:
SplashScreen object.
"""
uiDir = os.path.dirname(inspect.getfile(KrakenUI))
splashPixmap = QtGui.QPixmap()
splashImgPath = os.path.join(uiDir, 'images', 'Kraken... | c3f4d33071e3a8b1d67d0a69801c706aab652714 | 22,390 |
def _anatomical_swaps(pd):
"""Return swap and flip arrays for data transform to anatomical
use_hardcoded: no-brain implementation for 90deg rots
"""
use_hardcoded = True
# hardcoded for 90degs
if use_hardcoded:
if _check90deg(pd) != True:
raise(Exception('Not implemented'))
... | 2b958571597b72ca38de1310ca9a9e6a2caa69ac | 22,391 |
from typing import List
from typing import Dict
def block_variants_and_samples(variant_df: DataFrame, sample_ids: List[str],
variants_per_block: int,
sample_block_count: int) -> (DataFrame, Dict[str, List[str]]):
"""
Creates a blocked GT matrix and... | 4cf50f74b235adf5ef92ebde3a4a9259a3a49d87 | 22,392 |
def sparql_service_update(service, update_query):
"""
Helper function to update (DELETE DATA, INSERT DATA, DELETE/INSERT) data.
"""
sparql = SPARQLWrapper(service)
sparql.setMethod(POST)
sparql.setRequestMethod(POSTDIRECTLY)
sparql.setQuery(update_query)
result = sparql.query()
... | 8e68c6672222a831203e457deaaac1ed73169fbf | 22,393 |
def filtered_events(request):
"""Get the most recent year of stocking and
pass the information onto our annual_events view.
"""
dataUrl = reverse("api:api-get-stocking-events")
maxEvents = settings.MAX_FILTERED_EVENT_COUNT
return render(
request,
"stocking/found_events.html",
... | b99d772656bab246b9f412f50674e402b7ca7476 | 22,394 |
import requests
from datetime import datetime
def track_user_session(user=None, request=None):
"""Creates, filters and updates UserSessions on the core and sends UserSessions to the hub on next login
Filter the local UserSession objects per user and get their most recent user_session object
If its a LOG... | f5733eed845d23dac945c7d23d09a4cccb2f4e14 | 22,395 |
def score(string, goal):
"""
Compare randomly generated string to the goal, check how many
letters are correct and return
"""
check_counter = 0
string = generate(values)
for i in range(len(string)):
if string[i] == goal[i]:
check_counter += 1
return check_counter | afcfcc565a898b2cdd22e05793144c710fb58e26 | 22,396 |
from datetime import datetime
def validate_parent():
"""
This api validates a parent in the DB.
"""
parent_id = request.json.get('parent_id', None)
decision = request.json.get('decision', 0)
parent = query_existing_user(parent_id)
if parent:
parent.validated = decision
par... | 3fe52863b4de24705c96aeaa67ee264916b37dbe | 22,397 |
def parse_pdu(data, **kwargs):
"""Parse binary PDU"""
command = pdu.extract_command(data)
if command is None:
return None
new_pdu = make_pdu(command, **kwargs)
new_pdu.parse(data)
return new_pdu | 0a5a84368793f8d5983b08bc2123bd0adb994be6 | 22,398 |
def alchemy_nodes(mol):
"""Featurization for all atoms in a molecule. The atom indices
will be preserved.
Parameters
----------
mol : rdkit.Chem.rdchem.Mol
RDKit molecule object
Returns
-------
atom_feats_dict : dict
Dictionary for atom features
"""
atom_feats_d... | 8bccd62bafa77f6dc95bfba8992df48756b9ac0e | 22,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.