text string | label_name string | labels int64 |
|---|---|---|
import IMP
import IMP.test
import IMP.core
import pickle
class Tests(IMP.test.TestCase):
def test_pickle(self):
"""Test (un-)pickle of ConjugateGradients"""
m = IMP.Model()
p1 = IMP.Particle(m)
p2 = IMP.Particle(m)
d1 = IMP.core.XYZ.setup_particle(p1, IMP.algebra.Vector3D(... | Python | 1 |
float::<(&str, ErrorKind)>("-0.0"),
Ok(("", TomlValue::Float(-0.0)))
);
}
#[test]
fn test_unsigned_nan_float() {
match float::<(&str, ErrorKind)>("nan") {
Ok(("", TomlValue::Float(num))) => assert!(f64::is_nan(num)),
_ => panic!("nan testing we... | Rust | 0 |
Ops::Back => {
let val = out.value();
if val.len() > 1 {
txt.pop();
out.set_value(txt.as_str());
}
}
Ops::CE => {
txt.cl... | Rust | 0 |
r"""
:param _InstanceId: Prometheus 实例 ID
:type InstanceId: str
:param _GrafanaId: Grafana 可视化服务实例 ID
:type GrafanaId: str
"""
self._InstanceId = None
self._GrafanaId = None
@property
def InstanceId(self):
"""Prometheus 实例 ID
:rtype: str
... | Python | 1 |
return jsonify(msg="Payment initiated!",
response_code=response_data['ResponseCode'],
checkout_request_id=response_data['CheckoutRequestID'],
), response.status_code
return jsonify(response.content.deco... | Python | 1 |
ector_db_config.vertex_vector_search.index = index
elif isinstance(vector_config, Pinecone):
index_name = vector_config.index_name
api_key = vector_config.api_key
rag_corpus.vector_db_config.pinecone.index_name = index_name
rag_corpus.vector_db_config.api_auth.ap... | Python | 1 |
hasher.update(self.entropy.as_slice());
let hash = hasher.finalize();
let hash_0 = BitVec::<Msb0, u8>::from_element(hash[0]);
let (checksum, _) = hash_0.split_at(length / 3);
// Convert the entropy bytes into bits and append the checksum.
let mut encoding = BitVec::<Msb... | Rust | 0 |
<T>, value: T)
where
T: Hash + Eq + Ord,
{
assert!(set.contains(&value));
}
fn assert_set_insert<T>(set: &mut impl Set<T>, value: T)
where
T: Hash + Eq + Ord,
{
assert!(set.insert(value));
}
#[test]
fn test_hash_set() {
let mut set = std::col... | Rust | 0 |
.mean(T.sqr(T.maximum(0.,1.-target*train_output)))
if binary:
# W updates
W = lasagne.layers.get_all_params(cnn, binary=True)
W_grads = binary_connect.compute_grads(loss,cnn)
updates = lasagne.updates.adam(loss_or_grads=W_grads, params=W, learning_rate=LR)
updat... | Python | 1 |
not 0.0 <= betas[1] < 1.0:
raise ValueError(
"Invalid beta parameter at index 1: {}".format(betas[1])
)
defaults = dict(
lr=lr,
betas=betas,
eps=eps,
weight_decay=weight_decay,
warmup=warmup
)
s... | Python | 1 |
_a: true,
load_d: false,
a_or_ram: true,
alu_or_rom: false,
ram_storage: false
}
);
assert_eq!(
Hack::decoder(-5497),
DecoderOutput {
negate_output: false,
function: true,
... | Rust | 0 |
"""
Drawing the Mandelbrot set
based on R code by Myles Harrison
http://www.everydayanalytics.ca
original source of the Python code:
https://github.com/krother/Python3_Package_Examples
MIT License
"""
import numpy as np
from PIL import Image
def get_next_iter(z, c, index):
"""calculate the next generation ... | Python | 1 |
from collections import Counter
import sys
input = sys.stdin.readline
# 케빈 베이컨의 수는 나를 제외한 다른 사람까지의 dist의 총합이라고 볼 수 있다.
N, M = map(int, input().split())
graph = [[] for _ in range(N+1)]
for _ in range(M):
a, b = map(int, input().split())
graph[a].append((b, 1))
graph[b].append((a, 1))
import heapq
#각 위치에서... | Python | 1 |
) == "x = Symbol('x')\ny = Symbol('y')\nf = Function('f')\ne = f(x, y)"
assert python(f(x/(y + 1), y)) in [
"x = Symbol('x')\ny = Symbol('y')\nf = Function('f')\ne = f(x/(1 + y), y)",
"x = Symbol('x')\ny = Symbol('y')\nf = Function('f')\ne = f(x/(y + 1), y)"]
# Nesting of square roots
asser... | Python | 1 |
unsafe {
let ctx = seccomp_init(SCMP_ACT_TRAP);
assert!(!ctx.is_null());
allow_syscall(ctx, __NR_execve);
allow_syscall(ctx, __NR_brk);
allow_syscall(ctx, __NR_access);
allow_syscall(ctx, __NR_mmap);
allow_syscall(ctx, __NR_open);
allow_syscall(ctx, _... | Rust | 0 |
'''
3
5
477162 658880 751280 927930 297191
5
565469 851600 460874 148692 111090
10
784386 279993 982220 996285 614710 992232 195265 359810 919192 158175
'''
T = int(input()) # 테스트케이스 개수
for tc in range(1, T+1):
N = int(input())
arr = list(map(int, input().split()))
max_v = arr[0]
min_v = arr[0]
fo... | Python | 1 |
error!("Invalid .aurl/profiles: {}", e);
abort();
}
Ok(_) => (),
}
}
<filename>tests/test_day17.rs<gh_stars>0
use aoc_2021::day17 as day;
#[test]
fn test_part1() {
let mut inputs = "target area: x=20..30, y=-10..-5";
let mut expected = 45;
let mut result = day::par... | Rust | 0 |
{
if !event.alt_key()
&& !event.alt_key()
&& !event.ctrl_key()
&& !event.meta_key()
{
term.write(&event.key());
line.push_str(&e.key());
cursor_col += 1;
}
}
}
let mut shell_state = self.shell_state.lock().unwrap();
*... | Rust | 0 |
1;
}
if scan_idx <= (height << bwl) / 4 {
return 2;
}
return 3;
}
let padded_idx = coeff_idx + ((coeff_idx >> bwl) << TX_PAD_HOR_LOG2);
let stats = self.get_nz_mag(&levels[padded_idx..], bwl, tx_class);
self.get_nz_map_ctx_from_stats(stats, coeff_idx, bwl, tx_size, tx_cl... | Rust | 0 |
8955958665577945c89419d1af06b5f7636b4ac3da7f12184802ad867736",
),
]
.iter()
.map(|l| {
DescriptorBuilder::default()
.media_type(MediaType::ImageLayerGzip)
.size(l.0)
.digest(l.1.to_owned())
.build()
... | Rust | 0 |
let dtks = get_dtks(×, t_nxt);
let sol = vec![1.0, 1.0, 2.0, 3.0];
assert_eq!(dtks.len(), 4);
const TOL: f64 = 1.0e-12_f64;
for i in 0..4 {
assert!((dtks[i] - sol[i]).abs() < TOL);
}
}
#[test]
fn test_psis_n() {
// from previous test... | Rust | 0 |
, stmt: &Statement<MetaT>) -> ResultT;
fn visit_class(&mut self, class: &Class<MetaT>) -> ResultT;
fn visit_function(&mut self, function: &Function<MetaT>) -> ResultT;
}
use cfg_if::cfg_if;
cfg_if! {
if #[cfg(windows)] {
mod windows;
use self::windows as arch;
} else if #[cfg(unix)] {
... | Rust | 0 |
, which is expected to contain the relevant information or answer.
Args:
response (Any): The response object received from an OpenAI API call. It is expected to
follow the structure of OpenAI's chat completion response.
Returns:
str: A string containing the message ... | Python | 1 |
rchaudio.transforms.Resample(orig_freq=sr2, new_freq=16000)
wav1 = resample1(wav1)
wav2 = resample2(wav2)
if use_gpu:
wav1 = wav1.cuda(device)
wav2 = wav2.cuda(device)
with torch.no_grad():
emb1 = model(wav1)
emb2 = model(wav2)
si... | Python | 1 |
from typing import Generator
import pytest
from vidore_benchmark.retrievers.colidefics3_retriever import ColIdefics3Retriever
from vidore_benchmark.utils.torch_utils import tear_down_torch
@pytest.fixture(scope="module")
def retriever() -> Generator[ColIdefics3Retriever, None, None]:
yield ColIdefics3Retriever(... | Python | 1 |
}
None
}
fn is_deposit_event(&self, target_def_id: DefId) -> bool {
let path = self.tcx.def_path_str(target_def_id);
path.starts_with("pallet::Pallet") && path.ends_with("deposit_event")
}
fn is_closure_call(&self, target_def_id: DefId) -> bool {
let path: &str = &s... | Rust | 0 |
# Mutable/Immutable Data types
a = [54, 23, 10, 99, -90]
# these are prebuild functions
print(len(a))
print(sum(a))
print(max(a))
print(min(a))
# functions used in the list object, are list methods
a.append("Aayush")
a.append(-100)
a.insert(4, "Python")
a[0] = 100 # updating values
a.pop(1) # Remove by index
a.re... | Python | 1 |
#List are the container to store a set's of value of any type of data
leest=["Sanket",45,"G1",True,9.45]
leest[2]="2G1"#1. To change the Indexing Value
print("1.After Change the value of an index",leest)
leest.append("ITER")#2. Insert value at the last of the list
print("2.Insert value at the last index of the list ",... | Python | 1 |
def test_invalid_mnemonic(self):
for test in TEST_VECT_MNEMONIC_INVALID:
lang = test["lang"] if "lang" in test else ElectrumV1Languages.ENGLISH
self.assertFalse(ElectrumV1MnemonicValidator(lang).IsValid(test["mnemonic"]))
self.assertRaises(test["exception"], ElectrumV1M... | Python | 1 |
_rollback();
trans.finish().unwrap();
Err(err)
}
}
}
#[get("/data/feature/<id>")]
fn feature_get(conn: State<DbReadWrite>, read_conn: State<DbRead>, mut auth: auth::Auth, auth_rules: State<auth::CustomAuth>, id: i64) -> Result<String, HecateError> {
auth_rules.allows_feature_get... | Rust | 0 |
;
let res = crate::actor_delegate_proto::SignTransactionResponse {
task_id: get_uuid().as_bytes().to_vec(),
data_adhoc: crate::actor_delegate_proto::SignTransactionData {
transaction_data,
delegator_tea_nonce_hash,
d... | Rust | 0 |
# Copyright 2017 FUJITSU LIMITED
#
# 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 writ... | Python | 1 |
rded_at_begin: recorded_at_begin,
recorded_at_end: recorded_at_end,
ex_rate_sell_max: ex_rate_sell_max,
ex_rate_sell_min: ex_rate_sell_min,
ex_rate_buy_max: ex_rate_buy_max,
ex_rate_buy_min: ex_rate_buy_min,
... | Rust | 0 |
from luthien_control.control_policy.conditions.all_cond import AllCondition
from luthien_control.control_policy.conditions.any_cond import AnyCondition
from luthien_control.control_policy.conditions.comparison_conditions import (
ContainsCondition,
EqualsCondition,
GreaterThanCondition,
GreaterThanOrEqu... | Python | 1 |
import pytest
from selenium.webdriver import Firefox
from modules.browser_object_autofill_popup import AutofillPopup
from modules.page_object import AboutPrefs
from modules.page_object_autofill import CreditCardFill
from modules.util import Utilities
@pytest.fixture()
def test_case():
return "122391"
def test_... | Python | 1 |
# rename file name data.txt to details.txt using os module
import os
os.rename("unit 2/data.txt","unit 2/details.txt") | Python | 1 |
struct Name<'a> {
pub value: &'a str,
pub lpar: Vec<LeftParen<'a>>,
pub rpar: Vec<RightParen<'a>>,
}
impl<'a> Inflate<'a> for Name<'a> {
fn inflate(mut self, config: &Config<'a>) -> Result<Self> {
self.lpar = self.lpar.inflate(config)?;
self.rpar = self.rpar.inflate(config)?;
O... | Rust | 0 |
if mode == 'all': return ret
raise ValueError(f"未知的查找模式: {mode}")
# 没有索引的情况下遍历查找
data = await self.get()
return find_by(data, key, value, mode)
async def collect_by(self, key: str, values: Union[List[Any], Set[Any]]):
# 使用索引
ind = await self.indices(ke... | Python | 1 |
"dox", doc(cfg(not(feature = "v2_16"))))]
#[doc(alias = "webkit_dom_html_document_get_dir")]
#[doc(alias = "get_dir")]
fn dir(&self) -> Option<glib::GString>;
#[cfg_attr(feature = "v2_14", deprecated = "Since 2.14")]
#[cfg(any(not(feature = "v2_14"), feature = "dox"))]
#[cfg_attr(feature = "do... | Rust | 0 |
operation(input: &str) -> IResult<&str, Operation, SemverParseError<&str>> {
use Operation::*;
alt((
map(tag(">="), |_| GreaterThanEquals),
map(tag(">"), |_| GreaterThan),
map(tag("="), |_| Exact),
map(tag("<="), |_| LessThanEquals),
map(tag("<"), |_| LessThan),
))(i... | Rust | 0 |
unsafe fn read_reg16(&self, reg: usize) -> u16;
unsafe fn read_reg32(&self, reg: usize) -> u32;
unsafe fn read_reg64(&self, reg: usize) -> u64;
}
}
}
// Copyright 2020-2021, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>
// SPDX-License-Identifier: MIT OR Apache-2.0
#![allow... | Rust | 0 |
True))
>>> Heaviside(x, nan).rewrite(sign)
Piecewise((sign(x)/2 + 1/2, Ne(x, 0)), (nan, True))
>>> Heaviside(x - 2).rewrite(sign)
sign(x - 2)/2 + 1/2
>>> Heaviside(x**2 - 2*x + 1).rewrite(sign)
sign(x**2 - 2*x + 1)/2 + 1/2
>>> Heaviside(y).rewrite(sign)
... | Python | 1 |
t = np.ones((h, w, 3), dtype=np.uint8) * 255
random.seed(0)
draw_left = ImageDraw.Draw(img_left)
if txts is None or len(txts) != len(boxes):
txts = [None] * len(boxes)
for idx, (box, txt) in enumerate(zip(boxes, txts)):
if scores is not None and scores[idx] < drop_score:
con... | Python | 1 |
ath.join(args.output_dir, 'annotations', 'instances_train2025.json')
with open(train_out_path, 'w') as f:
json.dump(merged_train, f, indent=2)
print(f"Saved merged train annotations to: {train_out_path}")
# Merge validation set
merged_val = merge_datasets(orig_val_data, aug_val_data, 'val')... | Python | 1 |
window.update_result(result)
window.update_status("转写完成")
# 播放提示音
play_notification_sound()
else:
window.update_status("转写未能得到结果")
else:
# 实时模式已有结果
window.up... | Python | 1 |
SimpleObject::class_init(klass);
}
}
}
glib_wrapper! {
pub struct SimpleObject(Object<imp::SimpleObject>):
[Object => InstanceStruct<Object>];
match fn {
get_type => || imp::SimpleObject::get_type().to_glib(),
}
}
impl SimpleObject {
pub fn new(name: Option<&s... | Rust | 0 |
from appium import webdriver
from appium.options.android import UiAutomator2Options
from appium.webdriver.appium_service import AppiumService
from appium.webdriver.common.appiumby import AppiumBy
import time
# appium_service = AppiumService()
# appium_service.start()
desired_caps = {}
desired_caps['platformName'] = ... | Python | 1 |
())
} else {
Err(TotalCapacityError {})
}
}
}
// THIS FILE IS GENERATED. ONE SHOULD NOT MODIFY IT
//! This module provides terms for `Lexicon Model for Ontologies - LIngusitic MEtadata (LIME)` vocabulary
//!
//! This module requires `ns-lime` feature to be enabled.
//!
//! ## Vocabulary:... | Rust | 0 |
# -*- coding: utf-8 -*-
''' Home made test.'''
from __future__ import print_function
__author__= "Luis C. Pérez Tato (LCPT) and Ana Ortega (AOO)"
__copyright__= "Copyright 2015, LCPT and AOO"
__license__= "GPL"
__version__= "3.0"
__email__= "l.pereztato@gmail.com"
K= 1000 # Spring constant
l= 1e-7 # Distance between... | Python | 1 |
curr_num_good = num_good
curr_grid_next = grid_next
curr_grid_good = grid_good
curr_M = M
# If we found something with more than max needed, good enough to stop here
if num_good > max_pts_needed:
break
# If we found something
... | Python | 1 |
all;
mod find_one;
mod register;
#[derive(Derivative)]
#[derivative(Debug)]
pub enum RunnerStoreMsg {
FindAll {
#[derivative(Debug = "ignore")]
tx: OTx<Vec<Runner>>,
},
FindOne {
id: DRunnerId,
#[derivative(Debug = "ignore")]
tx: OTx<Result<Runner>>,
},
Re... | Rust | 0 |
schema::clients::uuid.eq(payload.client_id.unwrap()),
))
.map_err(|_| err!(Status::BadRequest, "invalid client"))?
.inner;
match &payload.grant_type.unwrap()[..] {
"password" => {
let credentials = payload.credentials.unwrap();
grant_token(Password::n... | Rust | 0 |
{
ring::digest::Context::new(&ring::digest::SHA256)
} else if hash_algorithm == "SHA1" {
ring::digest::Context::new(&ring::digest::SHA1)
} else {
panic!("Unknown hash algorithm: {}", hash_algorithm);
}
}
fn hash_pass(pass: &str, salt: &Vec<u8>, count: u32, hash_algorithm: &String) -... | Rust | 0 |
this AABB.
pub min_z: f32,
/// Maximum x-coordinate of this AABB.
pub max_x: f32,
/// Maximum y-coordinate of this AABB.
pub max_y: f32,
/// Maximum z-coordinate of this AABB.
pub max_z: f32,
}
impl AABB {
/// Create a new axis-aligned bounding box.
pub fn new(min_x: f32, min_y: f3... | Rust | 0 |
"""create table rss_fwd_record
Revision ID: 981aec5a86cb
Revises:
Create Date: 2025-01-12 00:23:19.262195
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '981aec5a86cb'
down_revision: Union[str, None] = None
branch_labe... | Python | 1 |
S synchronization required)
pub freq: f64, // TX central frequency in MHz (unsigned float, Hz precision)
pub rfch: u64, // Concentrator "RF chain" used for TX (unsigned integer)
pub powe: u64, // TX output power in dBm (unsigned integer, dBm precision)
pub modu: Modulation, // Modul... | Rust | 0 |
from kcwarden.api import Auditor
from kcwarden.custom_types.result import Severity
class OIDCIdentityProviderWithoutPKCE(Auditor):
DEFAULT_SEVERITY = Severity.Medium
SHORT_DESCRIPTION = "OIDC Identity Provider configured without PKCE"
LONG_DESCRIPTION = "The realm has configured an OIDC Identity Provider,... | Python | 1 |
import logging
from typing import List, Dict, Any, Optional
from datetime import datetime
import json
logger = logging.getLogger(__name__)
class ContextBuilder:
"""上下文构建器,将检索到的数据整理成适合LLM处理的格式"""
def __init__(self, max_context_length: int = 8000):
"""
初始化上下文构建器
Args:
... | Python | 1 |
# scikit-image 0.18 or later is required.
from logging.config import valid_ident
import numpy as np
from skimage import measure
from cqmore import Workplane
from cadquery import exporters
from cqmore.polyhedron import gridSurface
def gray_scott(feel, kill, generation, space_size = 200, init_size = 20, init_u = 0.5, ... | Python | 1 |
"The name of the wrapper element is not defined. The WS-I defines
that it should be the operation name with the 'Response' string as
suffix. But lets just do it really stupid for now and use the first
element.
"""
process_multiref(body_element)
response_element = list(b... | Python | 1 |
/features.html",
}
pub fn build_features_handler(req: &mut Request) -> IronResult<Response> {
let router = extension!(req, Router);
let name = cexpect!(req, router.find("name"));
let req_version = router.find("version");
let mut conn = extension!(req, Pool).get()?;
let (version, version_or_latest)... | Rust | 0 |
stream: *mut ktxStream,
createFlags: ktxTextureCreateFlags,
newTex: *mut *mut ktxTexture2,
) -> ktx_error_code_e;
}
extern "C" {
pub fn ktxTexture2_CompressBasis(
This: *mut ktxTexture2,
quality: ktx_uint32_t,
) -> ktx_error_code_e;
}
extern "C" {
pub fn ktxTextur... | Rust | 0 |
]
type BlockPercentEachYear: Get<Ratio>;
type OnUpdateLoan: Happened<(Self::AccountId, CurrencyId, Amount, Balance)>;
#[pallet::constant]
type UnsignedPriority: Get<TransactionPriority>;
}
#[pallet::storage]
#[pallet::getter(fn asset_pool_infos)]
pub type AssetPoolInfos<T: Config> = StorageMap<_, Twox64C... | Rust | 0 |
t error = "{\"Response\":{\"Error\":{\"Code\":\"AuthFailure.SecretIdNotFound\",\"Message\":\
\"The SecretId is not found, please ensure that your SecretId is \
correct.\"},\"RequestId\":\"c3d29f67-6e56-48b9-b583-2cfcde32cad1\"}}";
let res: Response = serde_json::from_str(error)?;
... | Rust | 0 |
cycle += 0.03 * Self::map_input(self.gamepad.left_thumb.x, 0.4, 3.0);
}
if last_lock_mode == true && self.gamepad.buttons_down_edge & GamepadButtonRightShoulder > 0 {
state.lock_zoom = zoom;
state.lock_rotate = rotate;
state.lock_cycle = cycle;
}
... | Rust | 0 |
"2_6": 0,
# "6_10": 0,
# ">10": 0
# }
# for agent in model.schedule.agents:
# x, y = agent.pos
# slope = agent._get_slope(x, y)
# if slope < -10:
# agent_slope_bins["<-10"] += 1
# elif slope < -6:
# agent_slope_bins["-10_-6"] += 1
# ... | Python | 1 |
e either `float` or
the same as `t`. H >= img_h.
cos_w (Tensor): shape [1, W, 1, d // 2] and dtype either `float` or
the same as `t`. W >= img_w.
sin_w (Tensor): shape [1, W, 1, d // 2] and dtype either `float` or
the same as `t`. W >= img_w.
Returns:
Ten... | Python | 1 |
address, result_value);
self.set_reg_at_compare(self.reg_a, result_value);
}
pub fn op_isc(&mut self, addressing: &Addressing, memory_map: &mut MemoryMap){
let value: u8 = self.get_operand(addressing, memory_map);
let result_value: u8 = value.wrapping_add(1);
let address = self.... | Rust | 0 |
var_1668) = &input.require_hibernate_support {
scope_1667.boolean(*var_1668);
}
#[allow(unused_mut)]
let mut scope_1669 = writer.prefix("NetworkInterfaceCount");
if let Some(var_1670) = &input.network_interface_count {
crate::query_ser::serialize_structure_crate_model_network_interface_c... | Rust | 0 |
print(f"Sampling steps: {sampling_steps}, Potential energy: {potential_energy:.2e} J, Energy drift: {energy_drift:.2e} J")
logging.info(f"Sampling steps: {sampling_steps}, Potential energy: {potential_energy:.2e} J, Energy drift: {energy_drift:.2e} J")
best_sampling_steps = min(sampling_results, key=lamb... | Python | 1 |
ctHash> = vec![];
assert_eq!(ProtocolData::default().system_contracts(), expected);
let mint_reference = [0u8; 32].into(); // <-- invalid addr
let proof_of_stake_reference = [2u8; 32].into();
let standard_payment_reference = [3u8; 32].into();
let auction_reference = [4u8; 32].in... | Rust | 0 |
# Copyright 2023 CreuBlana
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class SignOcaTemplateGenerate(models.TransientModel):
_name = "sign.oca.template.generate"
_description = "Generate a signature request"
def _default_signers(self):
templat... | Python | 1 |
f.game=ast.literal_eval(all_information['game'])
except Exception as e2:
error2+='but {}'.format(str(e2))
del self.all_operation
del self.choose_chess_locate
del self.operation_number
... | Python | 1 |
}
}
use advent::{get_my_values, iter_csv_line};
use anyhow::Result;
const MAX_AGE: usize = 9;
const RESET_AGE: usize = 7;
fn parse_input() -> Result<[usize; MAX_AGE]> {
let mut fish: [usize; MAX_AGE] = [0; MAX_AGE];
for age in get_my_values!()? {
fish[age.parse::<usize>()?] += 1;
}
Ok(fish... | Rust | 0 |
timers(&mut self) -> Vec<Token> {
let now = time::precise_time_ns();
let last = self.last_timeouts;
let ticks = (now - last) as usize / MICROSECOND;
self.last_timeouts = now;
self.timers.tick(ticks)
}
}
use {
super::exception::*,
super::process::Process,
super::*,... | Rust | 0 |
identity = vec![];
/// file.read_to_end(&mut identity).unwrap();
/// let identity = Identity::from_pkcs12(&identity, "hunter2").unwrap();
///
/// let listener = TcpListener::bind("0.0.0.0:8443").unwrap();
/// let acceptor = TlsAcceptor::new(identity).unwrap();
/// let acceptor = Arc::new(acceptor);
///
/// fn handle_c... | Rust | 0 |
.g. MV_GIGE_DEVICE
('nReserved', c_uint * 4), # < \~chinese 保留字节 \~english Reserved bytes
('SpecialInfo', N19_MV_CC_DEVICE_INFO_3DOT_0E), # < \~chinese 不同设备特有信息 \~english Special information
]
MV_CC_DEVICE_INFO = _MV_CC_DEVICE_INFO_
# 设备信息列表 \~english Devi... | Python | 1 |
# [ doc = r" Value read from the register" ]
pub struct R {
bits: u32,
}
# [ doc = r" Value to write to the register" ]
pub struct W {
bits: u32,
}
impl super::I2C_CTL {
# [ doc = r" Modifies the contents of the register" ]
# [ inline ( always ) ]
pub fn m... | Rust | 0 |
root_get()
.unwrap()
.oapi_extract_ext(doc.doc(), "x-toto")
.unwrap();
println!("{:#?}", ext);
}
<reponame>rbudnar/rust-webpack-template
use crate::cells::{ICellStrong, ICell};
use std::any::Any;
use std::rc::{Rc, Weak};
use std::cell::RefCell;
pub type PolarCellLinkWeak = Weak<RefCell<Pol... | Rust | 0 |
', (_message.Message,), {
'DESCRIPTOR' : _ENTITYSELECTOR,
'__module__' : 'gtfs_realtime_pb2'
# @@protoc_insertion_point(class_scope:transit_realtime.EntitySelector)
})
_sym_db.RegisterMessage(EntitySelector)
TranslatedString = _reflection.GeneratedProtocolMessageType('TranslatedString', (_message.Message,), {
... | Python | 1 |
ELINKNO>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _TCD20_CITER_ELINKNO;
#[doc = "`read()` method returns [tcd20_citer_elinkno::R](tcd20_citer_elinkno::R) reader structure"]
impl crate::Readable for TCD20_CITER_ELINKNO {}
#[doc = "`write(|w| ..)` method takes [tcd20_citer_elinkno::W](tcd20_citer_elinkno::W) wri... | Rust | 0 |
epeated measure effect
# ------------------------------------
# Sum Square Total
demeaned_Y = Y - mean(Y)
SST = np.sum(demeaned_Y**2)
# Sum Square Error
if projection_matrix is None:
projection_matrix = ICC_projection_matrix(Y.shape)
residuals = Y.flatten("F") - (projection_matrix ... | Python | 1 |
account_add_with_role_and_data(
Origin::signed(1),
101,
MASTER_ROLE_MASK,
0
));
assert_eq!(Evercity::fuse(), true);
assert_noop!(
Evercity::set_master(Origin::signed(2),),
RuntimeError::InvalidAction
);
});
}use... | Rust | 0 |
, predictions.flatten())
]
# Konversi ke DataFrame untuk analisis
pred_df = pd.DataFrame(prediction_results)
pred_df['date'] = pred_df['price'].astype(float)
# Hitung ringkasan prediksi
prediction_summary = {
"total_days": len(pre... | Python | 1 |
aggregated onto it.
///
/// ## Notes
///
/// This function is not necessarily useful from a BLS cryptography perspective, it mostly
/// exists to satisfy the Eth2 specification which expects the all-zeros serialization to be
/// meaningful.
pub fn empty() -> Self {
Self {
... | Rust | 0 |
\x13\n\x0c\
\n\x05\x04\x02\x02\x01\x03\x12\x03'\x16\x17\nI\n\x04\x04\x02\x02\x02\x12\
\x03*\x04\x1c\x1a<\x20ASN.1\x20DER\x20encoded\x20PKCS#8\x20private\x20ke\
y.\x20MUST\x20be\x20unencrypted.\n\n\r\n\x05\x04\x02\x02\x02\x04\x12\x04\
*\x04'\x18\n\x0c\n\x05\x04\x02\x02\x02\x05\x12\x03*\x04\t\n\x0c\n\x05\... | Rust | 0 |
64) -> int32;
}
extern "C" {
pub fn DAQmxSetExportedSampClkDelayOffset(taskHandle: TaskHandle, data: float64) -> int32;
}
extern "C" {
pub fn DAQmxResetExportedSampClkDelayOffset(taskHandle: TaskHandle) -> int32;
}
extern "C" {
pub fn DAQmxGetExportedSampClkPulsePolarity(taskHandle: TaskHandle, data: *mut i... | Rust | 0 |
}
#[doc = "Bits 13:15 - Transmitter FIFO mode configuration bits"]
#[inline(always)]
pub fn tx_fifo_mod(&self) -> TX_FIFO_MOD_R {
TX_FIFO_MOD_R::new(((self.bits >> 13) & 0x07) as u8)
}
#[doc = "Bits 16:18 - Receiver FIFO mode configuration bits"]
#[inline(always)]
pub fn rx_fifo... | Rust | 0 |
import numpy as np
from numpy import pi, log, sqrt
from numpy.testing import assert_, assert_equal
from scipy.special._testutils import FuncData
import scipy.special as sc
# Euler-Mascheroni constant
euler = 0.57721566490153286
def test_consistency():
# Make sure the implementation of digamma for real arguments... | Python | 1 |
from aiogram import Router
from aiogram.filters import CommandStart, Command
from aiogram.types import Message
from ..buttons.inline import main_menu
from ..filters.user_filter import HaveUserFilter, AdminFilter
from ..settings import settings
from ..conf import connection_pool
from ..storage.db.adapters.redis_client i... | Python | 1 |
indices[start_index_i + 0] = vertex_index_top_left;
indices[start_index_i + 1] = vertex_index_bottom_left;
indices[start_index_i + 2] = vertex_index_bottom_right;
indices[start_index_i + 3] = vertex_index_top_left;
indices[start_index_i + 4] = vertex_inde... | Rust | 0 |
# Initialize current page in session state
if 'current_preview_page' not in st.session_state:
st.session_state.current_preview_page = 1
col1, col2, col3 = st.columns([1, 2, 1])
with col1:
... | Python | 1 |
all previous slot(s)
result.push(&objects[idx]);
}
let mut insert_point = None;
// Find where the last value were inserted if result is in ordered.
for j in 0..states.len() {
if idx < states[j] { // found place to insert val... | Rust | 0 |
Provisioning URL."]
#[doc = ""]
#[doc = " @param[in] aInstance A pointer to an OpenThread instance."]
#[doc = " @param[in] aProvisioningUrl A pointer to the Provisioning URL (may be NULL to set as empty string)."]
#[doc = ""]
#[doc = " @retval OT_ERROR_NONE Successfully ... | Rust | 0 |
import streamlit as st
import requests
import os
# Set your Google Gemini API key
GEMINI_API_KEY = os.getenv("AIzaSyALjH2TdADi2sCAvcrCdQ_IumnpZ3QjolY") # Fetch from environment variable
if not GEMINI_API_KEY:
st.error("Missing API Key! Set the GOOGLE_API_KEY environment variable.")
# Function to review the Pyt... | Python | 1 |
/// Last time the condition transitioned from one status to another.
last_transition_time: DateTime<Utc>,
},
}
// The names of managers to be used to update the field in controller.
const POD_READY_MANAGER: &str = "ephemeron-podready";
const AVAILABLE_MANAGER: &str = "ephemeron-available";
impl ... | Rust | 0 |
raise ValueError(f"Unsupported LLM provider: {provider}")
if __name__ == "__main__":
loader = ModelLoader()
# Test Embedding
embeddings = loader.load_embeddings()
print(f"Embedding Model Loaded: {embeddings}")
result = embeddings.embed_query("Hello, how are you?")
print(f"Embedding Res... | Python | 1 |
fenhong.AStockChangeTable()
return g_table_astockchange.getOne(code)
def convertVolToStockTrunover(df, df_GuBen_change):
"""成交量转换手率, 通过历史股本变更表来计算
df: hisdat
return: df 换手率覆盖了v字段
"""
assert (len(df_GuBen_change) > 0)
#股本变动表
col = '变动后流通A股(股)'
#防止有超过当前日期的数据
df_GuBen_change ... | Python | 1 |
),
('糗', "qiǔ"),
('糘', "jiā"),
('糙', "cāo"),
('糚', "zhuāng"),
('糛', "táng"),
('糜', "mí,méi"),
('糝', "sǎn,sān,shēn"),
('糞', "fèn"),
('糟', "zāo"),
('糠', "kāng"),
('糡', "jiàng"),
('糢', "mó"),
('糣', "sǎn"),
('糤', "sǎn"),
('糥', "nuò"),
('糦', "xī"),
('糧', "l... | Rust | 0 |
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import gettext_lazy as _
User = get_user_model()
class CustomUserAdmin(UserAdmin):
list_display = (
"id",
"first_name",
"last_name... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.