content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def trader_tactic_snapshot(symbol, strategy, end_dt=None, file_html=None, fq=True, max_count=1000):
"""使用聚宽的数据对任意标的、任意时刻的状态进行策略快照
:param symbol: 交易标的
:param strategy: 择时交易策略
:param end_dt: 结束时间,精确到分钟
:param file_html: 结果文件
:param fq: 是否复权
:param max_count: 最大K线数量
:return: trader
"""... | 0b979008f3c950ed41aa85eff2031e6cb34b8685 | 6,700 |
def preprocess(batch):
""" Add zero-padding to a batch. """
tags = [example.tag for example in batch]
# add zero-padding to make all sequences equally long
seqs = [example.words for example in batch]
max_length = max(map(len, seqs))
seqs = [seq + [PAD] * (max_length - len(seq)) for seq in seqs... | 832b6453714e7b7eb23271b771bbc156a09d3784 | 6,701 |
def append_include_as(include_match):
"""Convert ``#include x`` to ``#include x as y``, where appropriate; also,
convert incorrect "as" statements. See INCLUDE_AS dict for mapping from
resource to its "as" target.
Parameters
----------
include_match : re._pattern_type
Match produced by ... | 0eaaa356efa33f0e64db6b3a843236fd15ebb66d | 6,702 |
def get_user_profiles(page=1, limit=10):
"""Retrieves a list of user profiles.
:param page: Page number
:type page: int
:param limit: Maximum number of results to show
:type limit: int
:returns: JSON string of list of user profiles; status code
:rtype: (str, int)
"""
# initialize q... | 7bcfe33925e49a90ac593fad53e4e169b107886e | 6,703 |
import sqlite3
def _repository():
"""Helper dependency injection"""
db = sqlite3.connect('covid_database.db', isolation_level=None)
return CovidTestDataRepository(db) | e30d30f3b4f9673df4863d261655aa6f38a527d7 | 6,704 |
def f(x):
"""Cubic function."""
return x**3 | 13832221de3490dbd92f4f1a26854baec7010023 | 6,705 |
from ruia_cache.response import CacheResponse
import os
def req_cache(*args, **kwargs):
"""
Cache decorate for `ruia.Request` class
:param args:
:param kwargs:
:return:
"""
fetch_func = args[0]
@wraps(fetch_func)
async def wrapper(self, delay=True):
cache_resp = None
... | 626605babe46e16e7f9e9eada74141d3bb7e7eb4 | 6,706 |
from outliers import smirnov_grubbs as grubbs
def correct_anomalies(peaks, alpha=0.05, save_name=""):
"""
Outlier peak detection (Grubb's test) and removal.
Parameters
----------
peaks : array
vector of peak locations
alpha : real
significance level for Grubb's test
save_n... | cf33123e963b245007c8be4777cecd1224d4e3fa | 6,707 |
def svn_wc_walk_entries(*args):
"""
svn_wc_walk_entries(char path, svn_wc_adm_access_t adm_access, svn_wc_entry_callbacks_t walk_callbacks,
void walk_baton,
svn_boolean_t show_hidden, apr_pool_t pool) -> svn_error_t
"""
return apply(_wc.svn_wc_walk_entries, args) | 791e0f635aa56329f78a1ed0f171217518f9be05 | 6,708 |
def dlp_to_datacatalog_builder(
taskgroup: TaskGroup,
datastore: str,
project_id: str,
table_id: str,
dataset_id: str,
table_dlp_config: DlpTableConfig,
next_task: BaseOperator,
dag,
) -> TaskGroup:
"""
Method for returning a Task Group for scannign a table with DLP, and creating B... | 53950a99dddc4f2a61dca12908c3b2a17a3765c4 | 6,709 |
import sys
def upload_assessors(xnat, projects, resdir, num_threads=1):
"""
Upload all assessors to XNAT
:param xnat: pyxnat.Interface object
:param projects: list of projects to upload to XNAT
:return: None
"""
# Get the assessor label from the directory :
assessors_list = get_assess... | 38e230c784cfdf1774efd2194c0c475671c8f512 | 6,710 |
import textwrap
def dedent(ind, text):
"""
Dedent text to the specific indentation level.
:param ind: common indentation level for the resulting text (number of spaces to append to every line)
:param text: text that should be transformed.
:return: ``text`` with all common indentation removed, and... | 271b9fd270d78c4bc952af31d3d9be0ff6bdab73 | 6,711 |
import os
def since(timestamp=None, directory=os.getcwd()): # noqa WPS404, B008
"""since."""
if not timestamp:
return WRONG_ARGUMENT
try:
timestamp = int(timestamp)
except Exception:
return WRONG_ARGUMENT
if not os.path.exists(directory):
return 'dir not found'
... | 9728e68aec54b7781fb07d7fdda243568c51eac3 | 6,712 |
def get_vendor(request):
"""
Returns the ``JSON`` serialized data of the requested vendor on ``GET`` request.
.. http:get:: /get_vendor/
Gets the JSON serialized data of the requested vendor.
**Example request**:
.. sourcecode:: http
GET /get... | e142854426ef406bdfe6e34d0629e80d49493c91 | 6,713 |
def ensure_bin_str(s):
"""assert type of s is basestring and convert s to byte string"""
assert isinstance(s, basestring), 's should be string'
if isinstance(s, unicode):
s = s.encode('utf-8')
return s | 3ce171f02a371073c5474596da9c963b0a77a415 | 6,714 |
def _word_accuracy(pred_data, ref_data):
"""compute word-level accuracy"""
pred_size = len(pred_data)
ref_size = len(ref_data)
if pred_size <= 0 or ref_size <= 0:
raise ValueError("size of predict or reference data is less than or equal to 0")
if pred_size != ref_size:
raise ValueErr... | c4abfcc439fca5d14b5edc8289ef9ee2d46807fe | 6,715 |
import logging
import inspect
import os
def check_interface(interface: str) -> str:
""" Check that the interface we've been asked to run on actually exists """
log = logging.getLogger(inspect.stack()[0][3])
discovered_interfaces = []
for iface in os.listdir("/sys/class/net"):
iface_path = os.p... | 0e3d42ee7c1e2d3f486681ca0bdde174c0650972 | 6,716 |
import requests
def api_retrieve_part(pt_id):
"""
Allows the client to call "retrieve" method on the server side to
retrieve the part from the ledger.
Args:
pt_id (str): The uuid of the part
Returns:
type: str
String representing JSON object which allows the clien... | 5043415dcdb95e59ec87271bf62d1f04f818af9b | 6,717 |
def smoP(dataMatIn, classLabels, C, toler, maxIter, kTup = ('lin',0)):
"""
完整的线性SMO算法
Parameters:
dataMatIn - 数据矩阵
classLabels - 数据标签
C - 松弛变量
toler - 容错率
maxIter - 最大迭代次数
kTup - 包含核函数信息的元组
Returns:
oS.b - SMO算法计算的b
oS.alphas - SMO算法计算的alphas
"""
oS = optStruct(np.mat(dataMatIn), np.mat(classLabel... | fb38ef33ab624a74f3da320c5e90a48aa307d588 | 6,718 |
def _get_output_data(output_list, heat, stack_id):
"""
获取output数据
"""
response = {
'code': 200,
'msg': 'ok',
'status': utils.INSTANTIATED,
'data': []
}
for item in output_list['outputs']:
output = heat.stacks.output_show(stack_id, item['output_key'])
... | aca183c1b158e6e7b9e414151e7f5d5505de1188 | 6,719 |
def _ensure_str(s):
"""convert bytestrings and numpy strings to python strings"""
return s.decode() if isinstance(s, bytes) else str(s) | 05f549166cc459371b380f62393bbc835aa7ff48 | 6,720 |
def get_polarimeter_index(pol_name):
"""Return the progressive number of the polarimeter within the board (0…7)
Args:
pol_name (str): Name of the polarimeter, like ``R0`` or ``W3``.
Returns:
An integer from 0 to 7.
"""
if pol_name[0] == "W":
return 7
else:
retu... | 0068931868e214896f6263e58fc09215352d502c | 6,721 |
def merge_sort(collection):
"""
Pure implementation of the fastest ordered collection with heterogeneous
: parameter collection : some mutable ordered collection with heterogeneous
comparable items inside
: return : a sollectiojn order by ascending
Examples :
>>> me... | b704792ef49629e7e9e04c22ffe03f08b3ef76fa | 6,722 |
def sma_centroids(dataframe, column, short_window, long_window, min_width=None, **kwargs):
"""Identify centermost point between two SMA interception points
Define regions as being bounded by two consecutive interceptions of SMAs
with different window widths, then choose the centermost data point within
... | 1157318d90ce514a3a85461851c158a0df9d2a3e | 6,723 |
def delMsg(msgNum):
"""Deletes a specified message from the inbox"""
global usrPrompt
try:
inboxMessages = json.loads(api.getAllInboxMessages())
# gets the message ID via the message index number
msgId = inboxMessages['inboxMessages'][int(msgNum)]['msgid']
msgAck = api.tras... | b3cc7a4568ca6eae3267cd5247abe88c5ccb8bec | 6,724 |
def capitalize_first(str):
"""Capitalizes only the first letter of the given string.
:param str: string to capitalize
:return: str with only the first letter capitalized
"""
if str == "":
return ""
return str[0].upper() + str[1:] | ed6dfdfd9709de1682c29ed152131b9da732441b | 6,725 |
def min_cost_edge(G, T):
"""Returns the edge with the lowest cost/weight.
Parameters
----------
G : NetworkX graph
T : Prim's Algorithm
Returns
-------
The edge with the lowest cost/weight.
"""
edge_list = possible_edges(G, T)
edge_list.sort(key = lambda e : cost(G... | 3720bb59cddf0b29beb9f9162941ddf7f86dd429 | 6,726 |
import io
import base64
def get_image_html_tag(fig, format="svg"):
"""
Returns an HTML tag with embedded image data in the given format.
:param fig: a matplotlib figure instance
:param format: output image format (passed to fig.savefig)
"""
stream = io.BytesIO()
# bbox_inches: expand the ... | f5c59a6f4f70fb6616cec4619d8cbf9ca2e28529 | 6,727 |
def reformat_language_tuple(langval):
"""Produce standardly-formatted language specification string using given language tuple.
:param langval: `tuple` in form ('<language>', '<language variant>'). Example: ('en', 'US')
:return: `string` formatted in form '<language>-<language-variant>'
"""
if lang... | 63c479d7dd273f31b9bdcc6c0ce81d4267a43714 | 6,728 |
def _create_ghostnet(variant, width=1.0, pretrained=False, **kwargs):
"""
Constructs a GhostNet model
"""
cfgs = [
# k, t, c, SE, s
# stage1
[[3, 16, 16, 0, 1]],
# stage2
[[3, 48, 24, 0, 2]],
[[3, 72, 24, 0, 1]],
# stage3
[[5, 72, 40, 0.25,... | 8b0bca5e4d711dce5150d8c3cdb187c9b1a23ec3 | 6,729 |
def re_suffix(string):
""" Remove any “os.extsep” prefixing a string, and ensure that
it ends with a “$” – to indicate a regular expression suffix.
"""
if not string:
return None
return rf"{string.casefold().lstrip(QUALIFIER).rstrip(DOLLA)}{DOLLA}" | fd1767f0d539e284f56c32f5ed4a8789a6638fca | 6,730 |
def _alternate_dataclass_repr(object) -> None:
"""
Overrides the default dataclass repr by not printing fields that are
set to None. i.e. Only prints fields which have values.
This is for ease of reading.
"""
populated_fields = {
field.name: getattr(object, f"{field.name}")
for f... | c9c07508a39c0732698c1ed6803ef00c4b2f65d6 | 6,731 |
def which_coords_in_bounds(coords, map_shape):
"""
Checks the coordinates given to see if they are in bounds
:param coords Union[array(2)[int], array(N,2)[int]]: [int, int] or [[int, int], ...], Nx2 ndarray
:param map_shape Tuple[int]: shape of the map to check bounds
:return Union[bool array(N)[boo... | 5606c24430e9967cade8bdeb789f10bed1248eb1 | 6,732 |
def get_activation_function(activation_function_name: str):
"""
Given the name of an activation function, retrieve the corresponding function and its derivative
:param cost_function_name: the name of the cost function
:return: the corresponding activation function and its derivative
"""
try:
... | f2a830c15cb93bd9fce1b66c2b5ca14530005cd5 | 6,733 |
def url_split(url, uses_hostname=True, split_filename=False):
"""Split the URL into its components.
uses_hostname defines whether the protocol uses a hostname or just a path (for
"file://relative/directory"-style URLs) or not. split_filename defines whether the
filename will be split off in an... | 5c76eb58c520043ab922c941806f24c60f9ee721 | 6,734 |
def memdiff_search(bytes1, bytes2):
"""
Use binary searching to find the offset of the first difference
between two strings.
:param bytes1: The original sequence of bytes
:param bytes2: A sequence of bytes to compare with bytes1
:type bytes1: str
:type bytes2: str
:rtype: int offset of... | fbcb221c77730c45be4c81a6ae7515e602468af5 | 6,735 |
def decomposeJonesMatrix(Jmat):
""" Decompose 2x2 Jones matrix to retardance and diattenuation vectors """
Jmat = Jmat / cp.sqrt(cp.linalg.det(Jmat))
q = cp.array([Jmat[0, 0] - Jmat[1, 1], Jmat[1, 0] + Jmat[0, 1], -1j * Jmat[1, 0] + 1j * Jmat[0, 1]]) / 2
tr = cp.trace(Jmat) / 2
c = cp.arccosh(tr)
... | 151320a0f77f2fb3a77d8e06b1e623c0fed6c673 | 6,736 |
def format_utc(time):
"""Format a time in UTC."""
return as_utc(time).strftime('%Y-%m-%d %H:%M:%S.%f') | 88624b8e166aa07172abd14c391945e33c77332f | 6,737 |
def plugin_scope():
"""Returns the capability as the remote network driver.
This function returns the capability of the remote network driver, which is
``global`` or ``local`` and defaults to ``local``. With ``global``
capability, the network information is shared among multipe Docker daemons
if th... | dba53f98ca73010d41e1a315f28a8279bb6aa4cd | 6,738 |
import os
def _create_chimeric_msa( # pylint: disable=too-many-arguments
output_folder,
cluster,
subexon_df,
gene2speciesname,
connected_subexons,
aligner='ProGraphMSA',
padding='XXXXXXXXXX',
species_list=None):
"""Return a modified subexon_df, the ... | 9adb45de5a51939b0dc2d728fdc2837a97fd3df9 | 6,739 |
def _expand_sources(sources):
"""
Expands a user-provided specification of source files into a list of paths.
"""
if sources is None:
return []
if isinstance(sources, str):
sources = [x.strip() for x in sources.split(",")]
elif isinstance(sources, (float, int)):
sources =... | 6e16eaae5edb68a5be7e0af4be777fc76b70d22a | 6,740 |
from typing import Optional
def get_stream(stream_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetStreamResult:
"""
This data source provides details about a specific Stream resource in Oracle Cloud Infrastructure Streaming service.
Gets detailed infor... | fd7eb6675f5d232e90a94e18e4c68e6d538ca7e4 | 6,741 |
import os
def components(path):
"""Split a POSIX path into components."""
head, tail = os.path.split(os.path.normpath(path))
if head == "":
return [tail]
elif head == "/":
return [head + tail]
else:
return components(head) + [tail] | f29ae64104255450f5889a7440679342af767c9b | 6,742 |
def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
"""
Fusion method.
"""
n_channels_int = n_channels
in_act = input_a + input_b
t_act = ops.Tanh()(in_act[:, :n_channels_int, :])
s_act = ops.Sigmoid()(in_act[:, n_channels_int:, :])
acts = t_act * s_act
return acts | 9412a3b20960b0a280a06569846df744f14a9d63 | 6,743 |
import json
def _classes_dict(filename):
"""
Open JSON file and read the data for the Classes (and Origins).
filename - the file name as a string.
Runtime: O(n)
"""
class_dict = {} # {'robot': ['blitzcrank']}
class_bonus_dict = {}
dict = { 1: {}, 2: {}, 3: {}, 4 : {}, 6 : {}} # { 1 : {... | 44fa2acec6c7235995bfdabaab149b4cba2cb7cc | 6,744 |
def set_incident_seen(incident, user=None):
"""
Updates the incident to be seen
"""
is_org_member = incident.organization.has_access(user)
if is_org_member:
is_project_member = False
for incident_project in IncidentProject.objects.filter(incident=incident).select_related(
... | 8b970ec492bdb72b6e05c053f7a5b9bf919b15e7 | 6,745 |
def single_parity_check(
llr: np.array,
mask_steps: int = 0,
last_chunk_type: int = 0,
) -> np.array:
"""Compute beta value for Single parity node."""
all_sign = np.sign(np.prod(llr))
abs_alpha = np.fabs(llr)
first_min_idx, second_min_idx = np.argsort(abs_alpha)[:2]
result =... | 5cc9984bb86fdfd777b2a968fb887388a5422e4f | 6,746 |
def _deserialize_job_result(user_input: JSON) -> JobResult:
"""Deserialize a JobResult from JSON."""
job = _deserialize_job(user_input['job'])
plan = _deserialize_plan(user_input['plan'])
is_done = user_input['is_done']
outputs = dict() # type: Dict[str, Asset]
for name, asset in user_input['... | 883629fa2650fc043124c6ccf721ed38093daa19 | 6,747 |
def _brute_force_knn(X, centers, k, return_distance=True):
"""
:param X: array of shape=(n_samples, n_features)
:param centers: array of shape=(n_centers, n_features)
:param k: int, only looking for the nearest k points to each center.
:param return_distance: bool, if True the return the distance al... | b185a8d9e901a12a1385ed5ffc3183a5cc51c1b5 | 6,748 |
def remove_rule(rule_id):
"""Remove a single rule"""
ruleset = packetfilter.get_ruleset()
ruleset.remove(rule_id)
packetfilter.load_ruleset(ruleset)
save_pfconf(packetfilter)
return redirect(url_for('rules', message=PFWEB_ALERT_SUCCESS_DEL), code=302) | fe45a3d5af532ff67e8aef21ab093438818c6dbc | 6,749 |
def HexToMPDecimal(hex_chars):
""" Convert bytes to an MPDecimal string. Example \x00 -> "aa"
This gives us the AppID for a chrome extension.
"""
result = ''
base = ord('a')
for i in xrange(len(hex_chars)):
value = ord(hex_chars[i])
dig1 = value / 16
dig2 = value % 16
result += chr(dig1 ... | 5d81c0e1ee3f4f94e615578e132377b803beb47b | 6,750 |
def fit_growth_curves(input_file, file_data_frame, file_data_units,
condition_unit, time_unit, cell_density_unit):
"""
:Authors:
Chuankai Cheng <chuankai@usc.edu> and J. Cameron Thrash <thrash@usc.edu>
:License:
MIT
:Version:
1.0
:Date:
2021-03-17
:Repository: https://github.com/t... | d551a094ea398e09dcc88f8f9668922b3e665317 | 6,751 |
def stringify(li,delimiter):
""" Converts list entries to strings and joins with delimiter."""
string_list = map(str,li)
return delimiter.join(string_list) | a4c35a19d8ea654a802cd3f92ababcbdfdf0ecfb | 6,752 |
def norm_w(x, w):
"""
Compute sum_i( w[i] * |x[i]| ).
See p. 7.
"""
return (w * abs(x)).sum() | a9825750cb6ee0bbbe87b0c4d1bd132bcfca90db | 6,753 |
def _tensor_run_opt_ext(opt, momentum, learning_rate, gradient, weight, moment):
"""Apply momentum optimizer to the weight parameter using Tensor."""
success = True
success = F.depend(success, opt(weight, moment, learning_rate, gradient, momentum))
return success | 89ae490ba0f05455dff03bcd57d4b6f52f7d8327 | 6,754 |
from typing import Dict
import yaml
def get_config_settings(env: str = "dev") -> Dict:
"""
Retrieves configuration from YAML file
"""
config_fh = construct_config_path(env)
with open(config_fh, "r") as f:
data = yaml.safe_load(f)
return data | 190a7f8cb2a297ee4ae6d5734d4d9f521a18bb3f | 6,755 |
def get_all(connection: ApiConnection, config: str, section: str = None) -> dict:
"""Get all sections of a config or all values of a section.
:param connection:
:param config:UCI config name
:param section:[optional] UCI section name
:return: JSON RPC response result
"""
return request(conne... | be4a76f87398ce1d4e0765314266647867964e39 | 6,756 |
def load_module(module, app):
"""Load an object from a Python module
In:
- ``module`` -- name of the module
- ``app`` -- name of the object to load
Return:
- (the object, None)
"""
r = __import__(module, fromlist=('',))
if app is not None:
r = getattr(r, app)
re... | 858d9d0bf91ff7d83ad391218b8ff1b37007b43b | 6,757 |
def get_routes(app: web.Application) -> list:
"""
Get the full list of defined routes
"""
return get_standard_routes(app) + get_custom_routes(app) | 7f5d365c28ee45096e089ee6913d3aec4d8214d8 | 6,758 |
def cb_round(series: pd.Series, base: Number = 5, sig_dec: int = 0):
""" Returns the pandas series (or column) with values rounded per the
custom base value
Args:
series (pd.Series): data to be rounded
base (float): base value to which data should be rounded (may be
deci... | 29599898fa8686c260e89d2efcdcceec108d5b4c | 6,759 |
def makeGaussian(size, sigma=3, center=None):
""" Make a square gaussian kernel.
size is the length of a side of the square
fwhm is full-width-half-maximum, which
can be thought of as an effective radius.
"""
x = np.arange(0, size, 1, float)
y = x[:, np.newaxis]
if center is None:
x0 = y0 = size ... | 8efef3cc265375d5412107a465a97380e8c4d101 | 6,760 |
import torch
def average_relative_error(y_pred, y_true):
"""Calculate Average Relative Error
Args:
y_true (array-like): np.ndarray or torch.Tensor of dimension N x d with actual values
y_pred (array-like): np.ndarray or torch.Tensor of dimension N x d with predicted values
Returns:
... | 2243eb82c78ff03181be3c10d50c3aa000e8476c | 6,761 |
from unittest.mock import Mock
def make_subprocess_hook_mock(exit_code: int, output: str) -> Mock:
"""Mock a SubprocessHook factory object for use in testing.
This mock allows us to validate that the RenvOperator is executing
subprocess commands as expected without running them for real.
"""
resu... | a047608503be8bc7fc4b782139e7d12145efb3cd | 6,762 |
def binstr2int(bin_str: str) -> int:
"""转换二进制形式的字符串为10进制数字, 和int2binstr相反
Args:
bin_str: 二进制字符串, 比如: '0b0011'或'0011'
Returns:
转换后的10进制整数
"""
return int(bin_str, 2) | 87c6ac16c2215e533cb407407bef926ed8668e3e | 6,763 |
def _nodeset_compare(compare, a, b, relational=False):
"""
Applies a comparison function to node-sets a and b
in order to evaluate equality (=, !=) and relational (<, <=, >=, >)
expressions in which both objects to be compared are node-sets.
Returns an XPath boolean indicating the result of the com... | 5751b793662689a1e0073cfe5fc4b86505952dcd | 6,764 |
def test_cl_shift(options):
"""
Create tests for centerline shifts
8 out of 8 points are on one side of the mean
>= 10 out of 11 points are on one side of the mean
>= 12 out of 14 points are on one side of the mean
>= 14 out of 17 points are on one side of the mean
>= 16 out of 20 points ar... | 60d874c8b1484ff23c4791043eae949912a969d0 | 6,765 |
def _scale(tensor):
"""Scale a tensor based on min and max of each example and channel
Resulting tensor has range (-1, 1).
Parameters
----------
tensor : torch.Tensor or torch.autograd.Variable
Tensor to scale of shape BxCxHxW
Returns
-------
Tuple (scaled_tensor, min, max), where min and max ar... | 64eed9bd70c543def6456f3af89fa588ec35bca8 | 6,766 |
def get_moscow_oh(opening_hours):
"""
returns an OpeningHourBlock from a fake json
corresponding to a POI located in moscow city
for different opening_hours formats.
"""
return get_oh_block(opening_hours, lat=55.748, lon=37.588, country_code="RU") | 42f795e262753cc82d8689c2a98e6a82e143a2c3 | 6,767 |
def get_firebase_credential_errors(credentials: str):
""" Wrapper to get error strings for test_firebase_credential_errors because otherwise the
code is gross. Returns None if no errors occurred. """
try:
test_firebase_credential_errors(credentials)
return None
except Exception as e... | fbca79e837a3d6dc85ee90bfd426008c6ce25ac2 | 6,768 |
def url(endpoint, path):
"""append the provided path to the endpoint to build an url"""
return f"{endpoint.rstrip('/')}/{path}" | dee733845984bfc4cf5728e9614cce08d19a2936 | 6,769 |
def is_collision(line_seg1, line_seg2):
"""
Checks for a collision between line segments p1(x1, y1) -> q1(x2, y2)
and p2(x3, y3) -> q2(x4, y4)
"""
def on_segment(p1, p2, p3):
if (p2[0] <= max(p1[0], p3[0])) & (p2[0] >= min(p1[0], p3[0])) & (p2[1] <= max(p1[1], p3[1])) & (p2[1] >= min(p1[1],... | 17dba61faebe50336cbc2cd2cc56c49474db5431 | 6,770 |
import numpy
def plot_bar_graph_one_time(
example_table_xarray, time_index, predictor_indices, info_string=None,
figure_object=None, axes_object=None):
"""Plots predictors at one time as bar graph.
:param example_table_xarray: xarray table in format returned by
`example_io.read_file`.... | 5b1faab11bd6e79bd617ca23a8f49aeb83de2aae | 6,771 |
def reshape_nda_to_2d(arr) :
"""Reshape np.array to 2-d
"""
sh = arr.shape
if len(sh)<3 : return arr
arr.shape = (arr.size/sh[-1], sh[-1])
return arr | 11c721b938e45fd07d2ed1674a569e6836913ff3 | 6,772 |
async def async_setup(hass, config):
"""Initialize the DuckDNS component."""
domain = config[DOMAIN][CONF_DOMAIN]
token = config[DOMAIN][CONF_ACCESS_TOKEN]
session = async_get_clientsession(hass)
result = await _update_duckdns(session, domain, token)
if not result:
return False
as... | 7208d0a25b219b6decbae314618e219705224a5a | 6,773 |
def mock_signal(*args):
"""Mock creation of a binary signal array.
:return: binary array
:rtype: np.ndarray
"""
signal = np.array([1, 0, 1])
return signal | ebeb1f40a43c2c51d941208da78e0bfc0acb6530 | 6,774 |
def matmul(a, b):
"""np.matmul defaults to bfloat16, but this helper function doesn't."""
return np.matmul(a, b, precision=jax.lax.Precision.HIGHEST) | a4efb25933a25067b0b37ada8271f09b76929cb8 | 6,775 |
from pathlib import Path
def find_preard(path, metadata_pattern='*.json'):
""" Match pre-ARD metadata with imagery in some location
Parameters
----------
path : str or Path
Path to a metadata file or directory of files (returning matches
inside the directory)
metadata_pattern : st... | 9c23ed7308a95cb1f525f9604bf01a4bf9fc5e5d | 6,776 |
def predictions(logit_1, logit_2, logit_3, logit_4, logit_5):
"""Converts predictions into understandable format.
For example correct prediction for 2 will be > [2,10,10,10,10]
"""
first_digits = np.argmax(logit_1, axis=1)
second_digits = np.argmax(logit_2, axis=1)
third_digits = np.argmax(logit... | 99e22cc4808634e6510196f2e9e79cba9dafd61c | 6,777 |
def execute_parent(parent_path, child_path, input_tensor_npy, return_full_ctx=False):
"""Execute parent model containing a single StreamingDataflowPartition by
replacing it with the model at child_path and return result."""
parent_model = load_test_checkpoint_or_skip(parent_path)
iname = parent_model.g... | 2757d22c46ee89f34cc89c702393d4a42d275c28 | 6,778 |
import os
def find_program(prog, paths):
"""Finds the specified program in env PATH, or tries a set of paths """
loc = spawn.find_executable(prog)
if(loc != None):
return loc
for loc in paths:
p = os.path.join(loc, prog)
if os.path.exists(p):
return p
return ... | 77c483ac139a1c555b6b9ca897663567fd59da3d | 6,779 |
def fibonacci(position):
"""
Based on a position returns the number in the Fibonacci sequence
on that position
"""
if position == 0:
return 0
elif position == 1:
return 1
return fibonacci(position-1)+fibonacci(position-2) | cc4fe0860fa97234ead2179e18d208a8567e0cb3 | 6,780 |
def visualize_gebco(source, band, min=None, max=None):
"""
Specialized function to visualize GEBCO data
:param source: String, Google Earth Engine image id
:param band: String, band of image to visualize
:return: Dictionary
"""
data_params = deepcopy(DATASETS_VIS[source]) # prevent mutation... | ccd382f1e1ede4cbe58bca6fc7eec15aa1b0a85a | 6,781 |
import sys
def show():
""" Send values for turning pixels on """
if not available:
return 2
else:
lockBus()
try:
bus.write_byte(arduinoAddress, 0x06)
except:
errorMsg = sys.exc_info()[0]
errorHandler(5, errorMsg)
unlockBus() | 1da6b710a38349de282e9307d3638a220473e32f | 6,782 |
import asyncio
import functools
def bound_concurrency(size):
"""Decorator to limit concurrency on coroutine calls"""
sem = asyncio.Semaphore(size)
def decorator(func):
"""Actual decorator"""
@functools.wraps(func)
async def wrapper(*args, **kwargs):
"""Wrapper"""
... | 030e4dea0efccf9d5f2cbe4a40f3e6f32dfef846 | 6,783 |
import socket
def _download_file(url, required_length, STRICT_REQUIRED_LENGTH=True):
"""
<Purpose>
Given the url, hashes and length of the desired file, this function
opens a connection to 'url' and downloads the file while ensuring its
length and hashes match 'required_hashes' and 'required_length'.... | a9df32371f24a85971807354636621224fc8f7bd | 6,784 |
def tune_speed_librosa(src=None, sr=_sr, rate=1., out_type=np.ndarray):
"""
变语速
:param src:
:param rate:
:return:
"""
wav = anything2wav(src, sr=sr)
spec = librosa.stft(wav)
spec = zoom(spec.T, rate=1 / rate, is_same=0).T
out = librosa.istft(spec)
# out = librosa.griffinlim(s... | 423b83c6a266e8ee2b259bf3497e53ff2087ca44 | 6,785 |
import pathlib
def fqn_from_file(java_filepath: pathlib.Path) -> str:
"""Extract the expected fully qualified class name for the given java file.
Args:
java_filepath: Path to a .java file.
"""
if not java_filepath.suffix == ".java":
raise ValueError("{} not a path to a .java file".for... | cb1d515af968c1653d31f0529ce40fa6241cf1f4 | 6,786 |
def assert_raises(*args, **kwargs):
"""Assert an exception is raised as a context manager or by passing in a
callable and its arguments.
As a context manager:
>>> with assert_raises(Exception):
... raise Exception
Pass in a callable:
>>> def raise_exception(arg, kwarg=None):
... ... | 6ef00a131f6ce5192e88fe9bab34f5cd04dd5a8a | 6,787 |
import click
def proxy(ctx, control, host, port, socket, proxy):
"""Settings to configure the connection to a Tor node acting as proxy."""
if control == 'port':
if host is None or port is None:
raise click.BadOptionUsage(
option_name='control',
message=f"--... | 4fe25cb7dc38116e26fe61b43e3903908e098459 | 6,788 |
import gzip
def get_gzip_uncompressed_file_size(file_name):
"""
this function will return the uncompressed size of a gzip file
similar as gzip -l file_name
"""
file_obj = gzip.open(file_name, 'r')
file_obj.seek(-8, 2)
# crc32 = gzip.read32(file_obj)
isize = gzip.read32(file_obj)
re... | bf1e40a83098fa32c95959e28069e4a4d4dcc2d7 | 6,789 |
def Capitalize(v):
"""Capitalise a string.
>>> s = Schema(Capitalize)
>>> s('hello world')
'Hello world'
"""
return str(v).capitalize() | 9072ea91b946694bbb1410fb10a5b1b1f5cdd7c2 | 6,790 |
def pg_index_exists(conn, schema_name: str, table_name: str, index_name: str) -> bool:
"""
Does a postgres index exist?
Unlike pg_exists(), we don't need heightened permissions on the table.
So, for example, Explorer's limited-permission user can check agdc/ODC tables
that it doesn't own.
"""
... | 98ebdc0db7f3e42050e61205fd17309d015352a0 | 6,791 |
def create_mock_data(bundle_name: str,
user_params: dict):
"""
create some mock data and push to S3 bucket
:param bundle_name: str, bundle name
:param user_params: dict, what parameters to save
:return:
"""
api.context(context_name)
api.remote(context_name, remote_co... | 0fd377eac24555306aceff26a61d4a2b4666d33d | 6,792 |
def _vertex_arrays_to_list(x_coords_metres, y_coords_metres):
"""Converts set of vertices from two arrays to one list.
V = number of vertices
:param x_coords_metres: length-V numpy array of x-coordinates.
:param y_coords_metres: length-V numpy array of y-coordinates.
:return: vertex_list_xy_metres... | ef5bed973f684670f979f6cdb0fcfc38b45a4557 | 6,793 |
from typing import Optional
from typing import Dict
from typing import Any
def info_from_apiKeyAuth(token: str, required_scopes) -> Optional[Dict[str, Any]]:
"""
Check and retrieve authentication information from an API key.
Returned value will be passed in 'token_info' parameter of your operation functi... | 29fec65450780e14dfc94979ba2fb73c00d2a4bf | 6,794 |
from datetime import datetime
def convert_unix2dt(series):
"""
Parameters
----------
series : column from pandas dataframe in UNIX microsecond formatting
Returns
-------
timestamp_dt : series in date-time format
"""
if (len(series) == 1):
unix_s = series/1000
else: ... | 92b912ba85b123e9f368b3613bff4a374826130a | 6,795 |
from volapi import Room
import sys
import time
def main():
"""Program, kok"""
args = parse_args()
if args.bind:
override_socket(args.bind)
try:
check_update()
except Exception as ex:
print("Failed to check for new version:", ex,
file=sys.stderr, flush=True)... | a9ffc9d47c78f49e11ec166d2b1552875a4c5244 | 6,796 |
import re
def sentence_segment(text, delimiters=('?', '?', '!', '!', '。', ';', '……', '…'), include_symbols=True):
"""
Sentence segmentation
:param text: query
:param delimiters: set
:param include_symbols: bool
:return: list(word, idx)
"""
result = []
delimiters = set([item for ite... | c8860a872e779873330eaded8e9951cabdbba01e | 6,797 |
def time_rep_song_to_16th_note_grid(time_rep_song):
"""
Transform the time_rep_song into an array of 16th note with pitches in the onsets
[[60,4],[62,2],[60,2]] -> [60,0,0,0,62,0,60,0]
"""
grid_16th = []
for pair_p_t in time_rep_song:
grid_16th.extend([pair_p_t[0]] + [0 for _ in range(pair_p_t[1]-1)])
retur... | 8986819bd39ae4830d04bf40ab158d310bb45485 | 6,798 |
def _double_threshold(x, high_thres, low_thres, n_connect=1, return_arr=True):
"""_double_threshold
Computes a double threshold over the input array
:param x: input array, needs to be 1d
:param high_thres: High threshold over the array
:param low_thres: Low threshold over the array
:param n_con... | 74a34ed39336c35dfc7eb954af12bb30b3089609 | 6,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.