text string | label_name string | labels int64 |
|---|---|---|
oworld\",\"encoding\":0},\"id\":1}"
);
}
}
// slog_demo/enemy.rs
use weapon::RailGun;
use PlayingCharacter;
use slog::Logger;
pub struct Enemy {
name: String,
logger: Logger,
weapon: RailGun
}
impl Enemy {
pub fn new(logger: &Logger, name: &str) -> Self {
let enemy_log = logger.ne... | Rust | 0 |
import discord
from discord.ext import commands
from PIL import Image, ImageSequence
import io
from func.checks import check_delay
# Definindo um cog com comandos
class CommandsCogTeste(commands.Cog, name="Comandos para testes"):
def __init__(self, bot):
self.bot = bot
@commands.command()... | Python | 1 |
ip + 4
}
Opcode::Halt => {
self.1 = ip;
halted = true;
break;
},
};
}
Ok((output, halted))
}
}
struct PhaseSettings([i32; AMPLIFIERS], [usize; AMPLIFIERS], usize);
impl Phase... | Rust | 0 |
box is pointing to is cleaned up as well because of the Drop trait implementation
// **** Enabling Recursive Types with Boxes *****
// At compile time, Rust needs to know how much space a type takes up.
//
// **Recursive type**: type whose size can't be known at compile time.
//
// However, b... | Rust | 0 |
(&mut self, data: Self::Item) {
self.1 = data;
}
}
impl SignalIdentifier for FSMSignals {
type IdType = SignalsEnum;
fn id(&self) -> Self::IdType {
self.0
}
}
impl PartialEq for FSMSignals {
fn eq(&self, other: &Self) -> bool {
self.0 == other.0
}
}
impl Eq for FSMSignals {
}
... | Rust | 0 |
#!/usr/bin/env python3
"""
Speaker Diarization时间戳对齐算法单元测试
测试场景:
1. 无重叠场景 - speaker segments完全不重叠
2. 部分重叠场景 - speaker segments部分时间重叠
3. 完全重叠场景 - 一个segment完全包含在另一个segment内
4. 边界条件 - 空segments、空chunks、时间戳相等等边界情况
5. 复杂混合场景 - 多种情况组合
重点验证:
- 每个chunk只被分配给一个speaker
- 时间戳对齐准确性
- 重叠处理的正确性
- 异常情况处理
"""
import unittest
import s... | Python | 1 |
iteable> Header<'data, V> {
/// Create a new header using the provided field name and value.
///
/// # Errors
/// Returns an error if `field` is not a valid HTTP header field.
/// See the docs for
/// [`InvalidHeaderError`](crate::InvalidHeaderError)
/// for details.
pub fn try_new(
field: &'data st... | Rust | 0 |
import random
n = random.randint(1,10)
a = -1
guess = 0
while a!=n:
guess+=1
a = int(input("Enter Your Number :"))
if a<n:
print("Your Number is Low")
else:
print("your number is high")
print(f"Your {a} is match with {n} after {guess} attemt") | Python | 1 |
streams: Vec<Upstream>,
pub certificates: Vec<Certificate>
}
impl KongfigOutput {
pub fn new(data: KongOutput, region: &Region) -> Self {
KongfigOutput {
host: data.kong.clone().config_url,
headers: vec![],
apis: kongfig_apis(data.apis, data.kong.clone(), region),
... | Rust | 0 |
bles::macros::table_row;
use simple_tables::core::Table;
#[test]
fn new_is_empty() {
#[table_row]
struct TableRow {
id: i32,
name: String,
}
#[table(rows = TableRow)]
struct ATable {}
assert!(ATable::new().get_rows().i... | Rust | 0 |
from typing import Any, Generic, TypeVar, Union
T = TypeVar("T")
class NullSafe:
'''Documentation at: <https://github.com/iann838/nullsafe-python>'''
def __getattr__(self, k: str) -> "NullSafe":
return undefined
def __getitem__(self, k: str) -> "NullSafe":
return undefined
def __b... | Python | 1 |
== 0:
return
if sum(num_matches) == 0:
return
best_matching_idx = int(np.array(certanty_sum_list).argsort()[-1])
print(certanty_sum_list, best_matching_idx)
mkpts1 = mkpts1_list[best_matching_idx]
mkpts2 = mkpts2_list[best_mat... | Python | 1 |
g(feature = "stlink")]
#[allow(unreachable_code)]
fn trace_itm(&self, target_clk: u32, trace_clk: u32) -> Result<()> {
let mut ctx = stlink::context()?;
let cfg = stlink::Config::new(
self.usb.vendor_id,
self.usb.product_id,
0x1,
0x81,
... | Rust | 0 |
Nevertheless, `read_i8`, `read_i8_le`, and `read_i8_ne` are provided for the
* sake of uniformity.
*/
pub fn read_i8_le(src: &mut dyn Read) -> io::Result<i8> {
let mut buf = [0; 1];
src.read_exact(&mut buf)?;
Ok(i8::from_le_bytes(buf))
}
/**
* Read a "network-endian" i8 from the specified bit source. S... | Rust | 0 |
h.exists(img1_path) or not os.path.exists(img2_path):
print(f"Error: One or both images not found")
sys.exit(1)
img1 = cv2.imread(img1_path, cv2.IMREAD_GRAYSCALE)
img2 = cv2.imread(img2_path, cv2.IMREAD_GRAYSCALE)
img1 = enhanced_preprocess_image(img... | Python | 1 |
test", "member1"], &[]);
run("virtual1", "exclude-from-test2", &["--workspace", "--exclude-from-test", "member2"], &[]);
}
#[test]
fn no_test() {
run("no_test", "no_test", &[], &[]);
if !(cfg!(windows) && cfg!(target_env = "msvc")) {
run("no_test", "link_dead_code", &[], &[("RUSTFLAGS", "-C link-de... | Rust | 0 |
iterator is exhausted without default."""
class EmptyAsyncIterator:
def __aiter__(self) -> "EmptyAsyncIterator":
return self
async def __anext__(self) -> int:
raise StopAsyncIteration
iterator = EmptyAsyncIterator()
# Should raise StopAsyncIteration when no defaul... | Python | 1 |
_date() {
let qdate = QDate::from_y_m_d(2019, 10, 22);
let qdatetime = QDateTime::from_date(qdate);
let actual_qdate = qdatetime.get_date();
assert_eq!((2019, 10, 22), actual_qdate.get_y_m_d());
}
#[test]
fn test_qdatetime_from_date_time_local_timezone() {
let qdate = QDate::from_y_m_d(2019, 10, 2... | Rust | 0 |
if "images" in result and result["images"]:
# 某些API返回图片数组
if isinstance(result["images"][0], str):
if result["images"][0].startswith("data:image"):
return result["images"][... | Python | 1 |
label_fontsize=25, title_fontsize=25,
label_font_family='Times New Roman', title_font_family='Times New Roman',
label_fontweight='bold', title_fontweight='bold',
label_pad=15, title_pad=15, mode='3d... | Python | 1 |
def process(text: str) -> str:
"""Capitalize the first letter of each line."""
return "\n".join(line.capitalize() for line in text.splitlines()) | Python | 1 |
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
n = len(nums)
for i in range(n):
swapped = False
for j in range(0, n-i-1):
if nums[j] > nums[j+1]:
... | Python | 1 |
ant::now();
loop {
metrics::gauge!("rate", 1.0);
metrics::increment_counter!("hits");
metrics::histogram!("histogram", 5.0);
if start.elapsed().as_secs() >= 5 {
break;
... | Rust | 0 |
p_relative_p: f32,
pub interval: Timeval,
pub leaked_count: u64,
pub allocated_count: u64
}
#[derive(Serialize)]
pub struct AllocationGroup< 'a > {
pub all: AllocationGroupData,
pub only_matched: AllocationGroupData,
pub backtrace_id: u32,
pub backtrace: Vec< Frame< 'a > >
}
#[derive(Seria... | Rust | 0 |
.rs<gh_stars>0
/*!
Generates an iterator type `Matcher` that looks roughly like
```ignore
mod intern_token {
extern crate regex as regex;
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Token<'input>(pub usize, pub &'input str);
// ~~~~~~ ~~~~~~~~~~~
... | Rust | 0 |
view(&self) -> Html<Model> {
match *self {
BodyPanel::PanelAccountState => html! {
<>
<PanelAccountState />
</>
},
BodyPanel::PanelVerifyRequest => html! {
<>
<PanelVerifyRequest />
... | Rust | 0 |
'rate_spread': float(rate_spread),
'profit': float(profit),
'date': sell_tx.date.isoformat(),
'time': sell_tx.time.isoformat()
}
transaction_matches.append(match_details)
rate_spreads.append(float(rate... | Python | 1 |
e - datetime(2024, 1, 1)).days
current_time = datetime(2024, 1, 1, hours, minutes, int(seconds)) + timedelta(days=days_elapsed)
# Generate duplicates if needed
for dup_num in range(plan['duplicates']):
# Add gap before duplicate
current_time += timedelta(seconds=... | Python | 1 |
>,
K: Ord,
F: FnMut(&T) -> K,
{
classify_by_key(a, b, key).try_fold(Ordering::Equal, cmp_fold)
}
/// Compare two sets represented by sorted, deduplicated iterators, using a comparator function.
///
/// See [`cmp()`].
///
/// # Examples
///
/// Using a custom comparator to reverse the ordering
///
/// ```
/... | Rust | 0 |
"""Perform containment checks on data values in a collection."""
from typing import List, Tuple, Set
# Make sure that you understand how each of these functions work
# For the containment_check_set function, make sure that you
# read the referenced web site and understand how the function works
def containment_che... | Python | 1 |
impl<T> From<T> for Existential<T> {
fn from(x: T) -> Self {
Existential(Quantified {
qs: vec![],
body: x,
})
}
}
impl<T> From<Existential<T>> for Universal<T> {
fn from(ex: Existential<T>) -> Self {
Universal(ex.0)
}
}
impl<T> Quantified<T> {
fn new... | Rust | 0 |
9.6~unreleased-1', '0.9.6~unreleased', Pf.INCORRECT, id='fritzing-parts'),
pytest.param('10.2+2.0.1-dmo1', '10.2+2.0.1', Pf.IGNORE, id='libcdio-paranoia'),
pytest.param('1.5.0~rc2+git20210630+ds-2', '1.5.0~rc2+git20210630', Pf.DEVEL | Pf.IGNORE, id='goldendict'),
])
def test_real_world(version: str, expected_ve... | Python | 1 |
conn.raw_send_packet(TCP_RST, &[], &[]);
conn.wait_rx_none();
// RST,ACK to anything
conn.raw_send_packet(TCP_RST|TCP_ACK, &[], &[]);
conn.wait_rx_none();
}
<filename>src/macros.rs
//! 相关宏程序等待更新中 ...
/// use database_type to create a "DataValue"
///
/// - @Number -> 1
/// - @String -> "hello worl... | Rust | 0 |
1D, 0x4405_7DD1),
(r"meshes\d\ex_emp_tower_01_b.nif", 0x5327_1E31, 0xAA16_C3A6),
(r"meshes\d\ex_emp_tower_01_a.nif", 0x5327_1E31, 0xAA16_C3AA),
(r"meshes\d\ex_imp_loaddoor_03.nif", 0x5327_1E3D, 0xD3A8_307E),
(r"meshes\d\ex_imp_loaddoor_02.nif", 0x5327_1E3D, 0xD3A8_347E),
(r"meshes\d\ex_imp_load... | Rust | 0 |
te.short_pays_long() {
calculate_margin(price, quantity, long_leverage)
} else {
calculate_margin(price, quantity, short_leverage)
};
let fraction_of_funding_period =
if hours_to_charge as i64 == SETTLEMENT_INTERVAL.whole_hours() {
Decimal::ON... | Rust | 0 |
s_):
fmt = fmt.decode("utf-8")
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore",
"Period with BDay freq is deprecated",
category=FutureWarning,
)
period = Period(ordin... | Python | 1 |
import json
from typing import Any, Dict
from tau_bench.envs.tool import Tool
class GetDailyProfitLossByFund(Tool):
@staticmethod
def invoke(data: Dict[str, Any], fund_id: str, date: str) -> str:
nav_records = data.get("nav_records", {})
trades = data.get("trades", {})
# Find N... | Python | 1 |
from benchopt import safe_import_context
# Protect the import with `safe_import_context()`. This allows:
# - skipping import to speed up autocompletion in CLI.
# - getting requirements info when all dependencies are not installed.
with safe_import_context() as import_ctx:
from skada import CORALAdapter, make_da_pi... | Python | 1 |
"""Support for create_protocol_engine module."""
from . import ProtocolEngine
from ..hardware_control import HardwareControlAPI
from opentrons.protocol_runner import protocol_runner, RunOrchestrator
def create_run_orchestrator(
hardware_api: HardwareControlAPI,
protocol_engine: ProtocolEngine,
) -> RunOrches... | Python | 1 |
Read<PreviousVelocity>, Read<EntityId>)>::query()
.filter(changed::<Velocity>())
.par_entities_for_each(world.inner(), |(entity, (vel, prev_vel, entity_id))| {
let entity_id = entity_id.0;
if vel.0 == prev_vel.0 {
return;
}
let (velocity... | Rust | 0 |
, command=self.app.mark_current_sentence, **button_kwargs).grid(row=1, column=0, padx=2, pady=2, sticky="ew")
ctk.CTkButton(editing_frame, text="✓ Mark Passed", command=self.app.mark_as_passed, fg_color="#2ECC71", hover_color="#27AE60", **button_kwargs).grid(row=1, column=1, padx=2, pady=2, sticky="ew")
... | Python | 1 |
s-proc";
const DIS_REGISTRY_FLAG: &str = "--dis-reg";
pub fn parsed_args() -> ParsedArgs {
let args: Vec<String> = std::env::args().collect();
let args = &args[1..];
let mut ioc_definitions = Vec::<String>::new();
let mut local_mode = false;
let mut cert_check = true;
let mut conn_check = tru... | Rust | 0 |
t\t\tp[i] = Array(sd).pack('V')[i-1] end\n"
payload_code += "\t\treturn p\n"
payload_code += "\trescue\n\treturn \"\"\n\tend\nend\n"
payload_code += "def ij(sc)\n"
payload_code += "\tif sc.length > 1000\n"
if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
... | Python | 1 |
import pygame
import time
pygame.init()
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
display_width = 800
display_height = 600
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Slither')
gameExit = False
lead_x = display_width/2
lead_y = display_height/2
l... | Python | 1 |
let mut write_opt = WriteOptions::default();
write_opt.disable_wal(true);
let output = Output {
value,
recipient: recipient.1,
};
let output_raw = serialize(&output).unwrap();
for i in 0..num_coins {
... | Rust | 0 |
from typing import List
def below_zero_original(operations: List[int]) -> bool:
""" You're given a list of deposit and withdrawal operations on a bank account that starts with
zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
at that point function should re... | Python | 1 |
;
let tests = [
// NIST ECB-AES128
AesTest::new_ecb(
&hex!("2b7e151628aed2a6abf7158809cf4f3c"),
&hex!("6bc1bee22e409f96e93d7e117393172a"),
&hex!("3ad77bb40d7a3660a89ecaf32466ef97"),
),
AesTest::new_ecb(
&hex!("2b7e151628aed2a6abf715880... | Rust | 0 |
scription: *const ::std::os::raw::c_char,
) -> SPXHR;
}
extern "C" {
pub fn speech_translation_config_add_target_language(
configHandle: SPXSPEECHCONFIGHANDLE,
language: *const ::std::os::raw::c_char,
) -> SPXHR;
}
extern "C" {
pub fn speech_translation_config_remove_target_language(
... | Rust | 0 |
>,
data: &'v Value,
}
impl<'v> Message<'v> {
pub fn new(schema_id: Uuid, data: &'v Value) -> Message<'v> {
Message {
object_id: Uuid::new_v4(),
schema_id,
order_group_id: Some(schema_id),
data,
}
}
}
//! PWM status LED
use embedded_hal::PwmPi... | Rust | 0 |
import threading
import multiprocessing
import time
def train_yolo(request_config: dict, trial_number: int) -> dict:
"""Simula el entrenamiento de YOLO."""
time.sleep(2) # Simula el tiempo de entrenamiento
return {"result": "success", "trial": trial_number}
def optuna_worker(q: multiprocessing.Queue, res... | Python | 1 |
from .automodel import AutoKAN, TinyAutoKAGN
from .baselines.conv_baseline import SimpleConv, EightSimpleConv
from .baselines.conv_kacn_baseline import SimpleConvKACN, EightSimpleConvKACN
from .baselines.conv_kagn_baseline import SimpleConvKAGN, EightSimpleConvKAGN
from .baselines.conv_kaln_baseline import SimpleConvKA... | Python | 1 |
const_range=None,
# parsimony_coefficient='auto',
init_depth=(2, 5),
p_crossover=0.35,
p_subtree_mutation=0.15,
p_hoist_mutation=0.145,
p_point_mutation=0.1,
... | Python | 1 |
;
} else {
strings.push(format!("{}:{}", c, x));
}
}
strings.join(" ")
}
fn join_columns(cs: &Vec<Column>) -> String {
let mut strings = vec![];
for c in cs {
strings.push(format!("{}", c));
}
strings.join(" ")
}
fn join_scalars(xs: &Vec<Scalar>) -> String {... | Rust | 0 |
ra_step_kwargs, return_dict=False)[0]
if callback_on_step_end is not None:
callback_kwargs = {}
for k in callback_on_step_end_tensor_inputs:
callback_kwargs[k] = locals()[k]
callback_outputs = callback_on_step_end(self,... | Python | 1 |
_unit.set(0usize, 1u8, {
let spd_press_is_valid: u8 = unsafe { ::core::mem::transmute(spd_press_is_valid) };
spd_press_is_valid as u64
});
__bindgen_bitfield_unit
}
}
#[repr(C, packed)]
#[derive(Default)]
pub struct sensor_humid_data {
pub shd_humid: f32,
pub _bitfiel... | Rust | 0 |
ec<String>>()
.join(", ")
)
}
}
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone, Hash)]
pub struct SizeAndAlign {
/// The alignment, in bytes.
pub align: i32, // i32 for use as a dynasm operand.
/// The size, in bytes.
pub size: i32, // Also i32 for dynasm.
}
i... | Rust | 0 |
wallet.id
cdata += wallet_hmac if wallet_hmac is not None else b'\0' * 32
return self.serialize(
cla=self.CLA_BITCOIN, ins=BitcoinInsType.SIGN_PSBT, cdata=bytes(cdata)
)
def get_master_fingerprint(self):
return self.serialize(
cla=self.CLA_BITCOIN,
... | Python | 1 |
"""
Run benchmarks for module using nose.
Parameters
----------
label : {'fast', 'full', '', attribute identifier}, optional
Identifies the benchmarks to run. This can be a string to pass to
the nosetests executable with the '-A' option, or one of several
... | Python | 1 |
preço = float(input("digite o preço da primerira loja: "))
preço2 = float(input("digite o preço da segunda loja: "))
if preço > preço2:
print(f"A primeira loja está cobrando {preço} ela está mais cara")
elif preço2 > preço:
print(f"A segunda loja está cobrando {preço2} ela está mais cara")
else:
print("Amba... | Python | 1 |
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from warnings import warn
from .api import from_bytes
from .constant import CHARDET_CORRESPONDENCE
# TODO: remove this check when dropping Python 3.7 support
if TYPE_CHECKING:
from typing_extensions import TypedDict
class ResultDict(Ty... | Python | 1 |
_val += 1 as u8;
assert_eq!(u8::to_str(u8_val), ~"0");
let mut u16_val: u16 = 65_535_u16;
assert_eq!(u16::to_str(u16_val), ~"65535");
u16_val += 1 as u16;
assert_eq!(u16::to_str(u16_val), ~"0");
let mut u32_val: u32 = 4_294_967_295_u32;
assert_eq!(u32::to_str(u... | Rust | 0 |
CopyValueRef {
bytes: self.bytes,
type_id: self.type_id,
alignment: self.alignment,
vtable: VTableRef::Box(Box::new(U::from(self.vtable.take()))),
}
}
#[inline]
pub fn upcast_ref<U: ?Sized + From<V>>(&self) -> CopyValueRef<U>
where
... | Rust | 0 |
ds.append(d.sum())
x = sum(xs)
d = sum(ds)
if reduce_group is not None:
dist.all_reduce(x, group=reduce_group)
dist.all_reduce(d, group=reduce_group)
if d == 0:
return None
return x / d
def _min_of(self, key, reduce_group):
... | Python | 1 |
mp::max(max, new_pos.distance());
(new_pos, max)
},
);
(pos.distance(), max)
}
#[cfg(test)]
mod tests {
use super::solve_both;
#[test]
fn test_solve_both() {
assert_eq!(solve_both("ne,ne,ne"), (3, 3));
assert_eq!(solve_both("ne,ne,sw,sw"), (0, 2));
asser... | Rust | 0 |
{
num: u8,
/// I/O Base
base: u16,
/// Control Base
ctrl: u16,
}
impl IDE {
pub fn new(num: u8) -> Self {
let ide = match num {
0 => IDE { num: 0, base: 0x1f0, ctrl: 0x3f4 },
1 => IDE { num: 1, base: 0x1f0, ctrl: 0x3f4 },
2 => IDE { num: 2, base: 0x17... | Rust | 0 |
n')
# ax2.plot(voo_changes_df['date'], voo_changes_df['percent_change_5m'], label='5 min', color='tab:cyan')
# ax2.legend()
# ax2.tick_params(axis='y', labelcolor=color)
# fig.tight_layout() # otherwise the right y-label is slightly clipped
# fig.legend()
# plt.show()
for symbol, changes_df in symbol_change_dfs.item... | Python | 1 |
class Solution:
def maximumImportance(self, n: int, roads: List[List[int]]) -> int:
count = [0] * n
for u, v in roads:
count[u] += 1
count[v] += 1
count.sort()
return sum((i + 1) * c for i, c in enumerate(count))
| Python | 1 |
10, 100)
assert len(G) == 10
assert sum(1 for _ in G.edges()) == 45
G = gnm_random_graph(10, 100, directed=True)
assert len(G) == 10
assert sum(1 for _ in G.edges()) == 90
G = gnm_random_graph(10, -1.1)
assert len(G) == 10
assert sum(1 for _ in G.edges()... | Python | 1 |
import os
JOKE_API_URL = os.getenv(
"JOKE_API_URL", "https://v2.jokeapi.dev/joke/Programming?type=single")
| Python | 1 |
orea",
"Malaysia",
"China",
"Indonesia",
"Philippines",
"India",
])
.marker(Marker::new().color(Rgb::new(234, 153, 153)).size(12));
let trace4 = Scatter::new(
vec![19097, 18601, 15595, 13546, 12026, 7434, 5419],
vec![43, 47, 56, 80, 86, 93, 80],
)
... | Rust | 0 |
ueError(
f"Incremental variable {incremental_chd_var_id} not present in {component_chd.id}"
)
prefix_par = ""
cumulative_var_par_id = ""
if self.parent:
prefix_par = f"{self.parent.id}_{component_par.id}"
cumulative_var_par_id = f"{prefix_par}... | Python | 1 |
# Nombre: Elton Yael Hernández Pérez
# Fecha: 24/10/2024
# Descripción: Este programa solicita dos números al usuario y utiliza ciclos `while`
# para imprimir los números consecutivos desde 0 hasta el número ingresado,
# y luego, los números pares desde 0 hasta otro número ingresado por el usuario.
# Ejemplo de ciclo ... | Python | 1 |
import requests
from bs4 import BeautifulSoup
import pandas as pd
import subprocess
import time
def is_file_in_use(file_path):
"""Checks if a file is currently opened."""
try:
with open(file_path, 'a'):
pass
except IOError:
return True
return False
def fetch_films(url, re... | Python | 1 |
ic_thresh=0, ret_shift=None,
force_calc_corr=False):
"""
对于含有多个因子的factor_df 进行快速分析
注意return 需要先进行 shift; ret_df 可以缺省
"""
factor_df = factor_df.copy()
if ret_df is None:
if rtype not in factor_df.columns:
... | Python | 1 |
float encoder (`encode_float_f32()`) works properly.
#[test]
fn test_encode_float_f32() {
// Check the encoder works properly.
let mut data = vec![];
data.encode_float_f32(-10.2);
assert_eq!(data, vec![51, 51, 35, 193]);
}
/// Test to make sure the u8 string encoder (`encode_string_u8()`) works prope... | Rust | 0 |
#[derive(Clone)]
pub struct ConnectionStats {
/// Non-smoothed Round Trip Time.
pub rtt: Duration,
/// Deviation of the rtt.
pub rtt_dev: Duration,
/// Total count of packets since start of the connection. Indexed by `PacketStat`.
pub total_packets: [u64; 6],
/// Total count of bytes since start of the connectio... | Rust | 0 |
> None:
"""Check for deprecated config keys and warn the user.
Args:
config_dict: The input config.
"""
deprecated_removed_keys = V2_REMOVED_KEYS & config_dict.keys()
deprecated_renamed_keys = V2_RENAMED_KEYS.keys() & config_dict.keys()
if deprecated_removed_keys or deprecated_renamed_k... | Python | 1 |
from typing import Literal, TypedDict
MobyOutputFormat = Literal["id", "brief", "normal"]
class MobyGameAlternateTitle(TypedDict):
description: str
title: str
class MobyGenre(TypedDict):
genre_category: str
genre_category_id: int
genre_id: int
genre_name: str
class MobyPlatform(TypedDict)... | Python | 1 |
where
TMapping: IpMapping,
{
type SerializeFieldMapping = SerializeFieldMapping<TMapping, IpPivot>;
fn data_type() -> &'static str {
"ip"
}
}
impl<TMapping> StaticSerialize for SerializeFieldMapping<TMapping, IpPivot>
where
TMapping: FieldMappin... | Rust | 0 |
filepath = os.path.join(opt.results_dir, self.eval_log_filename)
opt.tensorboard_log_dir = os.path.join(opt.results_dir, self.tensorboard_log_dir)
opt.device = torch.device("cuda:%d" % opt.device_ids[0] if opt.device >= 0 else "cpu")
opt.h5driver = None if opt.no_core_driver else "core"
... | Python | 1 |
import random
def roll_dice():
dice_drawing = {
1: (
"-----",
"| |",
"| o |",
"| |",
"-----",
),
2: (
"-----",
"|o |",
"| |",
"| o|",
"-----",
),
... | Python | 1 |
/// String with text.
Text(String),
/// Underlined text, e.g. `+Text+`.
Underlined {
attributes: Attributes,
elements: InlineElements,
},
}
#[derive(Debug, PartialEq)]
pub enum ListElement {
ListItem {
attributes: Attributes,
elements: InlineElements,
},
... | Rust | 0 |
67]);
colortab.insert(170, [160, 77, 78]);
colortab.insert(171, [84, 40, 41]);
colortab.insert(172, [40, 28, 24]);
colortab.insert(173, [49, 35, 30]);
colortab.insert(174, [57, 41, 35]);
colortab.insert(175, [30, 21, 18]);
colortab.insert(176, [95, 75, 69]);
colortab.insert(177, [116, 9... | Rust | 0 |
eration_handler;
use super::operation_handler::{OperationResources, PartitionMap};
use super::state::OperationState;
use cerberus_proto::worker as pb;
use communication::MasterInterface;
use errors::*;
use util::output_error;
const WORKER_OUTPUT_DIRECTORY: &str = "/tmp/cerberus/";
/// The `MapInput` is a struct used ... | Rust | 0 |
use chrono::DateTime;
use env_logger::Env;
use futures_util::{future, pin_mut, StreamExt};
use log::{debug, error, info};
use regex::Regex;
use rust_decimal::prelude::Decimal;
use serde::Deserialize;
use std::{
fs::File,
io::{prelude::*, BufReader},
sync::mpsc::{Receiver, Sender},
time::Duration,
{e... | Rust | 0 |
orials = [0, 1, 5, 10, -1]
for num in test_factorials:
result = calculate_factorial(num)
print(f"{num}! = {result}")
# 测试练习4:斐波那契数列
print("\n练习4:斐波那契数列测试")
fib_sequences = [0, 1, 8, 10]
for n in fib_sequences:
result = fibonacci_sequence(n)
print(f"前{n}项斐波那契数列: {... | Python | 1 |
#! usr/bin/python3.9
"""
Module initially auto generated using V5Automation files from CATIA V5 R28 on 2020-09-25 14:34:21.593357
.. warning::
The notes denoted "CAA V5 Visual Basic Help" are to be used as reference only.
They are there as a guide as to how the visual basic / catscript function... | Python | 1 |
o_string(), "はい。キウイは、少しならあげても大丈夫です。ではまた。");
f.insert("みかん".to_string(), "はい。みかんは、少しならあげても大丈夫です。ではまた。");
f.insert("パパイヤ".to_string(), "はい。パパイヤは、少しならあげても大丈夫です。ではまた。");
f.insert("マンゴー".to_string(), "はい。マンゴーは、少しならあげても大丈夫です。ではまた。");
f.insert("いちご".to_string(), "はい。いちごは、少しならあげても大丈夫です。ではまた。");
f.insert("ブル... | Rust | 0 |
scale_value_str = re.search(r'\d+$', option)
if scale_value_str is not None:
scale = int(scale_value_str.group())
else:
raise ValueError(
"Missing printer SCALE parameter integer "
... | Python | 1 |
"https://github.com/votrecompte/projet5",
"icon": "🤖"
}
]
for project in project_data:
st.markdown(f"<h3>{project['title']} {project['icon']}</h3>", unsafe_allow_html=True)
st.write(project["description"])
st.write(f"**Technologies** : {project['technologies']}")
st.write(f"[Lien vers le p... | Python | 1 |
center: bool
) -> tuple[ArrowSeries, int]:
"""Pad series with None values on the left and/or right side, depending on the specified parameters.
Arguments:
series: The input ArrowSeries to be padded.
window_size: The desired size of the window.
center: Specifies whether to center the pa... | Python | 1 |
self.types { Some(type_env) } else { None };
if self.interactive {
repl(arithmetic, env, type_env)
} else {
self.run_command(arithmetic, env, type_env)
}
}
fn run_command<T: ReplLiteral>(
self,
arithmetic: Box<dyn OrdArithmetic<T>>,
env: ... | Rust | 0 |
#!/usr/bin/python
# -*- encoding: utf-8 -*-
import torch
import logging
logger = logging.getLogger()
class Optimizer(object):
def __init__(self,
model,
lr0,
momentum,
wd,
warmup_steps,
warmup_start_lr,
... | Python | 1 |
CON register." ]
# [ inline ( always ) ]
pub fn tc0mci2_re_set(&mut self) -> _TC0MCI2_RE_SETW {
_TC0MCI2_RE_SETW { w: self }
}
# [ doc = "Bit 5 - Writing a one sets the corresponding bit in the CNTCON register." ]
# [ inline ( always ) ]
pub fn tc0mci2_fe_set(... | Rust | 0 |
} else {
if a.y2 + margin > cv.height {
self.pos += cv.height - margin - a.y2;
}
}
}
}
}
// 1区切り戻る
FuncType::BkSlash => {
let mut s: i32 = 0;
let mut i: usize;
let mut j: usize = self.plines.... | Rust | 0 |
:
subagent_stop_events.append(line)
print(f"\nFound {len(pre_tool_events)} Task tool invocations")
print(f"Found {len(subagent_stop_events)} SubagentStop events")
if pre_tool_events and subagent_stop_events:
print("\n✅ Events found! We can potentially correlate them")
print(
... | Python | 1 |
#!/usr/bin/env python3
import argparse
import glob
import os.path
import subprocess
import sys
def main():
project_root = os.path.abspath(os.path.dirname(sys.argv[0]) + '/../..')
gtkwave_scripts_dir = os.path.join(project_root, 'scripts/gtkwave')
parser = argparse.ArgumentParser()
parser.add_argumen... | Python | 1 |
/// This type implements [`TcpProvider`] so that it can be used as a
/// drop-in replacement for testing code that uses the network.
///
/// # Limitations
///
/// There's no randomness here, so we can't simulate the weirdness of
/// real networks.
///
/// So far, there's no support for DNS or UDP.
///
/// We don't hand... | Rust | 0 |
get(&obj, &"chrs".into())?;
let chrs_array: js_sys::Array = chrs.dyn_into()?;
let mut chrs: Vec<(String, usize)> = Vec::new();
for chr in chrs_array.iter() {
let name = js_sys::Reflect::get(&chr, &"name".into())?;
let name = name.as_string().unwrap();
let l... | Rust | 0 |
anyhow::anyhow!(
"attempted to push a control frame for an instruction \
sequence with a type that does not exist"
)
.context(format!("type: {:?} -> {:?}", &start_types, &end_types))
})?;
Ok(impl_push_control_with_ty(
types,
kind,
func,
c... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.