content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def home():
"""List devices."""
devices = Device.query.all()
return render_template('devices/home.html', devices=devices) | d0f9b14cedf83fbeb35166e1ad9b2de295e2584f | 3,643,100 |
def translate_value(document_field, form_value):
"""
Given a document_field and a form_value this will translate the value
to the correct result for mongo to use.
"""
value = form_value
if isinstance(document_field, ReferenceField):
value = document_field.document_type.objects.get(id=for... | 5c72764efde00fb4f5093a800706082c1171b5b6 | 3,643,101 |
def error_404(error):
"""Custom 404 Error Page"""
return render_template("error.html", error=error), 404 | 1f1429b8c86ed7a486c498cae6955961f3084ef5 | 3,643,102 |
def sum_num(n1, n2):
"""
Get sum of two numbers
:param n1:
:param n2:
:return:
"""
return(n1 + n2) | 08477e596317f6b8750debd39b5cf0aa56da857c | 3,643,103 |
def intensity_slice_volume(kernel_code,
image_variables,
g_variables,
blockdim,
bound_box,
vol_dim,
voxel_size,
poses,
... | c5f64f7ee5a95210a2c5598a7e31e36541fcb320 | 3,643,104 |
def mean_filter(img, kernel_size):
"""take mean value in the neighbourhood of center pixel.
"""
return cv2.blur(img, ksize=kernel_size) | 58d5684e0691407f6f77d40d5717523eb617dde9 | 3,643,105 |
def main():
"""Return the module instance."""
return AnsibleModule(
argument_spec=dict(
data=dict(default=None),
path=dict(default=None, type=str),
file=dict(default=None, type=str),
)
) | 846aa9bf9ce23ba7a05aeb91158ad04770b7721e | 3,643,106 |
from typing import Optional
from pathlib import Path
def load_RegNetwork_interactions(
root_dir: Optional[Path] = None,
) -> pd.DataFrame:
"""
Loads RegNetwork interaction datafile. Downloads the file first if not already present.
"""
file = _download_RegNetwork(root_dir)
return pd.read_csv(
... | 15571c71ac3bd386518a0f2ec4d293b20394c4b2 | 3,643,107 |
import sys
import json
import re
import requests
def hxlspec_main(args, stdin=STDIN, stdout=sys.stdout, stderr=sys.stderr):
""" Run hxlspec with command-line arguments.
Args:
args (list): a list of command-line arguments
stdin (io.IOBase): alternative standard input (mainly for testing)
... | e21e8ba95d91c116dda0ad320cdc9108e6a2a360 | 3,643,108 |
import time
import tqdm
import sys
def search_restaurant(house_list,
filter_by_distance=True,
search_range=3,
sort=True,
top_k=100,
save_csv=False,
offline_save=True):
"""Scraping re... | ba38c6b06e1213b70e96f502e81f03862975df79 | 3,643,109 |
def get_model_config(model, dataset):
"""Map model name to model network configuration."""
if 'cifar10' == dataset.name:
return get_cifar10_model_config(model)
if model == 'vgg11':
mc = vgg_model.Vgg11Model()
elif model == 'vgg16':
mc = vgg_model.Vgg16Model()
elif model == 'vgg19':
mc = vgg_mo... | eb3da4fa2e7308fe0b7394b6c654e171abaf2363 | 3,643,110 |
from datetime import datetime
def utc_now():
"""Return current utc timestamp
"""
now = datetime.datetime.utcnow()
return int(now.strftime("%s")) | 35edc0e19f236263a8f2efd0fa9be81663042484 | 3,643,111 |
def rrc_filter(alpha, length, osFactor, plot=False):
"""
Generates the impulse response of a root raised cosine filter.
Args:
alpha (float): Filter roll-off factor.
length (int): Number of symbols to use in the filter.
osFactor (int): Oversampling factor (number of samples per symbol... | 9fc5c916e646179ac465fb2d3d897d4dadadd9de | 3,643,112 |
def get_available_services(project_dir: str):
"""Get standard services bundled with stakkr."""
services_dir = file_utils.get_dir('static') + '/services/'
conf_files = _get_services_from_dir(services_dir)
services = dict()
for conf_file in conf_files:
services[conf_file[:-4]] = services_dir ... | b361eaefd0772ca9bcc75274f19e7550b02d1484 | 3,643,113 |
def build_insert(table, to_insert):
"""
Build an insert request.
Parameters
----------
table : str
Table where query will be directed.
to_insert: iterable
The list of columns where the values will be inserted.
Returns
-------
str
Built query.
"""
sq... | cf2e72c57e5502660ed3dcade6885076ff8c2014 | 3,643,114 |
from pathlib import Path
import json
def get_reference_data(fname):
"""
Load JSON reference data.
:param fname: Filename without extension.
:type fname: str
"""
base_dir = Path(__file__).resolve().parent
fpath = base_dir.joinpath('reference', 'data', fname + '.json')
with fpath.open()... | 73880586393ce9463a356d69880f2f285058637f | 3,643,115 |
def _is_l10n_ch_isr_issuer(account_ref, currency_code):
""" Returns True if the string account_ref is a valid a valid ISR issuer
An ISR issuer is postal account number that starts by 01 (CHF) or 03 (EUR),
"""
if (account_ref or '').startswith(ISR_SUBSCRIPTION_CODE[currency_code]):
return _is_l10... | 5709d8f67aefe9b9faac6f4541f8a050eb95c82f | 3,643,116 |
import struct
def little_endian_uint32(i):
"""Return the 32 bit unsigned integer little-endian representation of i"""
s = struct.pack('<I', i)
return struct.unpack('=I', s)[0] | 07f72baaf8f7143c732fd5b9e56b0b7d02d531bd | 3,643,117 |
def evaluate_scores(scores_ID, scores_OOD):
"""calculates classification performance (ROCAUC, FPR@TPR95) based on lists of scores
Returns:
ROCAUC, fpr95
"""
labels_in = np.ones(scores_ID.shape)
labels_out = np.zeros(scores_OOD.shape)
y = np.concatenate([labels_in, labels_out])
s... | f88a67f09496700ab783a3e91347b085767a2228 | 3,643,118 |
from typing import Union
def check_cardinality(attribute_name: str,
analysis: run_metadata_pb2.Analysis
) -> Union[None, str]:
"""Check whether the cardinality exceeds the predefined threshold
Args:
attribute_name: (string),
analysis: (run_metadata_pb2.Anal... | 8a9b9e0c709b64273a2120100730992276b52b46 | 3,643,119 |
def create_df_from(dataset):
"""
Selects a method, based on the given dataset name, and creates the corresponding dataframe.
When adding a new method, take care to have as index the ASN and the column names to be of the format "dataset_name_"+"column_name" (e.g., the column "X" from the dataset "setA", shou... | 3a5e6f1a9aa510ec19c6eeb1af8a89574b938ea1 | 3,643,120 |
def plasma_fractal(mapsize=256, wibbledecay=3):
"""
Generate a heightmap using diamond-square algorithm.
Return square 2d array, side length 'mapsize', of floats in range 0-255.
'mapsize' must be a power of two.
"""
assert (mapsize & (mapsize - 1) == 0)
maparray = np.empty((mapsize, mapsize), dtype=np.flo... | f3b0c65f7bff6526a91c8d398a430a72cf744421 | 3,643,121 |
def reduce_puzzle(values):
"""Reduce a Sudoku puzzle by repeatedly applying all constraint strategies
Parameters
----------
values(dict)
a dictionary of the form {'box_name': '123456789', ...}
Returns
-------
dict or False
The values dictionary after continued application o... | 36665a4f933a77ce7d472e02fbafaf81beda6cad | 3,643,122 |
import pickle
def read_ids():
"""
Reads the content from a file as a tuple and returns the tuple
:return: node_id, pool_id (or False if no file)
"""
if not const.MEMORY_FILE.exists():
return False
with open(const.MEMORY_FILE, 'rb') as f:
data = pickle.load(f)
assert typ... | 89606543b149cac636765a6f3e2aef34f2adc38b | 3,643,123 |
from pymbolic.primitives import Call
def _match_caller_callee_argument_dimension_(program, callee_function_name):
"""
Returns a copy of *program* with the instance of
:class:`loopy.kernel.function_interface.CallableKernel` addressed by
*callee_function_name* in the *program* aligned with the argument
... | 7c37a20776e1ff551dca3f2acd1b36e47cf6b06e | 3,643,124 |
def new_automation_jobs(issues):
"""
:param issues: issues object pulled from Redmine API
:return: returns a new subset of issues that are Status: NEW and match a term in AUTOMATOR_KEYWORDS)
"""
new_jobs = {}
for issue in issues:
# Only new issues
if issue.status.name == 'New':
... | 74c9c96aeeea1d15384d617c266daa4d49f3a203 | 3,643,125 |
import os
def resolve_test_data_path(test_data_file):
"""
helper function to ensure filepath is valid
for different testing context (setuptools, directly, etc.)
:param test_data_file: Relative path to an input file.
:returns: Full path to the input file.
"""
if os.path.exists(test_data_f... | d124bcbc36b48fd6572697c9a5211f794c3dce19 | 3,643,126 |
def make_data(revs, word_idx_map, max_l=50, filter_h=3, val_test_splits=[2, 3], validation_num=500000):
"""
Transforms sentences into a 2-d matrix.
"""
version = begin_time()
train, val, test = [], [], []
for rev in revs:
sent = get_idx_from_sent_msg(rev["m"], word_idx_map, max_l, True)
... | b141297c0ef8d2eeb2c6c62e00924f5e64ffe266 | 3,643,127 |
def init(param_test):
"""
Initialize class: param_test
"""
# initialization
param_test.default_args_values = {'di': 6.85, 'da': 7.65, 'db': 7.02}
default_args = ['-di 6.85 -da 7.65 -db 7.02'] # default parameters
param_test.default_result = 6.612133606
# assign default params
if no... | d86cd246d4beb5aa267d222bb12f9637f001032d | 3,643,128 |
def add_width_to_df(df):
"""Adds an extra column "width" to df which is the angular width of the CME
in degrees.
"""
df = add_helcats_to_df(df, 'PA-N [deg]')
df = add_helcats_to_df(df, 'PA-S [deg]')
df = add_col_to_df(df, 'PA-N [deg]', 'PA-S [deg]', 'subtract', 'width', abs_col=True)
return ... | ea866d161ca77d9d78f04fb613aa1ed8631566b2 | 3,643,129 |
def checkSeconds(seconds, timestamp):
""" Return a string depending on the value of seconds
If the block is mined since one hour ago, return timestamp
"""
if 3600 > seconds > 60:
minute = int(seconds / 60)
if minute == 1:
return '{} minute ago'.format(minute)
retu... | 2d07657a14300793a116d28e7c9495ae4a1b61ed | 3,643,130 |
def get_netrange_end(asn_cidr):
"""
:param str asn_cidr: ASN CIDR
:return: ipv4 address of last IP in netrange
:rtype: str
"""
try:
last_in_netrange = \
ip2long(str(ipcalc.Network(asn_cidr).host_first())) + \
ipcalc.Network(asn_cidr).size() - 2
except ValueEr... | 51305dc1540bbc0a361452a80d6732b1eb039fd4 | 3,643,131 |
def load_from_file(filepath, column_offset=0, prefix='', safe_urls=False, delimiter='\s+'):
"""
Load target entities and their labels if exist from a file.
:param filepath: Path to the target entities
:param column_offset: offset to the entities column (optional).
:param prefix: URI prefix (Ex: htt... | 2aa9b286e25c6e93a06afb927f7e0ad345208afb | 3,643,132 |
def create_app(*, config_object: Config) -> connexion.App:
"""Create app instance."""
connexion_app = connexion.App(
__name__, debug=config_object.DEBUG, specification_dir="spec/"
)
flask_app = connexion_app.app
flask_app.config.from_object(config_object)
connexion_app.add_api("api.yaml... | 2d5f698be823f18075bd21a8ffb92fa9b14d9a78 | 3,643,133 |
from typing import Any
from typing import Union
import os
import zipimport
import zipfile
def load_plugins(descr: str, package: str, plugin_class: Any,
specs: TList[TDict[str, Any]] = None) -> \
TDict[Union[str, int], Any]:
"""
Load and initialize plugins from the given directory
... | 62ec68740ffc30e478cb6bad2365b6ead2f2a46c | 3,643,134 |
def _get_repos_info(db: Session, user_id: int):
"""Returns data for all starred repositories for a user.
The return is in a good format for the frontend.
Args:
db (Session): sqlAlchemy connection object
user_id (int): User id
Returns:
list[Repository(dict)]:repo_info = {
... | 78a126369355c1c76fc6a1b673b365e3423cd011 | 3,643,135 |
def ultimate_oscillator(close_data, low_data):
"""
Ultimate Oscillator.
Formula:
UO = 100 * ((4 * AVG7) + (2 * AVG14) + AVG28) / (4 + 2 + 1)
"""
a7 = 4 * average_7(close_data, low_data)
a14 = 2 * average_14(close_data, low_data)
a28 = average_28(close_data, low_data)
uo = 100 * ((a7... | 9803eda656cdb9dd49621a93785b55cf5bc15e7c | 3,643,136 |
import hashlib
import os
def generate_csrf(request: StarletteRequest,
secret_key: str,
field_name: str):
"""Generate a new token, store it in the session and return a time-signed
token. If a token is already present in the session, it will be used to
generate a new time... | a79bcd6640112db3729a160689c00e6f24677398 | 3,643,137 |
def get_completions():
"""
Returns the global completion list.
"""
return completionList | 901718ea73b5328c277c357ecac859b40518890d | 3,643,138 |
def breadth_first_search():
"""
BFS Algorithm
"""
initial_state = State(3, 3, "left", 0, 0)
if initial_state.is_goal():
return initial_state
frontier = list()
explored = set()
frontier.append(initial_state)
while frontier:
state = frontier.pop(0)
if state.is_g... | 2c0dca233b2bdb4474dd17ee7386ed15f5af44c1 | 3,643,139 |
import pandas
def rankSimilarity(df, top = True, rank = 3):
""" Returns the most similar documents or least similar documents
args:
df (pandas.Dataframe): row, col = documents, value = boolean similarity
top (boolean): True: most, False: least (default = True)
rank (int): num... | 7ae5a90ced7dbbd79d5f296a6f31f1236384ba7a | 3,643,140 |
def change_controller(move_group, second_try=False):
"""
Changes between motor controllers
move_group -> Name of required move group.
"""
global list_controllers_service
global switch_controllers_service
controller_map = {
'gripper': 'cartesian_motor_controller',
'whole_... | 8521e1c2967368a5c8ac956fc26d4da879919a2d | 3,643,141 |
import base64
def base64_encode(text):
"""<string> -- Encode <string> with base64."""
return base64.b64encode(text.encode()).decode() | ce837abde42e9a00268e14cfbd2bd4fd3cf16208 | 3,643,142 |
def _signed_bin(n):
"""Transform n into an optimized signed binary representation"""
r = []
while n > 1:
if n & 1:
cp = _gbd(n + 1)
cn = _gbd(n - 1)
if cp > cn: # -1 leaves more zeroes -> subtract -1 (= +1)
r.append(-1)
n +=... | 5f9f57e02942264901f6523962b21d1c36accdb2 | 3,643,143 |
import os
def load_tests(loader, tests, pattern):
"""Provide a TestSuite to the discovery process."""
test_dir = os.path.join(os.path.dirname(__file__), name)
return driver.build_tests(test_dir, loader,
host=data['host'],
port=data['port'],
... | 75d15dc8fef7f04cbcc56235d8318ad1b4a31928 | 3,643,144 |
def powderfit(powder, scans=None, peaks=None, ki=None, dmono=3.355,
spacegroup=1):
"""Fit powder peaks of a powder sample to calibrate instrument wavelength.
First argument is either a string that names a known material (currently
only ``'YIG'`` is available) or a cubic lattice parameter. Th... | ae2bfddd0ab95924ec3d56a1f86cc4aa9a685c9e | 3,643,145 |
def get_neighbor_v6_by_ids(obj_ids):
"""Return NeighborV6 list by ids.
Args:
obj_ids: List of Ids of NeighborV6's.
"""
ids = list()
for obj_id in obj_ids:
try:
obj = get_neighbor_v6_by_id(obj_id).id
ids.append(obj)
except exceptions.NeighborV6DoesNot... | a51d618961fa3e60c0c464473838791d55ba1f6a | 3,643,146 |
import base64
def decode_b64_to_image(b64_str: str) -> [bool, np.ndarray]:
"""解码base64字符串为OpenCV图像, 适用于解码三通道彩色图像编码.
:param b64_str: base64字符串
:return: ok, cv2_image
"""
if "," in b64_str:
b64_str = b64_str.partition(",")[-1]
else:
b64_str = b64_str
try:
img = base6... | 66f0e7bb5028ad7247ef7cb468e904c2bc7afdb7 | 3,643,147 |
def _get_index_videos(course, pagination_conf=None):
"""
Returns the information about each video upload required for the video list
"""
course_id = str(course.id)
attrs = [
'edx_video_id', 'client_video_id', 'created', 'duration',
'status', 'courses', 'transcripts', 'transcription_s... | 5a3288ff8c2f371505fe2c6a3051992bfcc602eb | 3,643,148 |
def get_user_by_api_key(api_key, active_only=False):
"""
Get a User object by api_key, whose attributes match those in the database.
:param api_key: API key to query by
:param active_only: Set this flag to True to only query for active users
:return: User object for that user ID
:raises UserDoe... | b36373dbfcda80f6aac963153a66b54bce1d828d | 3,643,149 |
def get_pixel_values_of_line(img, x0, y0, xf, yf):
"""
get the value of a line of pixels.
the line defined by the user using the corresponding first and last
pixel indices.
Parameters
----------
img : np.array.
image on a 2d np.array format.
x0 : int
raw number of the st... | ea78efe02130302b34ba8402f21349035b05b2e0 | 3,643,150 |
def _filter_out_variables_not_in_dataframe(X, variables):
"""Filter out variables that are not present in the dataframe.
Function removes variables that the user defines in the argument `variables`
but that are not present in the input dataframe.
Useful when ussing several feature selection procedures... | 63b4cce75741a5d246f40c5b88cfebaf818b3482 | 3,643,151 |
import gzip
def file_format(input_files):
"""
Takes all input files and checks their first character to assess
the file format. 3 lists are return 1 list containing all fasta files
1 containing all fastq files and 1 containing all invalid files
"""
fasta_files = []
fastq_files = []
inv... | acd9a0f7b49884d611d0ac65b43407a323a6588b | 3,643,152 |
def sub_vector(v1: Vector3D, v2: Vector3D) -> Vector3D:
"""Substract vector V1 from vector V2 and return resulting Vector.
Keyword arguments:
v1 -- Vector 1
v2 -- Vector 2
"""
return [v1[0] - v2[0], v1[1] - v2[1], v1[2] - v2[2]] | 2c9878d6775fdcee554f959e392b2c8d2bad8c8e | 3,643,153 |
def create_validity_dict(validity_period):
"""Convert a validity period string into a dict for issue_certificate().
Args:
validity_period (str): How long the signed certificate should be valid for
Returns:
dict: A dict {"Value": number, "Type": "string" } representation of the
... | ba0ccdd5c009a930b4030b15fbafaa978fe753d4 | 3,643,154 |
def analyse_latency(cid):
"""
Parse the resolve_time and download_time info from cid_latency.txt
:param cid: cid of the object
:return: time to resolve the source of the content and time to download the content
"""
resolve_time = 0
download_time = 0
with open(f'{cid}_latency.txt', 'r') a... | 806a9969cc934faeea842901442ecececfdde232 | 3,643,155 |
import re
def process_ref(paper_id):
"""Attempt to extract arxiv id from a string"""
# if user entered a whole url, extract only the arxiv id part
paper_id = re.sub("https?://arxiv\.org/(abs|pdf|ps)/", "", paper_id)
paper_id = re.sub("\.pdf$", "", paper_id)
# strip version
paper_id = re.sub(... | a1c817f1ae7b211973efd6c201b5c13e1a91b57b | 3,643,156 |
import re
def augment_test_func(test_func):
"""Augment test function to parse log files.
`tools.create_tests` creates functions that run an LBANN
experiment. This function creates augmented functions that parse
the log files after LBANN finishes running, e.g. to check metrics
or runtimes.
No... | 081593b57dfc82df328617b22cf778fceffe4beb | 3,643,157 |
def get_cuda_arch_flags(cflags):
"""
For an arch, say "6.1", the added compile flag will be
``-gencode=arch=compute_61,code=sm_61``.
For an added "+PTX", an additional
``-gencode=arch=compute_xx,code=compute_xx`` is added.
"""
# TODO(Aurelius84):
return [] | dfb92aa00db7f5d515b7b296824f6bdd91fa2724 | 3,643,158 |
def nstep_td(env, pi, alpha=1, gamma=1, n=1, N_episodes=1000,
ep_max_length=1000):
"""Evaluates state-value function with n-step TD
Based on Sutton/Barto, Reinforcement Learning, 2nd ed. p. 144
Args:
env: Environment
pi: Policy
alpha: Step size
gamma: Discount facto... | 86d5ab58d4d185dcbf08a84bbc8eb67051d2af21 | 3,643,159 |
def open_file(path):
"""more robust open function"""
return open(path, encoding='utf-8') | 785ab196756365d1f27ce3fcd69d0ba2867887a9 | 3,643,160 |
def test_subscribe(env):
"""Check async. interrupt if a process terminates."""
def child(env):
yield env.timeout(3)
return 'ohai'
def parent(env):
child_proc = env.process(child(env))
subscribe_at(child_proc)
try:
yield env.event()
except Interru... | fa3170cc6167e92195587f06ae65b27da48fa8ff | 3,643,161 |
import tempfile
import os
import setuptools
def has_flag(compiler, flagname):
"""Return a boolean indicating whether a flag name is supported on
the specified compiler.
"""
fd, fname = tempfile.mkstemp('.cpp', 'main', text=True)
with os.fdopen(fd, 'w') as f:
f.write('int main (int argc, ch... | b407af028221187c683e2821c507c10ec218ea86 | 3,643,162 |
import gzip
def _parse_data(f, dtype, shape):
"""Parses the data."""
dtype_big = np.dtype(dtype).newbyteorder(">")
count = np.prod(np.array(shape))
# See: https://github.com/numpy/numpy/issues/13470
use_buffer = type(f) == gzip.GzipFile
if use_buffer:
data = np.frombuffer(f.read(), dty... | 42185d2425aa9aa14abc0a61a5bdabc95224d15c | 3,643,163 |
def test_target(target # type: Any
):
"""
A simple decorator to declare that a case function is associated with a particular target.
>>> @test_target(int)
>>> def case_to_test_int():
>>> ...
This is actually an alias for `@case_tags(target)`, that some users may find a bit... | ebbf94941e7b11224ee4c8ee9665cea231076f5d | 3,643,164 |
def plot_spatial(adata, color, img_key="hires", show_img=True, **kwargs):
"""Plot spatial abundance of cell types (regulatory programmes) with colour gradient
and interpolation (from Visium anndata).
This method supports only 7 cell types with these colours (in order, which can be changed using reorder_cma... | ffbf3cc0f6efdef9bf66b94bac22ef8bf8b39bab | 3,643,165 |
def stats_by_group(df):
"""Calculate statistics from a groupby'ed dataframe with TPs,FPs and FNs."""
EPSILON = 1e-10
result = df[['tp', 'fp', 'fn']].sum().reset_index().assign(
precision=lambda x: (x['tp'] + EPSILON) /
(x['tp'] + x['fp'] + EPSILON),
recall=lambda x: (x['tp'] + EPSIL... | c137e4076f837f51b0cab1acbe842ff827b62ee8 | 3,643,166 |
def uncolorize(text):
""" Attempts to remove color and reset flags from text via regex pattern
@text: #str text to uncolorize
-> #str uncolorized @text
..
from redis_structures.debug import uncolorize
uncolorize('\x1b[0;34mHello world\x1b[1;m')
# -> 'He... | 2bc011d755412ac1b9ca0b7e24afc3ed14dbe7ba | 3,643,167 |
def in_this_prow(prow):
"""
Returns a bool describing whether this processor inhabits `prow`.
Args:
prow: The prow.
Returns:
The bool.
"""
return prow == my_prow() | 0f159cc9b57f407cbfefe9892689664f6d902f94 | 3,643,168 |
def _keypair_from_file(key_pair_file: str) -> Keypair:
"""Returns a Solana KeyPair from a file"""
with open(key_pair_file) as kpf:
keypair = kpf.read()
keypair = keypair.replace("[", "").replace("]", "")
keypair = list(keypair.split(","))
keypair = [int(i) for i in keypair]
r... | 1fdb4d72945d89db7c8d26c96bcbbd18071258dc | 3,643,169 |
import binascii
def val_to_bitarray(val, doing):
"""Convert a value into a bitarray"""
if val is sb.NotSpecified:
val = b""
if type(val) is bitarray:
return val
if type(val) is str:
val = binascii.unhexlify(val.encode())
if type(val) is not bytes:
raise BadConver... | 17081bb8b382763fa5ace4d7d2969b6eed4581ed | 3,643,170 |
def unpack_uint64_from(buf, offset=0):
"""Unpack a 64-bit unsigned integer from *buf* at *offset*."""
return _uint64struct.unpack_from(buf, offset)[0] | ce01d76d18e45a42687d997459da9113d9e3e45f | 3,643,171 |
def del_none(dictionary):
"""
Recursively delete from the dictionary all entries which values are None.
Args:
dictionary (dict): input dictionary
Returns:
dict: output dictionary
Note:
This function changes the input parameter in place.
"""
for key, value in list(dic... | 48b76272ed20bbee38b5293ede9f5d824950aec5 | 3,643,172 |
from sys import path
import tempfile
def get_model(model_dir, suffix=""):
"""return model file, model spec object, and list of extra data items
this function will get the model file, metadata, and extra data
the returned model file is always local, when using remote urls
(such as v3io://, s3://, stor... | 121be1b8a0100db8b41a2c4aa66f57021bf54562 | 3,643,173 |
def get_table_header(driver):
"""Return Table columns in list form """
header = driver.find_elements(By.TAG_NAME, value= 'th')
header_list = [item.text for index, item in enumerate(header) if index < 10]
return header_list | 631e71e357beb37f50defe16fe894f5be3356516 | 3,643,174 |
from rx.core.operators.connectable.refcount import _ref_count
from typing import Callable
def ref_count() -> Callable[[ConnectableObservable], Observable]:
"""Returns an observable sequence that stays connected to the
source as long as there is at least one subscription to the
observable sequence.
"""... | e6f8b21e582d46fab75d9013121d764072630390 | 3,643,175 |
import logging
def no_dry_run(f):
"""A decorator which "disables" a function during a dry run.
A can specify a `dry_run` option in the `devel` section of `haas.cfg`.
If the option is present (regardless of its value), any function or
method decorated with `no_dry_run` will be "disabled." The call wil... | ba32ce4885e9b55aa858a14e963de414ed9f170f | 3,643,176 |
def radius_provider_modify(handle, name, **kwargs):
"""
modifies a radius provider
Args:
handle (UcsHandle)
name (string): radius provider name
**kwargs: key-value pair of managed object(MO) property and value, Use
'print(ucscoreutils.get_meta_info(<classid>).confi... | 9a5c5d62ff60a3a3a8499e4aaa944f758dc49f83 | 3,643,177 |
def _read_table(table_node):
"""Return a TableData object for the 'table' element."""
header = []
rows = []
for node in table_node:
if node.tag == "th":
if header:
raise ValueError("cannot handle multiple headers")
elif rows:
raise ValueErr... | e6ef6e5d5ec99ea2b15ddfcae61b4dd817f8232b | 3,643,178 |
def postorder(root: Node):
"""
Post-order traversal visits left subtree, right subtree, root node.
>>> postorder(make_tree())
[4, 5, 2, 3, 1]
"""
return postorder(root.left) + postorder(root.right) + [root.data] if root else [] | ddeaa6e0f2f466284d69908dfc7eb67bdc6748c8 | 3,643,179 |
def merge_triangulations(groups):
"""
Each entry of the groups list is a list of two (or one) triangulations.
This function takes each pair of triangulations and combines them.
Parameters
----------
groups : list
List of pairs of triangulations
Returns
-------
list
... | 0d39006892e0b248e1f50a62c86911c830b100ce | 3,643,180 |
from lxml import etree as et
from rasterio.crs import CRS
from rasterio.transform import Affine
def make_vrt_list(feat_list, band=None):
"""
take a list of stac features and band(s) names and build gdal
friendly vrt xml objects in list.
band : list, str
Can be a list or string of name of band(... | 83b2e8143bb63e152e569ab28af896509fa18a9f | 3,643,181 |
def compute_relative_pose(cam_pose, ref_pose):
"""Compute relative pose between two cameras
Args:
cam_pose (np.ndarray): Extrinsic matrix of camera of interest C_i (3,4).
Transforms points in world frame to camera frame, i.e.
x_i = C_i @ x_w (taking into account homogeneous dime... | b185554b2961bd7cd70df5df714c176f2d5b6dcc | 3,643,182 |
import sys
def compat_chr(item):
"""
This is necessary to maintain compatibility across Python 2.7 and 3.6.
In 3.6, 'chr' handles any unicode character, whereas in 2.7, `chr` only handles
ASCII characters. Thankfully, the Python 2.7 method `unichr` provides the same
functionality as 3.6 `chr`.
... | a5d45158cf0b48fd8863ac6356632080890fceee | 3,643,183 |
def cli_cosmosdb_cassandra_table_update(client,
resource_group_name,
account_name,
keyspace_name,
table_name,
default_tt... | d1629aa39d9573f0cb0e99a10fc635679c15abdc | 3,643,184 |
def determine_clim_by_standard_deviation(color_data, n_std_dev=2.5):
"""Automatically determine color limits based on number of standard
deviations from the mean of the color data (color_data). Useful if there
are outliers in the data causing difficulties in distinguishing most of
the data. Outputs vmin... | 1a8b1240c50a01f645862b7fce76bc93c62bcb26 | 3,643,185 |
def ec_double(point: ECPoint, alpha: int, p: int) -> ECPoint:
"""
Doubles a point on an elliptic curve with the equation y^2 = x^3 + alpha*x + beta mod p.
Assumes the point is given in affine form (x, y) and has y != 0.
"""
assert point[1] % p != 0
m = div_mod(3 * point[0] * point[0] + alpha, 2 ... | 4489ef72ceb1297983c5f4ac4132fc1e04105365 | 3,643,186 |
def scaled_dot_product_attention(q, k, v, mask):
"""
Calculate the attention weights.
q, k, v must have matching leading dimensions.
k, v must have matching penultimate dimension, i.e.: seq_len_k = seq_len_v.
The mask has different shapes depending on its type(padding or look ahead)
but it must ... | 22110522c4f33ec30c076240ade20f5b66cb3fcd | 3,643,187 |
import re
def _parse_message(message):
"""Parses the message.
Splits the message into separators and tags. Tags are named tuples
representing the string ^^type:name:format^^ and they are separated by
separators. For example, in
"123^^node:Foo:${file}^^456^^node:Bar:${line}^^789", there are two tags and
t... | c961f2a49a21682eb247d4138646abd86135c560 | 3,643,188 |
def model_fn(features, labels, mode, params):
"""Model function."""
del labels, params
encoder_module = hub.Module(FLAGS.retriever_module_path)
block_emb = encoder_module(
inputs=dict(
input_ids=features["block_ids"],
input_mask=features["block_mask"],
segment_ids=features["b... | ff40f74501f26e880a9cf1421a608240fd059fb8 | 3,643,189 |
def get_rotated_coords(vec, coords):
"""
Given the unit vector (in cartesian), 'vec', generates
the rotation matrix and rotates the given 'coords' to
align the z-axis along the unit vector, 'vec'
Args:
vec, coords - unit vector to rotate to, coordinates
Returns:
rot_coords: ro... | f8504df4b7afef524e4147ce6303055a4b7a3cea | 3,643,190 |
def merge_on_pids(all_pids, pdict, ddict):
"""
Helper function to merge dictionaries
all_pids: list of all patient ids
pdict, ddict: data dictionaries indexed by feature name
1) pdict[fname]: patient ids
2) ddict[fname]: data tensor corresponding to each patient
"""
set_ids = s... | d0968de287a1c62ebb7638e5f1af7bd63041665c | 3,643,191 |
import argparse
def parse_args():
"""Parse command line arguments"""
parser = argparse.ArgumentParser(description='Characterize the synapse pulse extender')
parser.add_argument("--syn_pd", dest="syn_pd", type=int, default=SYN_PD, help="Set DAC_SYN_PD bias. Default {}".format(SYN_PD))
args = parser.par... | bb616f6fcb2c82575777ba33797350768956834a | 3,643,192 |
import requests
import numpy
def do_inference(hostport, work_dir, concurrency, num_tests):
"""Tests PredictionService over Tensor-Bridge.
Args:
hostport: Host:port address of the PredictionService.
work_dir: The full path of working directory for test data set.
concurrency: Maximum number of concurre... | ed2cc97ccaf6e3a8be2ae690b190640c67365f9d | 3,643,193 |
def checkbox_2D(image, checkbox, debug=False):
"""
Find the course location of an input psf by finding the
brightest checkbox.
This function uses a 2 dimensional image as input, and
finds the the brightest checkbox of given size in the
image.
Keyword arguments:
image -- 2 d... | e300cb3c7363686b8f07fd35d740bcbac84f0b06 | 3,643,194 |
def test_true() -> None:
"""This is a test that should always pass. This is just a default test
to make sure tests runs.
Parameters
----------
None
Returns
-------
None
"""
# Always true test.
assert_message = "This test should always pass."
assert True, assert_message
... | f08cb5feb4e450b10b58fe32d751bf45985df84c | 3,643,195 |
def parseStylesheetFile(filename):
"""Load and parse an XSLT stylesheet"""
ret = libxsltmod.xsltParseStylesheetFile(filename)
if ret == None: return None
return stylesheet(_obj=ret) | 9e12e7ec5ace9eafe50e595d544bc09ff7ccef7d | 3,643,196 |
import torch
def tensor_to_index(tensor: torch.tensor, dim=1) -> np.ndarray:
"""Converts a tensor to an array of category index"""
return tensor_to_longs(torch.argmax(tensor, dim=dim)) | 7d72b18086a46c4f1c3f8cebaee28ddac12cf31c | 3,643,197 |
import glob
import random
import os
import time
import subprocess
import json
import gc
def matchAPKs(sourceAPK, targetAPKs, matchingDepth=1, matchingThreshold=0.67, matchWith=10, useSimiDroid=False, fastSearch=True, matchingTimeout=500, labeling="vt1-vt1", useLookup=False):
"""
Compares and attempts to match... | a1cf2a9bde0bc0bfcda761097db4cd8f281c8d6f | 3,643,198 |
def _le_(x: symbol, y: symbol) -> symbol:
"""
>>> isinstance(le_(symbol(3), symbol(2)), symbol)
True
>>> le_.instance(3, 2)
False
"""
return x <= y | 336b164cbc249a1a9e9a3d965950a52ac01292ab | 3,643,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.