text string | label_name string | labels int64 |
|---|---|---|
Error::InvalidResponse {
endpoint: self.endpoint,
source: e.into(),
})?;
let mut tweet = match response {
TweetOrError::Tweet(t) => t,
TweetOrError::Error { errors } => {
error!("Received {} errors!", errors.len());
... | Rust | 0 |
# coding=utf-8
# Copyright 2024 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | Python | 1 |
DatabaseType::MySql,
username: "".to_string(),
password: <PASSWORD>(),
hostname: "localhost".to_string(),
port: 3306,
database_name: "".to_string(),
use_tls: None,
}
}
/// Constructs a database connection URI for the settings obje... | Rust | 0 |
ListNodeRec_;
#[derive(Copy, Clone)]
#[repr(C)]
pub struct FT_ListRec_ {
pub head: FT_ListNode,
pub tail: FT_ListNode,
}
pub type FT_ListRec = FT_ListRec_;
/* ***************************************************************************
*
* freetype.h
*
* FreeType high-level API and common types (specificat... | Rust | 0 |
$s_fixed, "<U4>;
assert_eq!(Fix::from_num(2.5).checked_round(), Some(Fix::from_num(3)));
",
if_signed_else_empty_str! {
$Signedness,
"assert_eq!(Fix::from_num(-2.5).checked_round(), Some(Fix::from_num(-3)));
",
},
"assert!(Fix::max_value().checked_rou... | Rust | 0 |
discovered basic algebraic identities - https://en.wikipedia.org/wiki/Mah%C4%81v%C4%ABra_(mathematician)
"mahavira",
// <NAME> (b. <NAME>) - an American evolutionary theorist and biologist, science author, educator, and popularizer, and was the primary modern proponent for the significance of symbiosis in evol... | Rust | 0 |
= (Point3::new(0.0, 0.0, 0.0), Point3::new(3.0, 3.0, 3.0));
let parallelepiped = Parallelepiped::new(&min, &max, material_gen);
let hit_interval = Interval::new(0.0, std::f32::MAX).unwrap();
let ray = Ray::new(Point3::new(1.0, -1.0, 1.0), math::vec3(1.0, 2.0, 1.0), 1.0);
assert!(parall... | Rust | 0 |
from wikipedia2vec.dump_db import DumpDB
import json
import argparse
import nltk.data
from nltk.tokenize import RegexpTokenizer
from spacy.lang.en import English
nlp = English()
config = {"punct_chars": None}
nlp.add_pipe("sentencizer", config=config)
parser = argparse.ArgumentParser()
parser.add_argument("--paragrap... | Python | 1 |
,
UnaryOpCall,
Parenthesized,
}
impl HeadKind {
fn guess<T: TokenRead>(parser: &mut Parser<T>) -> Result<Self> {
Ok(match track!(parser.parse())? {
LexicalToken::Symbol(t) => match t.value() {
Symbol::OpenBrace => HeadKind::Tuple,
Symbol::DoubleLeftAngle =... | Rust | 0 |
import sys
from pathlib import Path
from PySide6.QtGui import QGuiApplication, QIcon
from PySide6.QtQml import QQmlApplicationEngine
from screenvivid import rc_main
from screenvivid import rc_icons
from screenvivid import rc_images
from screenvivid.models import (
ClipTrackModel, WindowControllerModel, VideoContr... | Python | 1 |
lish (Canada)",
"en_GB": "English (UK)",
"en_ZA": "English (South Africa)",
"eo": "Esperanto",
"es_ES": "Español",
"es_EC": "Español de Ecuador",
"es_CO": "Español de Colombia",
"es_AR": "Español de Argentina",
"es_DO": "Esp... | Python | 1 |
st_{int(time.time() * 1000)}"
payload = {"jsonrpc": "2.0", "method": method, "params": params, "id": request_id}
headers = {"Content-Type": "application/json", "X-API-Key": api_key}
async with httpx.AsyncClient(timeout=timeout) as client:
response = await client.post(url, json=payload, headers=he... | Python | 1 |
.edgecastcdn.net",
"*.xx.fbcdn.net",
]
.iter()
.map(|s| s.to_string())
.collect();
let output = filter_whitelist(&blacklist, &whitelist);
let expected: Vec<_> = vec!["zedo.com", "doubleclick.net"]
.iter()
.map(|s| s.to_string())
... | Rust | 0 |
#
# Copyright (c) 2023 Airbyte, Inc., all rights reserved.
#
from .source import SourceIntruder
__all__ = ["SourceIntruder"]
| Python | 1 |
"""engine.SCons.Tool.aixf77
Tool-specific initialization for IBM Visual Age f77 Fortran compiler.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 20... | Python | 1 |
mut rast_tri = setup_rasterizer_triangle();
rast_tri.edge_functions.eval(299, 299);
assert!(rast_tri.edge_functions.any_coverage());
assert_eq!(rast_tri.edge_functions.coverage_mask.mask, 0b1100);
rast_tri.edge_functions.eval(150, 224);
assert!(rast_tri.edge_functions.any_cove... | Rust | 0 |
f" ⚠️ Total warnings: {total_warnings}")
if total_errors > 0:
print(f" ❌ Total errors: {total_errors}")
print(f" 📁 Files with issues: {files_with_issues}")
print(f" 📁 Clean files: {processed_files - files_with_issues}")
# Exit with appropriate code based on warnings-only mode
if warnings_only... | Python | 1 |
return value
else:
return f"_{value}_"
else:
return value
def parse_objects(filedict):
algorithm = create_obj_from_json(enclose_class_name({filedict['algorithm']:filedict['algorithm_parameters']}))
protocol = create_obj_from_json(enclose_class_name(filedict['protocol']))
sc... | Python | 1 |
n");
}
#[test]
fn test_alternate_record_delimiter() {
let input: &[u8] = b"first,second,third|fourth,fifth,sixth";
let cursor = io::Cursor::new(input);
let mut out = Vec::new();
merge_input(
cursor,
&mut out,
OutputTemplate::parse("single: {2}", COMMA_BYTE, PIPE_BYTE)).unwrap()... | Rust | 0 |
# Copyright (C) 2014-2016 Optiv, Inc. (brad.spengler@optiv.com), KillerInstinct
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
try:
import re2 as re
except ImportError:
import re
from lib.cuckoo.common.abstracts import Signature
clas... | Python | 1 |
while i < 101 {
if i % 15 == 0 {
println!("FizzBuzz");
}
else if i % 3 == 0 {
println!("Fizz");
}
else if i % 5 == 0 {
println!("Buzz");
}
else {
println!("{}", i);
}
i+=1;
}
}
//! Test Chai... | Rust | 0 |
ld_eye.shape
left_side_threshold = threshold_eye[0: height, 0: int(width / 2)]
left_side_white = cv2.countNonZero(left_side_threshold)
right_side_threshold = threshold_eye[0: height, int(width / 2): width]
right_side_white = cv2.countNonZero(right_side_threshold)
if left_side_white == 0:
g... | Python | 1 |
0
pub const KEY_QUERY_VALUE: u32 = 0x0001;
pub const KEY_SET_VALUE: u32 = 0x0002;
pub const KEY_CREATE_SUB_KEY: u32 = 0x0004;
pub const KEY_ENUMERATE_SUB_KEYS: u32 = 0x0008;
pub const KEY_NOTIFY: u32 = 0x0010;
pub const KEY_CREATE_LINK: u32 = 0x0020;
pub const KEY_WOW64_32KEY: u32 = 0x0200;
pub const KEY_WOW64_64KEY: u... | Rust | 0 |
from web3 import Web3
from eth_account import Account
import time
# Connect to Base RPC network (replace with your own RPC URL)
base_rpc_url = 'YOUR_BASE_RPC_URL_HERE' # Replace with your Base RPC URL
web3 = Web3(Web3.HTTPProvider(base_rpc_url))
# Check connection
if not web3.is_connected():
print("Failed to con... | Python | 1 |
generated_metric_results(self,save_name:str='OmniDocBench_table'):
from .metrics import show_result, get_full_labels_results, get_page_split, METRIC_REGISTRY
p_scores={}
page_info={}
no_page_flag=False
samples=self.table_samples
pages=self.gt_samples
for page in... | Python | 1 |
import weaviate
import time
client = weaviate.Client("http://localhost:8080")
# Wait until weaviate is ready
while True:
try:
if client.is_ready():
break
except Exception:
pass
print("Waiting for Weaviate to be ready...")
time.sleep(2)
schema = client.schema.get()
doc_name... | Python | 1 |
import heapq
def a_star():
# Define the initial state and the goal state of the problem
initial_state = (0, 0, 0, 0, [])
goal_sum = 211
# Define the coins and their tax values
coins = [10, 5, 6, 2, 16, 19, 18, 5, 11, 12, 11, 7, 13, 19, 11, 12, 8, 17, 5, 18, 3, 12, 10, 14, 20, 18, 10, 11, 20, 13, ... | Python | 1 |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from typing import List
def coins_dp(values: List[int], target: int) -> int:
# memo[i]表示target为i的时候,所需的最少硬币数
memo = [0] * (target+1)
# 0元的时候为0个
memo[0] = 0
for i in range(1, target+1):
min_num = 999999
# 对于values中的所有n
# memo[i]为 m... | Python | 1 |
from openai import OpenAI
import os
from typing import Literal
import dotenv
dotenv.load_dotenv()
class LLMModel:
"""LLM model selection class supporting multiple providers."""
def __init__(self, model_type: Literal["1", "2"]):
"""Initialize the LLM model based on the selected type:
1-Ollama Ll... | Python | 1 |
)
class BaseOsmWidget(BaseGeometryWidget):
"""An OpenStreetMap base widget"""
map_srid = 3857
template_name = 'floppyforms/gis/osm.html'
class Media:
js = (
'floppyforms/openlayers/OpenLayers.js',
'https://www.openstreetmap.org/openlayers/OpenStreetMap.js',
... | Python | 1 |
+ size.y / 2.0;
let down = center.y - size.y / 2.0;
let vertices = vec![ right, down, 0.0,
right, up, 0.0,
left, up, 0.0,
right, down, 0.0,
left, up, 0.0,
left, down, 0.0 ];
let buf... | Rust | 0 |
# Generated by Django 5.2.4 on 2025-07-09 11:10
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('grow_your_wealth', '0003_alter_investment_company_alter_investment_name'),
]
operations = [
migrations.AlterMo... | Python | 1 |
_eq!(map.len(), 10);
let mut keys = {
let mut tmp = AssociatedKeys::default();
map.for_each(|(key, weight)| assert!(tmp.add_key(key, weight).is_ok()));
tmp
};
assert_eq!(
keys.add_key(
AccountHash::new([100u8; ACCOUNT_HASH_LENGTH]),... | Rust | 0 |
ed: bool,
pub direction: Direction,
pub dex: &'browser Dex,
pub rect: Rect,
pub style_sheet: &'browser StyleSheet,
}
#[derive(Copy, Clone, Debug)]
pub struct StyleSheet {
pub focused: Style,
pub unfocused: Style,
pub selected: Style,
pub type_colors: TypeColors,
pub stat_colors: StatColors,
/// Th... | Rust | 0 |
2)),
Some(Amber),
Some(Amber),
],
[
Some(parse_amphipod(b1)),
Some(parse_amphipod(b2)),
Some(Bronze),
Some(Bronze),
],
[
Some(parse_amphipod(c1)),
Some(parse_amphipod(c2)),
Some(Co... | Rust | 0 |
")?;
/// assert!(bucket.has(&"an id")?);
/// # Ok(())
/// # }
/// #
/// # fn main() {
/// # }
/// ```
#[cfg_attr(feature = "futures", cold)]
#[inline]
pub fn has(&mut self, holder_id: &T) -> Result<bool, V::Error> {
self.backend.has(holder_id)
}
/// Returns a... | Rust | 0 |
import json
from pathlib import Path
from typing import List, Union
from langchain_core.documents import Document
from langchain_core.utils import stringify_dict
from langchain_community.document_loaders.base import BaseLoader
class AirbyteJSONLoader(BaseLoader):
"""Load local `Airbyte` json files."""
def ... | Python | 1 |
nce/search#text-match-metadata).
///
/// For example, if you're looking for a list of popular users, you might try this query:
///
/// `q=tom+repos:%3E42+followers:%3E1000`
///
/// This query searches for users with the name `tom`. The results are restricted to users with more than 42 reposit... | Rust | 0 |
en: bool,
}
impl FlatCatOpts {
pub fn new() -> Self {
Default::default()
}
pub fn with_flatten(self, flatten: bool) -> Self {
FlatCatOpts { flatten }
}
}
impl Default for FlatCatOpts {
fn default() -> Self {
FlatCatOpts { flatten: true }
}
}
#[derive(Debug)]
pub struc... | Rust | 0 |
"""
This module contains the methods for the ``openxc-obd2scanner`` command line
program.
`main` is executed when ``openxc-obd2scanner`` is run, and all other callables in this
module are internal only.
"""
import sys
import argparse
from .common import device_options, configure_logging, select_device
import json
i... | Python | 1 |
import subprocess
import os
import sys
def transfer_commit_history(gitlab_repo, github_repo):
SKIP_EXTENSIONS = [".jpg", ".jpeg", ".png", ".gif", ".mov"]
try:
subprocess.run(['git', 'clone', gitlab_repo, 'gitlab_repo'])
os.chdir('gitlab_repo')
for ext in SKIP_EXTENSIONS:
s... | Python | 1 |
#!/usr/bin/env python3
"""The User module"""
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class User(Base):
"""user representation"""
__tablename__ = "users"
id = Column(Integer, primary_key=True)
email = Column(Stri... | Python | 1 |
"""
Package Python Neutrosophic Sets (PYNS)
----------------------------------------------------------------------------------
author: Giorgio Nordo - Dipartimento MIFT, Università di Messina, Italy
www.nordo.it | giorgio.nordo@unime.it
--------------------------------------------------------------------------------... | Python | 1 |
ith `fern`
//! frontend, to display neatly formatted console output and write same output to a file.
//!
//! Output in question is a trace of app's initialization, and keyboard presses when it's running.
//!
//! `fern` provides a way to write log output to a `std::sync::mpsc::Sender`, so we can use a
//! matching `std:... | Rust | 0 |
Countries::Vu => "VU",
PaymentLinksResourceShippingAddressCollectionAllowedCountries::Wf => "WF",
PaymentLinksResourceShippingAddressCollectionAllowedCountries::Ws => "WS",
PaymentLinksResourceShippingAddressCollectionAllowedCountries::Xk => "XK",
PaymentLinksResourceShip... | Rust | 0 |
rand::distributions::Alphanumeric).take(8).collect(),
]),
);
let env =
fs.create_salted_nested_environment("test_cli").expect("failed to create environment");
let fs = fs.for_each_concurrent(None, |()| async move {});
futures::pin_mut!(fs);
for Command { args, expected_stdout, expec... | Rust | 0 |
np.expand_dims(
np.array(picked_labels),
axis=-1), np.expand_dims(
picked_box_probs[:, 4], axis=-1),
picked_box_probs[:, :4]
],
... | Python | 1 |
def login(choosen_client_secret, name):
choosen_secret_data = cls.retrieve_setting(
type="youtube_client_secrets"
)[choosen_client_secret]
new_oauth_entry = cls.__oauth(choosen_secret_data)
current_oauths = ... | Python | 1 |
Result<(), failure::Error> {
// logger
let log_level = common::log_level();
let log = common::create_logger(log_level.clone());
// prepare data - we have stored 1326 request, apply just 1324, and 1325,1326 will be used for mempool test
let (requests, operations, tezos_env) = samples::read_data_app... | Rust | 0 |
# Copyright 2024 Leonin League
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | Python | 1 |
alerts-for-your-repository#viewing-the-alerts-for-a-repository)."
///
/// You must compress the SARIF-formatted analysis data that you want to upload, using `gzip`, and then encode it as a Base64 format string. For example:
///
/// ```nocompile
/// gzip -c analysis-data.sarif | base64 -w0
/// ... | Rust | 0 |
ind, {:?}", k);
}
}
}
Ok(d) => {
assert!(false, "No data expected, {:?}", d);
}
}
match dmx_recv.recv(None) {
Err(e) => {
match e.kind() {
ErrorKind::SourceDiscovered(_) => {
let interval = i... | Rust | 0 |
import uos
class VFS():
@staticmethod
def GetFSInfo():
"""@brief Get the used and available disk space.
@return A tuple containing
0 = The total disk space in bytes.
1 = The used disk space in bytes.
2 = The % used disk space."""
... | Python | 1 |
# config.py
import os
DB_PATH = "telemetry.db"
# Frequenza (Hz) per la telemetria
TELEMETRY_HZ = 10
# Parametri Training ML
EPOCHS = 5
BATCH_SIZE = 64
LEARNING_RATE = 0.001
LOCAL_TF_MODEL_PATH = "local_tf_model"
# Imposta il modello Falcon-7B invece di GPT-J
LOCAL_LLM_MODEL_NAME = "tiiuae/falcon-7b-instruct"
# L... | Python | 1 |
account(unlockable_account_dual_type)
assert locked is True
@pytest.mark.asyncio
async def test_async_send_transaction(
self,
async_w3: "AsyncWeb3",
unlockable_account_dual_type: ChecksumAddress,
unlockable_account_pw: str,
) -> None:
tx_params = TxParams()
... | Python | 1 |
serializer
@abstractmethod
def serialize(self, constraint: AbstractAuthConstraint) -> bytes:
raise NotImplementedError()
@abstractmethod
def deserialize(self, serialized_str: bytes) -> AbstractAuthConstraint:
raise NotImplementedError()
class ConstraintsSerializer(AbstractConstraintS... | Python | 1 |
order"):
embeddings = tf.nn.embedding_lookup(FM_V, feat_ids) # None * F * K
feat_vals = tf.reshape(feat_vals, shape=[-1, field_size, 1])
embeddings = tf.multiply(embeddings, feat_vals) #vij*xi
sum_square = tf.square(tf.reduce_sum(embeddings,1))... | Python | 1 |
def gen_from_pPCA(noise_var, data_mean, pc_axes, pc_variance):
"""
Generate samples from pPCA
Args:
noise_var: np.ndarray
Sensor noise variance
data_mean: np.ndarray
Thermometer data mean
pc_axes: np.ndarray
Principal component axes
pc_variance: np.ndarray
The variance of ... | Python | 1 |
SHOT_BIG_CHANCE = 0.3
SHOT_TARGET_BIG_CHANCE = 0.5
GOAL_BIG_CHANCE = 0.8
PASSING_POSITIONS = {
"£goalkeeper": 0.03,
"defender": 0.3,
"midfielder": 0.5,
"forward": 0.17
}
from data.database import StatsManager
STAT_FUNCTIONS = {
"Goals scored": StatsManager.get_goals_scored,
"Penalties scored"... | Python | 1 |
# coding: utf-8
"""
functions
"""
import os
import cv2
import numpy as np
def show_landmark(face, landmark):
"""
view face with landmark for visualization
"""
face_copied = face.copy().astype(np.uint8)
for (x, y) in landmark:
xx = int(face.shape[0]*x)
yy = int(face.shape[1... | Python | 1 |
.zCompany Name: z[Would you like to (1) Enter FAQ content directly or (2) Load from JSON file? Enter 1 or 2: 1z/
Enter FAQ content (Type 'done' when finished):Tz+FAQ Entry (e.g., Q: Question? A: Answer.): donerA zEnter path to FAQ JSON file: z-
Enter product categories (comma-separated): ,z5
Company information ... | Python | 1 |
if password:
lower_count, upper_count, num_count, wspace_count, special_count, strength, remarks = check_pwd(password)
st.write('### Your Password Analysis :')
st.write(f"**Lowercase characters :** {lower_count}")
st.write(f"**Uppercase characters :** {upper_count}")
... | Python | 1 |
, 40).unwrap();
let parsed = Schedule::from_str("*/5 * * * * *").unwrap();
let mut iter = parsed.iter_from(&from_date);
assert_eq!(
iter.next().unwrap(),
"2021-02-01T01:01:45Z".parse::<DateTime<Utc>>().unwrap()
);
assert_eq!(
iter.next().unwrap... | Rust | 0 |
pe_}\n"f"Low Spd Feedback: {self.arm_low_spd_feedback_3}\n")
elif(self.type_ == ArmMsgType.PiperMsgLowSpdFeed_4):
return (f"Type: {self.type_}\n"f"Low Spd Feedback: {self.arm_low_spd_feedback_4}\n")
elif(self.type_ == ArmMsgType.PiperMsgLowSpdFeed_5):
return (f"Type: {self.type_}... | Python | 1 |
ateKeyFileName = args.PrivateKeyFile.name
args.PrivateKeyFile.close()
except:
try:
#
# Get path to currently executing script or executable
#
if hasattr(sys, 'frozen'):
RsaToolPath = sys.executable
else:
RsaToolPath = sys.argv[0]
if RsaToolPath.startswit... | Python | 1 |
} else if !s.ends_with('/') || d == d_max {
writeln!(writer, "{}", &s)?;
}
}
Ok(())
}
/*fn parse_val<T: Idx>(buf: &str) -> IResult<&str, T> {
map_res(digit1, |s: &str| s.parse::<T>())(buf)
}*/
/// # Info
/// Internally, we use the `nom` parser with the full file content un memory.
/// Because we u... | Rust | 0 |
#!/usr/bin/python
# -*- encoding: utf-8 -*-
# File : str_feExtra.py
# Time : 2025/08/08 17:45:28
# Author : Y.ZHANG (UniOfSurrey)
# Email : yu.zhang@surrey.ac.uk
# Dec: This script implements feature extraction from symbolic expressions.
import pandas as pd
import re
# === Step 1: 读取CSV文件 ===
df = p... | Python | 1 |
} else if g == max {
2.0 + (b - r) / delta
} else {
4.0 + (r - g) / delta
}
}
};
let h = ((h * 60.0) + 360.0) % 360.0;
(h, s, v)
}
/// Convert to [CIE 1931](https://en.wikipedia.org/wiki/CIE_1931_col... | Rust | 0 |
(thread_rng())),
}
}
pub fn from_seed(seed: <StdRng as SeedableRng>::Seed) -> Self {
Self {
rng: RefCell::new(Box::new(StdRng::from_seed(seed))),
}
}
}
impl Default for CoinFlipStrategy {
fn default() -> CoinFlipStrategy {
CoinFlipStrategy::new()
}
}
im... | Rust | 0 |
ages, tools, **kwargs) -> LLMResponse:
# set max tokens if not provided
kwargs["max_tokens"] = kwargs.get("max_tokens", NOT_GIVEN)
try:
response = retry_on_exception(
self._perform_chat_completion, self.need_to_be_retried
)(
model=self.conf... | Python | 1 |
# coding: utf-8
import caffe
import numpy as np
class CNN(object):
"""
Generalized CNN for simple run forward with given Model
"""
def __init__(self, net, model):
self.net = net
self.model = model
try:
self.cnn = caffe.Net(str(net), str(model), caffe.TEST)
... | Python | 1 |
e(dict1, dict2):
"""Check allclose on dicts."""
assert set(dict1.keys()) == set(dict2.keys())
for key, val in dict1.items():
try:
np.testing.assert_allclose(val, dict2[key])
except TypeError:
assert val == dict2[key]
def test_future_swath_has_attrs():
"""Test th... | Python | 1 |
)]
enum Opt {
Fetch {
#[clap(short)]
all: bool,
#[clap(flatten)]
common: Common,
},
Add(Add),
}
assert_eq!(
Opt::Fetch {
all: false,
common: Common { arg: 42 }
},
Opt::parse_from(&["test... | Rust | 0 |
# Make a zero padded array for the numpy version to operate
paddeda = np.zeros((1005, 1005), dtype=bool)
paddeda[2:-2, 2:-2] = a[:, :]
npdilate = ndi.binary_dilation(np.ascontiguousarray(paddeda),
structure=kernel, iterations=2)
cdilate = dilate5(a, 2)
assert... | Python | 1 |
gnments: Nx1 int numpy array
cluster centers: k x d numpy array, the centers
loss: final loss value of the objective function of KMeans
"""
# centers = self._init_centers(points, k, **kwargs)
# instead of using random initialization, we will use the first k points
centers... | Python | 1 |
: u32 = 256;
pub const CRITICAL_LATITUDE: f64 = 85.051_128_78;
// Calculated with Vincenty method with WGS84, WebMercator parameters
pub const CRITICAL_LATITUDE_IN_METERS: f64 = 9_417_539.062_5;
}
/// Calc a resolution of a latitude
/// return: resolution [m/px]
pub fn meters_per_pixel( latitude: f64, level_of_d... | Rust | 0 |
# Copyright 2023 The DLRover Authors. All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | Python | 1 |
t W {
self.w.bits = (self.w.bits & !(0x03 << 2)) | ((value as u32 & 0x03) << 2);
self.w
}
}
#[doc = "Schmitt trigger enabled for GPIO8.\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum REG_GPIO_8_SMT_A {
#[doc = "0: `0`"]
DISABLED = 0,
#[doc = "1: `1`"]
ENABLE... | Rust | 0 |
te scatter plot
fig_push = go.Figure()
fig_push.add_trace(go.Scatter(
x=push_df['impressions'],
y=push_df['contributions'],
mode='markers',
marker=dict(color='green', size=8, opacity=0.6),
name='SEM - Google Search',
text=[... | Python | 1 |
_client::RouterClient;
pub use crate::state_channel_client::StateChannelClient;
}
pub mod gateway {
pub use crate::gateway_client::GatewayClient as Client;
}
pub mod local {
include!(concat!(env!("OUT_DIR"), "/helium.local.rs"));
pub use api_client::ApiClient as Client;
... | Rust | 0 |
import pytest
from email_reader import limpar_html
def test_limpar_html_remove_tags():
texto = '<b>Teste</b> com <a href="#">tags</a>.'
resultado = limpar_html(texto)
assert resultado == 'Teste com tags.'
def test_limpar_html_sem_tags():
texto = 'Texto limpo.'
resultado = limpar_html(texto)
as... | Python | 1 |
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, EmailStr
class EmailAddress(BaseModel):
"""Email address model"""
email: EmailStr
name: Optional[str] = None
class EmailData(BaseModel):
"""Email data model for webhook payload"""
email_id: str
from_email: EmailStr
... | Python | 1 |
val: str) -> int:
return int(val, base=10)
def coerce_float(val: str) -> float:
return float(val)
def coerce_boolean(val: str) -> bool:
return val == "true" or val == "1" or val == "on"
def maybe_coerce_integer(val: str | None) -> int | None:
if val is None:
return None
return coerce_i... | Python | 1 |
import numpy as np
import pandas as pd
class BVHWriter():
def __init__(self):
pass
def write(self, X, ofile):
# Writing the skeleton info
ofile.write('HIERARCHY\n')
self.motions_ = []
self._printJoint(X, X.root_name, 0, ofile)
# Writing th... | Python | 1 |
background-color: #333333;
color: #ffffff;
padding: 8px 16px;
border-radius: 5px;
}
QPushButton:hover {
background-color: #444444;
}
QPushButton:disabled {
background-color: #222222;
... | Python | 1 |
elf.soc.get_ddr4(n_transfers)
self.soc.reset_gens() # in case the readout tone was left on
complex_iq = iq.dot([1, 1j])
print("done, average number %d" % n)
self.soc.reset_gens()
if n == 0:
freq, power = periodogram(np.abs(complex_iq), fs=1 /... | Python | 1 |
# Copyright 2017 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | Python | 1 |
ck(tok.clone());
}
Some(tok)
}
pub fn peek_with_spaces(&mut self) -> Option<Token> {
let (tok, _) = self.tokens.peek()?.clone();
let range = self.abs_range(tok.len);
Some(Token {
kind: tok.kind,
range,
})
}
pub fn peek(&mut self)... | Rust | 0 |
S):
self.line_avoid_timer = con.LINE_AVOID_FAST
else:
self.line_avoid_timer = con.LINE_AVOID_SLOW
self.line_timer.reset()
antiline_vector = Vector2(0, 0)
if self.line is not None:
antiline_vector.set_angle_magn(
... | Python | 1 |
ve_dir, "self_attention")
create(save_root, "dir")
create(osp.join(save_root, "attention_map"), "dir")
if apply_heat_map:
create(osp.join(save_root, "heat_map"), "dir")
attn_maps = self.self_attn.mean(dim=0) / len(self.hook_steps) # 4096*4096... | Python | 1 |
1_div;
#[doc = "CLK_GPOUT1_SELECTED register accessor: an alias for `Reg<CLK_GPOUT1_SELECTED_SPEC>`"]
pub type CLK_GPOUT1_SELECTED = crate::Reg<clk_gpout1_selected::CLK_GPOUT1_SELECTED_SPEC>;
#[doc = "Indicates which SRC is currently selected by the glitchless mux (one-hot).
This slice does not have a glitchless mux... | Rust | 0 |
stonJoy {
state: u8,
}
impl KempstonJoy {
/// Simulates key press/release
pub fn key(&mut self, key: KempstonKey, state: bool) {
if state {
self.state |= key as u8;
} else {
self.state &= !(key as u8);
}
}
/// Reads joy value
pub fn read(&self) -... | Rust | 0 |
"""
En kloss er spinnvill.
To-do:
Animere
"""
import tkinter as tk # Import tkinter
import time
# Lag vindu
window = tk.Tk() # Create a window
window.title("Spiral") # Set title
window.geometry('400x400')
# Lag klokke-objekt
canvas = tk.Canvas(window, bg="#2e2e2e", width=400, height=400) # Lager et canvas-objek... | Python | 1 |
job_progress,
title=f"[b]Attributing with {escape(method_name)}",
border_style="green",
padding=(1, 2),
)
]
if sequences.sources is not None:
sources = []
for idx, src in enumerate(sequences.sources):
... | Python | 1 |
lf.url,
"layer_description": self.layer_properties["layer_description"],
"item_description": self.layer_properties["item_description"],
"layer_properties": self.layer_properties["layer_properties"],
}
if self.return_geometry:
try:
... | Python | 1 |
error,
self._expected_read_error,
self._incremental_scenario_config,
self._expected_analytics,
self._log_levels,
self._catalog,
)
def _configured_catalog(self, sync_mode: SyncMode) -> Optional[Mapping[str, Any]]:
if not self._expected_cata... | Python | 1 |
"::",
stringify!(ljoin)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<R_GE_gcontext>())).lmitre as *const _ as usize },
40usize,
concat!(
"Offset of field: ",
stringify!(R_GE_gcontext),
"::",
stringify!(lmitre... | Rust | 0 |
Y TTT EE CC III │
│ AA AA III RRRRRR BBBBBB YYYYY TTT EEEEE _____ CC III │
│ AAAAAAA III RR RR BB BB YYY TTT EE CC III │
│ AA AA IIIII RR RR BBBBBB YYY TTT EEEEEEE CCCCC IIIII │
│ ... | Python | 1 |
CGT_asimdsame_only(d: u32) -> bool {
(d & 0xbfa0fc00) == 0x2ea0ec00
}
pub const fn is_FMINP_asimdsame_only(d: u32) -> bool {
(d & 0xbfa0fc00) == 0x2ea0f400
}
pub const fn is_BIT_asimdsame_only(d: u32) -> bool {
(d & 0xbfe0fc00) == 0x2ea01c00
}
pub const fn is_BIF_asimdsame_only(d: u32) -> bool {
(d &... | Rust | 0 |
::number::one | This::is::a::kinda::very::long::header::number::two | This::is::a::kinda::very::long::header::number::one | This::is::a::kinda::very::long::header::number::two |
/// | ----------- | ----------- | ----------- | ----------- |
/// | This::is::a::kinda::long::content::number::one | This::is::a::kind... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.