content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def pe44(limit=1500):
"""
>>> pe44()
(5482660, 7042750, 1560090, 2166, 1019)
"""
pents = [i * (3 * i - 1) >> 1 for i in range(1, limit << 1)]
ps = set(pents)
for i in range(limit):
p1 = pents[i]
for j in range(i + 1, (limit << 1) - 1):
p2 = pents[j]
di... | e41f513c518b502de0c47f3a70390f9df01a1868 | 3,632,076 |
import re
def text_cut(questions):
"""
This def will cut the text into words by jieba and del the stopwords then return the words,else return a string when
fail to find the stop_list.
:param questions: A list of text.
:return: A list of cut-words
Raises: FileNotFoundError: An error occurred se... | c7cc8e52265b6e7cbe222d899952ee2ddc13231d | 3,632,077 |
def export_visible_cells(
self,
export_keyword="FLUXNUM",
visible_active_cells_value=1,
hidden_active_cells_value=0,
inactive_cells_value=0,
):
"""Export special properties for all visible cells.
Arguments:
export_keyword (string): The keyword to export.
Choices: 'FLUXNUM' o... | e7f03371a7c14385a2039ccb597e7e464f54b4f1 | 3,632,079 |
def sanitize_markdown(markdown_body):
"""
There are some symbols used in the markdown body, which when go through Markdown -> HTML
conversion, break. This does a global replace on markdown strings for these symbols.
"""
return markdown_body.replace(
# This is to solve the issue where <s> and... | adf21a9bbea1a95f0f4c0aca8d61ab6d69627074 | 3,632,080 |
def ProjectsInsightTypeInsightsService(api_version):
"""Returns the service class for the Project insights."""
client = RecommenderClient(api_version)
return client.projects_locations_insightTypes_insights | 7173907ad599fd4457050a2fb1d15d01d19098cf | 3,632,081 |
def get_course_dict(only_active=True):
""" Return a dictionary of courses.
By default only active courses.
key will be course ID.
courses[cid] = {id:, name:, title:}
"""
cdict = {}
reload_if_needed()
for course in COURSES:
if only_active:
if COURSES[cours... | 6e538b473224274c5ec7e8db17975c934e126c44 | 3,632,082 |
def _build_jinja2_expr_tmp(jinja2_exprs):
"""Build a template to evaluate jinja2 expressions."""
exprs = []
tmpls = []
for var, expr in jinja2_exprs.items():
tmpl = f"{var}: >-\n {{{{ {var} }}}}"
if tmpl not in tmpls:
tmpls.append(tmpl)
if expr.strip() not in exprs:
... | 3e5d944345316a40b7b8052f9b13801228607099 | 3,632,083 |
def normal(x, mu=0, sig=1):
""" Normal distribution log-likelihood.
:param x: *int, float, np.array.*
:param mu: (optional) *int, float, np.array.*
Location parameter of the normal distribution. Defaults to 0.
:param sig: (optional) *int, float.*
Standard deviatio... | fc88fd34b4c5e5be835c1d29b2f8f38b7f1f21b9 | 3,632,085 |
def BitmapFromImage(image):
"""
A compatibility wrapper for the wx.Bitmap(wx.Image) constructor
"""
return Bitmap(image) | 4593506342bfd8b3f1bb3e6077031291a8eb87aa | 3,632,087 |
def load_coco_name(path):
"""Load labels from coco.name
"""
coco = {}
with open(path, 'rt') as file:
for index, label in enumerate(file):
coco[index] = label.strip()
return coco | 2da456b7c2879ec5725172280dacbcaaacd86bfc | 3,632,088 |
def qsat(T, p) :
"""
Saturation vapour pressure.
Derived variable name: qsat
Parameters
----------
T : numpy array or xarray DataArray
Temperature. (K)
p : numpy array or xarray DataArray
Pressure (Pa).
Returns
-------
qs : numpy array or xarray DataArray
... | 2e257dade4531e49f813b3fb96b71f0298819509 | 3,632,089 |
def extract_features(df, action):
"""
提取特征
:param df: DataFrame 样本(训练和测试)
:param action: str action
:return:
x: DataFrame 特征
y: Series 标签
"""
# 特征-训练每个任务都需要初始化
DENSE_FEATURE_COLUMNS = ['videoplayseconds']
# 1,特征处理
# dense
df.fillna(value={f: 0.0 for f in DEN... | af648a66146d1af34777c85417745c55e95f0122 | 3,632,090 |
def quick_sort(input_list):
"""Quick sort."""
if not isinstance(input_list, (list, tuple)):
raise ValueError('input takes list/tuple only')
if isinstance(input_list, (tuple)):
input_list = list(input_list)
if not all(isinstance(val, (int, float)) for val in input_list):
raise V... | 41224487ab352dc88ebd39007a02cf2fe2993651 | 3,632,091 |
from typing import List
def validate_execution_order(relations: List[RelationDescription], keep_going=False):
"""
Make sure we can build an execution order.
We'll catch an exception and set a flag if the keep_going option is true.
"""
try:
ordered_relations = etl.relation.order_by_depende... | 773303496c3a0ac62e195ea62622e4605acb19fc | 3,632,092 |
def now():
"""Returns a java.util.Date object that represents the current time
according to the local system clock.
Returns:
Date: A new date, set to the current date and time.
"""
return Date() | 4d32130ed1af12370012186084b270dde6fdd986 | 3,632,093 |
def create_session_factory(session_id_store, backend_store, *, loop=None):
"""Creates new session factory.
Create new session factory from two storage:
session_id_store and backend_store.
"""
return _SessionFactory(session_id_store=session_id_store,
backend_store=backend_... | c8f302af26894e16f5a24aa9ca460400746fed06 | 3,632,094 |
def process(callable_, *args, **kwargs):
"""
Submit a callable to a background process.
Return an proxy object for the future return value.
NOTE: Use only, if you really need control over the type of background execution.
"""
return _submit(callable_, 'cpu', *args, **kwargs) | ac596fef8e72f1ba65450928aba9ea173764d564 | 3,632,096 |
def encode_entities(string):
""" Encodes HTML entities in the given string ("<" => "<").
For example, to display "<em>hello</em>" in a browser,
we need to pass "<em>hello</em>" (otherwise "hello" in italic is displayed).
"""
if isinstance(string, basestring):
string = ... | 949d76b25ff65020b3b560a0fd984107c13d1bfb | 3,632,097 |
async def upload_data_generation_file(
background_tasks: BackgroundTasks,
doc: UploadFile = File(...),
current_user: User = Depends(auth.get_current_user_and_bot)
):
"""
Uploads document for training data generation and triggers event for intent creation
"""
TrainingDataGenerationProcessor.i... | 742f61a13491f2fe84301d3bcd9c5f5ee18e3df0 | 3,632,099 |
def histogram(name, tensor, max_bins):
""" 转换直方图数据到potobuf格式 """
values = make_np(tensor)
sum_sq, bucket_limit, bucket = make_histogram(values.astype(float), max_bins)
hist = HistogramProto(min=values.min(), max=values.max(), num=len(values.reshape(-1)),
sum=values.sum(), sum_s... | 9f9d04b281f018ea02276c29ae4b8c83b4790799 | 3,632,100 |
def max_pool_1d(input_tensor, pool_sizes=(2), stride_sizes=(1), paddings='same', names=None):
"""[summary]
Arguments:
input_tensor {[float, double, int32, int64, uint8, int16, or int8]} -- [A Tensor representing prelayer values]
Keyword Arguments:
pool_size {tuple} -- [Size of kern... | 9124428ba21d8108fd95b95cf36c97f147f2c1dc | 3,632,101 |
import base64
import gzip
import json
def decompress_metadata_string_to_dict(input_string): # pylint: disable=invalid-name
"""
Convert compact string format (dumped, gzipped, base64 encoded) from
IonQ API metadata back into a dict relevant to building the results object
on a returned job.
Parame... | c521da786d2a9f617c560916cc5f058b20cb3e21 | 3,632,102 |
import struct
import socket
def inet_atoni(ip):
"""Like inet_aton() but returns an integer."""
return struct.unpack('>I', socket.inet_aton(ip))[0] | 3bd18b7aecf9a5a45033c7873163ee1387cb8a13 | 3,632,104 |
from typing import Optional
import warnings
def align_method_FRAME(
left, right, axis, flex: Optional[bool] = False, level: Level = None
):
"""
Convert rhs to meet lhs dims if input is list, tuple or np.ndarray.
Parameters
----------
left : DataFrame
right : Any
axis: int, str, or Non... | 77e30224e3d1e0077bc8b2fbac3cddc405b724b6 | 3,632,105 |
import re
def rep_unicode_in_code(code):
""" Replace unicode to str in the code
like '\u003D' to '='
:param code: type str
:return: type str
"""
pattern = re.compile('(\\\\u[0-9a-zA-Z]{4})')
m = pattern.findall(code)
for item in set(m):
code = code.replace(item, chr(int(item[2... | 70e28ea741f0347190628876b59e27a56a5c0ccf | 3,632,106 |
def delete_bucket_on_project(current_session, project_name, bucket_name):
"""
Remove a bucket from a project, both on the userdatamodel
and on the storage associated with that bucket.
Returns a dictionary.
"""
response = pj.delete_bucket_on_project(current_session, project_name, bucket_name)
... | 13ce8ef1b98bddbbed9cacecce9495914e2f723d | 3,632,107 |
def redir(url, text=None, target='_blank'):
"""Links to a redirect page
"""
text = text or url
html = '<a href="%(url)s" target="%(target)s">%(text)s</a>' % {
'url' : redir_url(url),
'text' : text,
'target' : target,
}
html = mark_safe(html)
return html | f1b5930887b3e0f2cce4751d2368dd2b4df6d5a2 | 3,632,108 |
def notifier_limit_over_checker(username, language_code, hard_limit):
"""
Function that takes a username and checks if they're above a hard monthly limit. This is currently UNUSED.
True if they're over the limit, False otherwise.
:param username: The username of the person.
:param language_code: Th... | a6e939f04a6b1598241d00a2c6dc6399df629d60 | 3,632,109 |
def lateral_steering_transform(steering, camera_position):
"""
Transform the steering of the lateral cameras (left, right)
Parameters:
steering (numpy.float): Original steering
Returns:
out (numpy.float): New steering
"""
if (camera_position == LEFT):
steering += ... | 7530b91fc4c59427f5a8fe22714ee48718bfed5f | 3,632,110 |
def fv_creator(fp, df, F, int_fwm):
"""
Cretes frequency grid such that the estimated MI-FWM bands
will be on the grid and extends this such that to avoid
fft boundary problems.
Inputs::
lamp: wavelength of the pump (float)
lamda_c: wavelength of the zero dispersion wavelength(ZDW) (... | 315dcc82fa3cd39937d905092f3b47de807d4e9f | 3,632,111 |
def calc_F1_score(scores, changepoints, tolerance_delay, tuned_threshold=None, div=500, both=True):
"""
Calculate F1 score. If tuned_threshold is None, return the tuned threshold.
Args:
scores: the change scores or change sign scores
changepoints: changepoints or starting points of gradual ... | 50865a03b47c30feb43352f6131c2e867318b1a0 | 3,632,112 |
def mul_pt_exn(pt, curve, k):
"""Computes point kP given point P, curve and k using Montgomery Ladder.
Args:
pt (tuple(int, int)): Point P.
curve (tuple(int, int, int)): Curve.
k (int): Multiplier.
Raises:
InverseNotFound: Thrown when point kP is the point at infinity.
... | 236dc176a2cf644a5c93054a93cc02535b4b77ef | 3,632,113 |
def get_scene_nodes():
"""
Returns al nodes in current scene as GamEX nodes
:return: list<gx.dcc.DCCNode>
"""
node_list = list()
_append_children(get_root(), node_list)
return node_list, len(node_list) | 264bd1920f43aa4caaf07f17dbfbb3ca6bf1d2e1 | 3,632,115 |
import pdb
def interpolate(src_codes, dst_codes, step=5):
"""Interpolates two sets of latent codes linearly.
Args:
src_codes: Source codes, with shape [num, *code_shape].
dst_codes: Target codes, with shape [num, *code_shape].
step: Number of interplolation steps, with source and target inc... | e8c1e813e3445c03cfb0f841b0ae60eacfedb27f | 3,632,116 |
def get_flavored_transforms(penalty, kind):
"""
Gets the tranformation functions for all flavored penalties.
Parameters
----------
penalty: PenaltyConfig, PenaltyTuner
The penalty configs/tuner whose flavored penalties we want.
kind: str
Which kind of flavor we want; ['adaptive... | 2d70b1da646aea7fe5dd1f1957e0e5b31f0644de | 3,632,117 |
def f(spam, eggs):
"""
:type spam: list of string
:type eggs: (bool, int, unicode)
"""
return spam, eggs | 7d315898332b099eb1105f77b08bfe69e29c051e | 3,632,118 |
def GetAllowedGitilesConfigs():
"""Returns the set of valid gitiles configurations.
The returned structure contains the tree of valid hosts, projects, and refs.
Please note that the hosts in the config are gitiles hosts instead of gerrit
hosts, such as: 'chromium.googlesource.com'.
Example config:
{
... | 57dd75b253ed77585f23f06a095c2f1c0bcbf23a | 3,632,119 |
import requests
def cbsodatav3_to_gcs(id, third_party=False, schema="cbs", credentials=None, GCP=None, paths=None):
"""Load CBS odata v3 into Google Cloud Storage as Parquet.
For given dataset id, following tables are uploaded into schema (taking `cbs` as default and `83583NED` as example):
- ``cbs.8... | 6283163698925cf3743660810464b359f3719720 | 3,632,120 |
def process_chunk_of_genes(packed_args):
""" Control flow of compute coverage of pangenome per species and write results """
species_id, chunk_id = packed_args[:2]
if chunk_id == -1:
global semaphore_for_species
num_of_genes_chunks = packed_args[2]
tsprint(f" MIDAS2::process_chun... | a2f5d515a4695f1ab76bc3407241a16f99739e9f | 3,632,121 |
def get_Up(N=16, dt=0.1):
"""
INPUTS
N (int): is the length of the preview horizon;
dt (float): time step size;
OUTPUTS
Up: size [N, N] matrix;
"""
Up = np.tril(np.ones((N, N)), 0) * (1 / 6)
for i in range(N):
Up += np.diag(np.ones(N - i) * i, k=-i) / 2
Up += np.dia... | b10ed27076ba0c27ec3cb80777c01f6082a3f9a6 | 3,632,122 |
def print_person(first, last, middle=None):
"""Prints out person's names
This funciton prints out a person's name. It's not too useful
Args:
first (str): This person's first name
last (str): This person's last name
middle (str): Optional. This person's middle name
"""
middl... | 643ce351ec13a076c9fd36af39c97505084f1437 | 3,632,123 |
def get_governing_regions(strict=True):
"""! Creates a sorted list of governing regions which may simply be
federal states or intermediate regions which themselves are a real
subset of a federal state and to which a certain number of counties
is attributed.
Governing regions are generally denoted b... | c1d85343381f065d95862d6c4a71ea3ef2af80d0 | 3,632,124 |
def _chomp_element(base, index, value):
"""Implementation of perl = and chomp on an array element"""
if value is None:
value = ''
base[index] = value.rstrip("\n")
return len(value) - len(base[index]) | 66cfde7c8d8f2c92f0eebb23f717bf50b676ca31 | 3,632,125 |
def write_primitive(group, name, data, ds_kwargs):
"""Note: No dataset chunk options (like compression) for scalar"""
data_type = type(data)
# Write dataset
if data_type == np.ndarray:
ds = group.create_dataset(name, data=data, **ds_kwargs) # enable compression for nonscalar numpy array
el... | 531dd9190bb94b6bde3f70a80170bfbcd62c75c8 | 3,632,126 |
def measurecrime(gps, radius):
"""Measures crime around a given location"""
latitude, longitude = gps
minlat = latitude - radius
maxlat = latitude + radius
minlong = longitude - radius
maxlong = longitude + radius
baseurl = (DATABASE + WHERE + LAT + GT + str(minlat) + AND + LAT + LT +
... | 3a216b56744b32ec846a4edc590dd7ff72f4e69c | 3,632,127 |
def _weights(name, shape, mean=0.0, stddev=0.02):
""" Helper to create an initialized Variable
Args:
name: name of the variable
shape: list of ints
mean: mean of a Gaussian
stddev: standard deviation of a Gaussian
Returns:
A trainable variable
"""
var = tf.get_variable(
name, shape,
... | a9e378cebaec6aa45b52d393a73d032e742df594 | 3,632,128 |
def packed_function(function):
"""returns a function with a single input"""
# needed in python 3.x since lambda functions are not automatically unpacked
# as they were in python 2.7
if hasattr(function, '__code__'):
if function.__code__.co_argcount > 1:
return pack(function)
retu... | eb6996ed0215a2e4f33509665aed754731626316 | 3,632,129 |
from bs4 import BeautifulSoup
import re
async def read_ratings(session, archive_url, archive_timestamp, archive_content):
"""
Extract a movie rating from its imdb page
:raise: A ScrapeError if the rating could not be extracted
:return:
"""
try:
soup = BeautifulSoup(archive_content, 'ht... | 074203a533d6ef650f221ec825f16e85ed63d60d | 3,632,130 |
import time
def generate_nonce():
"""
Generates nonce for signature
Returns:
nonce (int) : timestamp epoch
"""
return int(time.time() + 100) | c439fc6598b4f5359d71bde8865afacb6162df19 | 3,632,131 |
def dense(x, inp_dim, out_dim, name = 'dense'):
"""
Used to create a dense layer.
:param x: input tensor to the dense layer
:param inp_dim: no. of input neurons
:param out_dim: no. of output neurons
:param name: name of the entire dense layer.i.e, variable scope name.
:return: tensor with sh... | dda9c6deb6cc2c270bfa3a53b7b771dbaa61c77e | 3,632,132 |
def read_observation_time_range(observation_id):
"""Get the time range of values for a observation.
Parameters
----------
observation_id: string
UUID of associated observation.
Returns
-------
dict
With `min_timestamp` and `max_timestamp` keys that are either
dt.dat... | c0f45341bf36c40e0cf97710cb593372b058219c | 3,632,133 |
import ray
def compute_mean_image(batches):
"""Computes the mean image given a list of batches of images.
Args:
batches (List[ObjectID]): A list of batches of images.
Returns:
ndarray: The mean image
"""
if len(batches) == 0:
raise Exception("No images were passed into `compute_mean_image`.")
... | c6d43fb36e207a890f83965a1491e30597c54b44 | 3,632,134 |
def get_sevt(r: Request, resp: Response):
"""
SEVT web server route for GET request.
:param r Request object, provides access to method, headers & cookies:
:param resp Response Object used for modification of status code:
:return returns the content of the internal resources response... | f27d3412526aaee37dd1d8350ee91b04fc7e1215 | 3,632,135 |
def mse(actual, predicted):
"""
https://ml-cheatsheet.readthedocs.io/en/latest/linear_regression.html#cost-function
MSE = the mean of (actual_outcome - predicted_outcome) squared
"""
return np.mean(np.power(actual - predicted, 2)) | cf514e2dbd126806f8921d479b9813cd1b3a08c5 | 3,632,136 |
def topsorted(outputs):
"""
Topological sort via non-recursive depth-first search
"""
assert isinstance(outputs, (list, tuple))
marks = {}
out = []
stack = [] # pylint: disable=W0621
# i: node
# jidx = number of children visited so far from that node
# marks: state of each node,... | e6d0204784f7b8169092a9fb6f56044f3be365be | 3,632,140 |
from scipy.spatial.distance import cdist
def merge_small_enclosed_subcavs(subcavs, minsize_subcavs = 50, min_contacts = 0.667, v = False):
"""
The watershed algorithm tends to overspan a bit, even when optimizing seeds.
This function aims at identifying small pockets (< minsize_subcavs)
that are heavily in contac... | 4f9b5e2cef4ffc7d64912bc31b18d3639ec62c26 | 3,632,142 |
import ast
def is_py3(file_path):
"""Check if code is Python3 compatible."""
# https://stackoverflow.com/a/40886697
code_data = open(file_path, "rb").read()
try:
ast.parse(code_data)
except SyntaxError:
return False
return True | 78a48bdcc682108ce4fbe6fffe4a235898beec1c | 3,632,143 |
import time
def getDate():
"""获得时间"""
return time.localtime() | 6f4f127b96ab6f754cc20e76219a54d039938320 | 3,632,144 |
def wordEncrypt(word):
"""
Encrypt a word into list of keys using the cipher in file_cipher.
Definition
----------
def wordEncrypt(word):
Input
-----
word string
Output
------
list with numeric keys
Examples
... | 4b8abcd86bb77b3997fd856f0a47fd928e9e8c49 | 3,632,146 |
def is_special_identifier_char(c):
"""
Returns `True` iff character `c` should be escaped in an identifier
(i.e. it is a special character).
"""
return c in (
ESCAPEMENT_SYM, OLD_COMMENT_SYM, FILE_INCLUSION_SYM, UNIT_START_SYM,
UNIT_END_SYM, ALIAS_SYM, SLOT_SYM, INTENT_SYM,
C... | 762c5b2441753bb5f8f770092a56e48f5299d886 | 3,632,147 |
def delete_board(request):
"""
Removes the saved game board from user's profile.
User must be authenticated, i.e. must have the matching token.
Game board in the user's profile identified by game_id must exist.
user_id: unique user identifier (same as username).
token: authentication token that ... | 768968b7d3e3a220f1915d2286aaede7a29b3a2b | 3,632,148 |
def test_module(client: Client) -> str:
"""Tests API connectivity and authentication'
Returning 'ok' indicates that the integration works like it is supposed to.
Connection to the service is successful.
Raises exceptions if something goes wrong.
:type client: ``Client``
:param Client: RubrikPo... | 2f0662bacec47a30464ab36bbe162c69c32b129a | 3,632,150 |
import logging
def cnn_v0(state,
num_actions,
scope,
channels=32,
activation_fn=None,
is_training=True,
reuse=False,
use_timestep=True):
"""CNN architecture for discrete-output DQN.
Args:
state: 2-Tuple of image and timestep tensors... | e5769dc5bffdc1e0a6e3d415c83238e5682e4c9a | 3,632,151 |
def get_collections(expand=False, as_dataframe=False):
"""Get available collections.
Collections are folders on the local disk that contain downloaded or
created data along with associated metadata.
Args:
expand (bool, Optional, Default=False):
include collection details and format... | 45bce659dbd62a3f28d7d1d48f32e6503d11c3bd | 3,632,152 |
def jsonable_safe(obj):
"""Convert to JSON-able, if possible.
Based on fastapi.encoders.jsonable_encoder.
"""
try:
return jsonable_encoder(obj, exclude_none=True)
except:
return obj | 5c9a8e4e6ab11ddb0735a122eabe9c28649c7371 | 3,632,153 |
def classify_segment(data: list, no_of_outliers: int, acceptable_outlier_percent: float = .34) -> object:
"""
:param data: A list of Datapoints-current window
:param no_of_outliers: The number of datapoints in the current window assigned as outliers
:param acceptable_outlier_percent: The acceptable out... | 0ca846244ff8137e7dd145dd76c1cd35f276e641 | 3,632,154 |
def nearest_neighbor(v, candidates, k=1):
"""
Input:
- v, the vector you are going find the nearest neighbor for
- candidates: a set of vectors where we will find the neighbors
- k: top k nearest neighbors to find
Output:
- k_idx: the indices of the top k closest vectors in sorted fo... | 77cf4a84a3b6150e0e46d3a3c42f033600fad785 | 3,632,155 |
def reverse(x):
"""
:type x: int
:rtype: int
"""
new_str = str(x)
i = 1
rev_str = new_str[::-1]
if rev_str[-1] == "-":
rev_str = rev_str.strip("-")
i = -1
if (int(rev_str)>=2**31):
return 0
return (int(rev_str)) * i | 5775fe83f500ac844fa9fc94a4d71fc3bb6f165b | 3,632,156 |
def create_request(
service: str,
request: str,
settings: list = None,
ovrds: list = None,
append: dict = None,
**kwargs,
) -> blpapi.request.Request:
"""
Create request for query
Args:
service: service name
request: request name
setti... | 9a10ca81cb0ae773293a9ed3abeb1bd4914f3195 | 3,632,157 |
def delete_byID(iid):
""" Delete an item by ID
"""
global conn, curs
try:
sql = "DELETE FROM tbl_inc_exp WHERE id={}".format(iid)
curs.execute(sql)
conn.commit()
return True
except:
return False | 88174e4c216d4e6a716b38a2ab2651c53ba4565e | 3,632,158 |
def get_props(adapter=None,
device=None,
service=None,
characteristic=None,
descriptor=None):
"""
Get properties for the specified object
:param adapter: Adapter Address
:param device: Device Address
:param service: GATT Service UUID
:par... | 3dc1bd3cdab5520d7edc1770682da5ad6b95a643 | 3,632,160 |
def table_entry_pretty_print(entry, indent, line_wrap=-1):
###############################################################################
"""Create and return a pretty print string of the contents of <entry>"""
output = ""
outline = "<{}".format(entry.tag)
for name in entry.attrib:
outline += "... | 9ecf205fcdb9a3c2e3eaf97c8fe31dc97cb2d90e | 3,632,161 |
def part_1(input_data: list[int]) -> int:
"""Count the number of times a depth measurement increases from the previous measurement.
Args:
input_data (str): depths
Returns:
int: number of depth increases
"""
inc_count = 0
for i, depth in enumerate(input_data):
if i != 0 a... | 3ee506aca019f9393c93ced75e430d53b31a9fc2 | 3,632,162 |
from typing import Optional
def find_base_split_commit(split_dir, base_commit) -> Optional[str]:
""" Return the hash of the base commit in the specified
split repository derived from the specified monorepo base commit. """
mono_base_commit = git_output('rev-list', '--first-parent', '-n', '1', '--grep'... | 47c347f86936446c61cc368b646aa4bdedfedeed | 3,632,163 |
def evaluate(roughness, eta, wo, wi, dist):
# return brdf value (didn't multiply cos)
"""Evaluate BRDF and PDFs for Walter BxDF."""
# eta is assumed > 1, and it is the refractive index of the side of the
# surface facing away from the normal.
rGain = 1.0
boostReflect = 1.0
tAlbedo = np.arr... | cda0b86434456647e21dd3622cdf6331d267112d | 3,632,164 |
def round_floats(number):
"""A function which converts float values of comparison scores into floats
with no more than two decimal figures. No precision is lost this way - the
point is to convert numbers like 1.7499999999 into 1.75.
Arguments:
number (float): the value of a comparison score
... | a9603b6a4ee30385d320f73b3a769704008197f0 | 3,632,165 |
async def async_create_entities(hass, config):
"""Create the template binary sensors."""
sensors = []
for device, device_config in config[CONF_SENSORS].items():
value_template = device_config[CONF_VALUE_TEMPLATE]
icon_template = device_config.get(CONF_ICON_TEMPLATE)
entity_picture_t... | 2a978648f6db6aebf0c56eea92e5deb30cf9f05b | 3,632,166 |
import aiohttp
async def fetch_user(bearer: str) -> dict:
"""Fetch information about a user from their bearer token."""
headers = {"Authorization": f"Bearer {bearer}"}
async with aiohttp.ClientSession(headers=headers, raise_for_status=True) as sess:
resp = await sess.get(f"{API_BASE}/users/@me")
... | 8f5132f261f518bd3d9e05d7acfb5ed893f63a55 | 3,632,167 |
def single_varint(data, index=0):
"""
The single_varint function processes a Varint and returns the
length of that Varint.
:param data: The data containing the Varint (maximum of 9
bytes in length as that is the maximum size of a Varint).
:param index: The current index within the data.
:ret... | 55b052300cc0cf5ac2fd8f7451ac121b408c1313 | 3,632,169 |
def dict_from_corpus(corpus):
"""
Scan corpus for all word ids that appear in it, then construct and return a mapping
which maps each `wordId -> str(wordId)`.
This function is used whenever *words* need to be displayed (as opposed to just
their ids) but no wordId->word mapping was provided. The res... | f9bbe1677ec1abc93c5f47095dc5f93e32278d42 | 3,632,170 |
def mat2dict(matobj):
"""
A recursive function that constructs nested dictionaries from matobjects
"""
dictionary = {}
for strg in matobj._fieldnames:
elem = matobj.__dict__[strg]
if isinstance(elem, scio.matlab.mio5_params.mat_struct):
dictionary[strg] = mat2dict(elem)
... | 948b1640d2fc67f712f81a5e6a2655fe58df3b66 | 3,632,172 |
import random
def build_stop_sign():
"""
This function creates a stop sign with GLabel
:return: object, sign
"""
random_x = random.randint(0, 640)
random_y = random.randint(30, 500)
sign = GLabel('Stop Clicking !!! ', x=random_x, y=random_y)
sign.color = 'firebrick'
sign.font = 'Ti... | bcfb44fbe7259ffa0a14b2511f99cf001a2f42c2 | 3,632,173 |
def name_atom(atom):
"""->symbol
Return the atom symbol for a depiction. Carbons atoms
in general are not returned"""
symbol = "%s"%(atom.symbol,)
weight = atom.weight
charge = atom.charge
hcount = atom.hcount
explicit_hcount = atom.explicit_hcount
out_symbol = symbol
# pyrole ... | 5b6661046720f10ca2f28196f2c76a4732dc9d96 | 3,632,174 |
import math
def rot3D(x, r):
"""perform 3D rotation
Args:
x (np.array): input data
r (float): rotation angle
Returns:
np.array: data after rotation
"""
Rx = np.array([[1, 0, 0], [0, math.cos(r[0]), -math.sin(r[0])], [0, math.sin(r[0]), math.cos(r[0])]])
Ry = np.array([[... | df37aa011e3291a87309ceb72d11f8a531475a5e | 3,632,176 |
def _shake_shake_layer(x,
output_filters,
num_blocks,
stride,
is_training):
"""Builds many sub layers into one full layer."""
for block_num in range(num_blocks):
curr_stride = stride if (block_num == 0) else 1
x =... | 246ddba479735b94d2c94ba02bdb5c571a68bbc2 | 3,632,178 |
from typing import Optional
def filter_nan_values(data: DataFrame, used_cols: Optional[list[str]] = None):
"""
Filter NaNs in columns that are used for futher calculations
:param data: Dataframe with full dataset
:type data: DataFrame
:param used_cols: Columns to check, None checks al... | 95296587ff765c48c5e3f3f9db911a9971f50984 | 3,632,179 |
def dropout(inputs,
is_training,
scope,
keep_prob=0.5,
noise_shape=None):
""" Dropout layer.
Args:
inputs: tensor
is_training: boolean tf.Variable
scope: string
keep_prob: float in [0,fv_noise]
noise_shape: list of ints
Returns:... | 738553ae4e958e34a3daea680bd5736f288609d2 | 3,632,180 |
def test_trained_model(test_data,
clf_name,
model_dir_path = '',
iteration_number = 0,
is_abnormal = False,
threshold_value = 0):
"""
Test any model.
:param test_data:
:param clf_name:
... | 7e1692e17590c1c8d3718073793e52ad5f07f055 | 3,632,181 |
import glob
def tumor_list(version):
"""
version: cross validation version and train or val
"""
path_list = []
for i in version:
paths = sorted(glob.glob(f'./data/tumor_-150_150/{i}/label_*/*.npy'))
path_list.extend(paths)
return path_list | da390686072613177a4f3f5b483d980640090d1c | 3,632,182 |
def roles_allowed(roles):
"""Takes a list of roles allowed to access decorated endpoint.
Aborts with 403 status if user with unauthorized role tries to access
this endpoint.
:param list roles: List of roles that should have access to the endpoint.
"""
def roles_allowed_decorator(fn):
@... | 8d039b09529f65b2d1123c8dffd634d2d6873404 | 3,632,183 |
from typing import List
from typing import Optional
def get_offsets(
text: str,
tokens: List[str],
start: Optional[int] = 0) -> List[int]:
"""Calculate char offsets of each tokens.
Args:
text (str): The string before tokenized.
tokens (List[str]): The list of the strin... | 08a300d7bbc078b40c44fdb75baeafff50c6907b | 3,632,184 |
def get_content_ref_if_exists_and_not_remote(check):
"""
Given an OVAL check element, examine the ``xccdf_ns:check-content-ref``
If it exists and it isn't remote, pass it as the return value.
Otherwise, return None.
..see-also:: is_content_href_remote
"""
checkcontentref = check.find("./{%... | 5232813333fff299e4afd8dadc1e6e700441f5b0 | 3,632,185 |
def sat_pass(sats, t_arr, index_epoch, location=None):
"""Find when a satellite passes above the horizon at a gps location.
Calculate the :samp:`Altitude` & :samp:`Azimuth` of a
:class:`~skyfield.sgp4lib.EarthSatellite` object from
:func:`~embers.sat_utils.sat_ephemeris.load_tle` at
every instant o... | 5f68fa486533dec605fe084f8848b836177920d2 | 3,632,186 |
def get_logit_model(x_train: pd.DataFrame, y_train: pd.Series) -> LogisticRegression:
"""
Train and return a logistic regression model
"""
lr = LogisticRegression(penalty='l2',
solver='lbfgs',
fit_intercept=False,
interc... | c267769bdab34bc6fb272fc2376e56c0c28f2964 | 3,632,187 |
from typing import Dict
from typing import Any
from typing import Tuple
def makearglists(args: Dict[str, Any]) -> Tuple[str, str]:
"""
Returns the python code for argument declaration and argument passing to
the function that does the work
Parameters
----------
args: dict
Arg info for... | 4cbcb1f3fbff72f12249bc7c952120e84bbda644 | 3,632,188 |
def task1():
"""Task1 function of API3
Returns:
[str]: [Return string]
"""
logger.info("In API3 task1 function")
return "task1 success!" | 2d506d97ed116704f85cb335b5e324c974b28087 | 3,632,189 |
def _METIS_PartGraphKway(nvtxs, ncon, xadj, adjncy, vwgt, vsize,
adjwgt, nparts, tpwgts, ubvec, options, objval, part):
"""
Called by `part_graph`
"""
return _METIS_PartGraphKway.call(
nvtxs, ncon, xadj, adjncy, vwgt, vsize, adjwgt, nparts, tpwgts, ubvec,
options... | 35965ed224058372e0831a10040065fde7c1b558 | 3,632,190 |
def payment_insert(conn, payment_info):
"""
Inserts a row in 'payment' table with the values passed in 'payment_info'
Parameters:
conn: Connection object
payment_info: a tuple of values to insert
"""
try:
sql = " INSERT into payment(payment_id, user_id, payment_method, paymen... | ad763dae5d8f313f34ebea7909097d558abc0565 | 3,632,192 |
def plot_pareto_frontier(
frontier: ParetoFrontierResults,
CI_level: float = DEFAULT_CI_LEVEL,
show_parameterization_on_hover: bool = True,
) -> AxPlotConfig:
"""Plot a Pareto frontier from a ParetoFrontierResults object.
Args:
frontier (ParetoFrontierResults): The results of the Pareto fro... | e36389fc64801af71302f70ebc74600b34e9a7d1 | 3,632,193 |
def filenames(
directory, file_stem, file_ext=DEFAULT_FILE_EXT, stamp_regex=DEFAULT_STAMP_REGEX
):
"""Generate all filenames with matching stem
Parameters
----------
directory : pathlib.Path
Path to directory holding file
file_stem : str
File stem, filename without timestamp and... | 81f27c939ae2934d4e58079fcc3ac53c2b2228a1 | 3,632,194 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.