content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
async def get_bot_queue(
request: Request,
state: enums.BotState = enums.BotState.pending,
verifier: int = None,
worker_session = Depends(worker_session)
):
"""Admin API to get the bot queue"""
db = worker_session.postgres
if verifier:
bots = await db.fetch("SELECT bot_id, prefix,... | bfbd51933b140bfd60cc7ec2a401d02048ffdeae | 15,584 |
def ask_for_rating():
"""Ask the user for a rating"""
heading = '{} {}'.format(common.get_local_string(30019),
common.get_local_string(30022))
try:
return int(xbmcgui.Dialog().numeric(heading=heading, type=0,
defaultt=''))
... | a7a854e02b11ac1313d69f508851d162a7748006 | 15,585 |
def isthai(text,check_all=False):
"""
สำหรับเช็คว่าเป็นตัวอักษรภาษาไทยหรือไม่
isthai(text,check_all=False)
text คือ ข้อความหรือ list ตัวอักษร
check_all สำหรับส่งคืนค่า True หรือ False เช็คทุกตัวอักษร
การส่งคืนค่า
{'thai':% อักษรภาษาไทย,'check_all':tuple โดยจะเป็น (ตัวอักษร,True หรือ False)}
"""
listext=list(t... | 6a6bff64ba3b3939414e9f3aa83d169cd026e1c3 | 15,586 |
from typing import List
from typing import Optional
def _convert_object_array(
content: List[Scalar], dtype: Optional[DtypeObj] = None
) -> List[Scalar]:
"""
Internal function ot convert object array.
Parameters
----------
content: list of processed data records
dtype: np.dtype, default i... | 7b093057b05afa93ced881289d22b1eda91018f0 | 15,587 |
def update_room_time(conn, room_name: str, req_time: int) -> int:
"""部屋のロックを取りタイムスタンプを更新する
トランザクション開始後この関数を呼ぶ前にクエリを投げると、
そのトランザクション中の通常のSELECTクエリが返す結果がロック取得前の
状態になることに注意 (keyword: MVCC, repeatable read).
"""
cur = conn.cursor()
# See page 13 and 17 in https://www.slideshare.net/ichirin2501... | 78066e9666ee28217f790fb8c26d2ade8c2ace7c | 15,588 |
def get_layer_coverage(cat, store, store_obj):
"""Get correct layer coverage from a store."""
coverages = cat.mosaic_coverages(store_obj)
# Find the correct coverage
coverage = None
for cov in coverages["coverages"]["coverage"]:
if store == cov['name']:
coverage = cov
... | 498c4a8db1a82dafd8569314e4faf13517e75aba | 15,589 |
import logging
import time
def retarget(songs, duration, music_labels=None, out_labels=None,
out_penalty=None, volume=None, volume_breakpoints=None,
springs=None, constraints=None,
min_beats=None, max_beats=None,
fade_in_len=3.0, fade_out_len=5.0,
**kwa... | 8ed317392e74545916d1ef33e282bce5c6846009 | 15,590 |
def st_get_ipfs_cache_path(user_did):
"""
Get the root dir of the IPFS cache files.
:param user_did: The user DID
:return: Path: the path of the cache root.
"""
return _st_get_vault_path(user_did) / 'ipfs_cache' | 4217b178025c395619d9def035d11cc96f2b139a | 15,591 |
def create_img_caption_int_data(filepath):
""" function to load captions from text file and convert them to integer
format
:return: dictionary with image ids and associated captions in int format
"""
print("\nLoading caption data : started")
# load caption data
img_caption_dict = load... | 6d1a449c1b5be7759c65740440865c72546514ef | 15,592 |
def eigenvector_2d_symmetric(a, b, d, eig, eps=1e-8):
"""Returns normalized eigenvector corresponding to the provided eigenvalue.
Note that this a special case of a 2x2 symmetric matrix where every element of the matrix is passed as an image.
This allows the evaluation of eigenvalues to be vectorized over ... | 88a97af77e3f3097b6742db340f8e9559fb8164a | 15,593 |
from typing import Optional
def get_protection_path_name(protection: Optional[RouteProtection]) -> str:
"""Get the protection's path name."""
if protection is None:
return DEFAULT_PROTECTION_NAME
return protection | f3abaf21c9ba3cfe6c0ae793afaf018fce20dec9 | 15,594 |
def _get_object_description(target):
"""Return a string describing the *target*"""
if isinstance(target, list):
data = "<list, length {}>".format(len(target))
elif isinstance(target, dict):
data = "<dict, length {}>".format(len(target))
else:
data = target
return data | 57ad3803a702a1199639b8fe950ef14b8278bec1 | 15,595 |
def build_tf_xlnet_to_pytorch_map(model, config, tf_weights=None):
""" A map of modules from TF to PyTorch.
I use a map to keep the PyTorch model as
identical to the original PyTorch model as possible.
"""
tf_to_pt_map = {}
if hasattr(model, "transformer"):
if hasattr(model, "l... | b822a5f5effcf1d925dec0e6c6b166ecb89b6627 | 15,596 |
def dynamicviewset(viewset):
"""
The activate route only makes sense if
user activation is required, remove the
route if activation is turned off
"""
if not settings['REQUIRE_ACTIVATION'] and hasattr(viewset, 'activate'):
delattr(viewset, 'activate')
return viewset | f31a191c7c4d51163f588fa4e728f92fb7d43816 | 15,597 |
import random
def generate_arabic_place_name(min_length=0):
"""Return a randomly generated, potentially multi-word fake Arabic place name"""
make_name = lambda n_words: ' '.join(random.sample(place_names, n_words))
n_words = 3
name = make_name(n_words)
while len(name) < min_length:
n_word... | 7efc760b8dcf5f8807e2d203542fa637908cbad2 | 15,598 |
def find_cutoffs(x,y,crdist,deltas):
"""function for identifying locations of cutoffs along a centerline
and the indices of the segments that will become part of the oxbows
from MeanderPy
x,y - coordinates of centerline
crdist - critical cutoff distance
deltas - distance between neighboring poin... | 82de02759c70ab746d2adcfafd04313cbb0a8c4e | 15,599 |
def training_set_multiplication(training_set, mult_queue):
"""
Multiply the training set by all methods listed in mult_queue.
Parameters
----------
training_set :
set of all recordings that will be used for training
mult_queue :
list of all algorithms that will take one recordin... | db7105d64ba760ba88088363547795fff833cce6 | 15,601 |
def addDictionaryFromWeb(url, params=None, **kwargs):
"""
指定した URL にあるページに含まれる辞書メタデータ(JSON-LD)を取得し、
メタデータに記載されている URL から地名解析辞書(CSVファイル)を取得し、
データベースに登録します。
既に同じ identifier を持つ辞書データがデータベースに登録されている場合、
削除してから新しい辞書データを登録します。
登録した辞書を利用可能にするには、 ``setActivateDictionaries()``
または ``activateDict... | 52ea0c105dd5b5725859cd440f10a1fe163d36be | 15,602 |
from re import T
def test_nested_blocks(pprint):
"""
Expected result:
procedure test(x, y: Integer);
begin
x:=1;
y:=200;
for z:= 1 to 100 do
begin
x := x + z;
end;
y:=x;
end;
"""
def brk(offset=0):
"force a new line and indent by given offset"
return... | 7ef533d66f57483fac98bc249fd121e7c47f3d9a | 15,603 |
from typing import Sequence
import asyncio
async def read(
sensors: Sequence[Sensor], msg: str = "", retry_single: bool = False
) -> bool:
"""Read from the Modbus interface."""
global READ_ERRORS # pylint:disable=global-statement
try:
try:
await SUNSYNK.read(sensors)
R... | 7e871984d3b86207a2e9c9909b5f83d3ef9c3c4a | 15,604 |
def boxlist_iou_guide_nms(boxlist, nms_thresh, max_proposals=-1, score_field="scores"):
"""
Performs non-maximum suppression on a boxlist, with scores specified
in a boxlist field via score_field.
Arguments:
boxlist(BoxList)
nms_thresh (float)
max_proposals (int): if > 0, then o... | 1824575d4768b2145730caa0f9f9809dd784260d | 15,605 |
def get_payload_bin(payload, seconds):
"""
Since we can't run the ysoserial.exe file in ubuntu (at least not
easily with mono) we build the different payloads in windows and
save them to the PAYLOADS map above.
:param payload: The payload name
:param seconds: The seconds to wait
:return: Th... | eec033969157ec2a67b2f9edbba5b355d25f55bc | 15,607 |
def srange(start, step, length, dtype=None):
"""
Like np.arange() but you give the start, the step, and the number
of steps. Saves having to compute the end point yourself.
"""
stop = start + (step * length)
return np.arange(start, stop, step, dtype) | ba71777c720063cbf5429085d8d249d83634b4f7 | 15,608 |
def get_tool_by_id(tool_id):
"""
returns the tool given the id
"""
tool = ToolType.objects.get(pk=tool_id)
return tool | 7cee1d4a484028db94049227f9a968541974cd1e | 15,609 |
import http
def domainr(text):
"""<domain> - uses domain.nr's API to search for a domain, and similar domains
:type text: str
"""
try:
data = http.get_json('http://domai.nr/api/json/search?q=' + text)
except (http.URLError, http.HTTPError):
return "Unable to get data for some reaso... | d44e49c25256a10f242cb8515b1e970cf509676d | 15,610 |
def manage_blog():
""" 博文管理页面路由 """
if 'adminname' in session:
if request.method == 'POST':
del_result = manage_del_blog(db, Post, Comment, request.form.get('edit_id'))
return del_result
else:
blog_list = Post.query.order_by(Post.post_time.desc()).all()
... | be73948d29e96413bff987447c5b9baa87177ccf | 15,611 |
def split(nodes, index, axis=0):
"""
Split a array of nodes into two separate, non-overlapping arrays.
Parameters
----------
nodes : numpy.ndarray
An N x M array of individual node coordinates (i.e., the
x-coords or the y-coords only)
index : int
The leading edge of wher... | 4ba4a078e35c7a4164675eab2fe36c943264bb28 | 15,612 |
def smart_oracle(oracle, text, code, block_len, max_rand):
"""Call oracle normally, or repeatedly call oracle in case of random prefix.
Returns "clean" oracle ouptut regardless of whether the oracle adds a
random prefix.
"""
if not max_rand:
return oracle(text, code) if code else oracle(text... | fb20586236509838333b2723b24ead9fba9f2887 | 15,613 |
def inference_video_feed(request, project_id):
"""inference_video_feed
"""
return Response({
"status": "ok",
"url": "http://" + inference_module_url() + "/video_feed?inference=1",
}) | 7751737093b0f1cd72301e3dcd07c9ab929c9931 | 15,615 |
from datetime import datetime
def extract_start_timestamp() -> datetime:
"""Define extraction start timestamp.
Returns:
Extraction start timestamp used for testing.
"""
timestamp = datetime(2019, 8, 6, tzinfo=timezone.utc)
return timestamp | f03668c5b19a05c623040b8be1ff6fca23765437 | 15,616 |
def phi_pdf(X, corr=None):
"""
Standard normal PDF/Multivariate pdf.
**Input:**
* **X** (`float`)
Argument.
* **corr** (`ndarray`)
Correlation matrix.
**Output**
Standard normal PDF of X.
"""
norm_pdf = None
if isinstance(X, int) or isinstance(X, float):
... | 31566a5e0c50eaae7be367f7ccfd5dc0c1bfcd94 | 15,617 |
def computeStatistic( benchmarks, field, func ):
"""
Return the result of func applied to the values of field in benchmarks.
Arguments:
benchmarks: The list of benchmarks to gather data from.
field: The field to gather from the benchmarks.
func: The function to apply to the data... | 7eced912d319a3261170f8274c4562db5e28c34c | 15,618 |
import re
def bus_update_request(payload):
"""Parser for `bus_update_request` tracepoint"""
try:
match = re.match(bus_update_request_pattern, payload)
if match:
match_group_dict = match.groupdict()
return BusUpdateRequest(**match_group_dict)
except Exception as e:
... | ea5d95eaef4964b900b5201a8878886529f8c132 | 15,619 |
def update_employee(request,id):
"""
Updating the employee profile.
"""
try:
obj = User.objects.get(id=id)
total_cl = obj.no_of_cl
total_sl = obj.no_of_sl
total_wh = obj.no_of_wh
attendance_cl = Attendance.objects.filter(id=id,leave_type='... | bcbfd2183ad6ea835b8e6fc4d6818b0bd31ea051 | 15,620 |
def func(TI, S0, alpha, T1):
""" exponential function for T1-fitting.
Args
----
x (numpy.ndarray): Inversion times (TI) in the T1-mapping sequence as input for the signal model fit.
Returns
-------
a, b, T1 (numpy.ndarray): signal model fitted parameters.
"""
mz = 1 - alp... | 605393be1aaf9f70f7f65c56dc5a31d4a38390e7 | 15,621 |
def make_random_coordinate():
""" Make a random coordinate dictionary"""
return make_coordinate(randint(0, 100), randint(0, 100)) | 7719714d19e94a5be2ae3f93fc5290514bfe4b5e | 15,623 |
def inv_qft_core(qubits):
"""
Generates a quil programm that performs
inverse quantum fourier transform on given qubits
without swaping qubits at the end.
:param qubits: A list of qubit indexes.
:return: A Quil program to compute the invese QFT of the given qubits without swapping.
""... | 3c7982cdb44398e1730a3aaaeee2c323694fae96 | 15,624 |
def analysis_precheck(_id, feature_table, rep_seqs, taxonomy, metadata):
"""
Do prechecks as to decrease the chance of job failing.
Input:
- feature_table: QIIME2 artifact of type FeatureTable[Frequency]
- rep_seqs: QIIME2 artifact of type FeatureData[Sequence]
"""
feature_table_path = save_uploaded_file(_id,... | 65dde12b312926d185722a09779c8d11705d71dc | 15,625 |
import socket
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Deluge from a config entry."""
host = entry.data[CONF_HOST]
port = entry.data[CONF_PORT]
username = entry.data[CONF_USERNAME]
password = entry.data[CONF_PASSWORD]
api = await hass.async_add_ex... | 70ab1c52569274eb7125e56f38028db3eb792259 | 15,626 |
import cmath
def powerFactor(n):
"""Function to compute power factor given a complex power value
Will this work if we're exporting power? I think so...
"""
# Real divided by apparent
pf = n.real.__abs__() / n.__abs__()
# Determine lagging vs leading (negative).
# NOTE: cmath.phase returns ... | 1a507818f9c9906d27a1374cc9b757766b3038c1 | 15,627 |
import requests
import html
def send_request(url, raise_errors):
"""
Sends a request to a URL and parses the response with lxml.
"""
try:
response = requests.get(url, headers={'Accept-Language': '*'}, verify=_PEM_PATH)
response.raise_for_status()
doc = html.fromstring(response... | ddf8dc7c899b97cebdc45727bd43ca1acf015ecb | 15,628 |
def _static_idx(idx, size):
"""Helper function to compute the static slice start/limit/stride values."""
assert isinstance(idx, slice)
start, stop, step = idx.indices(size)
if (step < 0 and stop >= start) or (step > 0 and start >= stop):
return 0, 0, 1, False # sliced to size zero
if step > 0:
retur... | 8c586375f018be36c0e7688549a551d17d4e2bc8 | 15,629 |
def crop_array(input_array, ylength, xlength=None, orgn=(0,0)):
"""Crops an image in numpy array format. Pads crops outside
of input image with zeros if necessary. If no y dimension
is specified, outputs a square image.
"""
if xlength == None:
xlength = ylength
ylength = int(ylength)
... | 4daeb126a8424fc038a5a42448d17eada9d12ee3 | 15,630 |
def get_service_defaults(servicename, version, **_):
"""
Load the default configuration for a given service version
Variables:
servicename => Name of the service to get the info
version => Version of the service to get
Data Block:
None
Result example:
{'accepts': '... | 2ba13382e2d5a668f1653f90fed5efe01200d6e2 | 15,631 |
def read_nnet3_model(model_path: str) -> nnet3.Nnet:
"""Read in a nnet3 model in raw format.
Actually if this model is not a raw format it will still work, but this is
not an official feature; it was due to some kaldi internal code.
Args:
model_path: Path to a raw nnet3 model, e.g., "data/fina... | b5dbadeb0f2072dfeccd1f4fdc77990680d12068 | 15,632 |
def flat_list_of_lists(l):
"""flatten a list of lists [[1,2], [3,4]] to [1,2,3,4]"""
return [item for sublist in l for item in sublist] | c121dff7d7d9a4da55dfb8aa1337ceeea191fc30 | 15,633 |
def cancel(api, order_ids=None):
"""
DELETE all orders by api["symbol"] (or) by symbol and order_id:
"""
if DETAIL:
print(cancel.__doc__, "symbol", api['symbol'], "order_ids", order_ids)
if order_ids is None:
order_ids = [] # must be a list
# format remote procedure call to excha... | 24688256b20d3fdcc40eebb393ab98a963037d96 | 15,634 |
def decrypt(mess, key):
"""Decrypt the cypher text using AES decrypt"""
if len(key) % 16 != 0:
a = 16 - len(key) % 16
key = key.ljust(len(key) + a)
cipher = AES.new(key)
plain_txt = cipher.decrypt(mess)
return plain_txt | eb587960d63539e1e57158f84174af5b5dae3fb5 | 15,636 |
def multiVecMat( vector, matrix ):
"""
Pronásobí matici vektorem zprava.
Parametry:
----------
vector: list
Vektor
matrix: list
Pronásobená matice. Její dimenze se musí shodovat s dimenzí
vektoru.
Vrací:
list
Pole velikosti ve... | 8a10241173ab981d6007d8ff939199f9e86806e5 | 15,637 |
def verify_state(
state_prec_gdf,
state_abbreviation,
source,
year,
county_level_results_df,
office,
d_col=None,
r_col=None,
path=None,
):
"""
returns a complete (StateReport) object and a ((CountyReport) list) for the state.
:state_prec_gdf: (GeoDataFrame) containing pr... | 245baf26d1fad646abcee493bfa31935f2d1db59 | 15,638 |
import requests
def remove_profile(serial, profile_id):
"""hubcli doesn't remove profiles so we have to do this server-side."""
r = requests.post(
url=f"https://{ AIRWATCH_DOMAIN }/API/mdm/profiles/{ profile_id }/remove",
json={"SerialNumber": serial},
headers={
"aw-tenant-... | 8a47cd5c6588c3140d9e44aac94b59916517345a | 15,639 |
def KELCH(df, n):
"""
Keltner Channel
"""
temp = (df['High'] + df['Low'] + df['Close']) / 3
KelChM = pd.Series(temp.rolling(n).mean(), name='KelChM_' + str(n))
temp = (4 * df['High'] - 2 * df['Low'] + df['Close']) / 3
KelChU = pd.Series(temp.rolling(n).mean(), name='KelChU_' + str(n))
te... | 3335fd45ce073eec33d65b7a6d23c07b6a71a662 | 15,641 |
def wait_until_complete(jobs):
"""wait jobs finish"""
return [j.get() for j in jobs] | 530c3af30ca40025891980191c1f121d8f026a53 | 15,643 |
import io
def torquery(url):
"""
Uses pycurl to fetch a site using the proxy on the SOCKS_PORT.
"""
output = io.BytesIO()
query = pycurl.Curl()
query.setopt(pycurl.URL, url)
query.setopt(pycurl.PROXY, 'localhost')
query.setopt(pycurl.PROXYPORT, SOCKS_PORT)
query.setopt(pycurl.PROXYTYPE, pycurl.PRO... | 7ae660a9a5c3af7be0fbf8789cc96d481863a2c4 | 15,644 |
def check_for_negative_residual(vel, data, errors, best_fit_list, dct,
signal_ranges=None, signal_mask=None,
force_accept=False, get_count=False,
get_idx=False, noise_spike_mask=None):
"""Check for negative residual feat... | 3901af224a080e99aa0cfdef22a27b8951ee4c3c | 15,645 |
import requests
import shutil
def download(url, filename, proxies=None):
"""
Telechargement de l'URL dans le fichier destination
:param url: URL a telecharger
:param filename: fichier de destination
"""
error = ''
try:
req = requests.get(url, proxies=proxies, stream=True)
... | da097b46aef574623ac975aa8d5e9506ff191d53 | 15,647 |
import json
async def validate_devinfo(hass, data):
"""检验配置是否缺项。无问题返回[[],[]],有缺项返回缺项。"""
# print(result)
devtype = data['devtype']
ret = [[],[]]
requirements = VALIDATE.get(devtype)
if not requirements:
return ret
else:
for item in requirements[0]:
if item not i... | 7e0822ae36617f209447221dc49f0485e88759e9 | 15,648 |
from datetime import datetime
def worldbank_date_to_datetime(date):
"""Convert given world bank date string to datetime.date object."""
if "Q" in date:
year, quarter = date.split("Q")
return datetime.date(int(year), (int(quarter) * 3) - 2, 1)
if "M" in date:
year, month = date.spl... | f36fb2c763da59ae58a08f446e4cbd566d6e87e0 | 15,650 |
from typing import Sequence
def select(
key: bytes, seq: Sequence[BucketType], *, seed: bytes = DEFAULT_SEED
) -> BucketType:
"""
Select one of the elements in seq based on the hash of ``key``.
Example partitioning of input on ``stdin`` into buckets::
bucketed_lines = {} # type: Dict[int, s... | d9f3a2f3aa759f252965478e0f065a555b23a24d | 15,651 |
def unescape(s):
"""
unescape html
"""
html_codes = (
("'", '''),
('"', '"'),
('>', '>'),
('<', '<'),
('&', '&')
)
for code in html_codes:
s = s.replace(code[1], code[0])
return s | c1434498694d90b219c962c0ce75b6c8978533bb | 15,652 |
def ua_mnem(*args):
"""ua_mnem(ea_t ea, char buf) -> char"""
return _idaapi.ua_mnem(*args) | 23322dd3780c9184ebed9f6006a0fad37000f29a | 15,653 |
import time
def tic(*names):
"""
Start timer, use `toc` to get elapsed time in seconds.
Parameters
----------
names : str, str, ...
Names of timers
Returns
-------
out : float
Current timestamp
Examples
--------
.. code-block:: python
:linenos:... | af9d93a092bed7849150cb3256a8fac6cc20f7d9 | 15,654 |
def retrieve_database():
"""Return the contents of MongoDB as a dataframe."""
return pd.DataFrame(list(restaurant_collection.find({}))) | 20d53dff1cc3164cedef303f8c4e38f7774e9f5e | 15,657 |
from typing import List
def readAbstractMethodsFromFile(file: str) -> List[AbstractMethod]:
"""
Returns a list of `AbstractMethods` read from the given `file`. The file should have one `AbstractMethod`
per line with tokens separated by spaces.
"""
abstractMethods = []
with open(file, "r") as... | 44a1fb346bfbb0eb71882b623887744dbbfb5143 | 15,658 |
from typing import Callable
def recursive_descent(data: np.ndarray, function: Callable):
"""
**Recursivly process an `np.ndarray` until the last dimension.**
This function applies a callable to the very last dimension of a numpy multidimensional array. It is foreseen
for time series proce... | c5955f5c3968aae53ae222cc4c0288320c3fb1c6 | 15,660 |
def watt_spectrum(a, b):
""" Samples an energy from the Watt energy-dependent fission spectrum.
Parameters
----------
a : float
Spectrum parameter a
b : float
Spectrum parameter b
Returns
-------
float
Sampled outgoing energy
"""
return _dll.watt_spect... | 0682a8791cb1b1cce93b4449bebfa2ac098fde20 | 15,661 |
def get_definition_from_stellarbeat_quorum_set(quorum_set: QuorumSet) -> Definition:
"""Turn a stellarbeat quorum set into a quorum slice definition"""
return {
'threshold': quorum_set['threshold'],
'nodes': set(quorum_set['validators']) if 'validators' in quorum_set else set(),
'childre... | 6259c820c4b920672f8b2333826f9996de3cd405 | 15,662 |
def values(names):
"""
Method decorator that allows inject return values into method parameters.
It tries to find desired value going deep. For convinience injects list with only one value as value.
:param names: dict of "value-name": "method-parameter-name"
"""
def wrapper(func):
@wraps... | 72e958692a14254b26e7ff1241103aa0a1063a33 | 15,663 |
from operator import or_
def select_user(with_dlslots=True):
"""
Select one random user, if can_download is true then user must have
download slots available
:returns User
"""
with session_scope() as db:
try:
query = db.query(User).filter(User.enabled.is_(True))
... | 2ba3e6c8b0f5488aa770fa982d3206c2dde5d0e1 | 15,664 |
def silero_number_detector(onnx=False):
"""Silero Number Detector
Returns a model with a set of utils
Please see https://github.com/snakers4/silero-vad for usage examples
"""
if onnx:
url = 'https://models.silero.ai/vad_models/number_detector.onnx'
else:
url = 'https://models.sil... | 46fa5a33b9e33cfebdc081e062f98711e3e8be61 | 15,665 |
def etaCalc(T, Tr = 296.15, S = 110.4, nr = 1.83245*10**-5):
"""
Calculates dynamic gas viscosity in kg*m-1*s-1
Parameters
----------
T : float
Temperature (K)
Tr : float
Reference Temperature (K)
S : float
Sutherland constant (K)
nr : ... | 3f8182ea29fd558e86280477f2e435247d09798e | 15,666 |
def refine_markers_harris(patch, offset):
""" Heuristically uses the max Harris response for control point center. """
harris = cv2.cornerHarris(patch, 2, 5, 0.07)
edges = np.where(harris < 0, np.abs(harris), 0)
point = np.array(np.where(harris == harris.max())).flatten()
point += offset
return... | afa080a8292c210f04483cddf8d81e297b5f2aec | 15,667 |
def get_realtime_price(symbol):
"""
获取实时股价
:param symbol:
:return:
"""
try:
df = get_real_price_dataframe()
df_s = df[df['code'] == symbol]
if len(df_s['trade'].get_values()):
return df_s['trade'].get_values()[0]
else:
return -1
except:... | af81787ab00283309829a6af2ef04155f73f360c | 15,668 |
def create_employee(db_session: Session, employee: schemas.EmployeeRequest):
""" Create new employee """
new_employee = Employee(
idir=employee.idir,
status=employee.status,
location=employee.location,
phone=employee.phone)
db_session.add(new_employee)
db_session.commit()... | 1f858412e0e2c94ca40414054c28d67639b620aa | 15,669 |
def sim_categorical(var_dist_params, size):
"""
Function to simulate data for
a categorical/Discrete variable.
"""
values = var_dist_params[0]
freq = var_dist_params[1]
data_sim = np.random.choice(a=values, p=freq, size=size)
return data_sim | 1b81eac17f041a9200b8c96b9c86310d6d3b003f | 15,670 |
def validSolution(board: list) -> bool:
"""
A function validSolution/ValidateSolution/valid_solution()
that accepts a 2D array representing a Sudoku board,
and returns true if it is a valid solution, or false otherwise
:param board:
:return:
"""
return all([test_horizontally(board),
test_vertically... | 023741cac4106372e8b4c9b8b7c7e60fb9837a7b | 15,671 |
async def test_create_saves_data(manager):
"""Test creating a config entry."""
@manager.mock_reg_handler("test")
class TestFlow(data_entry_flow.FlowHandler):
VERSION = 5
async def async_step_init(self, user_input=None):
return self.async_create_entry(title="Test Title", data="T... | 66905b55dcbf3d04b9a1d7d6cbdf843c8694eafb | 15,672 |
def drawingpad(where=None, x=0, y=0, image=None, color=0xffffff, fillingColor=0x000000, thickness=3):
"""Create a drawing pad.
Args:
where (np.ndarray) : image/frame where the component should be rendered.
x (int) : Position X where the component should be placed.
y (int) : Position Y ... | 25d16ee18b25965dd9d8ecbabb46353950c53297 | 15,673 |
def json_request(url, **kwargs):
"""
Request JSON data by HTTP
:param url: requested URL
:return: the dictionary
"""
if 'auth_creds' in kwargs and 'authentication_enabled' in kwargs['auth_creds']:
if 'sessionToken' in kwargs:
url += "&sessionToken=%s" % kwargs['auth_creds'... | d0a496b36905a0a505d3eab721c8e23ab0eb0e21 | 15,674 |
import io
import json
def list():
"""
List all added path
"""
try:
with io.open(FILE_NAME, 'r', encoding='utf-8') as f:
data = json.load(f)
except:
data = {}
return data | 98d426ece920648d1789c4b2e09ee62eb1cb990d | 15,675 |
import pickle
def load(filename):
"""
Load an EigenM object
"""
with open(filename, 'rb') as f:
return pickle.load(f) | 2653cbbe6a1323725c8ba0f771778e1c738daf12 | 15,676 |
def resize_image_bboxes_with_crop_or_pad(image, bboxes, xs, ys,
target_height, target_width, mask_image=None):
"""Crops and/or pads an image to a target width and height.
Resizes an image to a target width and height by either centrally
cropping the image or padding ... | 80c215d0cb750ce55d4d38ef2748f9b89789519c | 15,677 |
def sharpe_ratio(R_p, sigma_p, R_f=0.04):
"""
:param R_p: 策略年化收益率
:param R_f: 无风险利率(默认0.04)
:param sigma_p: 策略收益波动率
:return: sharpe_ratio
"""
sharpe_ratio = 1.0 * (R_p - R_f) / sigma_p
return sharpe_ratio | d197df7aa3b92f3a32cc8f11eb675012ffe8af57 | 15,678 |
def xr_vol_int_regional(xa, AREA, DZ, MASK):
""" volumen integral with regional MASK
input:
xa, AREA, DZ .. same as in 'xr_vol_int'
MASK .. 2D xr DataArray of booleans with the same dimensions as xa
output:
integral, int_levels .. same as in 'xr_vol_int'
... | 4840d66ec6164d16df56f9efeebf9d242bc60613 | 15,679 |
from typing import List
def test(
coverage: bool = typer.Option( # noqa: B008
default=False, help='Generate coverage information.'
),
html: bool = typer.Option( # noqa: B008
default=False, help='Generate an html coverage report.'
),
) -> List[Result]:
"""Run tests."""
coverag... | 0b9fe2d265fd604ae32df29bcde71041a1f5dfcf | 15,680 |
import winreg as _winreg
import _winreg
def _get_win_folder_from_registry(csidl_name: Any) -> Any:
"""This is a fallback technique at best. I'm not sure if using the
registry for this guarantees us the correct answer for all CSIDL_*
names."""
if PY3:
else:
shell_folder_name = {
"CSIDL... | 76dda1c71ea7184a327c0d32a35ecbf45579dd7c | 15,681 |
def transitions2kernelreward(transitions, num_states, num_actions):
"""Transform a dictionary of transitions to kernel, reward matrices."""
kernel = np.zeros((num_states, num_actions, num_states))
reward = np.zeros((num_states, num_actions))
for (state, action), transition in transitions.items():
... | 72165577890342cf1e3f01dbe853cd0024a0324e | 15,682 |
def _inline_svg(svg: str) -> str:
"""Encode SVG to be used inline as part of a data URI.
Replacements are not complete, but sufficient for this case.
See https://codepen.io/tigt/post/optimizing-svgs-in-data-uris
for details.
"""
replaced = (
svg
.replace('\n', '%0A')
.r... | 4e3c25f5d91dd7691f42f9b9ace4d64a297eb32f | 15,683 |
def contact_infectivity_asymptomatic_00x40():
"""
Real Name: b'contact infectivity asymptomatic 00x40'
Original Eqn: b'contacts per person normal 00x40*infectivity per contact'
Units: b'1/Day'
Limits: (None, None)
Type: component
b''
"""
return contacts_per_person_normal_00x40() * i... | 2c71d8955078186636de0d0b369b37a71dcec3fc | 15,684 |
import click
def implemented_verified_documented(function):
""" Common story options """
options = [
click.option(
'--implemented', is_flag=True,
help='Implemented stories only.'),
click.option(
'--unimplemented', is_flag=True,
help='Unimplement... | 8c1dd5aaa0b962d96e9e90336183a29e2cf360db | 15,685 |
import requests
def create_collection(self, name, url, sourceType, **options):
"""Creates a new collection from a web or S3 url. Automatically kick off default indexes"""
(endpoint, method) = self.endpoints['create_collection']
try:
headers = {'Authorization': self.token.authorization_header()}
data = ... | 37f7128526b5b7b1a22a9f946774f934827aa555 | 15,686 |
from typing import Union
def rmse(estimated: np.ndarray, true: np.ndarray) -> Union[np.ndarray, None]:
"""
Calculate the root-mean-squared error between two arrays.
:param estimated: estimated solution
:param true: 'true' solution
:return: root-mean-squared error
"""
return np.sqrt(((esti... | 10eb4974f5d95ca20b5336e2e9637eb6426802ae | 15,687 |
def energy_com(data):
""" Calculate the energy center of mass for each day, and use this quantity
as an estimate for solar noon.
Function infers time stamps from the length of the first axis of the 2-D
data array.
:param data: PV power matrix as generated by `make_2d` from `solardatatools.data_tra... | 1b276b003f8527672fb95ad03b69536043a7ba17 | 15,688 |
import random
def cifar_noniid(dataset, no_participants, alpha=0.9):
"""
Input: Number of participants and alpha (param for distribution)
Output: A list of indices denoting data in CIFAR training set.
Requires: cifar_classes, a preprocessed class-indice dictionary.
Sample Method: take a uniformly ... | 8ecbb6df113d04b5ff737bb065bc4e578d06c69b | 15,689 |
from typing import Dict
def example_metadata(
request,
l1_ls5_tarball_md_expected: Dict,
l1_ls7_tarball_md_expected: Dict,
l1_ls8_folder_md_expected: Dict,
):
"""
Test against arbitrary valid eo3 documents.
"""
which = request.param
if which == "ls5":
return l1_ls5_tarball_... | fd67c395aa7d773bc5757ca5649fed60b023e14f | 15,690 |
def register_middleware(app: FastAPI):
"""
请求响应拦截 hook
https://fastapi.tiangolo.com/tutorial/middleware/
:param app:
:return:
"""
@app.middleware("http")
async def logger_request(request: Request, call_next):
# https://stackoverflow.com/questions/60098005/fastapi-starlette-get-... | 3455c7d406c405ae0df681d90bfcf57facddaa03 | 15,691 |
def asfarray(a, dtype=_nx.float_):
"""
Return an array converted to float type.
Parameters
----------
a : array_like
Input array.
dtype : string or dtype object, optional
Float type code to coerce input array `a`. If one of the 'int' dtype,
it is replaced with float64.
... | 8d26529602853e36dd8dc619d6210c475dcb7cd0 | 15,692 |
def read_geotransform_s2(path, fname='MTD_TL.xml', resolution=10):
"""
Parameters
----------
path : string
location where the meta data is situated
fname : string
file name of the meta-data file
resolution : {float,integer}, unit=meters, default=10
resolution of the grid... | 322a5bb149f0cc28dc813adebb3dad861e3a3218 | 15,693 |
def embed_into_hbox_layout(w, margin=5):
"""Embed a widget into a layout to give it a frame"""
result = QWidget()
layout = QHBoxLayout(result)
layout.setContentsMargins(margin, margin, margin, margin)
layout.addWidget(w)
return result | a7a5182ac6e555f3adcbe7a9b11a6826517d08f4 | 15,694 |
def make_word_ds(grids, trfiles, bad_words=DEFAULT_BAD_WORDS):
"""Creates DataSequence objects containing the words from each grid, with any words appearing
in the [bad_words] set removed.
"""
ds = dict()
stories = grids.keys()
for st in stories:
grtranscript = grids[st].tiers[1].make_si... | 43f405605d461dd6972f131c1474dad6b8acf35c | 15,695 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.