content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_tokenizer_from_saved_model(saved_model: SavedModel) -> SentencepieceTokenizer:
"""
Get tokenizer from tf SavedModel.
:param SavedModel saved_model: tf SavedModel.
:return: tokenizer.
:rtype: SentencepieceTokenizer
"""
# extract functions that contain SentencePiece somewhere in ther... | 6b524f9f14e286aa6ef43fe77773f9ec6503cf75 | 21,300 |
import heapq
def heapq_merge(*iters, **kwargs):
"""Drop-in replacement for heapq.merge with key support"""
if kwargs.get('key') is None:
return heapq.merge(*iters)
def wrap(x, key=kwargs.get('key')):
return key(x), x
def unwrap(x):
_, value = x
return value
iter... | 0693f667fb6b495680066488347d9894e84f6f0a | 21,301 |
import argparse
def parse_args():
""" parse CLI arguments
Parameters
----------
args : :class: `list`
A list of arguments; generally, this should be ``sys.argv``.
Resturns
----------
:class: `argpase.Namespace`
An object returned by ``argparse.parse_args``.
"""
... | 70c0db9745125ca040cf054b15f8840803738176 | 21,302 |
def parse_archive_links(html):
"""Parse the HTML of an archive links page."""
parser = _ArchiveLinkHTMLParser()
parser.feed(html)
return parser.archive_links | 7894052d602cbe0db195b6fb9a9c1252163d5266 | 21,303 |
import json
def processing_requests():
"""
Handles the request for what is in processing.
:return: JSON
"""
global processing
global processing_mutex
rc = []
response.content_type = "application/json"
with processing_mutex:
if processing:
rc.append(processing)... | 76334b997efb659fb9d7502ec14357e8e6660293 | 21,304 |
def detect_feature(a, b=None):
"""
Detect the feature used in a relay program.
Parameters
----------
a : Union[tvm.relay.Expr, tvm.IRModule]
The input expression or module.
b : Optional[Union[tvm.relay.Expr, tvm.IRModule]]
The input expression or module.
The two arguments can... | 2b9bf11d9b37da7b4473a6da83867911b22586ec | 21,305 |
def get_urls_from_loaded_sitemapindex(sitemapindex):
"""Get all the webpage urls in a retrieved sitemap index XML"""
urls = set()
# for loc_elem in sitemapindex_elem.findall('/sitemap/loc'):
for loc_elem in sitemapindex.findall('//{http://www.sitemaps.org/schemas/sitemap/0.9}loc'):
urls.update(g... | 1a94166272385768929e1db70b643293e7c325b5 | 21,306 |
def genLinesegsnp(verts, colors = [], thickness = 2.0):
"""
gen objmnp
:param objpath:
:return:
"""
segs = LineSegs()
segs.setThickness(thickness)
if len(colors) == 0:
segs.setColor(Vec4(.2, .2, .2, 1))
else:
segs.setColor(colors[0], colors[1], colors[2], colors[3])... | 71fc5c936fbe5dfdc528fc14fd6c0dd10d15ff3c | 21,307 |
import os
from datetime import datetime
import time
def ncores_traditional_recommendation_process(user_model_df, user_model_genres_distr_df, user_expected_items_df,
items_mapping_dict, user_blocked_items_df, recommender_label,
... | 18a808bac73fc51596f89a3219180431e0109cfa | 21,308 |
def enhance_puncta(img, level=7):
"""
Removing low frequency wavelet signals to enhance puncta.
Dependent on image size, try level 6~8.
"""
if level == 0:
return img
wp = pywt.WaveletPacket2D(data=img, wavelet='haar', mode='sym')
back = resize(np.array(wp['d'*level].data), img.shape,... | 7c05531bd85dd42296871f884a04cd30c187346e | 21,309 |
def thumbnail(img, size = (1000,1000)):
"""Converts Pillow images to a different size without modifying the original image
"""
img_thumbnail = img.copy()
img_thumbnail.thumbnail(size)
return img_thumbnail | 4eb49869a53d9ddd42ca8c184a12f0fedb8586a5 | 21,310 |
def calculate_new_ratings(P1, P2, winner, type):
"""
calculate and return the new rating/rating_deviation for both songs
Args:
P1 (tuple or float): rating data for song 1
P2 (tuple or float): rating data for song 2
winner (str): left or right
type (str): elo or glicko
... | 23853c6fd4d6a977e0c0f28b5665baebcab3ae86 | 21,311 |
def age(a):
"""age in yr - age(scale factor)"""
return _cosmocalc.age(a) | 7f4cb143c1b5e56f3f7b1ebc0a916a371070740d | 21,312 |
import argparse
def cli_parser() -> argparse.ArgumentParser:
"""Create parser with set arguments."""
parser = argparse.ArgumentParser(
# Also possible to add prog title to output,
# if ommitted the filename is used (e.g. cli-simple.py)
prog="CLI-COPERNICUS-DOWNLOAD",
descriptio... | 849a44cfd6ec32f3082a96f4b74c48865644b5ec | 21,313 |
def _read_array(raster, band, bounds):
""" Read array from raster
"""
if bounds is None:
return raster._gdal_dataset.ReadAsArray()
else:
x_min, y_min, x_max, y_max = bounds
forward_transform = affine.Affine.from_gdal(*raster.geo_transform)
reverse_transform = ~forward_tr... | 12ad55500950d89bdc84ab29157de9faac17e76a | 21,314 |
def makePlayerInfo(pl_name):
""" Recupere toutes les infos d'un player
:param arg1: nom du joueur
:type arg1: chaine de caracteres
:return: infos du player : budget, profit & ventes (depuis le debut de la partie), boissons a vendre ce jour
:rtype: Json
"""
info = calculeMoneyInfo(pl_name, 0)
drinkInfo = ma... | 4ebc7f11397091fa3d0c62db7fcfd82720eac530 | 21,315 |
def _FinalizeHeaders(found_fields, headers, flags):
"""Helper to organize the final headers that show in the report.
The fields discovered in the user objects are kept separate from those
created in the flattening process in order to allow checking the found
fields against a list of those expected. Unexpected... | 9d44f10c4890ca48cc00f79b24e0019e346028d0 | 21,316 |
import zipfile
import os
def create_zip(archive, compression, cmd, verbosity, interactive, filenames):
"""Create a ZIP archive with the zipfile Python module."""
try:
with zipfile.ZipFile(archive, 'w') as zfile:
for filename in filenames:
if os.path.isdir(filename):
... | 2fcb5bd079762d16fca8f3c0998f54812e8d9122 | 21,317 |
def get_outmost_points(contours):
"""Get the bounding rectangle of all the contours"""
all_points = np.concatenate(contours)
return get_bounding_rect(all_points) | 173631e3397226459d0bf3a91157d2e74660e506 | 21,318 |
def dhcp_release_packet(eth_dst='ff:ff:ff:ff:ff:ff',
eth_src='00:01:02:03:04:05',
ip_src='0.0.0.0',
ip_dst='255.255.255.255',
src_port=68,
dst_port=67,
bootp_chaddr='00:01:02:03:04:05',
... | 63885cb982fbea5f5ff45c850b1bbf00e1154004 | 21,319 |
import os
def get_unique_dir(log_dir='', max_num=100, keep_original=False):
"""Get a unique dir name based on log_dir.
If keep_original is True, it checks the list
{log_dir, log_dir-0, log_dir-1, ..., log_dir-[max_num-1]}
and returns the first non-existing dir name. If keep_original is False
then... | 0cc517f67929fd29e1a38d0dc0aae73e3e4c9252 | 21,320 |
from typing import Optional
from datetime import datetime
def dcfc_30_e_plus_360(start: Date, asof: Date, end: Date, freq: Optional[Decimal] = None) -> Decimal:
"""
Computes the day count fraction for the "30E+/360" convention.
:param start: The start date of the period.
:param asof: The date which t... | 99cc53d69eb1151056475967459be072cff4f773 | 21,321 |
def get_current_func_info_by_traceback(self=None, logger=None) -> None:
"""
通过traceback获取函数执行信息并打印
use eg:
class A:
def a(self):
def cc():
def dd():
get_current_func_info_by_traceback(self=self)
dd()
... | c89496eb7303acb91ef64587d10d5b7350e9a00e | 21,322 |
def augment_timeseries_shift(x: tf.Tensor, max_shift: int = 10) -> tf.Tensor:
"""Randomly shift the time series.
Parameters
----------
x : tf.Tensor (T, ...)
The tensor to be augmented.
max_shift : int
The maximum shift to be randomly applied to the tensor.
Returns
-------
... | 2a9265ea72478d9c860f549637ea629e4b86f4f0 | 21,323 |
def endpoint(fun):
"""Decorator to denote a method which returns some result to the user"""
if not hasattr(fun, '_zweb_post'):
fun._zweb_post = []
fun._zweb = _LEAF_METHOD
fun._zweb_sig = _compile_signature(fun, partial=False)
return fun | 8050a6d1c6e23c1feeec4744edd45b7ae589aab8 | 21,324 |
import torch
def focal_prob(attn, batch_size, queryL, sourceL):
"""
consider the confidence g(x) for each fragment as the sqrt
of their similarity probability to the query fragment
sigma_{j} (xi - xj)gj = sigma_{j} xi*gj - sigma_{j} xj*gj
attn: (batch, queryL, sourceL)
"""
# -> (batch, qu... | 968baad0fa6f78b49eeca1056556a6c2ff3a9cef | 21,325 |
def get_fibonacci_iterative(n: int) -> int:
"""
Calculate the fibonacci number at position 'n' in an iterative way
:param n: position number
:return: position n of Fibonacci series
"""
a = 0
b = 1
for i in range(n):
a, b = b, a + b
return a | 0ece23b00d810ce1c67cf5434cf26e1e21685c20 | 21,326 |
def get_sample_content(filename):
"""Return sample content form file."""
with open(
"tests/xml/{filename}".format(
filename=filename), encoding="utf-8") as file:
return file.read() | 2ba60ad6473ec53f6488b42ceb7090b0f7c8f985 | 21,327 |
def create_contrasts(task):
"""
Create a contrasts list
"""
contrasts = []
contrasts += [('Go', 'T', ['GO'], [1])]
contrasts += [('GoRT', 'T', ['GO_rt'], [1])]
contrasts += [('StopSuccess', 'T', ['STOP_SUCCESS'], [1])]
contrasts += [('StopUnsuccess', 'T', ['STOP_UNSUCCESS'], [1])]
c... | 221b1b1ebcc6c8d0e2fcb32d004794d1b0a47522 | 21,328 |
def project(raster_path, boxes):
"""Project boxes into utm"""
with rasterio.open(raster_path) as dataset:
bounds = dataset.bounds
pixelSizeX, pixelSizeY = dataset.res
#subtract origin. Recall that numpy origin is top left! Not bottom left.
boxes["left"] = (boxes["xmin"] * pixelSizeX) +... | 92e7bc01492b3370767ac56b18b2f937caafc6c3 | 21,329 |
def mean_relative_error(preds: Tensor, target: Tensor) -> Tensor:
"""
Computes mean relative error
Args:
preds: estimated labels
target: ground truth labels
Return:
Tensor with mean relative error
Example:
>>> from torchmetrics.functional import mean_relative_error... | 23c7efe3a91179c670383b1687583dc903052a54 | 21,330 |
from typing import Dict
from typing import Any
def render_dendrogram(dend: Dict["str", Any], plot_width: int, plot_height: int) -> Figure:
"""
Render a missing dendrogram.
"""
# list of lists of dcoords and icoords from scipy.dendrogram
xs, ys, cols = dend["icoord"], dend["dcoord"], dend["ivl"]
... | 1dc61a5ddffc85e6baa9bfbb28620a3039dc8993 | 21,331 |
from typing import List
import logging
def sort_by_fullname(data: List[dict]) -> List[dict]:
""" sort data by full name
:param data:
:return:
"""
logging.info("Sorting data by fullname...")
try:
data.sort(key=lambda info: info["FULL_NAME"], reverse=False)
except Exception as excep... | 0b4ecf53893bda7d226b3c26fe51b9abc073294b | 21,332 |
def get_vrf_interface(device, vrf):
""" Gets the subinterfaces for vrf
Args:
device ('obj'): device to run on
vrf ('str'): vrf to search under
Returns:
interfaces('list'): List of interfaces under specified vrf
None
Raises:
None
... | 57dedbd148f208038bd523c1901827ac7eca8754 | 21,333 |
def rsptext(rsp,subcode1=0,subcode2=0,erri='',cmd='',subcmd1='',subcmd2=''):
""" Adabas response code to text conversion """
global rspplugins
if rsp in rspplugins:
plugin = rspplugins[rsp] # get the plugin function
return plugin(rsp, subcode1=subcode1, subcode2=subcode2,
... | 3cc817e812ea7bba346338e09965e025639631eb | 21,334 |
def to_dataframe(data: xr.DataArray, *args, **kwargs) -> pd.DataFrame:
"""
Replacement for `xr.DataArray.to_dataframe` that adds the attrs for the given
DataArray into the resultant DataFrame.
Parameters
----------
data : xr.DataArray
the data to convert to DataFrame
Returns
--... | 69179fc48ce9ca04e8ee99967ce44b15946f9a57 | 21,335 |
def check_position(position):
"""Determines if the transform is valid. That is, not off-keypad."""
if position == (0, -3) or position == (4, -3):
return False
if (-1 < position[0] < 5) and (-4 < position[1] < 1):
return True
else:
return False | f95ab22ce8da386284040626ac90c908a17b53fa | 21,336 |
def mobilenet_wd4_cub(num_classes=200, **kwargs):
"""
0.25 MobileNet-224 model for CUB-200-2011 from 'MobileNets: Efficient Convolutional Neural Networks for Mobile
Vision Applications,' https://arxiv.org/abs/1704.04861.
Parameters:
----------
num_classes : int, default 200
Number of cl... | f9e367058261da89a3714b543270628ab3941e12 | 21,337 |
import torch
def base_plus_copy_indices(words, dynamic_vocabs, base_vocab, volatile=False):
"""Compute base + copy indices.
Args:
words (list[list[unicode]])
dynamic_vocabs (list[HardCopyDynamicVocab])
base_vocab (HardCopyVocab)
volatile (bool)
Returns:
MultiV... | e6e9d42186c05d33a04c58c506e0e9b97eadac6a | 21,338 |
def font_encoding(psname):
"""Return encoding name given a psname"""
return LIBRARY.encoding(psname) | fd5d2b000624a4d04980c88cc78cd97bf49bca94 | 21,339 |
def shader_with_tex_offset(offset):
"""Returns a vertex FileShader using a texture access with the given offset."""
return FileShader(shader_source_with_tex_offset(offset), ".vert") | 0df316dd97889b3b2541d6d21970768e1cb70fe6 | 21,340 |
def braycurtis(u, v):
"""
d = braycurtis(u, v)
Computes the Bray-Curtis distance between two n-vectors u and v,
\sum{|u_i-v_i|} / \sum{|u_i+v_i|}.
"""
u = np.asarray(u)
v = np.asarray(v)
return abs(u-v).sum() / abs(u+v).sum() | 693b7f0108f9f99e0950d81c2be1e9dc0bd25d86 | 21,341 |
def _load_pyfunc(path):
"""
Load PyFunc implementation. Called by ``pyfunc.load_pyfunc``.
:param path: Local filesystem path to the MLflow Model with the ``fastai`` flavor.
"""
return _FastaiModelWrapper(_load_model(path)) | f8349d3580c5ca407a47b24f901c8f9a7f532c77 | 21,342 |
def fit_pseudo_voigt(x,y,p0=None,fit_alpha=True,alpha_guess=0.5):
"""Fits the data with a pseudo-voigt peak.
Parameters
-----------
x: np.ndarray
Array with x values
y: np.ndarray
Array with y values
p0: list (Optional)
It contains a initial guess the for the pseudo-vo... | 8abd61b44665632cc4e2ae21f52116757e00d2b9 | 21,343 |
import os
import logging
def get_ready_directories(directory):
"""Returns a directory with list of files
That directories should have a 'buildinfo' and 'inventory.yaml' file
which are not empty.
"""
log_files = {}
for root, _, files in os.walk(directory):
build_uuid = root.split('/')... | 5ffca6fd995d3ed977967b8090d2478d42be919b | 21,344 |
from datetime import datetime
def get_name_of_day(str_date):
"""
Возвращает имя дня.
"""
day = datetime.fromisoformat(str_date).weekday()
return DAYS_NAME.get(day) | ae12d7b8ec44c2fb6edcf252ed3463a385353f30 | 21,345 |
def k_fold_split(ratings, min_num_ratings=10, k=4):
"""
Creates the k (training set, test_set) used for k_fold cross validation
:param ratings: initial sparse matrix of shape (num_items, num_users)
:param min_num_ratings: all users and items must have at least min_num_ratings per user and per item to be... | 8b151e291e3365d7986cdc7b876ef630efcb60b4 | 21,346 |
def merge_dict(a, b, path:str=None):
"""
Args:
a:
b:
path(str, optional): (Default value = None)
Returns:
Raises:
"""
"merges b into a"
if path is None: path = []
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dic... | cd260c005b07c9c84b14a14cae3d4dc54fe26b8c | 21,347 |
import json
def validateSignedOfferData(adat, ser, sig, tdat, method="igo"):
"""
Returns deserialized version of serialization ser which Offer
if offer request is correctly formed.
Otherwise returns None
adat is thing's holder/owner agent resource
ser is json encoded unicode string of req... | 4aebe14b8a90dc1c3e47763ce49e142d77f99bd9 | 21,348 |
def get_relevant_phrases(obj=None):
""" Get all phrases to be searched for. This includes all SensitivePhrases, and any RelatedSensitivePhrases that
refer to the given object.
:param obj: A model instance to check for sensitive phrases made specifically for that instance.
:return: a dictionary of repl... | 951166c89dc8e257bce512d13cee592e1266efae | 21,349 |
import struct
def _prepare_cabal_inputs(
hs,
cc,
posix,
dep_info,
cc_info,
direct_cc_info,
component,
package_id,
tool_inputs,
tool_input_manifests,
cabal,
setup,
setup_deps,
setup_dep_info,
srcs,
... | 4d42e6b772a64bc721e30907417dd8c734ce79e6 | 21,350 |
def split_kp(kp_joined, detach=False):
"""
Split the given keypoints into two sets(one for driving video frames, and the other for source image)
"""
if detach:
kp_video = {k: v[:, 1:].detach() for k, v in kp_joined.items()}
kp_appearance = {k: v[:, :1].detach() for k, v in kp_joined.item... | 0396003a17172a75b121ddb43c9b9cf14ee3e458 | 21,351 |
def low_shelve(signal, frequency, gain, order, shelve_type='I',
sampling_rate=None):
"""
Create and apply first or second order low shelve filter.
Uses the implementation of [#]_.
Parameters
----------
signal : Signal, None
The Signal to be filtered. Pass None to create ... | 130fd593988d1fd0b85795389dab554d59fedb97 | 21,352 |
from typing import Union
def get_breast_zone(mask: np.ndarray, convex_contour: bool = False) -> Union[np.ndarray, tuple]:
"""
Función de obtener la zona del seno de una imagen a partir del area mayor contenido en una mascara.
:param mask: mascara sobre la cual se realizará la búsqueda de contornos y de ... | 429344c0645fa7bcfa49abcaf9b022f61c48bc35 | 21,353 |
def replace(temporaryans, enterword, answer):
"""
:param temporaryans: str, temporary answer.
:param enterword: str, the character that user guesses.
:param answer: str, the answer for this hangman game.
:return: str, the temporary answer after hyphens replacement.
"""
# s = replace('-----',... | 80d8625dca573744e9945190ee169438754b1829 | 21,354 |
def extract_timestamp(line):
"""Extract timestamp and convert to a form that gives the
expected result in a comparison
"""
# return unixtime value
return line.split('\t')[6] | 84618f02e4116c70d9f6a1518aafb0691a29ef07 | 21,355 |
def svn_stream_from_stringbuf(*args):
"""svn_stream_from_stringbuf(svn_stringbuf_t str, apr_pool_t pool) -> svn_stream_t"""
return _core.svn_stream_from_stringbuf(*args) | 9710061adb6d80527a3f3afa84bf41e0fa6406c6 | 21,356 |
def get_autoencoder_model(hidden_units, target_predictor_fn,
activation, add_noise=None, dropout=None):
"""Returns a function that creates a Autoencoder TensorFlow subgraph.
Args:
hidden_units: List of values of hidden units for layers.
target_predictor_fn: Function that will pred... | 88c58b2c43c26aa8e71baf684688d27db251cdb6 | 21,357 |
def plot_histogram(ax,values,bins,colors='r',log=False,xminmax=None):
"""
plot 1 histogram
"""
#print (type(values))
ax.hist(values, histtype="bar", bins=bins,color=colors,log=log,
alpha=0.8, density=False, range=xminmax)
# Add a small annotation.
# ax.annotate('Annotation', ... | d11e89c005275a176fd00d0e2ac5173ee8f490b1 | 21,358 |
def build_model():
"""Build the model.
Returns
-------
tensorflow.keras.Model
The model.
"""
input_x = tf.keras.Input(
shape=(30,), name='input_x'
) # shape does not include the batch size.
layer1 = tf.keras.layers.Dense(5, activation=tf.keras.activations.tanh)
lay... | 81e2ee2533903beaa4a087613e63ea383d8a746b | 21,359 |
import torch
def evaluate_generator(generator, backbone_pool, lookup_table, CONFIG, device, val=True):
"""
Evaluate kendetall and hardware constraint loss of generator
"""
total_loss = 0
evaluate_metric = {"gen_macs":[], "true_macs":[]}
for mac in range(CONFIG.low_macs, CONFIG.high_macs, 10):... | 53941e29cae9a89c46ce598291638d7df28db4ff | 21,360 |
import os
import pickle
def load_data(config, var_mode):
"""Main data loading routine"""
print("Loading {} data".format(var_mode))
# use only the first two characters for shorter abbrv
var_mode = var_mode[:2]
# Now load data.
var_name_list = [
"xs", "ys", "Rs", "ts",
"img1s"... | 9fcc7138494ed3e91567364fe3fa968d44ec69ba | 21,361 |
def getCameras():
"""Return a list of cameras in the current maya scene."""
return cmds.listRelatives(cmds.ls(type='camera'), p=True) | a3a6f202250f92c1cab46df92c78b53b15fd5cae | 21,362 |
import re
def convert_quotes(text):
"""
Convert quotes in *text* into HTML curly quote entities.
>>> print(convert_quotes('"Isn\\'t this fun?"'))
“Isn’t this fun?”
"""
punct_class = r"""[!"#\$\%'()*+,-.\/:;<=>?\@\[\\\]\^_`{|}~]"""
# Special case if the very first chara... | 82b5cabc2f4b77f5c39ab785c02e04ff4ca4f517 | 21,363 |
import warnings
def time_shift(signal, n_samples_shift, circular_shift=True, keepdims=False):
"""Shift a signal in the time domain by n samples. This function will
perform a circular shift by default, inherently assuming that the signal is
periodic. Use the option `circular_shift=False` to pad with nan va... | f5017a5b9988ff5dc10e49b1f2d4127293564607 | 21,364 |
def get_avgerr(l1_cols_train,l2_cols_train,own_cols_xgb,own_cols_svm,own_cols_bay,own_cols_adab,own_cols_lass,df_train,df_test,experiment,fold_num=0):
"""
Use mae as an evaluation metric and extract the appropiate columns to calculate the metric
Parameters
----------
l1_cols_train : list
l... | 74bfe9ce91f04a2ce3955098f9d1145c5c60ef4a | 21,365 |
from operator import and_
def get_repository_metadata_by_changeset_revision( trans, id, changeset_revision ):
"""Get metadata for a specified repository change set from the database."""
# Make sure there are no duplicate records, and return the single unique record for the changeset_revision. Duplicate recor... | 33f5da869f8fde08e2f83d7a60a708e4848664a1 | 21,366 |
import pickle
import gc
def generate_encounter_time(t_impact=0.495*u.Gyr, graph=False):
"""Generate fiducial model at t_impact after the impact"""
# impact parameters
M = 5e6*u.Msun
rs = 10*u.pc
# impact parameters
Tenc = 0.01*u.Gyr
dt = 0.05*u.Myr
# potential parameters... | 0871e3b6f09e9bf1154182a3d0a24713a90f2fbb | 21,367 |
def get_census_centroid(census_tract_id):
"""
Gets a pair of decimal coordinates representing the geographic center (centroid) of the requested census tract.
:param census_tract_id:
:return:
"""
global _cached_centroids
if census_tract_id in _cached_centroids:
return _cached_centroid... | ba3dde30ce9bd3eab96f8419580edfda051c5564 | 21,368 |
def configure_context(args: Namespace, layout: Layout, stop_event: Event) -> Context:
"""Creates the application context, manages state"""
context = Context(args.file)
context.layout = layout
sensors = Sensors(context, stop_event)
context.sensors = sensors
listener = KeyListener(context.on_key,
... | b24ee704939cf3f02774b6fe3c9399042247500a | 21,369 |
def offsetEndpoint(points, distance, beginning=True):
""" Pull back end point of way in order to create VISSIM intersection.
Input: list of nodes, distance, beginning or end of link
Output: transformed list of nodes
"""
if beginning:
a = np.array(points[1], dtype='float')
b =... | a6733d5670221fbd14b527d63430ebd94e022a5a | 21,370 |
def _remove_parenthesis(word):
"""
Examples
--------
>>> _remove_parenthesis('(ROMS)')
'ROMS'
"""
try:
return word[word.index("(") + 1 : word.rindex(")")]
except ValueError:
return word | f47cce7985196b1a9a12284e888b4097b26c32f4 | 21,371 |
def check_closed(f):
"""Decorator that checks if connection/cursor is closed."""
def g(self, *args, **kwargs):
if self.closed:
raise exceptions.Error(f"{self.__class__.__name__} already closed")
return f(self, *args, **kwargs)
return g | fcb7f8399ae759d644e47b6f8e8a6b887d9315fc | 21,372 |
def get_box_filter(b: float, b_list: np.ndarray, width: float) -> np.ndarray:
"""
Returns the values of a box function filter centered on b, with
specified width.
"""
return np.heaviside(width/2-np.abs(b_list-b), 1) | 2885133af9f179fa5238d4fc054abfd48f317709 | 21,373 |
def search(ra=None, dec=None, radius=None, columns=None,
offset=None, limit=None, orderby=None):
"""Creates a query for the carpyncho database, you can specify"""
query = CarpynchoQuery(ra, dec, radius, columns,
offset, limit, orderby)
return query | aad189695ef93e44aa455635dae2791843f7d174 | 21,374 |
def repetitions(seq: str) -> int:
"""
[Easy] https://cses.fi/problemset/task/1069/
[Solution] https://cses.fi/paste/659d805082c50ec1219667/
You are given a DNA sequence: a string consisting of characters A, C, G,
and T. Your task is to find the longest repetition in the sequence. This is
a ma... | 4dde2ec4a6cd6b13a54c2eafe4e8db0d87381faa | 21,375 |
from uuid import getnode as getmac
from gmusicapi.utils import utils
import netifaces
def get_gmusicmanager( useMobileclient = False, verify = True, device_id = None ):
"""
Returns a GmusicAPI_ manager used to perform operations on one's `Google Play Music`_ account. If the Musicmanager is instantiated but ca... | 546567e498a183e289f9b77931e10c6114121bc2 | 21,376 |
def measure(data, basis, gaussian=0, poisson=0):
"""Function computes the dot product <x,phi>
for a given measurement basis phi
Args:
- data (n-size, numpy 1D array): the initial, uncompressed data
- basis (nxm numpy 2D array): the measurement basis
Returns:
- A m-sized numpy 1D ar... | 0a25ea52a67441972b65cdad7c76cb772ec6bc6d | 21,377 |
def getUserByMail(email):
"""Get User by mailt."""
try:
user = db_session.query(User).filter_by(email=email).one()
return user
except Exception:
return None | 423d5dc969d43e0f4a1aafc51b5a05671a1fc3e1 | 21,378 |
def parse_headers(headers, data):
"""
Given a header structure and some data, parse the data as headers.
"""
return {k: f(v) for (k, (f, _), _), v in zip(headers, data)} | 456c2ab2d2f7832076a7263be8815b9abeec56dd | 21,379 |
def dataset_parser(value, A):
"""Parse an ImageNet record from a serialized string Tensor."""
# return value[:A.shape[0]], value[A.shape[0]:]
return value[:A.shape[0]], value | 0b07b6eec9e3e23f470970c489ad83c416d650e7 | 21,380 |
def default_csv_file():
""" default name for csv files """
return 'data.csv' | e0a1267e1e8e463d435f3116e970132c4eab949d | 21,381 |
import sys
def get_gc_alt(alt, unit='km'):
"""
Return index of nearest altitude (km) of GEOS-Chem box (global value)
"""
if unit == 'km':
alt_c = gchemgrid('c_km_geos5_r')
elif unit == 'hPa':
alt_c = gchemgrid('c_hPa_geos5')
else:
err_str = 'No case setup for altitude u... | 47744e39b3bcfecd2b3be60f71ad6de8eb85722a | 21,382 |
def download(object_client, project_id, datasets_path):
"""Download the contents of file from the object store.
Parameters
----------
object_client : faculty.clients.object.ObjectClient
project_id : uuid.UUID
datasets_path : str
The target path to download to in the object store
Re... | 91da7409b4cc518d87b6502e193a4174c045be0e | 21,383 |
from pathlib import Path
from typing import Any
def get_assets_of_dataset(
db: Session = Depends(deps.get_db),
dataset_id: int = Path(..., example="12"),
offset: int = 0,
limit: int = settings.DEFAULT_LIMIT,
keyword: str = Query(None),
viz_client: VizClient = Depends(deps.get_viz_client),
... | 344095c94884059ed37662521f346d6c03bb4c7f | 21,384 |
def check_rule(body, obj, obj_string, rule, only_body):
"""
Compare the argument with a rule.
"""
if only_body: # Compare only the body of the rule to the argument
retval = (body == rule[2:])
else:
retval = ((body == rule[2:]) and (obj == obj_string))
return retval | 9237da310ebcc30f623211e659ac2247efb36f69 | 21,385 |
from warnings import warn
def pdm_auto_arima(df,
target_column,
time_column,
frequency_data,
epochs_to_forecast = 12,
d=1,
D=0,
seasonal=True,
m =12,
... | d5dd6d8ddf01358cde26f9e467e410419290da2e | 21,386 |
def get_lines(filename):
"""
Returns a list of lines of a file.
Parameters
filename : str, name of control file
"""
with open(filename, "r") as f:
lines = f.readlines()
return lines | 1307b169733b50517b26ecbf0414ca3396475360 | 21,387 |
def _check_socket_state(realsock, waitfor="rw", timeout=0.0):
"""
<Purpose>
Checks if the given socket would block on a send() or recv().
In the case of a listening socket, read_will_block equates to
accept_will_block.
<Arguments>
realsock:
A real socket.socket() object to check for... | f4f493f03a2cd824a2bdc343f9367611011558eb | 21,388 |
def str_to_pauli_term(pauli_str: str, qubit_labels=None):
"""
Convert a string into a pyquil.paulis.PauliTerm.
>>> str_to_pauli_term('XY', [])
:param str pauli_str: The input string, made of of 'I', 'X', 'Y' or 'Z'
:param set qubit_labels: The integer labels for the qubits in the string, given in ... | 3a5be0f84006979f9b7dbb6ed436e98e7554cf68 | 21,389 |
from typing import Type
def _GetNextPartialIdentifierToken(start_token):
"""Returns the first token having identifier as substring after a token.
Searches each token after the start to see if it contains an identifier.
If found, token is returned. If no identifier is found returns None.
Search is abandoned w... | e486ba1f5e9ee1b2d6c01aa5aa9d5d5270e0db10 | 21,390 |
def _challenge_transaction(client_account):
"""
Generate the challenge transaction for a client account.
This is used in `GET <auth>`, as per SEP 10.
Returns the XDR encoding of that transaction.
"""
builder = Builder.challenge_tx(
server_secret=settings.STELLAR_ACCOUNT_SEED,
cli... | a1762788077d7e9403c7e5d3b94e78cca11f0ce8 | 21,391 |
def mapCtoD(sys_c, t=(0, 1), f0=0.):
"""Map a MIMO continuous-time to an equiv. SIMO discrete-time system.
The criterion for equivalence is that the sampled pulse response
of the CT system must be identical to the impulse response of the DT system.
i.e. If ``yc`` is the output of the CT system with an ... | 6aa83119efcad68b1fdf3a0cbc5467c53d2a30bb | 21,392 |
def normalize_type(type: str) -> str:
"""Normalize DataTransfer's type strings.
https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransfer-getdata
'text' -> 'text/plain'
'url' -> 'text/uri-list'
"""
if type == 'text':
return 'text/plain'
elif type == 'url':
return 'tex... | 887c532218a7775ea55c6a39953ec244183af455 | 21,393 |
def _parity(N, j):
"""Private function to calculate the parity of the quantum system.
"""
if j == 0.5:
pi = np.identity(N) - np.sqrt((N - 1) * N * (N + 1) / 2) * _lambda_f(N)
return pi / N
elif j > 0.5:
mult = np.int32(2 * j + 1)
matrix = np.zeros((mult, mult))
fo... | 5afc399cc6f303ba35d7e7c6b6b039130fcd1b17 | 21,394 |
def get_log(id):
"""Returns the log for the given ansible play.
This works on both live and finished plays.
.. :quickref: Play; Returns the log for the given ansible play
:param id: play id
**Example Request**:
.. sourcecode:: http
GET /api/v2/plays/345835/log HTTP/1.1
**Exampl... | 7a67f7b9d89df39824e566fcb11083be9d3f76e8 | 21,395 |
def filterLinesByCommentStr(lines, comment_str='#'):
"""
Filter all lines from a file.readlines output which begins with one of the
symbols in the comment_str.
"""
comment_line_idx = []
for i, line in enumerate(lines):
if line[0] in comment_str:
comment_line_idx.append(i)
... | 8a6ce56187afc2368ec81d11c38fe7af2eacb14f | 21,396 |
def assemble_result_from_graph(type_spec, binding, output_map):
"""Assembles a result stamped into a `tf.Graph` given type signature/binding.
This method does roughly the opposite of `capture_result_from_graph`, in that
whereas `capture_result_from_graph` starts with a single structured object
made up of tenso... | a25b4d935dfcb62acad15da5aeafee390b03a38c | 21,397 |
def parse(peaker):
# type: (Peaker[Token]) -> Node
"""Parse the docstring.
Args:
peaker: A Peaker filled with the lexed tokens of the
docstring.
Raises:
ParserException: If there is anything malformed with
the docstring, or if anything goes wrong with parsing. #... | abd8b495281c159f070a890a392d7a80da740fa4 | 21,398 |
def listify(what, *, debug=False):
"""
non-reversible version of listify_safe(). In this case "None" always means "no columns".
output: list
"""
l, _ = listify_safe(what, debug=debug)
return l | 677c7f9cacc270a2346e3ee002911b31825fbad9 | 21,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.