text string | label_name string | labels int64 |
|---|---|---|
= ();
type Error = Error;
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>
where
T: ser::Serialize,
{
ser::SerializeSeq::serialize_element(self, value)
}
fn end(self) -> Result<Self::Ok> {
// close sequence
self.ser.buf.push(b']');
// c... | Rust | 0 |
class Employe():
def __init__(self,nom,prenom,salaire):
self.nom=nom
self.prenom=prenom
self.salaire=salaire
class Manager(Employe):
def __init__(self, nom, prenom, salaire):
super().__init__(nom, prenom, salaire)
self.emp_supervises = []
def ajouter_emp(self,employe... | Python | 1 |
import urllib.request as urllib2
from io import TextIOWrapper
dataurl = 'https://adventofcode.com/2024/day/5/input'
def part1(rules,updates):
total = 0
for update in updates:
pages = [int(x) for x in update.split(',')]
valid = True
for rule in rules:
orders = [int(x... | Python | 1 |
ern crate rocket;
extern crate pbkdf2;
extern crate rocket_contrib;
#[macro_use]
extern crate log;
extern crate simplelog;
use crate::ws::RocketToWsMsg;
use db::Pool;
use pacosako::{DenseBoard, SakoSearchResult};
use rand::{thread_rng, Rng};
use rocket::response::NamedFile;
use rocket::response::{Flash, Redirect};
use ... | Rust | 0 |
// into the denominator, because the common sample rate of 44.1 kHz
// is not a multiple of 500.
Some(Hertz(hz)) => self.samples_played * 500 / (hz as u64),
// When the sample rate is not known, we definitely have not started
// playback.
None => 0
}
... | Rust | 0 |
ero().serialized_size();
field_serialization_test::<Fq6>(byte_size);
}
generate_field_serialization_test!($($tail)*);
};
(fq12; $($tail:tt)*) => {
#[test]
fn test_fq12_serialization() {
let byte_size = Fq12::zero().serialized_size();
field_se... | Rust | 0 |
import pytest
from torch import nn
from reinvent.models.transformer.core.network.encode_decode.model import EncoderDecoder
from reinvent.models.transformer.core.vocabulary import build_vocabulary
from reinvent.models.transformer.libinvent.libinvent import LibinventModel
from reinvent.models import meta_data
from tests... | Python | 1 |
obp_idx & 0x3F)
}
}
use serde::{Deserialize, Serialize};
use crate::component::{NextScene, Object};
use crate::direction::Direction;
use crate::point::Point;
use crate::{component, util, Assets, Context2D, KeyboardState};
use super::cell::{cell_cursor, OverworldCell, OverworldCellType, Surroundings};
use super::c... | Rust | 0 |
from discord.ext import commands
import discord
import datetime
from discord import app_commands
class MuteCog(commands.Cog):
def __init__(self, bot:commands.bot):
self.bot = bot
@app_commands.command(description = "Mutes someone on this discord server.")
@app_commands.checks.has_permissions(moder... | Python | 1 |
tic HASH_TEST_VEC: &'static [&'static str] = &[
&"abc",
&"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
&"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
];
static HASH_SHA256_TRUTH: &'static [&'static str] = &[
&"ba7816bf8... | Rust | 0 |
it_handling(self, sample_criterion_thread):
"""Test that backends handle rate limits appropriately."""
backends = [
BackendFactory().create_backend(ModelBackend.BEDROCK),
BackendFactory().create_backend(ModelBackend.LITELLM),
BackendFactory().create_backend(ModelBacke... | Python | 1 |
)
metric_load_result.additional_properties = d
return metric_load_result
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__... | Python | 1 |
crate::semirings::{SerializableSemiring, WeaklyDivisibleSemiring, WeightQuantize};
use crate::tests_openfst::utils::test_eq_fst;
use crate::tests_openfst::FstTestData;
use std::path::Path;
#[derive(Serialize, Deserialize, Debug)]
pub struct ConcatOperationResult {
fst_2_path: String,
result_static_path: Strin... | Rust | 0 |
@score.setter
def score(self, value: (float | None)):
self._score = value
| Python | 1 |
lue("", r#"KlogHas("lin")"#), MetricValue::Bool(true));
assert_eq!(state.evaluate_value("", r#"KlogHas("l.ne")"#), MetricValue::Bool(true));
assert_eq!(state.evaluate_value("", r#"KlogHas("fi.*ne")"#), MetricValue::Bool(true));
assert_eq!(state.evaluate_value("", r#"KlogHas("fi.*sec")"#), Metric... | Rust | 0 |
# Split by newlines and format each paragraph as a quote
thinking_paragraphs = thinking_text.split("\n\n")
for paragraph in thinking_paragraphs:
if paragraph.strip():
# Format as Slack quote (> at the beginning of each line)
... | Python | 1 |
eline_2_ops.extend(timeline_2.integrate_ops::<FakeFileSystem<StdRng>, _>(
&ops_from_timeline_1_to_timeline_2,
None,
));
}
assert_eq!(timeline_1.paths_with_ids(), timeline_2.paths_with_ids());
assert_eq!(timeline_1.paths(), ["a/", "a~/", "a~~/"]);
... | Rust | 0 |
function does not check if necessary tags are present. Instead, it only checks if the defined
/// tags are valid.
///
/// ```
/// #[editor_plugin(specific_to=Map)]
/// pub struct Sync {
///
/// #[option(
/// label = "URL",
/// description = ""
/// )]
/// url: String,
/// }
/// ```
///... | Rust | 0 |
def __init__(self, vqvae: VQModel, text_encoder: CLIPTextModel, tokenizer:
CLIPTokenizer, transformer: Transformer2DModel, scheduler:
VQDiffusionScheduler, learned_classifier_free_sampling_embeddings:
LearnedClassifierFreeSamplingEmbeddings):
super().__init__()
self.register_modules(vqvae=vqvae, tra... | Python | 1 |
import asyncio
import time
import ray
from ray.exceptions import RayTaskError
@ray.remote
class Actor:
async def f(self):
try:
await asyncio.sleep(5)
except asyncio.CancelledError:
print("Enter cancelled")
for i in range(5):
print(i)
await asyncio.sleep(1)
print("Actor task canceled.")
acto... | Python | 1 |
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. 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 requir... | Python | 1 |
session)
await invalidate_license_cache(session, license.license_key)
return {"success": True, "message": "License cache invalidated successfully"}
def create_headers(request: ThreatIntelRegisterRequest) -> Dict[str, str]:
return {
"x-api-key": request.requesting_api_key,
"Content-Type": ... | Python | 1 |
s,
teacher_forcing_ratio=args.teacher_forcing_ratio,
tf_decay_rate=args.tf_decay_rate,
max_norm=args.max_norm,
mid_sample_size=args.mid_sample_size,
dual_sample_size=args.dual_sample_size,
nlu_st=(args.nlu_st == 1),
... | Python | 1 |
positions
"""
x = x.reshape(-1, self.dimension)
grad_logpdf = np.dot(self.mean.reshape(1, -1) - x, self.precision)
return grad_logpdf
def pdf(self, x):
"""Probability density function.
Args:
x (np.ndarray): Positions at which the pdf is evaluated
... | Python | 1 |
ty_args = ty_args
.into_iter()
.map(|t| instantiate_base(context, t))
.collect();
let tvars = make_tparams(context, loc, constraints);
assert!(ty_args.len() == tvars.len());
let mut res = vec![];
let subst = std::mem::replace(&mut context.subst, /* dummy value */ Subst::new());
... | Rust | 0 |
ps://stackoverflow.com/questions/600293/how-to-check-if-a-number-is-a-power-of-2
const fn is_power_of_two(num: usize) -> bool {
num != 0 && ((num & (num - 1)) == 0)
}
// tests module for small unit tests
#[cfg(test)]
mod tests2 {
use super::*;
#[test]
fn test_is_power_of_two() {
assert!(!is_p... | Rust | 0 |
# _*_ codign:utf8 _*_
"""====================================
@Author:Sadam·Sadik
@Email:1903249375@qq.com
@Date:2023/5/9
@Software: PyCharm
@disc:
======================================="""
import logging
import piexif
def get_gps_info(raw_path):
# 读取图片的exif信息
exif_dict = piexif.load(raw_path)
# 获取GPS信息... | Python | 1 |
de películas.
Para el tema dado, sugiere {count} películas.
Utiliza el siguiente esquema JSON:
{schema}
""",
"library_prompt": "Basado en la siguiente lista de películas en la biblioteca Plex del usuario: {movies}, sugiere {count} películas relacionadas con el tema: {theme}. Sol... | Python | 1 |
4565 base 10
let val_be = to_fixed_bytes(&val);
assert_eq!( Uint256::from_bytes_be(&val_be), get_uint256("12345") );
}
}<filename>verifier/src/public_input_offsets.rs
use num256::uint256::Uint256 as Uint256;
use crate::uint256_ops;
/* ----------------
The following constants are offsets of data e... | Rust | 0 |
, value_match={value_match}")
if name_match and value_match and index_match:
filtered_candidates.append(candidate)
logger.info(f"最终过滤后的候选元素数量: {len(filtered_candidates)}")
# 根据索引选择元素
if filtered_candidates:
matches.append(filtere... | Python | 1 |
# richard -- video index system
# Copyright (C) 2012, 2013, 2014, 2015 richard contributors. See AUTHORS.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the Licens... | Python | 1 |
{ZX_ERR_NOT_FOUND, ZX_OK},
futures::stream::StreamExt,
futures::task::Poll,
pin_utils::pin_mut,
test_case::test_case,
wlan_common::assert_variant,
};
/// Hold the client and service ends for DeviceMonitor to allow mocking DeviceMonitor responses
/// for unit tests.
... | Rust | 0 |
get_first_word(word: &str) -> &str {
let word = word.trim();
let words: Vec<&str> = word.split(|c: char| " ,.-;:'".contains(c)).collect();
words[0]
}
pub fn get_first_letter(word: &str) -> char {
word.chars().next().unwrap()
}
pub fn is_title_case(first_word: &str) -> bool {
let mut chars = fir... | Rust | 0 |
top: Some(stop_tx)}.start();
Arbiter::set_system(sys, name.to_string());
SystemRunner {
core: core,
stop: stop_rx,
}
}
}
/// Helper object that runs System's event loop
#[must_use="SystemRunner must be run"]
pub struct SystemRunner {
core: Core,
stop: Receiv... | Rust | 0 |
de YouTube/TikTok.'}\n\nENLACES/FUENTES RELEVANTES:\n{chr(10).join(sorted(normal_links)) if normal_links else 'No se encontraron fuentes relevantes.'}\n\nINSTRUCCIÓN CRÍTICA: Utiliza TODA la información proporcionada arriba. Si hay múltiples noticias, datos o elementos, inclúyelos TODOS en tu respuesta de forma natura... | Python | 1 |
from timeit import default_timer as timer
import numpy as np
from numba import roc, float32
from numba.roc.hsadrv.error import HsaKernelLaunchError
import unittest
class TestMatMul(unittest.TestCase):
def test_matmul_naive(self):
@roc.jit
def matmul(A, B, C):
i = roc.get_global_id(0)
... | Python | 1 |
ompiling a separate server binary. I wanted something simple, light
//! weight, easy to use, and that could conveniently search structs and
//! collections in my binary. So, I made `indicium`.
//!
//! # What's New?
//!
//! * `0.3.7`: An experimental feature is now disabled by default to reduce
//! resource consumption.... | Rust | 0 |
d_to_string(path)?;
// RPMs can only have 1 line in the license - so use the first.
let license_string = license_string
.lines()
.next()
.ok_or_else(|| format_err!(ErrorKind::License, "empty license file {}!", path))?
.to_owned();
... | Rust | 0 |
# THIS FILE HAS BEEN AUTOGENERATED. To update:
# 1. modify the `_deps` dict in setup.py
# 2. run `make deps_table_update``
deps = {
"Pillow": "Pillow<10.0.0",
"accelerate": "accelerate>=0.20.3",
"av": "av==9.2.0",
"beautifulsoup4": "beautifulsoup4",
"black": "black~=23.1",
"codecarbon": "codecar... | Python | 1 |
write is therefore quite simple:
// 1). Write the significant digits, using an itoa algorithm for the radix.
// We never need to backtrack, because we cannot have rounding error.
// 2). Calculate the scientific exponent for the value.
// This is exponent + mantissa digits.
// 3). Determine if we should us... | Rust | 0 |
flags=re.IGNORECASE)
cleaned_response = re.sub(r"\s*```$", "", cleaned_response.strip())
linked_entity = json.loads(cleaned_response)
entity["wiki_id"] = linked_entity["entity_id"]
elif not data:
... | Python | 1 |
e".to_string()
};
let channel_position = &guild_channel.position;
let channel_id = &guild_channel.id;
let channel_bitrate = if guild_channel.bitrate != None {
guild_channel.bitrate.unwrap().to_string() + " kbps"
} else {
"N/A".to_string()
};
let channel_nsfw = &guild_channel... | Rust | 0 |
rank_snapshots (id) {
id -> Bigint,
user_id -> Bigint,
update_time -> Datetime,
mapped_spotify_id -> Integer,
timeframe -> Unsigned<Tinyint>,
ranking -> Unsigned<Tinyint>,
}
}
table! {
track_stats_history (id) {
id -> Bigint,
followers -> Unsigned... | Rust | 0 |
_ids_to_do}")
return app_ids_to_do
def main() -> None:
gem_sack_price_in_euros = 0.40
# Positive value to ensure under-cutting is possible
price_offset_in_euros = 0.1
app_ids_previously_processed = [
205890,
359400,
395620,
398140,
448720,
468250,... | Python | 1 |
for StartLocalTransactionResponse {
fn clear(&mut self) {
self.transaction_id.clear();
self.unknown_fields.clear();
}
}
impl ::std::fmt::Debug for StartLocalTransactionResponse {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
::protobuf::text_format::fmt(s... | Rust | 0 |
# Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License
"""The Indexing Engine text chunk package root."""
| Python | 1 |
:?}", section).is_empty());
}
#[test]
fn far_too_small() {
let data = hex!("fd4df0");
assert_matches!(
PmtSection::from_bytes(&data),
Err(DemuxError::NotEnoughData {
expected: 4,
actual: 3,
..
})
);
... | Rust | 0 |
import json
ip=["apple","banana","grapes"]
#store to file
# with open ("file4.json","w") as f:
# json.dump(ip,f)
#read firts and add existing one
# ip1="pineapple"
# with open ("file4.json","r") as f:
# data=json.load(f)#data will change from json string to list
# if ip1 not in data["fruits"]:
# data[... | Python | 1 |
medias = []
classifica = []
times = [
('Jeff',[10, 12, 9]),
('Rodr', [11, 9, 13])
]
for equipes, pontuacao in times:
media = sum(pontuacao) / len(pontuacao)
medias.append((pontuacao, media))
medias = sorted(medias)
print(medias)
print(i)
print(pontuacao) | Python | 1 |
nimation> {
self.animations.get_mut(self.current_animation)
}
}
fn update_sprite_atlas(mut query: Query<(&mut TextureAtlasSprite, &Animations)>) {
for (mut sprite, animations) in query.iter_mut() {
let current_anim_index = animations.current_animation;
if let Some(anim) = animations.ani... | Rust | 0 |
= self.z * self.y;
let z3 = z3 + z3;
let x3 = f - (d + d);
let c = c + c;
let c = c + c;
let c = c + c;
let y3 = e * (d - x3) - c;
let tmp = G2Projective {
x: x3,
y: y3,
z: z3,
};
G2Projective::conditional_sele... | Rust | 0 |
intPass<'tcx> for IndexRefutableSlice {
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
if_chain! {
if !expr.span.from_expansion() || is_expn_of(expr.span, "if_chain").is_some();
if let Some(IfLet {let_pat, if_then, ..}) = IfLet::hir(cx, expr);
... | Rust | 0 |
u32;
type Currency = Currency;
type Event = Event;
type MaxAuction = MaxAuction;
type NFT = NFT;
type TokenData = nft::TokenData<Balance>;
type TokenId = u64;
}
pub type NativeCurrency =
orml_currencies::BasicCurrencyAdapter<Runtime, Balances, Amount, BlockNumber>;
parameter_type_with_key! {
pub ExistentialDe... | Rust | 0 |
import json
import os
import logging
def save_results(chunk_size_metrics, retrieval_metrics, scores, output_dir='results/'):
"""
Saves the evaluation results to JSON files.
Args:
chunk_size_metrics (dict): Metrics related to chunk sizes.
retrieval_metrics (dict): Metrics related to ret... | Python | 1 |
v` as mutable
//[nll2015]~^^ ERROR cannot borrow `v` as mutable
//[migrate2018]~^^^ ERROR cannot borrow `v` as mutable
//[nll2018]~^^^^ ERROR cannot borrow `v` as mutable
}
fn reservation_conflict() {
let mut v = vec![0, 1, 2];
let shared = &v;
v.push(shared.len());
//[nll2015]~^ ERROR can... | Rust | 0 |