content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import tqdm
def eval_clustering(X, Xdist_dict, Y_true, cluster_type, params, target_metric='silhouette'):
"""
Evaluate a single clustering configuration (algorithm + hyperparameters).
@param X: feature matrix (scipy.sparse.csr_matrix, (n_reports x n_features))
@param Xdist_dict: dict of distance matri... | 96cc57b589c0ce7fb7dc2bcb394ccb136c13dda8 | 69,500 |
import random
def generate_random_fp_value(precision, inf, sup):
""" Generate a random floating-point value of format precision """
assert isinstance(precision, ML_FP_Format)
value = random.uniform(0.5, 1.0) * S2**random.randrange(precision.get_emin_normal(), 1) * (sup - inf) + inf
rounded_value = pre... | afc7ea0cfc449b8e5bcb2cd216e6d136746b2c2b | 69,501 |
from typing import Optional
from typing import List
def _parse_args_schema(query_args: Optional[List[ArgDef]]):
"""
Parse query args schema
"""
parameters = []
for query_arg in (query_args or []):
arg_name = _arg_name(query_arg)
arg_type, arg_format, arg_req = _arg_type(query_arg)
... | 0c184dae1fa68d21b551c3701cecb09d63907089 | 69,502 |
def check_bee_nectar_eq_hive_nectar(landed_bees, game):
""" Check the sum of all the nectar in the hives equals the sum of the nectar
carried by bees that have landed
returns: True if they are same
"""
hive_nectar = sum(sum(hive.nectar for hive in board.hives) for board in game.boards)
l... | 86f8045c5639ca73edad7273e58bbc5fbf112220 | 69,503 |
def encrypt(plaintext, key):
"""
:param plaintext: string
:param key: int
:return:
"""
ciphertext = ""
for char in plaintext:
oNum = ord(char)
if oNum > 127: # not a ASCII character
new_char = char
else:
if(oNum + key > 127): # If value is t... | 855e941e73cf15b00d3c2fa94eefaaf3c3ad31a4 | 69,504 |
def as_index(keys, axis=semantics.axis_default, base=False, stable=True, lex_as_struct=False):
"""
casting rules for a keys object to an index object
the preferred semantics is that keys is a sequence of key objects,
except when keys is an instance of tuple,
in which case the zipped elements of the... | a3f1151d165bb05ff6f190744aad1b7570ddb7ba | 69,505 |
def series2shp(series, filepath):
"""Writes a ``pandas.Series`` of PySAL polygons to a file
Parameters
----------
series : pandas.Series
The data to write out.
Returns
-------
filepath : str
Path to the file.
"""
f = ps_open(filepath, "w")
for pol... | c8060881433d4f8dae107adab9df3f3233705468 | 69,506 |
def unit_format_suffix_handle_exc(value, suffix, precision=2):
"""Print a given value but handle None and exceptions during processing."""
if value is None:
# TRANSLATORS: do not translate {unit}; "None" is equivalent to "Not Applicable" or "No Value"
return _("[None] {unit}").format(unit=suffi... | 6cebcd18298594e1b0eb46005f18456518635537 | 69,507 |
def PrePlot(num=None, rows=None, cols=None):
"""Takes hints about what's coming.
num: number of lines that will be plotted
rows: number of rows of subplots
cols: number of columns of subplots
"""
if num:
_Brewer.InitIter(num)
if rows is None and cols is None:
return
if... | 680839d139813c4d0b74050997465cb6f75b9678 | 69,508 |
import os
def which(command):
"""
:param command:
:type command: str
:return: The path of program file or None
:rtype: str
"""
result = None
for p in os.getenv("PATH").split(os.path.pathsep):
full_path = os.path.join(p, command)
if os.path.exists(full_path):
... | 74518bdcd8f96c71c18391542fcdfbdee9833e9a | 69,509 |
def index(request):
"""
show index page
:param :
:return:
:rtype:
"""
return render_to_response('index.html') | 3d55b0f308bb94158f5f38cd1a86ee1b9c377bfa | 69,510 |
import re
def sequence_objects(module: ModuleType, items: BindingSeq) -> BindingSeq:
"""
:param module: The module to extract callable definitions from.
:type module: ModuleType
:param items: The callables and bindings for extraction.
:type items: Iterator[Tuple[str, object]]
:returns: a list ... | 0dbf096b262046493ebbe5d03a59baa7e4d78557 | 69,511 |
def selection_probs(utilities, market_share):
"""Customer selection probability for all products and 'do not fly'
Parameters
----------
utilities: dict
Utilities of products based on choice model parameters
market_share: float
Host's market share
Returns
-------
tuple
... | b4f994b421ff97aeee90808358436590a1feb43e | 69,512 |
def remove_pc(X, npc=1):
"""
Remove the projection on the principal components
:param X: X[i,:] is a data point
:param npc: number of principal components to remove
:return: XX[i, :] is the data point after removing its projection
"""
pc = compute_pc(X, npc)
if npc == 1:
XX = X -... | 6b1a369904580dd881c5d4dba7753328b6e8168e | 69,513 |
def zeros(shape,name=None):
"""
zeros tensors
"""
initial = tf.zeros(shape,dtype=tf.float32)
return tf.compat.v1.Variable(initial) | f291ae0dd8c5afe2115bcf54c92b224b8355761f | 69,514 |
def solucion_c(imc: float) -> str:
"""Devuelve una categoría de acuerdo al imc
:param imc: Índice de masa corporal
:imc type: float
:return: Categoría
:rtype: str
"""
categorias = {
imc < 16 : "criterio de ingreso hospitalario",
16 <= imc < 17 : "infrapeso",
17... | ca05b9b7af9df3237e8aa1170638e7e695e6bcad | 69,515 |
import re, string
def clean_text(orig_text,verbose=False):
"""Prepare for NLP by removing problematic characters.
Adapted from code kindly provided by Dr. Brian Powell at WVU.
"""
if verbose: print("ORIGINAL")
if verbose: print(orig_text)
if verbose: print("REMOVE URLS")
clean_text = re.s... | 1ac8b6baff72fc72db748a699975da818781f215 | 69,516 |
def melscale(f):
""" Converts f (in Hertz) to the melscale defined according to Huang-Acero-Hon (2.6) """
return 1125.0 * np.log(1 + f / 700.0) | 996870454615e71fbb2d7cac0b4142c878b7d452 | 69,517 |
from typing import Optional
def default_shape_importer(_: ShExJ.IRIREF, cntxt: "Context") -> Optional[ShExJ.Schema]:
""" Resolve an import declaration """
return None | 079882761b928ad3ad06419892ad9d979cc5e678 | 69,518 |
def make_jitter_plots(data, names, ylabel, dx=0.1, offset=0.0,
xlabels=None, ax_handle=None, alpha=1, color=None,
marker=None, markersize=12, return_plot_pointer=False):
"""
Make a jitter plot of columns from a pandas dataframe
Parameters
----------
data:... | 3efe6c530dacbedd583f62d4104c2d5f43b15098 | 69,519 |
def gen_split_idx(num_all, num_train, num_val, num_test, seed=1234):
"""Generate train/val/test split indices
Args:
num_all: total number of data
num_train: number of training data
num_val: number of validation data
num_test: number of testing data
seed: seed of random number generator
Retu... | aa33ff25a0eaa20091035f4ee1597c2971e4aa81 | 69,520 |
import numpy
from typing import Mapping
from typing import Iterator
def _get_redundant_cluster_cnv_cpx_vids(
cluster: numpy.ndarray,
is_carrier: Mapping[Text, numpy.ndarray],
cnv_cpx_sample_overlap: float
) -> Iterator[Text]:
"""
Find CNVs that are redundant with CPX events
for eac... | 421008b9c648a985fa7d573b0b9565eebb627292 | 69,521 |
def link_menus(*menu_items):
"""
Links a list of menu items into a loop of menu items
:param menu_items:
:return: the first menu item
"""
def link(a, b):
a[NEXT] = b
b[PREV] = a
prev = menu_items[-1]
for menu_item in menu_items:
link(prev, menu_item)
prev... | 57342c8f458ffe186c59b365375e73a65273ee6d | 69,522 |
import math
import random
def solve(simulation_api: SimulationAPI, reward_threshold: float, timeout_s: float = 60, num_hof=1):
"""
Run a genetic algorithm on the current simulation_control scenario until reward exceeds the threshold or timeout is reached
"""
# need to have a reward function, and to im... | fcd7f40127fa77fb91566f3eeadae61a3152b599 | 69,523 |
import binascii
def des_descrypt(s):
"""
DES 解密
:param s: 加密后的字符串,16进制
:return: 解密后的字符串
"""
secret_key = KEY
iv = secret_key
k = des(secret_key, CBC, iv, pad=None, padmode=PAD_PKCS5)
de = k.decrypt(binascii.a2b_hex(s), padmode=PAD_PKCS5)
sessionID = de.split('_')
openid = ... | 449976440bbabdedd80028fe1434cf478ad3fbf0 | 69,524 |
def splitter(model):
"""
Splits model parameters into multiple groups to allow fine-tuning
"""
params = list(model.parameters())
return [
# weights and biases of the first linear layer
params[:2],
# weights and biases of the second linear layer
params[2:],
] | 2ac16b536bd50884c50ade3fb67f6ca43a16799d | 69,525 |
import subprocess
def test_replicate_with_failing_rw(monkeypatch):
""" Test that replicate fails nicely when both processes fail. """
# Mocking
mock_url = 'mock_url'
mock_query = 'mock_query'
mock_table = 'mock_table'
mock_append = True
mock_reader = MockPopen()
mock_reader.returncode = -1
mock_writer = Moc... | 50d0490daf66c351d9b57a8e43a29d9294e9cf7d | 69,526 |
def render_static(request, template):
"""
Takes an html file and renders it Commcare HQ's styling
"""
return render(request, "hqwebapp/blank.html", {'tmpl': template}) | 1b629d0b9186b23b6b5aefa9b78cc9235171767b | 69,527 |
import logging
import sys
def setup_logger(debug=False):
""" setup debugger """
logging.basicConfig(stream=sys.stderr,
level=logging.DEBUG if debug else logging.INFO,
format=("[%(asctime)-15s] %(levelname)s "
"[%(process)d#%(modul... | 4dc29830c10b01e62f6b78df457bc939adac4c8c | 69,528 |
def read_fits_header(filename, **kwargs):
""" Read the FITS header for a given filename.
Args:
filename (str): The filename.
**kwargs: Parsed to fits.getheader.
Returns:
astropy.header.Header: The header object.
"""
return fits.getheader(filename, **kwargs) | 0b8401817d169ca0cff198dedd05abfd2065e2e7 | 69,529 |
from typing import Dict
from typing import Any
from typing import Optional
import math
def sequential_colors(
node_and_value: Dict[Any, float],
light_background: bool = True,
use_log_scale: bool = False,
theme_path: Optional[str] = None,
) -> Dict[Any, str]:
"""
Generates a node -> color mappi... | e25133ee1fe761618748a48664675e7556573cb8 | 69,530 |
import os
from typing import cast
def rotational_minctracc(source: MincAtom,
target: MincAtom,
conf: RotationalMinctraccConf,
resolution: float,
# mask: MincAtom = None, # TODO: add mask, resample_source to conf ??
... | a10ca38d33b834f11c67447dbaa0718646983f45 | 69,531 |
def dup_normal(f, K):
"""
Normalize univariate polynomial in the given domain.
Examples
========
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.densebasic import dup_normal
>>> dup_normal([0, 1.5, 2, 3], ZZ)
[1, 2, 3]
"""
return dup_strip([ K.normal(c) for c in f... | ba67c492e3a2cbf7844aa3aede4b5fef775b0a91 | 69,532 |
def create_c3nn_classifier(ninput=100, nfilters=32, kernel_size=4, ndense=128, pool_size=2, dropout_rate=0.2,
noutput=1, pooling=False):
""" An easy way of creating a CNN with 3 convolutional layers and 2 dense layers
Parameters
----------
ninput:
input shape
nfil... | 04f37c440951b0671f3cb0f219c8d1fcad391e5f | 69,533 |
from typing import List
def filter(
df: DataFrame,
rule_type: str,
diameters: List[int],
logger: Logger = getLogger(__name__)
) -> List[int]:
"""
Filter a pandas dataframe with 'Diameters' and 'Rule usage' criteria.
Parameters
----------
df: DataFrame
Pandas dataframe
... | 95b2440a4ac2bdbc6d2b45341e7a7e4ed418633f | 69,534 |
def get_setup_fabric_dirs_string():
"""
Returns the commands required to set up the fabric directories. This is not in the env, because modifying this
is likely to break FabSim in most cases.
This is stored in an individual function, so that the string can be appended in existing commands, reducing
... | a73f3da5b7c20c588f71320f0089066ce54bf93e | 69,535 |
def _fit_shift(
Z, y, f, f_s, w, max_shift, periodic, n_iter, init_shift, Ww):
"""
Z : matrix, M x T
y : float
f : vector, length M
f_s : vector, length M
w : vector, length T
"""
M, T = Z.shape
best_loss = np.inf
best_shift = 0.0
for i in range(n_iter):
... | 79eba28f490c3aecd77befba19714b4990f79731 | 69,536 |
from datetime import datetime
def to_timedelta(src, cal=None, is_duration=False):
"""
converts a string to a datetime.timedelta. If cal is specified
it will be used for getting the working times. if is_duration=True
working times will not be considered. Valid units are
d for Days
w for Weeks
... | 01bcbad90d1f5335a6620b93d4eb24eac890f916 | 69,537 |
def Dust(C, **kwargs):
"""
SulfurDioxide RGB:
(See `Quick Guide <http://rammb.cira.colostate.edu/training/visit/quick_guides/Dust_RGB_Quick_Guide.pdf>`__ for reference)
.. image:: /_static/Dust.png
Parameters
----------
C : xarray.Dataset
A GOES ABI multichannel file opened with xa... | 4e36f4b2f66d9caf361e8d6208225367262b219b | 69,538 |
def slant_stack_frequency(traces, dx, cmax, fmax):
"""
Slant stack method after McMechan and Yedlin 1981
"""
nr = len(traces)
dt = traces[0].stats.delta
nt = traces[0].stats.npts
t = np.linspace(0.0, nt*dt, nt)
traces.detrend()
traces.taper(0.05,type='hann')
U, f = get_fft(trace... | 42310963e0244c72287cf3e8909e6f088fb668de | 69,539 |
from typing import List
import random
def algo_chao(s: List, k: int) -> List:
"""Chao weighted random sampling
"""
n = len(s)
assert len(s) >= k
wsum = 0
r = s[:k]
assert len(r) == k
for i in range(0, n):
wsum = wsum + s[i]["priority"]
if i < k:
continue
... | 788007e08129c79c49128874be4da64b21cbff22 | 69,540 |
def get_arch(os_list):
"""
根据os_list判断需要下载哪些架构的包
"""
arm, x86 = 0, 0
for os_item in os_list:
if not arm and "aarch64" in os_item:
arm = 1
if not x86 and "x86_64" in os_item:
x86 = 1
if arm and x86:
break
if arm and not x86:
arc... | 1522db842d971a30fb54c05919f98da83aaf1d0a | 69,541 |
def getOptions():
"""Generates arguments for specifying database and other parameters"""
options = {}
options['lexical_kb'] = ["https://raw.githubusercontent.com/chapmanbe/pyConTextNLP/master/KB/lexical_kb_05042016.tsv"]
options['domain_kb'] = ["https://raw.githubusercontent.com/chapmanbe/pyConTextNLP/m... | ecd193161645419b241679b2496f76d26e0468fd | 69,542 |
def get_protein_coding_read_count(pcgenes, count_file):
"""
Extract the counts of fragments mapped to protein coding genes.
:param pcgenes: set of protein coding gene IDs
:param count_file: HTSeq count file
:returns: number of fragments on protein coding genes
:returns: dictionary of gene ids a... | d2ce448472a4c6773d69bad260b9088558ddb1d5 | 69,543 |
def checkIPIsValid(ip):
"""
Method used to check a selected IP is possible to use with a Qt's QHostAddress.
The IP can be either IPv4 address or *"localhost"* string with possible capital
letters anywhere. IPv6 is not supported for now.
Args:
ip: A str with an IP address selected.
"""
if ip.upper() ==... | 8b3f0a5f7ae079a0461d45efcafd0f8ce3e859ce | 69,544 |
import urllib
def graphql(obj,query_ids=None):
""" access to /graphq/query/ """
if not type(obj) is dict:
raise TypeError("Expecting dict type variable")
if type(query_ids) is list:
query_ids="\n".join(query_ids)
if query_ids is None:
f=open("query_id",'r')
query_ids=f.read()
f.close()
args = urlli... | 7fdd37e82bbb015928e7bbca6cb18b61297c9a73 | 69,545 |
def tile_pauli_fidpairs(base_fidpairs, nQubits, maxweight):
"""
Tiles a set of base fiducial pairs on `maxweight` qubits to a
set of fiducial pairs on `nQubits` qubits such that every set
of `maxweight` qubits takes on the values in each base pair in
at least one of the returned pairs.
Paramete... | e3e62678287adfa522d287022d13334a76bde820 | 69,546 |
def gen_color_dict(bundles):
"""
Helper function.
Generate a color dict given a list of bundles.
"""
def incr_color_idx(color_idx):
return (color_idx + 1) % 20
custom_color_dict = {}
color_idx = 0
for bundle in bundles:
if bundle not in custom_color_dict.keys():
... | 74ad30fc71a4316de4aa91f68eee7a1fb0029ba2 | 69,547 |
def simulation_step(x, dt, rates):
"""
Returns the boolean vector x(t+dt) from x(t). Time unit is day, rates are per day and per nucleotide.
Rates is a dict containing keys ["consensus", "non_consensus"].
rates["consensus"] and rates["non_consensus"] are dict containing the rates for the keys ["first", ... | 658e9e71e5451c3b759539d9e0c27becdc0d9ffd | 69,548 |
def _read_md5_sum_file(path):
""" Reads a MD5 checksum file and returns hashes as a dictionary.
"""
with open(path, "r") as f:
hashes = {}
while True:
line = f.readline()
if not line:
break
h, name = line.rstrip().split(' ', 1)
... | 5f5cfce0f8774baf17041a05b017ba9967d43267 | 69,549 |
def get_data_2g(args, infoMiss=None):
"""
Generate synthetic data with 2 groups.
Parameters
----------
args : local namespace
Arguments selected to run the model.
infoMiss : dict | None, optional.
Parameters to generate data with missing values.
Returns
-------
... | 9b5d875612f09706b37f1c7e87ff83db9ef06398 | 69,550 |
from typing import List
def device_types() -> List[xcrun.simctl.device_type.DeviceType]:
"""Return all available device types."""
device_type_info = _list(xcrun.simctl.SimulatorControlType.device_type.list_key())
return xcrun.simctl.device_type.from_xcrun_info(device_type_info) | cac646e85aad4ba3c78ce245dae7129c029946a8 | 69,551 |
def process_sample_data(sample_data, config):
"""
sample_data is a top level config map that has two types of entries
- samples: keyed on sample name and containing paths and other data
- 'reads_patterns': list of patterns to find samples. These are passed to
collect_sample_reads() below
... | e27a0a376c6cc91bbc88ccfa6aa0b77fa04f503c | 69,552 |
from typing import Sequence
def to_dot(*models: type, termini: Sequence[type] = []) -> str:
"""Generate Graphviz [DOT language](https://graphviz.org/doc/info/lang.html) representation of
entity relationship diagram for given data model classes.
Args:
*models (type): Data model classes to diagram.... | 9fd5eeb6c9abb5f34115f2362c2ebabdcdca7443 | 69,553 |
def _GetValue(parent_element):
"""Get the text nested inside an XML element's value element.
Args:
parent_element: An ElementTree element
Returns:
String inside value tag inside parent or, if no such tag can be found, None
"""
if parent_element is not None:
value_element = parent_element.find(_D... | 20e4c2f1cef7ecba4055d533459dd8c83d348e7e | 69,554 |
from typing import Tuple
import os
def read_txt_file(file_path: str) -> Tuple[np.ndarray, np.ndarray]:
"""
Reads a txt file which contains data points from the huggingface dataset
:param file_path: The path to the txt file to read
:return: Tuple with all texts and labels from the file
"""
emo... | 5e5ccbd9a39fad16c6cc6ce36705bf72ff713439 | 69,555 |
from re import DEBUG
import string
def find_and_replace_formulas_in_markdown(md: str, support_formulas=True, support_custom_emojis=False):
"""Takes markdown as a string and returns the markdown, but every formula is replaced with a random string, as well
as a dict to translate these strings back to the formul... | f1c0179ef929c71db3416b921d2eba8007887f3b | 69,556 |
def track_and_predict(vid_path, net):
"""
Returns:
pred: Tracks the snitch, and return the class for the final
coordinates of the snitch
pred_gt: Uses the end point location of the snitch, projects to 2D,
then computes the class coordinates. This is only returned as a
... | 47e4f75ba43acbff4656d99140411a1c1f3765a4 | 69,557 |
def abs_area(x):
"""Calculate the area under the absolute values of the given points.
The integral is done using the trapezoid rule.
Parameters
----------
x : ndarray
The input points to use for the calculationss
Returns
-------
abs_area : float
The absolute area u... | 2dacea58c9217d2091b72a451f826d060c7165e6 | 69,558 |
def feature_count_near(INPUT, cloud, clust_centers):
"""Compute the "count-near" feature.
For each cluster, the number of landmarks within a neighborhood radius
arround them is counted. The neighborhood radius is defined as the mean of
all distances computed in `feature_distEuclidean_kNN`.
Paramet... | 96e8a5e5dc14298a3f35f958b851c1cda1026a68 | 69,559 |
import math
def make_bonds(pdb1):
""" create bonded list based on overlap of vdw radii """
margin = 1.3
bond_list = []
nbond = 0
for i in range(pdb1.natom):
for j in range(i+1,pdb1.natom):
dist2 = 0.
for k in range(3):
dist2 += (pdb1.coords[i][k] - pdb1.coords[j][k])**2
dist = ... | 4ca098e15f912c7d7658562992c502c2271cc1bd | 69,560 |
def _decode_csv(line):
"""Takes the string input tensor and returns a dict of rank-2 tensors."""
# Takes a rank-1 tensor and converts it into rank-2 tensor
row_columns = tf.expand_dims(line, -1)
columns = tf.decode_csv(row_columns, record_defaults=CSV_COLUMN_DEFAULTS)
features = dict(zip(CSV_COLUMN... | 4bd8c2731f1f2f13ff8d797d56c6aea78254afcd | 69,561 |
def impz(b, a=1, FS=1, N=1, step=False):
"""
Calculate impulse response of a discrete time filter, specified by
numerator coefficients b and denominator coefficients a of the system
function H(z).
When only b is given, the impulse response of the transversal (FIR)
filter specified by b is c... | 994142a203e017d5ba3fbe6cbc4535420b4fa61e | 69,562 |
async def present(
hub,
ctx,
name,
resource_group,
virtual_network,
ip_configurations,
gateway_type=None,
vpn_type=None,
sku=None,
enable_bgp=None,
active_active=None,
bgp_settings=None,
address_prefixes=None,
tags=None,
connection_auth=None,
**kwargs,
):
... | 2cc3d4f60d7032af6e945e2861be133a3aecd40c | 69,563 |
def get(identifier: str) -> 'BaseRenderer':
"""Gets the `BaseRenderer` that matches the identifier.
Parameters
----------
identifier : str
The identifier for the `BaseRenderer`
Returns
-------
`BaseRenderer`
The renderer associated with the `identifier`.
Raises
---... | 99e220b878ff381c5a1478cf91e7536b22f8520f | 69,564 |
import os
def get_log_and_extra_based_on_config(log_agent, app_root_dir, log_config_name):
"""
根据config文件读取log,并将extra里面的数据进行替换. 将重置 log_agent 的状态.
:param log_agent: LogAgent
:param app_root_dir: str
:param log_config_name: str
:return: logs: [{}, {}];
configs: {}, 包含配置文件中的所有内容
... | 97ad99f81ce3ff87f41aad3c8bf6363f9aa3456a | 69,565 |
import torch
def stratified_sum_pooling(values: torch.Tensor,
labels: torch.LongTensor) -> (torch.Tensor):
"""Group-wise sum."""
winning_values = stratify_with(
values,
labels,
fn=lambda x: torch.sum(x, dim=1, keepdim=True).squeeze(),
fill_value=0.0)
... | fdd3b62f8bb8942882338f11e62e88d1f0dcf0f1 | 69,566 |
def is_wl():
"""Whether the model point is whole life
``True`` if the model point is whole life, ``False`` if other wise.
By default, the value is read from the ``is_wl`` column
in :func:`model_point`.
This attribute is used to determin :func:`policy_term`.
If ``True``, :func:`policy_term` is d... | 4eb618afdfd063f61c1d3a2322b2ca91aea36a71 | 69,567 |
import os
def data(name: str) -> str:
"""
Data endpoint for nn text gen projects.
Args:
name (str): The name of the nn text project to get data for.
Returns:
str: The populated data template for the given nn text gen project, or
an error template if the given project is n... | 0866482fa8940671674d7d27f7bf1979541e24e1 | 69,568 |
from typing import List
from typing import Any
def klue_ner_char_macro_f1(preds: np.ndarray, labels: np.ndarray, label_list: List[str]) -> Any:
"""KLUE-NER character level macro f1 (except O tag)"""
label_indices = list(range(len(label_list)))
preds = np.array(preds).flatten().tolist()
trues = np.arra... | 049c90957517962a442edaa5ab6804aa03856c6e | 69,569 |
def randargmax(a, rng=None, max_fn=np.max):
"""
Returns index of max element, with random tie breaking.
If random tie breaking is not needed, use np.argmax() instead.
:param Union[list, np.ndarray] a: A list or np.ndarray.
:param object rng: Random number generator. If None, np.random is used.
... | a95441b8ad996e5000dc609c8e2a927754ad2758 | 69,570 |
def parse_inkbird(self, data, source_mac, rssi):
"""Inkbird parser"""
msg_length = len(data)
firmware = "Inkbird"
result = {"firmware": firmware}
if msg_length == 11:
device_type = "IBS-TH"
inkbird_mac = source_mac
xvalue = data[2:10]
(temp, hum) = unpack("<hH", xvalu... | 855dcb074731d8f48d24044003f75909927434af | 69,571 |
from galaxy import tools
from galaxy.tools.special_tools import load_lib_tools
from galaxy.tools.toolbox.lineages.tool_shed import ToolVersionCache
import time
def _get_new_toolbox(app):
"""
Generate a new toolbox, by constructing a toolbox from the config files,
and then adding pre-existing data managers... | 4c2a30c170ed10bac733bddf4db6fb45fe663422 | 69,572 |
from typing import List
from typing import Dict
from typing import Tuple
import sys
def determine_phase_estimation(args: List[str], flags: Dict[str, str]
) -> Tuple[int, Matrix, Matrix]:
"""
Read the given flags dictionary and arguments map and convert to usable
input for th... | cebb33103cff0209803c5c28ec2171d45c52a2d7 | 69,573 |
def parse_id(text):
""" Parse and return the <job>:<id> string.
Args:
text String to parse
Returns:
This node's job name, this node's id
"""
sep = text.rfind(":")
if sep < -1:
raise ValueError("Invalid ID format")
nid = int(text[sep + 1:])
if nid < 0:
raise ValueError("Expected non-negat... | 23dbc417abf7fb799da78e63acf18b2d0ffc450f | 69,574 |
def reconstruct_grid_volume(grid, n_block=(4, 4, 4)):
"""
Reconstruct the warped grid volume with its blocks.
:param grid: A dictionary of grid blocks, with the key (i, j, k) referring to the block indices, the values are of
shape [n_batch, nx_block, ny_block, nz_block, 3].
:param n_block: The ... | 916bee093a26d9d16b12ca135aa7e8596997a8fb | 69,575 |
import time
import sys
import lsm_connections_probability # Creates the 3D Grid and the connections according to Maass 2002
import lsm_dynamical_synapses_v1 # Creates the dynamical synapses according to Maass 2002 and using the output
def simulation_2DoF_Arm(brian_clock, brian):
"""
Net_shape: tuple (X,Y,Z) -... | 4b72dab439e5c0eb38ccd5e830dbb3d391c75981 | 69,576 |
import glob
def spncci_slurp (directory):
"""
Arguments:
directory (string): Location of the SpNCCI results files.
Should be of the form '/location/of/files/*.res'
Returned:
data (nested dictionary): Maps from (Nmax, Nsigmamax) to hw to
SpNCC... | 6f9c0d3c4dfd0f231f943d16813855fb19e28a6a | 69,577 |
import copy
def pyramidal_solve_kt(slice3d,\
slice3d_orig,\
slice3d_shape,\
weights_list,\
factors,\
rp):
"""Solves a k-t slice: dim0=receivers,dim1=kx,dim2=t
"""
#init
lmafit_tol_list = vj.config['lma... | 7c36f3b42c93813a849dc2a7cb56257ea516a2e0 | 69,578 |
def read_DF_from_path(resultFile):
"""Read daylight factor values from a radiance .res result file."""
result = []
resultFile = open(resultFile, "r")
for line in resultFile:
res = float(line)
if res > 100:
res = 100
result.append(res)
return result | 583ec1892d26038fdd43d9acf152a9b7c65dc364 | 69,579 |
def get_real_sms_messages_data(domains, datespan, interval,
datefield='date', is_commtrack=False, additional_params_es={}):
"""
Returns SMS sent in timespan.
Returned based on date SMS was sent
"""
sms_after_date = (SMSES()
.domain(domains)
.received(gte=datespan.star... | ee27034e9f31d0804ac6243dc9f93c913a10917e | 69,580 |
def _get_target_directory(yaml_path):
"""Get target directory to copy appengine yaml to."""
return SRC_DIR_GO if _is_go_yaml(yaml_path) else SRC_DIR_PY | 62c8a6b5caccca8855409400332de3c9dca41b09 | 69,581 |
from typing import List
def load_data(name: str, path: str) -> List:
"""根据名字加载不同的数据集
"""
#TODO: 把lqcmc的数据生成正负样本, 拿来做测试
def load_snli_data(path):
with jsonlines.open(path, 'r') as f:
return [(line['origin'], line['entailment'], line['contradiction']) for line in f]
... | bbfe0af0f86933372e57208336ce5b3ee3f42275 | 69,582 |
def directories(name, dirs, **kwargs):
"""
type dir {
path string [required]
user string
group string
mode string
}
type dirs []dir
"""
results = {"name": name, "result": False, "changes": {}, "comment": []}
for d in dirs:
# path is require... | c610e97fd58755bd9cd21cc6962028ddc726fd1d | 69,583 |
def add_metpy_logo(fig, x=10, y=25, zorder=100, size='small', **kwargs):
"""Add the MetPy logo to a figure.
Adds an image of the MetPy logo to the figure.
Parameters
----------
fig : `matplotlib.figure`
The `figure` instance used for plotting
x : int
x position padding in pixels
... | 49e87a6d64d257614e0370b27dca9283470d90c7 | 69,584 |
import configparser
def process_config(conf_file):
"""
read configuration from files and saved to a dict
"""
params = {}
config = configparser.ConfigParser()
config.read(conf_file)
for section in config.sections():
if section == 'database':
for option in config.options(section):
params[option] = eval... | 204077bbade5203267a6719d9fb559ef5f0ee126 | 69,585 |
async def handle_stream_changed_get(request: request.Request):
"""Route receiving the challenge requests for the topic StreamChanged
Parameters
----------
request: sanic.request.Request
The challenge request received from Twitch
"""
return dispatcher().accept_subscription(request, Topic... | 6c5cab4578e64a35b60fb80cdf14453229b15701 | 69,586 |
def parse_phone_number(phone_number):
"""Parse phone number.
Args:
phone_number (str): Phone number. ie. 050xxxxxxx
Returns:
str: E164 formatted phone number. ie. +23350xxxxxxx
Raises:
InvalidPhoneNumberError: If `phone_number` is not successfully
parsed as a local... | 3359322dff4645b50b6da6e5490d127340f8da34 | 69,587 |
def getRootHelp():
"""帮助文档"""
max_l = 0
for a in action_names:
if len(a[0]) > max_l:
max_l = len(a[0])
max_l += 4
msg_help = "<pre>API Version " + config['version']
msg_help += "\n\nSupport Functions:\n\t" + "\n\t".join([a[0]+(" "*(max_l-len(a[0])))+a[1] for a in action_name... | 3e363adc65b6f5c9d91e7ec12df6021b302ba17d | 69,588 |
def cutout_image(image, offsetx, offsety, size, output_size=224):
"""Computes (square) cutouts of an image given x and y offsets and size."""
(c, h, w) = image.shape
scale = jnp.stack([output_size / size, output_size / size])
translation = jnp.stack([-offsety * output_size / size, -offsetx * output_siz... | f82d10299e9a9580bbddf5e3fc213d48d1188df7 | 69,589 |
def path_to_import(path):
"""Convert a path to import."""
if path.name == '__init__.py':
import_path = str(path.parent)
else:
import_path = str(path)[:-len(PY_EXTENSION)]
return import_path.replace('/', '.') | 780f345a0fbbfdc6df5cc4916253c0e7acb1f736 | 69,590 |
def unexpected(parser, at_token=None):
"""Helper function for creating an error when an unexpected lexed token
is encountered."""
token = at_token or parser.token
return LanguageError(
parser.source,
token.start,
u'Unexpected {}'.format(get_token_desc(token))
) | c450aa592f63a84171294c19fdf1ac43245a760a | 69,591 |
from typing import Sequence
from typing import Mapping
from typing import Any
from typing import Optional
import functools
import collections
def transcription_metrics(
targets: Sequence[Mapping[str, Any]],
predictions: Sequence[Mapping[str, Any]],
codec: event_codec.Codec,
spectrogram_config: spectro... | 33ad1c21c4a6b5119dd1ef1127d248be4fd2d3f1 | 69,592 |
def resnet50_learning_rate_schedule(base_learning_rate, steps_per_epoch):
"""Creates a piecewise LR schedule for the common ResNet-50 ImageNet setup."""
boundaries = [
int(40 * steps_per_epoch),
int(60 * steps_per_epoch),
int(80 * steps_per_epoch),
int(90 * steps_per_epoch),
]
values = [... | f74a148be20452643fad4a938d106ccb14bf1f21 | 69,593 |
import torch
def setdiff(A, B):
"""
Returns the set difference tensor with all the elements in A not belonging to B
Parameters
----------
A : Tensor
the first input tensor
B : Tensor
the second input tensor
Returns
-------
Tensor
the set difference tensor
... | a2f16aaf74a0f74c56b897989ac86074998b5569 | 69,594 |
def is_empty(text: str) -> bool:
"""Determine if XML string is empty.
The XML string is considered empty if it only contains processing
instructions and comments.
:param text:
XML text to check for being empty.
:return:
True if the given XML `text` is empty.
"""
return (
... | 251a8a09c69a84f7574573211c8eb8ae4a0a53df | 69,595 |
def vectorise_data(raw):
"""Converts a list of [x,y,z] data to Vector(x,y,z)"""
temp = []
for vert in raw:
temp.append(Vector(vert[0], vert[1], vert[2]))
return temp | 77eabee827d8e5c820b4b4edf4b53167b3d6671f | 69,596 |
def get_value(source, steps):
"""
根据入参字典以及取值步骤取出结果
steps 为取值步骤组成的列表
"""
try:
# 循环取值步骤列表
for step in steps:
# 如果为数字则转为数字(数字代表从列表取值),否则为字符
step = step if not step.isdigit() else int(step)
# 如果 step 是数字,则是从 list 中取值
if isinstance(step, in... | bccaea5544dd685b028a54b5318b7a7c930042b0 | 69,597 |
import torch
def quat_to_rot(rot, conv='wxyz', device='cpu'):
"""converts quat into rotation matrix
Args:
rot ([type]): [description]
conv (str, optional): [description]. Defaults to 'wxyz'.
Raises:
Exception: [description]
Returns:
[type]: [description]
"""
i... | 13ea4ec693d894fc253d416f9a600b299da6d87c | 69,598 |
def height_from_height_wrist(segment_length):
"""
Calculates body height based on the height of the elbows from the ground
args:
segment_length (float): height of the wrists
Returns:
float: total body height
"""
if segment_length <= 0:
raise ValueError('segment_length m... | f655043783dda410fe20e27ed14f33d148eb7af9 | 69,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.