content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def torch_vad(sig, winLen=400, winSht=160, ener_thres=5.7,
mean_scale=0.5, prop_thres=0.12, frm_context=2,
twice_log_max_signed_int16=20.794354380710768,
eps=1.19209e-07):
""" Equivalent to KALDI's energy-based VAD implementation
(https://github.com/kaldi-asr/kaldi/... | 85b935c6842f82f411c7d1a0c967d8753cb38b29 | 3,613,021 |
async def create_sync_payload(dc, key):
"""Converts dictionary to JSON, encrypts it with provided public key (PEM)
and returns it as a Base64-encoded string.
"""
return await _run_async(_create_sync_payload, dc, key) | dec64b2a8f2bb81a6cc82a4c419adbf0f21bca3e | 3,613,022 |
def graph_to_xarray(graph):
"""
Convert a hetnetpy.hetnet.Graph to an xarray.Dataset
"""
data_vars = dict()
for metaedge in graph.metagraph.get_edges(exclude_inverts=True):
data_array = metaedge_to_data_array(graph, metaedge)
name = metaedge.get_abbrev()
data_vars[name] = dat... | 3540f30651bb5b98dc18eb793574c7c5259d603c | 3,613,024 |
def get_shared_segments(poly1, poly2, bool_ret=False):
"""Returns the line segments in common to both polygons.
Parameters
----------
poly1 : libpysal.cg.Polygon
A Polygon.
poly2 : libpysal.cg.Polygon
A Polygon.
bool_ret : bool
Return only a ``bool``. Default is ``False`... | 7e3305b7d5c9bbade0a86d32c060c2f54bd05992 | 3,613,025 |
def get_latest_resources_asset(name):
"""
Searches through hazm's releases and find latest release that contains
resources.
Parameters
----------
name: str
The resource name
Returns
-------
asset: GitReleaseAsset
The resources asset
"""
g = Github()
repo... | ef9b3f450441cf2b6527b9ad6241cae59d3e472b | 3,613,026 |
def conv1x1_1bit(in_channels,
out_channels,
stride=1,
groups=1,
bias=False,
binarized=False):
"""
Convolution 1x1 layer with binarization.
Parameters:
----------
in_channels : int
Number of input channels.
... | a949c3b86f1331492e183528628a6ed2e13ff189 | 3,613,027 |
def get_vec_by_query(text):
"""提取文本向量
"""
token_ids, segment_ids = tokenizer.encode(text, max_length=maxlen)
# print("token_ids={},segment_ids={}".format(token_ids, segment_ids))
vec = encoder.predict([[token_ids], [segment_ids]])[0]
# print('vec size={}, element={}'.format(len(vec), vec[-1]))
... | 0f6f531344a79e169482975ebf35ac43304bcfad | 3,613,028 |
def serving_input_receiver_fn():
"""An input function for TensorFlow Serving."""
def _preprocess_image(image_bytes):
"""Preprocess a single raw image."""
image = tf.image.decode_jpeg(image_bytes, channels=IMG_CHANNEL)
image.set_shape((None, None, IMG_CHANNEL))
image = tf.image.r... | 47c6cc3056455a68be484fac114889943d04debe | 3,613,029 |
def _process_optimization_results(results, results_arguments):
"""Expand the solutions back to the original problems.
Args:
results (list):
list of dictionaries with the harmonized results objects.
results_arguments (list):
each element is a dictionary supplying the star... | 64a74f22d5391c88fb0fdccc3c7d610c4e67f928 | 3,613,030 |
def is_valid_continuous_partition_object(partition_object):
"""Tests whether a given object is a valid continuous partition object.
:param partition_object: The partition_object to evaluate
:return: Boolean
"""
if (partition_object is None) or ("weights" not in partition_object) or ("bins" not in pa... | b1576c909a9e09db35362aff1e00ef69cf33be02 | 3,613,031 |
def get(
hostname,
refresh_key,
authorization_host,
org_id,
sddc_id,
tier1,
nat,
verify_ssl=True,
cert=None,
cursor=None,
page_size=None,
sort_by=None,
sort_ascending=None,
):
"""
Retrieves nat rules for Given SDDC
CLI Example:
.. code-block:: bash
... | 2fac63ca341a3f6589444daeddad79ba99c832aa | 3,613,032 |
from typing import Optional
from typing import Callable
def add_fiber_array(
component: Component,
grating_coupler: Component = grating_coupler_te,
gc_port_name: str = "W0",
component_name: Optional[str] = None,
taper_factory: Callable = taper,
taper_length: float = 10.0,
get_route_factory... | de2a99ca12f28debc321a855b8adb894ba457672 | 3,613,033 |
def run(prefix, items, timestamp, delta, output_path=None, creation_dir=None, parent_dir_name="logs", silent=False, interactive=False):
""" collects log items and creates an archive with all collected items.
items is a list of instances of 'Item' subclasses (see the collectables submodule).
timestamp and de... | 01368171994e097d7034bc9b31bd0c433d46d5e8 | 3,613,034 |
def get_instruments(instruments, level):
"""Returns a list of themis instruments for L2 data"""
if level == 'l1':
instr_list = ['bau', 'eff', 'efp', 'efw', 'esa', 'fbk', 'fff_16',
'fff_32', 'fff_64', 'ffp_16', 'ffp_32', 'ffp_64',
'ffw_16', 'ffw_32', 'ffw_64', ... | b797856b35f72eb34fa2d23a2e8d5ff7ade77516 | 3,613,035 |
def add_release(
target_name,
target_resource_group,
remote_url=None,
remote_branch=None,
remote_access_token=None,
vsts_account_name=None,
vsts_project_name=None,
registry_resource_id=None,
registry_name=None):
"""
Creates a build definiti... | 9365757705cd2244b754d9a3d31e71652e3e0d07 | 3,613,036 |
def connect():
"""initialize a connection to a mysql db on a local host server """
try:
return mysql.connect(
host="127.0.0.1",
port="3306",
user="root",
password=ROOT_PASSWORD
, auth_plugin='mysql_native_password',
database="sales"... | e44a386670720922488a6ee2556ac13966e90d82 | 3,613,037 |
def scatter(x, y, z, color=default_color, size=default_size,
size_selected=default_size_selected,
color_selected=default_color_selected, marker="diamond",
selection=None, grow_limits=True, **kwargs):
"""Plots many markers/symbols in 3d
:param x: {x}
:param y: {y}
:pa... | 872d90ff1dfffbe80db8eb53af1469f96297675f | 3,613,038 |
def create_openapi_spec(app: falcon.API) -> APISpec:
"""Creates an OpenAPI Spec for the Sustainerds API"""
spec = APISpec(
title="Sustainerds API",
version="1.0.0",
openapi_version="3.0.0",
plugins=[MarshmallowPlugin()],
)
return spec | 1b5db71cc6266fd108a5138df559802ccae92dda | 3,613,039 |
def trigger_oauth_expires_delete(identity):
""" Delete a specific trigger identity for trigger bunq_oauth_expires """
# We don't store trigger identities, so this call can be ignored
return "" | 355084d71efc7789335b7f0ca15e90165a2b5e26 | 3,613,040 |
def bibTex_abs_format_export_post():
"""
:return:
"""
results, status = export_post(request, 'BibTex Abs')
if status == 200:
maxauthor, keyformat, authorcutoff, journalformat = export_post_extras(request, 'BibTex Abs')
return return_bibTex_format_export(solr_data=results, include_ab... | 8d6a37504c8c5a51af2db18ce210e15f1d245b83 | 3,613,041 |
def ligands_rmsd_calculator(pdb_target, pdb_reference, resname="GRW"):
"""
:param pdb_target: problem pdb file
:param pdb_reference: reference pdb file
:param write2report: if True export results in a file
:param write2pdb: pdb file with the result of the superposition between "pdb_target" and "pdb... | 9cd18c0d6413fc18a6d558cdea4f98af3259acdf | 3,613,042 |
def knn_points_idx(p1, p2, K, sorted=False, version=-1):
"""
K-Nearest neighbors on point clouds.
Args:
p1: Tensor of shape (N, P1, D) giving a batch of point clouds, each
containing P1 points of dimension D.
p2: Tensor of shape (N, P2, D) giving a batch of point clouds, each
... | 8243f48bbe2c8c0c54f88d9fe04e6d541584e7be | 3,613,043 |
def modularity_individual(individual, graph: igraph.Graph):
"""
Decode an individual into a community membership vector and
calculates the modularity of the individual community set.
"""
members = decode(individual)
try:
return graph.modularity(members)
except igraph.InternalError as... | 9f9b8a341ad7012ac77d89316d01d74f8fa2f75a | 3,613,044 |
def api_get_challenge_detail(challengeID: int):
"""
查询挑战详情
{
"name":"名称",
"id":ID,
"description":描述,
"level":等级,
"hasFinished":是否完成
"problemsetList":[
{
"name":"名称",
"hasFinished":"是否完成",
"id":"ID"
... | 149c746dfcb1b593cea078dfa594557b54e6633a | 3,613,045 |
def superop2chi(superop: np.ndarray) -> np.ndarray:
"""
Converts a superoperator into a list of Kraus operators.
Operators with small norm may be excluded.
:param superop: a dim**2 by dim**2 superoperator
:return: a dim**2 by dim**2 process matrix
"""
return kraus2chi(superop2kraus(superop... | ab7c60b927225ba002011d8b6f02d5d82208c7cb | 3,613,046 |
def is_instation(stmt):
"""Check whether the statement is an 'instance' or
'instance-list' definition
"""
return is_instance(stmt) or is_instance_list(stmt) | 172d592c7bf2beca1a46cfa4b86206a1824032e3 | 3,613,047 |
def check_multigene(overlaps, min_overlap_bp=0, min_query_overlap=0, min_gene_overlap=.5):
"""
overlaps is a list of: (gene, overlap_bp, overlap_gene_ratio, overlap_query_ratio)
"""
if all(x[1]>=min_overlap_bp and x[2]>=min_gene_overlap and x[3]>=min_query_overlap for x in overlaps):
new_name = ... | 5f7c3ba7231939e2e54ce236a79025952d5e9a84 | 3,613,048 |
def unpickle():
"""Unpickle the bot token"""
with open('token.pickle', 'rb') as file:
token = pik(file)
return token | 3246a7da2d7257fa35cc6de78deabc726a1155e8 | 3,613,049 |
def calcInertiaTensor(coords):
""""Calculate inertia tensor from coords"""
coords = getCoords(coords)
center = calcCenter(coords)
coords = coords - center
return dot(coords.transpose(), coords) | a16376078bb85c8e18f455df08d741b07171e287 | 3,613,050 |
from typing import Optional
from typing import Set
from typing import Callable
def auto_eq(only: Optional[Set[str]] = None, exclude: Optional[Callable[[str], bool]] = None):
"""
Decorator.
Auto-adds a __hash__ function by hashing its attributes.
:param only: Only include these attributes
:param exclude: Exclude ... | 0278531c2b572754581310629f4c805e06cd8ee2 | 3,613,051 |
import tempfile
def AddLoggingParent(android_manifest, logging_parent_value):
"""Add logging parent as an additional <meta-data> tag.
Args:
android_manifest: A string representing AndroidManifest.xml
logging_parent_value: A string representing the logging
parent value.
Raises:
RuntimeError: I... | 6cd03b7dae970ea58a8493f3047ec77748724776 | 3,613,052 |
def replace_nans_binmean(d, by, aggreagation="mean"):
""""Replace each NaN value in `d` by the mean in each bin when grouping by `by`."""
return d.where(~np.isnan(d), mean_per_bin(d, by, aggreagation=aggreagation)) | 4d24e58c04ee44d90a5e9820fa942cf244c28059 | 3,613,053 |
from typing import Sequence
def repeatAndVarySequence(seq, poss, channels, names, args, iters):
"""
Repeat a sequence and vary part(s) of it. Returns a new sequence.
Given N specifications of M steps, N parameters are varied in M
steps.
Args:
seq (Sequence): The sequence to be repeated.
... | 481f8f2765398362757f88fa10a42dd81066e252 | 3,613,054 |
def conv_bn(inp, oup, stride):
"""
:param inp:
:param oup:
:param stride:
:return:
"""
return nn.Sequential(
nn.Conv2d(inp, oup, 3, stride, 1, bias=False),
nn.BatchNorm2d(oup),
#nn.ReLU6(inplace=True),
nn.ReLU(inplace=True)
) | cbe7326aba5d2d7508deebfcd531a5c2d593ce3e | 3,613,055 |
from re import T
def normalize(x, axis=-1, mean=None, variance=None, epsilon=1e-5):
"""Normalizes an array by subtracting mean and dividing by sqrt(var)."""
if mean is None:
mean = T.mean(x, axis, keepdims=True)
if variance is None:
# this definition is traditionally seen as less accurate ... | 2804df3370d92d32c13a87aaf647cd2a951f9087 | 3,613,056 |
def _get_restart_standard_names(restart_properties: RestartProperties = None):
"""Return a list of variable names needed for a smooth restart. By default uses
restart_properties from RESTART_PROPERTIES."""
if restart_properties is None:
restart_properties = RESTART_PROPERTIES
return_dict = {}
... | 8e45f22c7305160e29799a9480a9a35a9da81c82 | 3,613,057 |
import json
async def portfolio_style_report(folio_id, request, *,factor_code=""):
"""
:param folio_id:
:param request:
:return:
{
'T': 290,
'rolling_reg': [[{
'month': 7,
'day': 25,
'year': 2017
}, {
'crisk': [0.2244239767675... | 658ef0dd99fcdf4cad6652d3404bf43dae86df41 | 3,613,058 |
def flatten(l, types=(list, )):
"""
Given a list/tuple that potentially contains nested lists/tuples of arbitrary nesting,
flatten into a single dimension. In other words, turn [(5, 6, [8, 3]), 2, [2, 1, (3, 4)]]
into [5, 6, 8, 3, 2, 2, 1, 3, 4]
This is safe to call on something not a list/tuple -... | 5bdffb984fcd2614e4e71f19353b3d277dea368e | 3,613,059 |
def bitwise_or(rasters, extent_type="FirstOf", cellsize_type="FirstOf", astype=None):
"""
The BitwiseOr operation
The arguments for this function are as follows:
:param rasters: array of rasters. If a scalar is needed for the operation, the scalar can be a double or string
:param extent_type: one ... | ecaf7522c8943259d9b4d43b446cf77762c8de83 | 3,613,060 |
import scipy
import math
def Theory_Algebraic(N,Kappa,d) :
"""
Theoretical approximation for the algebraic connectivity
of periodic RGGs
Parameters
-----------
N : int
Network size
Kappa : float
Expected mean degree of the ensemble
d: int
Dimension of the embedding space
Returns
---------
Mu... | 3229d3bc0990207d70464ef33cf37f51debcfd00 | 3,613,061 |
def define_passes(ext_val):
"""
Overwrite function based depending on enum flag.
:param ext_val:
:return:
"""
if ext_val in [EXTENSIONS.CGINC, EXTENSIONS.GLSLINC, EXTENSIONS.SHADER]:
return format_write_cginc_first
elif ext_val in [EXTENSIONS.CS]:
return format_write_cs_first... | 3a1eba7e9983e60fcce74e243ce20e58dcea4e8b | 3,613,062 |
def get_path_prefix(path):
"""
gets path_prefixe given path
"""
temp_path=list(filter(None, path.split("/")))
j=0
path_prefix=[]
for node in temp_path:
path_prefix.append([node])
return path_prefix | 728c019d842c3b5bf7c6f6b8cebf13a1ad90bd41 | 3,613,063 |
from typing import Any
def test_pull_request_exists(monkeypatch: MonkeyPatch, branch: str) -> None:
"""It matches the branch in the process output."""
def stub(*args: Any, **kwargs: Any) -> Any:
return pretend.stub(stdout="topic")
with monkeypatch.context() as m:
m.setattr("subprocess.ru... | 2dc808e1127a7ec2fe4ca7506528e5a4819ae06a | 3,613,064 |
def classify_image(interpreter, image, top_k=1):
""" return a sorted array of classification results """
set_input_tensor(interpreter, image)
interpreter.invoke()
output_details = interpreter.get_output_details()[0]
output = np.squeeze(interpreter.get_tensor(output_details['index']))
# if model... | 212968b55e48517fec376b247cd09439545e0e14 | 3,613,065 |
import math
def occupancy_to_color(occupancy):
"""
Return corresponding color from blue to red spectrum
"""
# color = [255*(1-isoval), 255*(1-isoval), 255] # white to blue
# color = [255*isoval, 0, 255*(1-isoval)] # blue to red
color = "gray" + str(int(math.floor((1-occupancy)*100))).zfill(2)
if(color == "g... | 838a6025c473b51dab6c38c28f70ba7bafed3071 | 3,613,066 |
def reshape(a):
"""Combine the last two dimensions of a numpy array"""
all_head_size = a.shape[-2] * a.shape[-1]
new_shape = a.shape[:-2] + (all_head_size,)
return a.reshape(new_shape) | 7381657c14b8b9245af2d85c1d1b7a0f5d40fff8 | 3,613,068 |
import torch
def encode_selection(selection: SelectionNode, db: Database) -> EncodedSelection:
"""
Encoding is a vector of:
-------------------------------------------------------------------------------
| *col | *rel | *hist | *freq | onehot dtype | op one hot | operand encoding |
... | 831aecc8737a304f5f3375c39ca3c1834cc90559 | 3,613,070 |
def dict_keys(this):
"""
Return PyIterable for Dict keys.
"""
return mkiterable(this.getvalue().keys()) | 1e4575f109019e5314d53075987fcd1cf85c426d | 3,613,071 |
def EMA2(df, n):
"""
线性加权移动平均 WMA
Args:
df (pandas.DataFrame): Dataframe格式的K线序列
n (int): 线性加权移动平均的周期
Returns:
pandas.DataFrame: 返回的DataFrame包含1列, 是"ema2", 代表计算出来的线性加权移动平均线
Example::
# 获取 CFFEX.IF1903 合约的线性加权移动平均线
from tqsdk import TqApi, TqSim
fro... | d658d9813a55e26f22fb1dcb0490c94edee1b7d4 | 3,613,072 |
import random
def pusher(obj_scale=None,
obj_mass=None,
obj_damping=None,
object_pos=(0.45, -0.05, -0.275),
distr_scale=None,
axisangle=(0, 0, 1, 1.5),
distr_mass=None,
distr_damping=None,
goal_pos=(0.45, -0.05, -0.3230),
... | 10db02142bfdbf95a9c548e6e98bb1ece0f393ca | 3,613,073 |
def create_from_pairs(pairs):
"""
Build graph from `pairs` of words.
Accumulate weight for the edges that appear multiple time
"""
DG = nx.DiGraph()
for (n1, n2, w) in pairs:
if DG.has_edge(n1, n2):
DG.edge[n1][n2]['weight'] = w
else:
DG.add_edge(n1, n2, {... | 8cd39dcbfabbddfc737e533afa3ec72c2d64095f | 3,613,074 |
def get_panelist_by_id(panelist_id: int):
"""Retrieve a panelist based on their ID"""
return panelists.get_panelist_by_id(panelist_id, database_connection) | 88ea2e420390fdf4972c1a8010905d8a7f33ff50 | 3,613,076 |
from apps.jsonapp import JSONApp
def main_json(config, in_metadata, out_metadata):
"""
Alternative main function
-------------
This function launches the app using configuration written in
two json files: config.json and input_metadata.json.
"""
# 1. Instantiate and launch the App
pri... | 9306c9877f0558f04b31693c0f1bd63422716b93 | 3,613,077 |
def new_figure_manager(*args, **kwargs):
"""Create a new figure manager instance."""
_warn_if_gui_out_of_main_thread()
return _backend_mod.new_figure_manager(*args, **kwargs) | bbef99f717cf2cb18622279c4b968d098505e75d | 3,613,078 |
def given(distribution: Series, **givens) -> Series:
"""
Condition the distribution on given and/or not-given values of the
variables.
:param distribution: The probability distribution to condition
e.g. P(A,B,C,D).
:param givens: Names and values of variables to condition o... | 2925671206004d4a3fc3fd4a4b782ff894a71cff | 3,613,079 |
def cosine_similiarity(vec_left, vec_right):
"""
余弦相似度
:param vec_left:
:param vec_right:
:return:
"""
num = np.dot(vec_left, vec_right)
denom = np.linalg.norm(vec_left) * np.linalg.norm(vec_right)
cos = -1 if denom == 0 else num / denom
return cos | a3eb01f3739f1faf4d1dd84c4260a755224e19a9 | 3,613,080 |
def albedo_diffuse_bubbly_ice(wavelengths, a, f, ni="p2016"):
"""compute diffuse albedo of pure ice without taking into account for the surface reflectance and
using the assymptotic radiative transfer theory
:param a: bubble radius (m)
:param f: is bubble fractional volume w/r to total volume (m3/m3).... | 91bf8a741c8c731fdc9113baa0372bac59f2d28a | 3,613,081 |
def reflectance(*reference):
"""Reference to a factbase resource describing reflectance.
Parameters
----------
*reference : :obj:`str`
Keys pointing to the metadata object describing the resource within the
reflectance category in the layout file of a factbase.
Returns
-------
:obj:`Cube... | 782e169afa080cbccaf83863869cda84a9fa27d6 | 3,613,083 |
import six
def get_validator_or_converter(name):
"""
Get a validator or converter by name
"""
if name == 'unicode':
return six.text_type
try:
v = get_validator(name)
return v
except UnknownValidator:
pass
raise SchemingException('validator/converter not foun... | 1635469ff793f98f01665af53c246c9b0af63801 | 3,613,084 |
def _d_sellmeier(b, c, lambda0):
"""
Calculate the first derivative (wrt wavelength) of the Sellmeier equation.
This is a private method.
Args:
b : array of three Sellmeier Coefficients [--]
c : array of three Sellmeier Coefficients [microns**2]
lambda0 : wavelength in vacuum... | 1c3431f8c6b5ae7cd95e5f7ca74ff09004f5a6d6 | 3,613,085 |
def is_running():
"""
Check JDB process state
"""
return jdb_process is not None and jdb_process.poll() is None | aeafa3ca9f925e91eedb9e327f3389134b5ac974 | 3,613,086 |
def get_non_us_city(location: str) -> str:
"""
Deals with two types of non-US locations:
"New Delhi (India)" and "Perth, Western Australia (Australia)"
:param location: geo location of the person
:return city
:raises LocatorException: could not infer the city name
"""
sep_idx = location.... | a7b69a8937141f7bff288d19bb92e41beb3a98c5 | 3,613,087 |
def row_to_top(df, index):
"""Bring row to top
Parameters
----------
df: pandas.dataframe
Dataframe to copy
index: int
Index of row to bring to top
Returns
-------
df_cp: pandas.dataframe
Copy of dataframe with specified row at top
"""
df_cp = pd.concat... | 519af78bb1a77debf69f23d4b6b6218d3c6087bb | 3,613,088 |
def init_cache(cname):
"""
Wipes and initializes a cache dir for container name `cname`.
"""
cache = abspath('.tmptest/test-kraken-integration/{cname}/cache'.format(cname=cname))
if os.path.exists(cache):
subprocess.check_call(['rm', '-rf', cache])
os.makedirs(cache)
os.chmod(cache, ... | 0f1b4a035b0a44e065a60ba9cce4699113f0dd9e | 3,613,089 |
def encodeMask(M):
"""
Encode binary mask M using run-length encoding.
:param M (bool 2D array) : binary mask to encode
:return: R (object RLE) : run-length encoding of binary mask
"""
[h, w] = M.shape
M = M.flatten(order='F')
N = len(M)
counts_list = []
pos = 0
# counts
counts_list.append(1)
diffs ... | bafe9ba42701d85fa3a572e86d0846a15fda067f | 3,613,090 |
def flatten_model_graph(ir_model: Model):
"""
Flatten the subgraph into root graph.
"""
def _flatten(graph: Graph):
"""
flatten this graph
"""
model = graph.model
node_to_remove = []
for node in graph.hidden_nodes:
node_graph = model.graphs.ge... | ebe7a0c1519914de3088b65481f3368457dbbe1b | 3,613,091 |
def get_cache():
"""returns the cache"""
return _cache | bb73c2f143bc2595085e63c028330b254f495464 | 3,613,092 |
def parse_message(message, nodata=False):
"""Parse df message from bytearray.
@message - message data
@nodata - do not load data
@return - [binary header, metadata, binary data]
"""
header = read_machine_header(message)
h_len = __get_machine_header_length(header)
meta_raw = message[h_l... | 9fbd2744e3c91e6db6ede20fd5bb50c84dbdc2e5 | 3,613,093 |
def reblock_array(df, nblocks, weights=None):
"""
Reblock df into nblocks new blocks
:param df: data to reblock
:type df: numpy array-like
:param nblocks: number of resulting blocks
:type nblocks: int
:param weights: weights used to average data
:type weights: array
:return: reblock... | 24adfe10ba1fbef5b7efb3d006a8e81be89d3f7a | 3,613,094 |
def B_measure(D, Cm, verbose=False):
"""
Computes the B measure for each network edge with infinite distance, thus not existing in the original Distance graph.
The formal definition is as follow:
.. math::
b_{ij} = <d_{ik}> / d_{ij}^m
b_{ji} = <d_{jk}> / d_{ij}^m
which is the average distance of all edges t... | 075ec0e4a3c50bd48cd8684317f63915c5eacc63 | 3,613,095 |
def count_paths_recursive(graph, node_val, target):
"""A more conventional recursive function (not a recursive generator)"""
if node_val >= target:
return 1
total = 0
for next_node in graph[node_val]:
total += count_paths_recursive(graph, next_node, target)
return total | be2aba80ed7dc734fb30f3b8b1a675d97e73c860 | 3,613,097 |
import re
def check_valency(mol):
"""
Checks that no atoms in the mol have exceeded their possible
valency
:return: True if no valency issues, False otherwise
"""
try:
Chem.SanitizeMol(mol, sanitizeOps=Chem.SanitizeFlags.SANITIZE_PROPERTIES)
return True, None
except ValueEr... | ebcbcb31b89aae27066f841495d2aa4930a74e04 | 3,613,098 |
import time
import yaml
def ensure_pod(ctx):
"""创建configmap"""
name = "kubectld-%s-u%s" % (ctx["source_cluster_id"], ctx["username_slug"])
name = name.lower()
k8s_client = K8SClient(ctx)
try:
pod = k8s_client.v1.read_namespaced_pod(name, namespace=constants.NAMESPACE)
if pod.stat... | a14dd0896e661d00ca088cdbf5a45e16ef47bd78 | 3,613,099 |
def lidar_to_camera(points, r_rect, velo2cam):
""" transformation from lidar coordinate to camera coordinate
:param points: non-homo coodinates [..., 3] or homogeneous coordinates [..., 4]
:param r_rect: [4, 4] camera rectification matrix
:param velo2cam: [4, 4] transformation from velo to camera
:... | 6f259ba6c81b7e2956937e62bbc99e07cdc071bf | 3,613,100 |
import jinja2
def _render(value, params):
"""Renders text, interpolating params."""
return str(jinja2.Template(value).render(params)) | b8d9698dfaf1c2500abfa272c8da98a0cf3dd482 | 3,613,101 |
def expand (properties):
""" Given a property set which may consist of composite and implicit
properties and combined subfeature values, returns an expanded,
normalized property set with all implicit features expressed
explicitly, all subfeature values individually expressed, and all
... | 2ea6eb3159414f04bdd8571ba3bdc63ea15400aa | 3,613,102 |
def login_required(f):
"""Redirects requests to /login if the user isn't authenticated"""
@wraps(f)
def decorated_function(*args, **kwargs):
user_id = session.get('user_id', None)
if user_id:
user = User.query.filter_by(id=user_id).one_or_none()
if user is not None:
... | 0e61a1e6e0da98a502e9ccc204d26da903003a64 | 3,613,103 |
def ClusterSetSslCert(mvip,
username,
password,
cert,
key):
"""
Set the SSL certificate used by the cluster
Args:
mvip: the management IP of the cluster
username: the admin user of the cluste... | b4f4794cec600ee887551a9cb489e2944d44110e | 3,613,104 |
def organization_daily_metrics_view(request):
"""
:param request:
:return:
"""
# admin, analytics_admin, partner_organization, political_data_manager, political_data_viewer, verified_volunteer
authority_required = {'verified_volunteer'}
if not voter_has_authority(request, authority_required)... | 512383e4987efd9c7e357c7363fd6f15b36d0794 | 3,613,105 |
def from_gen(
generator, n_iter, width, height, range, make_xy_proportional=False, log=False
):
"""Create a 2D histogram with `width * height` bins from `generator`.
The generator should be compiled using Numba's `njit` or `jit`.
Parameters
----------
generator : generator() -> x, y
A ... | 66018fcc0beb268ff2644ba5da01f104006b274f | 3,613,106 |
import math
def inWhichGrid(coord, grid_info):
"""
Specify which grid it is in for a given coordinate
:param coord: (latitude, longitude)
:param grid_info: grid_info dictionary
:return: row, column, grid ID
"""
lat, lng = coord
row = math.floor((grid_info['maxLat'] - lat) / grid_info['... | 260d31b57413902febf503ac3f7a11232940d245 | 3,613,107 |
def aup():
"""Send the user to Acceptable Use Policy page"""
# Read AUP from markdown dir
domain_name = domain_name_edgecase()
with open(
brand_dir + "/" + domain_name + "/signup_content/signup_modal.md", "r"
) as file:
aup_md = file.read()
return render_template("AUP.html", aup... | 96059408cf368fe00210b684f02a00a2b4a03d39 | 3,613,109 |
def transpose(matrix):
"""Matrix transpose
Args:
matrix: list of list
Returns:
list: list of list
"""
return list(map(list, zip(*matrix))) | 22c45de26bc19ca69ac0d04af8e2e02697290035 | 3,613,110 |
from datetime import datetime
def timestamp(s, tz=None):
"""Parse a HOBO timestamp value to Python DateTime"""
for fmt in TIME_FMTS:
try:
dt = datetime.strptime(s, fmt)
return dt.replace(tzinfo=tz) if tz else dt
except ValueError as e:
pass
raise ValueEr... | 79647ce17ef38f803c9073d2ba4075f3b93a3ec6 | 3,613,112 |
def decodeVarint32FromHttp(response):
"""Decode an 32 bit integer from a varint byte representation.
Expects an HTTP Response to read from.
"""
return _HttpDecodeVarint32(response) | b35886873bd15d608a8408907f80225c321ad869 | 3,613,113 |
def get_schema_names():
"""Return a dict of vertex and edge base names."""
names = [] # type: list
for path in _find_paths(_CONF['spec_paths']['schemas'], '*.yaml'):
names.append(_get_file_name(path))
return names | 9b746b756f7f8cd27e8a26dfcc9184d00cf58bd3 | 3,613,114 |
def gen_fix_fixups(*args):
"""
gen_fix_fixups(_from, to, size)
Relocate the bytes with fixup information once more (generic
function). This function may be called from 'loader_t::move_segm()' if
it suits the goal. If 'loader_t::move_segm' is not defined then this
function will be called automatically when... | b5e7e1b82c5f1a38fd5c48762cf873f5c4e117c6 | 3,613,116 |
import math
def line_fit(x,y):
"""Least-squares fit intercept and slope
.. versionadded:: 1.2
:arg x: sequence of independent variable data
:arg y: sequence of dependent variable data
:rtype: a :class:`~type_b.LineFitOLS`
``y`` must be a sequence of uncertain real... | 941e039b1b3d56f4f45e814227b89f88d9c9fc06 | 3,613,117 |
import pytz
def parse_resolution(json):
"""
Parse a JSON response from the server into a Resolution object.
"""
frequency = Frequency.by_tag(json.get("frequency"))
timezone = pytz.timezone(json.get("timezone"))
return Resolution(frequency, timezone) | e5e64c98aad5f3ef357fda95b3d71068a22e5731 | 3,613,118 |
def unbiased_ccd_image_dict(ccd, **kwargs):
"""Get the images keys by amp for a ccd
Parameters
----------
ccd : `MaskedCCD` or `ImageF`
CCD data object
Keywords
--------
bias : `str` or `None`
Method for bias subtraction
superbias_frame : `MaskedCCD` or `None`
B... | bf5637a6f6e6538e615102e43cd45a0a1ffb1ea8 | 3,613,119 |
def get_learning_rate_scheduler(optimizer, args):
"""Build the learning rate scheduler."""
# Add linear learning rate scheduler.
if args.lr_decay_iters is not None:
num_iters = args.lr_decay_iters
else:
num_iters = args.train_iters
num_iters = max(1, num_iters)
init_step = -1
... | 9dcc1350f63aa719a5fffbf7ec0c756186dbfe6d | 3,613,120 |
import tempfile
import pkg_resources
def plot_raster(demeter_gdf,
landclass_list,
target_year,
font_scale=1.5,
scope='conus',
resolution='0.083333',
value_to_nan=True,
nan_less_than=0.01,
na... | f333b99df7b420ae208e6e7a48a2dbffb944ec8f | 3,613,121 |
def meshgrid(*xi, **kwargs):
"""Return coordinate matrices from coordinate vectors.
Given one-dimensional coordinate arrays x1, x2, ..., xn, this function
makes N-D grids.
For one-dimensional arrays x1, x2, ..., xn with lengths ``Ni = len(xi)``,
this function returns ``(N1, N2, N3, ..., Nn)`` shap... | 72af359258994b69a80ef11a3005a03f624bc853 | 3,613,123 |
def y_dot(t,y,x,nu,F):
"""y_dot(t,y,x,nu,F)
Describes the differential equation for velocity as given in CW 12.
"""
return -(nu*y)+x-(x**3)+(F*np.cos(t)) | c9494fe04ba01785872ba238387f938f9f53e72e | 3,613,124 |
def split_code_into_blocks(code):
"""Split code into blocks of code, comments, and string literals."""
def is_noncode_start(code, idx=0):
"""String starts something other than source code (eg, a comment)."""
return (is_quote(code, idx) or
is_multiline_comment_start(code, idx) o... | 47d4faf1f8dc9be7ace265926598496b96ba1150 | 3,613,126 |
def lstExcel(filepath, colname):
"""
lstExcel function analyses the excel file and creates a list of the elements, that should be translated.
Parameter:
filepath:str: Path of the excel file.
colname:str: Name of the column to be translated.
Returns list.
"""
df = pd.read_excel(fi... | d49e75e4e7974cad9fb925de083db099705050d6 | 3,613,127 |
def get_model_json_string(model_bigg_id):
"""Get the model JSON for download."""
path = join(settings.model_dump_directory,
model_bigg_id + '.json')
try:
with open(path, 'r') as f:
data = f.read()
except IOError as e:
raise NotFoundError(e.message)
return ... | bb635c4c52d8a584a50efe9f55a5590fdb73fa8a | 3,613,128 |
def compute_shot(way, labels):
"""Computes the `shot` of the episode containing labels.
Args:
way: An int constant tensor. The number of classes in the episode.
labels: A Tensor of labels of shape [batch_size].
Returns:
shots: An int 1D tensor: The number of support examples per class.
"""
class... | 324919b0a73e7c0add83d392e14aab13cb269477 | 3,613,129 |
def new_line(string: str):
"""
Append a new line at the end of the string
Args:
string: String to make a new line on
Returns: Same string with a new line character
"""
return string + "\n" | f4deeaa94a6980f95a3020fa54570fbe1f0a6e9e | 3,613,130 |
def convert_to_unicode(text, encoding='utf-8', errors='ignore'):
"""字符串转换为unicode格式(假设输入为utf-8格式)
"""
if isinstance(text, bytes):
text = text.decode(encoding, errors=errors)
return text | 6c7d9a7788cd596a9a31a2b8f2aacd25e99c1813 | 3,613,132 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.