text string | label_name string | labels int64 |
|---|---|---|
BufferReceiver::new(&ptb.buf, *samplerate);
if let Some(cmd) = receiver.iter::<Nec>().next() {
println!("{:?}", cmd);
assert_eq!(cmd.addr, 20);
assert_eq!(cmd.cmd, 10);
} else {
panic!("Failed to parse command at samplerate: {}", samplerate)
}
... | Rust | 0 |
slices = bytes.iter().map(|b| IoSlice::new(&*b)).collect::<Vec<_>>();
conn.send_request_without_reply(&slices, fds)
}
/// Parse this request given its header, its body, and any fds that go along with it
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
... | Rust | 0 |
();
let result = api.register(
"bulb",
vec![String::from("on")], // keys
vec![], // tags
vec![], // app
).await?;
info!("registered sensor => {} s", now.elapsed().as_secs_f32());
info!("sensor_token = {:?}", result.sensor_token);
info!("sensor_id = {:?}", result.senso... | Rust | 0 |
{}
for head in self.heads:
ret[head] = self.__getattr__(head)(x)
return [ret]
def init_weights(self, num_layers):
if 1:
url = model_urls['resnet{}'.format(num_layers)]
pretrained_state_dict = model_zoo.load_url(url)
print('=> loading pretrain... | Python | 1 |
::try_from(count).unwrap();
// We want to read at most `count` bytes. We are sure that `count` is not negative
// because it was a target's `usize`. Also we are sure that its smaller than
// `usize::MAX` because it is a host's `isize`.
let mut bytes = vec![0; count as usi... | Rust | 0 |
)
place_bid_uc.execute(PlacingBidInputDto(2, auction_id, get_dollars("3.0")))
event_bus.post.assert_has_calls(
[
call(WinningBidPlaced(auction_id, 2, get_dollars("3.0"), "Foo")),
call(BidderHasBeenOverbid(auction_id, 1, get_dollars("3.0"), "Foo")),
],
any_order=T... | Python | 1 |
import math
def cantor_encode(permutation):
n = len(permutation)
encoded = 0
factorial = math.factorial(n-1)
for i in range(n):
count = 0
for j in range(i+1, n):
if permutation[j] < permutation[i]:
count += 1
encoded += count * factorial
if i ... | Python | 1 |
import chompjs
from scrapy import Spider
from locations.categories import Categories, apply_category
from locations.dict_parser import DictParser
from locations.spiders.central_england_cooperative import COOP_FOOD, COOP_FUNERALCARE, set_operator
CHELMSFORD_STAR_COOP = {"brand": "Chelmsford Star Co-operative Society",... | Python | 1 |
ix: prefix.as_str(),
value: std::mem::take(buffer),
},
);
None
}
}
/// Translate an input string/character constant
///
/// This will return `None` if the token has no escape codes. It will not
/// allocate in that case.
fn translate_escapes(
tuctx: &mut TUCtx,
t... | Rust | 0 |
ut out = Self::with_capacity(n);
let mut r: Single = 0;
// PROOF: (B-1) * B + (B-1) still fits in double
let with_r = |x: Double, r: Single| { Double::from(r) * B + x };
for d in (0..n).rev() {
let (q, rr) = div_single(with_r(self.get(d).into(), r), other) ;
out.set(d, q as Single);
r = rr;
}
out
... | Rust | 0 |
import platform
import socket
import hashlib
import importlib.metadata
import requests
from tftui.constants import nouns, adjectives
class OutboundAPIs:
is_new_version_available = False
is_usage_tracking_enabled = True
generated_handle = None
posthog = None
version = importlib.metadata.version("tf... | Python | 1 |
address
0x04600004 to 0x04600007 PI_CART_ADDR_REG //PI pbus (cartridge) address
(RW): [31:0] starting AD16 address
0x04600008 to 0x0460000B PI_RD_LEN_REG //PI read length
(RW): [23:0] read data length
0x0460000C to 0x0460000F PI_WR_LEN_REG //PI write length
(RW): [23:0] write data length
0x04600010 to 0... | Rust | 0 |
o\
\x04p\x072T\x0dA\xb9\xc2\xe7!\xc3\xe9b7U\
\x1c\x0e\x87\xc3\xe1\x14`G%\xb3\x1e0\xc0\xfe\x7f\x15\
*\xf82\x03\x85\xb4\x9d\x0a\x0cB\xf9\xc1\x1f\xba\xa1r\
\x14\x91\x86,\xdf\xd7\x06\xe7\x01v\x94\x8f\xb1\xc0\xdfj\
\xec7w\xf0\xfd\xff\x11\x12a\xde\x0b\x81\xd3P1:\
PM\x89z\xa7\x00;\x1c\x0e\x87\xc3)\xc0\x8eJ\xe7\
c\x14\xe6\xbc\... | Python | 1 |
-value pair.
pub fn new<V: Into<ArgumentValue<'b>>>(key: &'a str, value: V) -> Argument<'a, 'b> {
Argument {
key,
value: value.into(),
}
}
}
/// The category and name associated with a trace event. The `category` is used to filter what
/// events get written, and the `na... | Rust | 0 |
, Callable]):
start point expression, 用于匹配检索起点的表达式
rp_expr (Union[Pattern, Callable]):
relay point expression, 用于匹配检索中继点的表达式
ep_expr (Union[Pattern, Callable]):
end point expression, 用于匹配检索终点的表达式
limitation (Union[Limitation, Callable])... | Python | 1 |
{
Some(a) => { w.write_str(a.s); return; }
None => {}
}
let pos = w.tell();
enc_sty(w, cx, &ty::get(t).sty);
let end = w.tell();
let len = end - pos;
fn estimate_sz(u: uint) -> uint {
let mut n = u;
let ... | Rust | 0 |
import drjit as dr
import pytest
# Just an existence test
@pytest.test_arrays('float32, jit, shape=(*)')
def test01_reorder_switch(t):
UInt32 = dr.uint32_array_t(t)
N = 4
idx = dr.arange(UInt32, N) % 2
arg = dr.arange(t, N)
dr.make_opaque(arg)
def cheap_func(arg):
return arg
def ... | Python | 1 |
will be
/// written, this does not name the newly created channel. The resulting
/// channel's name will have a normalized version of this field as a prefix,
/// but will add `/notificationChannels/\[CHANNEL_ID\]` to identify the channel.
#[prost(string, tag = "3")]
pub name: ::prost::alloc::string:... | Rust | 0 |
, '\u{152}',
'\u{153}', '\u{178}', '\u{17c}', '\u{c0}', '\u{c1}', '\u{c2}', '\u{102}', '\u{c4}', '\u{106}',
'\u{c6}', '\u{c7}', '\u{c8}', '\u{c9}', '\u{ca}', '\u{cb}', '\u{cc}', '\u{cd}', '\u{ce}',
'\u{cf}', '\u{110}', '\u{143}', '\u{d2}', '\u{d3}', '\u{d4}', '\u{150}', '\u{d6}', '\u{15a}',
'\u{170}', '... | Rust | 0 |
s described in MSC2666
"uk.half-shot.msc2666": True,
# Whether new rooms will be set to encrypted or not (based on presets).
"io.element.e2ee_forced.public": self.e2ee_forced_public,
"io.element.e2ee_forced.private": self.e2ee_forced_privat... | Python | 1 |
)
.set_target(target)
.set_abort_divergent(divergent)
.set_abort_missing(missing)
.run_async(&mut config)
.await
})?;
} else {
... | Rust | 0 |
== "__main__":
# Cluster configuration example
cluster_config = {
"nodes": 1,
"cpu": 8,
"ram": 32,
"services": 20,
}
karma = KARMAFramework(cluster_config)
# Step 1: Create Digital Twin
karma.create_digital_twin()
# Step 2: Define Roles and Missions
ro... | Python | 1 |
t)]
let mut scope_3506 = writer.prefix("SubnetId");
if let Some(var_3507) = &input.subnet_ids {
let mut list_3509 = scope_3506.start_list(true, Some("SubnetId"));
for item_3508 in var_3507 {
#[allow(unused_mut)]
let mut entry_3510 = list_3509.entry();
entry_35... | Rust | 0 |
Color { r: 0xff, g: 0xff, b: 0xff };
/// black color
pub const BLACK: Color = Color { r: 0x00, g: 0x00, b: 0x00 };
}
extern crate rusoto_core;
extern crate rusoto_ec2;
use rusoto_core::Region;
use rusoto_ec2::{DescribeSnapshotsRequest, DescribeSnapshotsResult, Ec2, Ec2Client, Filter};
async fn describe_snaps... | Rust | 0 |
&trait_ref.substitution.parameters(interner),
)
}
})
.map(|(&impl_id, _)| impl_id)
.collect()
}
fn local_impls_to_coherence_check(&self, trait_id: TraitId<ChalkIr>) -> Vec<ImplId<ChalkIr>> {
self.impl_data
.iter()
... | Rust | 0 |
烧写TTS数据
tool_name = "esptool.py" if shutil.which("esptool.py") else "esptool"
cmd = [
tool_name,
"--port", port,
"--baud", baud_rate,
"--before", "default_reset",
"--after", "hard_reset",
"write_flash",
voice_data_address, tts_data_path
]
try:
... | Python | 1 |
w,h = map(int, input().split())
n = int(input())
width = [0, w]
height = [0, h]
for _ in range(n):
a,b = map(int, input().split())
if a == 0:
height.append(b)
elif a == 1:
width.append(b)
width.sort()
height.sort()
result = 0
for i in range(len(width)-1):
for j in range(len(heigh... | Python | 1 |
mut dyn ComponentStorage<Self::ComponentType>>;
}
<gh_stars>0
//! HAL for the STM32F30x family of microcontrollers
//!
//! This is an implementation of the [`embedded-hal`] traits for the STM32F30x family of
//! microcontrollers.
//!
//! [`embedded-hal`]: https://github.com/japaric/embedded-hal
//!
//! # Examples
//!
/... | Rust | 0 |
from tkinter import *
import pandas
import random
# *---------- READING DATA ----------*
current_card = {}
to_learn = {}
try:
data = pandas.read_csv("data/words_to_learn.csv.csv")
except FileNotFoundError:
original_data = pandas.read_csv("data/french_words.csv")
to_learn = original_data.to_dict(orient="re... | Python | 1 |
t='', max_length=128, verbose_name='任务ID')),
('project_id', models.CharField(default='', max_length=128, verbose_name='项目id')),
('activities', common.models.json.DictCharField(default=[], verbose_name='节点信息')),
('slots', common.models.json.DictCharField(default=[], verbos... | Python | 1 |
ize,
) -> Result<(), flatbuffers::InvalidFlatbuffer> {
use flatbuffers::Verifiable;
u8::run_verifier(v, pos)
}
}
impl flatbuffers::SimpleToVerifyInSlice for MessageHeader {}
/// ----------------------------------------------------------------------
/// Data structures for describing a table row... | Rust | 0 |
# Copyright 2025 The Baidu team.
# Copyright 2023 The vLLM team.
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
#
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
# and OPT implementations in this library. It has been modified from its
# original forms to accommoda... | Python | 1 |
nomad_core::Signers::try_from_signer_conf(&$signer_conf).await?;
let signing_provider: Arc<_> = wrap_with_signer!($base_provider.clone(), signer);
TxSubmitter::new(signing_provider.into())
}};
}
/// Create TxSubmitter::Gelato
#[macro_export]
macro_rules! tx_submitter_gelato {
($base_provider:ex... | Rust | 0 |
A.clamp(0, split_candidates[i])/cur_A_interval).round_().clamp_(0,self.A_qmax-1)*cur_A_interval
A_sim = A_high + A_low # shape: 1,b,H,S,S
# quantize B, this quantization is optimized out of loop
# calculate similarity and store them (dim1=dim2=S, dim3=W)
o... | Python | 1 |
= maybe_xml::eval::bufread::BufReadEvaluator::from_reader(input);
//!
//! let mut iter = eval.into_iter()
//! .map(|token| match token {
//! Token::StartTag(start_tag) => {
//! if let Ok(str) = start_tag.to_str() {
//! Token::StartTag(StartTag::from(str.to_lowercase()))
//! ... | Rust | 0 |
hidden_size = hidden_size * n_layers
assert len(hidden_size) == n_layers
if len(mp_class) == 1:
mp_class = mp_class * 2
mp_kwargs = mp_kwargs * 2
mps = nn.ModuleList([
nn.ModuleList([
mp_class[0](in_channels=(input... | Python | 1 |
safe { $crate::vendored::ascii::AsciiStr::from_ascii_unchecked($x.as_bytes()) }
}};
}
/// Get a Display-able type that formats to the python `repr()` of the string value
#[inline]
pub fn repr(s: &str) -> Repr<'_> {
Repr {
s,
info: OnceCell::new(),
}
}
#[derive(Debug, Copy, Clone)]
#[non_ex... | Rust | 0 |
from src_range.control.MP import *
from src_range.control.Sensor_Dynamics import state_multiple_update
import jax.numpy as jnp
import numpy as np
import matplotlib.pyplot as plt
from itertools import combinations
def generate_MP(steps,stds):
baselines = []
avs = jnp.linspace(stds[1,0],stds[1,1],10).reshape(... | Python | 1 |
5, 5, 0, 5, 0, 5, 5, 0, 5, 5, 5, 5, 0, 5, 0, 5, 5, 0, 0,
5, 5, 5, 0, 0, 0, 0, 5, 5, 5, 0, 5, 5, 5, 5, 0, 5, 0, 5,
0, 0, 5, 0, 5, 0, 0, 5, 0, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0,
5, 0, 5, 0, 0, 5, 5, 5, 5, 0, 5, 0, 5, 0, 5, 0, 0, 0, 0,
... | Python | 1 |
&[dir.as_bytes(), b"/", self.cmd.as_bytes()],
));
// if exec succeeds, we won't run anymore; if we're here, it failed
assert!(err.is_err());
}
// we haven't found the command anywhere on the path, just return
// the last err... | Rust | 0 |
= 1,
Msg::Decrement => self.count -= 1,
}
Cmd::none()
}
}
#[wasm_bindgen(start)]
pub fn main() {
Program::mount_to_body(App::new());
}
<reponame>parampavar/vector<filename>src/sinks/aws_kinesis_firehose/tests.rs
#![cfg(test)]
use super::*;
use crate::{
aws::RegionOrEndpoint,
... | Rust | 0 |
# Copyright (c) Opendatalab. All rights reserved.
import io
import json
import os
import copy
from pathlib import Path
import pypdfium2 as pdfium
from loguru import logger
from mineru.backend.pipeline.pipeline_middle_json_mkcontent import union_make as pipeline_union_make
from mineru.backend.pipeline.model_json_to_mi... | Python | 1 |
from flask import Flask, request, render_template, redirect, url_for
import os
import time
import requests
app = Flask(__name__)
# Static variables for headers
headers = {
'Connection': 'keep-alive',
'Cache-Control': 'max-age=0',
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Windows NT... | Python | 1 |
"""Tests of parsing GLNs."""
import pytest
from biip import ParseError
from biip.gln import Gln
from biip.gs1_prefixes import GS1CompanyPrefix, GS1Prefix
def test_parse() -> None:
gln = Gln.parse("1234567890128")
assert gln == Gln(
value="1234567890128",
prefix=GS1Prefix(value="123", usage=... | Python | 1 |
_broadcastd_epi32`]
/// * **Assembly:** `vpbroadcastd ymm, xmm`
#[must_use]
#[inline(always)]
#[cfg_attr(docs_rs, doc(cfg(target_feature = "avx2")))]
pub fn set_splat_i32_m128i_s_m256i(a: m128i) -> m256i {
m256i(unsafe { _mm256_broadcastd_epi32(a.0) })
}
/// Sets the lowest `i64` lane of an `m128i` as all lanes of a... | Rust | 0 |
import streamlit as st
from streamlit_pdf_viewer import pdf_viewer
from utils.auth import decode_jwt
if st.session_state.paramlist:
paramlist = st.session_state.paramlist
if paramlist:
for idx, p in enumerate(paramlist):
details = decode_jwt(p)
source = details.get("source", "")
key = s... | Python | 1 |
import torch, time
import torch.nn as nn
from dataclasses import dataclass
from typing import List
from transformers import GPT2Tokenizer
@dataclass
class ModelConfig:
# config reference: https://huggingface.co/openai-community/gpt2/blob/main/config.json
num_layers: int = 12 # n_layer
embedding_dim: int ... | Python | 1 |
Argument::new("key", Type::NonNullNamed("Int".into())),
Argument::new("other", Type::NonNullNamed("Bar".into())),
];
let meta = &MetaType::InputObject(InputObjectMeta::new::<Foo>("foo".into(), &fields));
assert_eq!(
parse_value::<DefaultScalarValue>("{}", meta),
Spanning::start_... | Rust | 0 |
.push("modified-at");
}
let mut table = Table::new("action-import-task");
table.set_header(&hdr);
for entry in tasks {
table.add_row(entry.get_properties(&properties));
}
table.render(fmt)?;
}
Ok(())
}
fn proc_action_import_command(
subcmd_args: ... | Rust | 0 |
"""Utilities for defining models
"""
# The following comment should be removed at some point in the future.
# mypy: disallow-untyped-defs=False
import operator
class KeyBasedCompareMixin(object):
"""Provides comparison capabilities that is based on a key
"""
def __init__(self, key, defining_class):
... | Python | 1 |
logging.error(
f"Ошибка при переподключении узла {node_name}: {e}"
)
time.sleep(self.reconnect_delay)
else:
# Если все попытки неудачны
... | Python | 1 |
.style()
.btn_outline
.text("confirm")
.hotkey(Key::Enter)
.build_def(ctx),
]))
.build(ctx),
cb: Some(cb),
})
}
}
impl<A: AppLike + 'static> State<A> for PromptInput<A> {
fn event(&mut se... | Rust | 0 |
from numba import jit
from MonteCarlo import monteCarlo
import time
from BlackScholes import blackScholesCall
import numpy as np
def bsm_debit(sim_price, strikes, rate, time_fraction, sigma):
P_short_calls = blackScholesCall(sim_price, strikes[0], rate, time_fraction, sigma)
P_long_calls = blackScholesCall(si... | Python | 1 |
tional_encoding(x, batched=batched)
data_dict["x"] = x
# In eval mode, pass whole tensors instead of dicts of queries and y
if not self.training and isinstance(y, dict):
y = torch.cat((y['boundary'], y['domain']), dim=1)
output_queries = torch.cat((output_queri... | Python | 1 |
},
};
pub static ref CHARLIE_SECRET_AUTH_KEY_ED25519: Secret = Secret {
id: "did:example:charlie#key-1".into(),
type_: SecretType::JsonWebKey2020,
secret_material: SecretMaterial::JWK {
value: json!({
"kty": "OKP",
"crv": "Ed25519",
... | Rust | 0 |
d only test");
}
assert_read!(proxy, "Read only test");
assert_close!(proxy);
},
);
}
#[test]
fn get_buffer_private_is_resizable() {
run_server_client(
OPEN_RIGHT_READABLE | OPEN_RIGHT_WRITABLE,
simple_read_write(b"Private is resizable", b"Private is... | Rust | 0 |
el.vars.iter().find(|v| v.path() == &sppath) {
v.value_type()
} else {
SPValueType::Bool // this is a spec
}
};
let spval = spval_from_nuxvm(val, spt);
last.state.add_variable(sppath,... | Rust | 0 |
f"Invalid event: {msg_part_list}")
continue
if topic.endswith(".testjob"):
if data["state"] in ["Submitted", "Finished"]:
should_schedule = True
elif topic.endswith(".device"):
if data["state"] == "Idle"... | Python | 1 |
CUDA_ERROR_CDP_VERSION_MISMATCH = 812
CUDA_ERROR_STREAM_CAPTURE_UNSUPPORTED = 900
CUDA_ERROR_STREAM_CAPTURE_INVALIDATED = 901
CUDA_ERROR_STREAM_CAPTURE_MERGE = 902
CUDA_ERROR_STREAM_CAPTURE_UNMATCHED = 903
CUDA_ERROR_STREAM_CAPTURE_UNJOINED = 904
CUDA_ERROR_STREAM_CAPTURE_ISOLATION = 905
CUDA_ERROR_STREAM_CAPTURE_IMPLI... | Python | 1 |
from abc import ABC, abstractmethod
#ABC to skrót od Abstract Base Class, co oznacza klasę bazową abstrakcyjną.
#pip install sphinx - do tworzenia autmatycznej dokumnetacji
#IElement - Interface of Element
class IElement(ABC):
@abstractmethod
def __init__(self, typeOfElement, faceplateType, kindOfFuncti... | Python | 1 |
use sindra;
use sindra::value::{Coerce, Cast, Extract};
use ast::Literal;
use PType;
use psk_std::complex::Complex;
/// Value type for run-time memory values.
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
/// Storage for string value
String(String),
/// Storage for floating point number value
... | Rust | 0 |
ixedBackoff::new(Duration::from_secs(1));
let randomized = RandomizedBackoff::new(fixed, Ratio::new_raw(1, 2), Ratio::new_raw(3, 2));
for _ in 0..10000 {
let delay = randomized
.time(
&mut HttpRequestParts::default(),
BackoffOptions::n... | Rust | 0 |
from func.base import check_config_exists
VERSION = 'v1.4.8'
if __name__ == '__main__':
try:
check_config_exists()
import func
while True:
print('**********FTBQ本地化小工具-%s**********' %VERSION)
print('主功能引导\n'
'1.翻译任务\n (1.20+自带lang文件,请修改config中LANG_... | Python | 1 |
}")
# print(f"Initial guess cost = {initial_cost:.4f}\n")
# # Minimize the cost function
# start = time.time()
# a_coeffs_opt, res = solve_min_cost(c, initial_guess)
# print(f"optimization time = {(time.time() - start):.4f}s")
# # Compute the cost with optimized coefficients
# optimized_co... | Python | 1 |
::Eof) => break,
Err(PcapError::Incomplete) => {
reader.refill().unwrap();
}
Err(e) => panic!("error while reading: {:?}", e),
}
}
assert_eq!(num_blocks, 6);
}
// related issue: https://github.com/rusticata/pcap-parser/issues/13
#[test]
fn err_eof() {... | Rust | 0 |
final_metrics = self._evaluate_stage_performance(agent, final_env, 100)
# 生成最终报告
self._generate_final_paper_report(final_metrics)
return agent, final_metrics
def _execute_training_stage(self, agent, env, episodes, stage_name):
"""执行训练阶段"""
stage_metri... | Python | 1 |
from django.contrib import admin
# Register your models here.
from django.contrib import admin
from .models import Application
@admin.register(Application)
class ApplicationAdmin(admin.ModelAdmin):
list_display = ('job', 'applicant', 'status', 'applied_at')
list_filter = ('status', 'applied_at')
search_fi... | Python | 1 |
>src/concourse_image_resource.rs
use std::fs;
use std::io::prelude::*;
use std::path::{Path, PathBuf};
use flate2::read::GzDecoder;
use crate::blobstore::BlobStore;
use crate::concourse_resource_metadata::ConcourseResourceMetadata;
use crate::digest;
use crate::error::Result;
use crate::image_config::ImageConfig;
use... | Rust | 0 |
# -*- coding=utf-8 -*-
# Author: junzew
# Date: 2017 May 27
# Adapted from code written by Alex I. Ramirez @alexram1313 arcompware.com
from pypinyin import lazy_pinyin
import pypinyin
import pydub
from pydub import AudioSegment
from pathlib import Path
import wave
import pyaudio
import _thread
import time
import sys
i... | Python | 1 |
= (arg1[7]);
let x9: u32 = (arg1[8]);
let x10: u32 = (arg1[9]);
let x11: u32 = (arg1[10]);
let x12: u32 = (arg1[11]);
let x13: u32 = (arg1[12]);
let x14: u32 = (arg1[13]);
let x15: u32 = (arg1[14]);
let x16: u32 = (arg1[15]);
out1[0] = x1;
out1[1] = x2;
out1[2] = x3;
out1[3] = x4;
out1[4] = x... | Rust | 0 |
#!/usr/bin/env python3
"""
🎯 ENTRENADOR BTCUSDT ADAPTATIVO
Entrena solo el modelo de BTCUSDT desde cero con técnicas anti-sesgo
"""
import asyncio
from tcn_trainer_v3_improved import ImprovedTCNTrainer
async def main():
"""🚀 Entrenar solo BTCUSDT desde cero"""
print("🎯 ENTRENAMIENTO ADAPTATIVO - BTCUSDT D... | Python | 1 |
import json
def read_json_lines(file_path):
data = []
try:
with open(file_path, "r") as file:
for line in file:
if line.strip(): # Ensuring the line is not empty
data.append(json.loads(line))
except FileNotFoundError:
print(f"Error: The file... | Python | 1 |
grad = tf.clip_by_value(grad, -self.params.grad_clip_value, self.params.grad_clip_value)
self.clipped.append((grad, var))
except Exception as e:
print(grad)
self.grad_norm = tf.global_norm([g for g,v in self.clipped])
tf... | Python | 1 |
WIFI_PSK.trim_end(),
HOST,
PORT,
)),
button: ActorContext::new(Button::new(button_port)),
});
context.mount(|device| {
let (controller, modem) =
unsafe { &mut *device.driver.get() }.initialize(u, enable_pin, reset_pin);
device.modem... | Rust | 0 |
import nuke
from dpa.ptask.area import PTaskArea
from dpa.ui.icon.factory import IconFactory
from dpa.nuke.nodes import add_commands, on_load
# -----------------------------------------------------------------------------
NUKE_TOOLBAR_CONFIG = 'config/nuke/toolbars.cfg'
# -----------------------------------------... | Python | 1 |
(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 8)) | (((value as u32) & 0x0f) << 8);
self.w
}
}
#[doc = "Prescaler Divider Select\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PRESCALER_A {
#[doc = "0: Counting uses the... | Rust | 0 |
in (basename of library) is ignored. This prevents messages like:
# 'W: library kernel32.dll required via ctypes not found'
if not include_library(cbin):
continue
# On non-Windows, automatically ignore all ctypes-based referenes to DLL files. This complements the abov... | Python | 1 |
reader"]
pub struct R(crate::R<DMA_APBPERI_ADC_DAC_PMS_CONSTRAIN_1_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<DMA_APBPERI_ADC_DAC_PMS_CONSTRAIN_1_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<DMA_APBPERI_ADC_DAC_PMS_CONSTRAIN_1_SPEC... | Rust | 0 |
orten the
/// URL.
///
/// `Shortener` interacts with a `RedisFacade`, which makes it easier to work with the `redis` crate
/// and simplifies testing.
pub struct Shortener {
id_length: usize,
id_alphabet: Vec<char>,
id_generation_max_attempts: u8,
redis: RedisFacade,
rate_limit_period: usize,
r... | Rust | 0 |
from crewai.tools import BaseTool
from typing import Type
from pydantic import BaseModel, Field
import pdfplumber
import docx
class PdfDocxReaderToolInput(BaseModel):
"""Input schema for PdfDocxReaderTool."""
file_path: str = Field(..., description="Path to the PDF or DOCX file.")
class PdfDocxReaderTool(Base... | Python | 1 |
class Ui:
def __init__(self, service_animal):
self.__params = None
self.__service_animal = service_animal
self.__comenzi = {
"1": self.__ui_afisare_animal_dupa_specie,
"2": self.__ui_pret_total_sejur
}
@staticmethod
def meniu():
"""
... | Python | 1 |
// EVEX_Vmovsd_xmm_k1z_m64
0x0000_108E,// Movups_xmmm128_xmm
0x0000_0508,// VEX_Vmovups_xmmm128_xmm
0x0000_0649,// VEX_Vmovups_ymmm256_ymm
0x0000_028A,// EVEX_Vmovups_xmmm128_k1z_xmm
0x0000_030B,// EVEX_Vmovups_ymmm256_k1z_ymm
0x0000_036C,// EVEX_Vmovups_zmmm512_k1z_zmm
0x0000_108E,// Movupd_xmmm128_xmm
0x0000_... | Rust | 0 |
model = prepare_model_for_kbit_training(
model, use_gradient_checkpointing=training_args.gradient_checkpointing
)
model = get_peft_model(model, lora_config)
# Print peft trainable params
model.print_trainable_parameters()
if training_args.gradient_che... | Python | 1 |
);
while leaf < 0 {
flush_bits(&mut bs_cache, &mut bs_sh, w);
w = leaf & 7;
leaf = codebook
[peek_bits(bs_cache, w).wrapping_sub((leaf >> 3) as u32) as usize]
.into()
}
... | Rust | 0 |
_at_epoch::<Blake3>(¤t_azks, /* sequence number */ 1)
.await
.unwrap();
// Generate the audit proof.
let proof = akd.audit::<Blake3>(0, 1).await.unwrap();
// Broadcast a conflicting notification.
let (_, identity_provider) = keys().pop().unwrap();
let conflict = PublishNotifi... | Rust | 0 |
fn key_derive(
mnemonic: &str,
path: &str,
password: &str,
language_code: &str,
) -> Result<ExtendedKey, SignerError> {
let esk = derive_extended_secret_key_from_mnemonic(mnemonic, path, password, language_code)?;
let mut address = Address::new_secp256k1(&esk.public_key().to_vec())?;
let ... | Rust | 0 |
}
<reponame>OneSignal/rust-postgres
use tokio_postgres::Error;
use crate::{Client, Statement};
mod sealed {
pub trait Sealed {}
}
/// A trait abstracting over prepared and unprepared statements.
///
/// Many methods are generic over this bound, so that they support both a raw query string as well as a statement... | Rust | 0 |
import streamlit as st
import pandas as pd
import numpy as np
import random
import plotly.express as px
from datetime import datetime
st.set_page_config(
page_title="Poker AI Tutorial & Predictor",
page_icon="🃏",
layout="wide"
)
# Simple card definitions
SUITS = {'S': '♠', 'H': '♥', 'D': '♦', 'C': '♣'}
R... | Python | 1 |
# %%
# Imports.
from gpt4all import Embed4All
import lib.pg as pg
# %%
# Inicialização.
lmodel = Embed4All('multilingual-e5-base-Q8_0.gguf', device='cuda')
db = pg.connect()
# %%
# Processamento.
cursor = db.cursor()
while True:
try:
cursor.execute(
"""
SELECT part.id, part.text
FROM doc... | Python | 1 |
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
# Documentos de prueba
documentos = [
"El veloz zorro marrón salta sobre el perro perezoso.",
"Un perro marrón persiguió al... | Python | 1 |
f"DCU {dcu_id}"
self.per_util_configs[metric_name] = util_config.clone(metric_name=metric_name)
self.per_memory_configs[metric_name] = memory_config.clone(metric_name=metric_name)
self.per_mem_value_configs[metric_name] = mem_value_config.clone(metric_name=metric_name)
s... | Python | 1 |
_idx_norm,
rand_idx_truncnorm,
draws_idx_norm,
draws_idx_truncnorm,
fixed_idx,
num_panels,
idx_ln_dist,
force_positive_chol_diag,
rand_idx_stddev,
rand_idx_chol,
):
"""Compute the probabilities of all alternatives."""
if jax.config.jax_enable_x64:
UTIL_MAX = 700 # O... | Python | 1 |
[test]
fn flex_row_grow() {
let (mut tree, root) = layout_tree! {
(node(display = Flex, width = Px(300.), height = Px(10.))
(node(flex_grow = 1., flex_basis = Px(0.)))
(node(flex_grow = 2., flex_basis = Px(0.)))
)
};
tree.calculate(roo... | Rust | 0 |
image_bgr_dynamic = image_data_dynamic[:, :, :3]
# Write frame to dynamic camera video
out_dynamic.write(image_bgr_dynamic)
# *** Save right-camera images every 2 steps if enabled ***
if args.save_right_camera_figures and (i % 2 == 0) and (i < 100):
cv2.imwrite(os.path.... | Python | 1 |
struct InMemoryEventRepo {
calendar_events: std::sync::Mutex<Vec<CalendarEvent>>,
}
impl InMemoryEventRepo {
pub fn new() -> Self {
Self {
calendar_events: std::sync::Mutex::new(vec![]),
}
}
}
#[async_trait::async_trait]
impl IEventRepo for InMemoryEventRepo {
async fn ins... | Rust | 0 |
fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
let text = request
.cookies()
.get_private("captcha_text")
.map(|cookie| cookie.value().to_owned());
Outcome::Success(CaptchaText(text))
}
}
extern crate bindgen;
extern crate... | Rust | 0 |
config['delimiter'],
config['header_row'],
config.get('encoding', 'utf-8'))
if df_original is None or df_original.empty:
print(f" LƯU Ý: File {source_filename} rỗng hoặc k... | Python | 1 |
RTCPeerConnection,
RTCPeerConnection,
Arc<RTCDataChannel>,
mpsc::Sender<()>,
mpsc::Receiver<()>,
)> {
let (offer_pc, answer_pc) = new_pair(api).await?;
let (done_tx, done_rx) = mpsc::channel(1);
let dc = offer_pc
.create_data_channel(EXPECTED_LABEL, options)
.await?;
Ok(... | Rust | 0 |
expected_output = fs::read_to_string(&expected_out_file).map_or_else(
|err| panic!("Unable to read file {:?}: {:?}", input_file, err),
|s| normalized(s.trim().chars()).collect::<String>(),
);
let parsed_warrior = match corewars_parser::parse(&input) {
ParseResult::Ok(core, _) => core,
... | Rust | 0 |
import os
from copy import deepcopy
from datetime import datetime
from lagent.actions import AsyncWebBrowser, WebBrowser
from lagent.agents.stream import get_plugin_prompt
from lagent.prompts import InterpreterParser, PluginParser
from lagent.utils import create_object
from . import models as llm_factory
from .mindse... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.