text
string
label_name
string
labels
int64
il, ('music', { 'track': ('title', {str}), 'album': ('album', {str}, filter), 'artists': ('authorName', {str}, {lambda x: re.split(r'(?:, | & )', x) if x else None}), 'duration': ('duration', {int_or_none}), })), **traverse_obj(awem...
Python
1
_to_find.data.len() && parser.pos < parser.code.len() as i16 { let find_char = label_to_find.data[current_index].to_ascii_lowercase(); let match_char = parser.code[parser.pos as usize + current_index].to_ascii_lowercase(); if find_char != match_char { break; } else { current_index += 1; ...
Rust
0
nome=input("digite seu nome: ") .strip() ## retira os espaços do inicio e do final do nome print(nome.upper()) print(nome.lower()) print(len(''.join(nome.split()))) print(nome.find(' '))
Python
1
# https://leetcode.com/problems/regions-cut-by-slashes/ class Solution: def regionsBySlashes(self, grid: List[str]) -> int: conv = {'/': ['UL', 'DR'], '\\': ['UR', 'DL'], ' ': ['ULDR']} par = {} def parent(u): if u not in par: par[u] = u elif par[u] ...
Python
1
: Rectangle, is_checked: bool, is_mouse_over: bool, (label, _): Self::Output, style_sheet: &Self::Style, ) -> Self::Output { let style = if is_mouse_over { style_sheet.hovered(is_checked) } else { style_sheet.active(is_checked) }; ...
Rust
0
) gen_samples_args.add_argument("--out-dir", "-o", type=str, help="Output directory. Will be totally overwritten!") gen_samples_args.add_argument("--read-length", "-l", type=int, help="Read length", default=100) gen_samples_args.add_argument("--error-rate", "-e", type=float, help="Base error rate", default=0) gen_sampl...
Python
1
let (line_begin, line_end, _, _) = pos.info_pos_extended(); Span(line_begin, line_end) } } #![forbid(unsafe_code)] #![deny( missing_debug_implementations, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unused_import_braces, unused_qualifications, clippy::...
Rust
0
data. pub fn is_empty(&self) -> bool { self.len() == 0 } /// Returns the total length of the attribute value data, in bytes. pub fn len(&self) -> u64 { match self { Self::Resident(inner) => inner.len(), Self::NonResident(inner) => inner.len(), Self::...
Rust
0
.index(msg) _pkt_lst.pop(lst_i) pkt_id = _pkt_ids.pop(lst_i) except: pass print("Sending back masterInfo from:", pkt_id) elif pkt.src == 0x0B and pkt.cmdSet == 0x0C: p = No...
Python
1
st KEY_Sinh_uu: Keysym = <KEY>; /* U+0D8C SINHALA UUYANNA */ pub const KEY_Sinh_ri: Keysym = <KEY>; /* U+0D8D SINHALA IRUYANNA */ pub const KEY_Sinh_rii: Keysym = 0x1000d8e; /* U+0D8E SINHALA IRUUYANNA */ pub const KEY_Sinh_lu: Keysym = <KEY>; /* U+0D8F SINHALA ILUYANNA */ pub const KEY_Sinh_luu: Keysym = <KEY>; /...
Rust
0
tweet.texto = "#DíaMundialDelOrgasmoFemenino Lol Respeten un poco Este TT es igual como" \ + " si fuese #ILoveReggaeton Que gracia siempre #CojenComoObjetoSexual" tweet.favoritos = 0 tweet.retweets = 71 tweet.es_humor = 1 tweet.cuenta = 142482558 s...
Python
1
class HealthFitnessManagementSystem: def __init__(self): self.daily_logs = [] self.goals = { 'calories': None, 'exercise_minutes': None, 'water_liters': None } def set_goals(self): print("\nSet your fitness goals:") self...
Python
1
icense information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; extern crate libc; use getopts::{optflag, getopts, usage}; use std::ffi::CString; use std::io::stdio::{stdin_raw, stdout_raw, stderr_raw}; use std::io::{File, Open, Read, Append, Write}; use std::...
Rust
0
from launch import LaunchDescription from launch_ros.actions import Node def generate_launch_description(): return LaunchDescription([ Node( package='velarray_ros2', executable='velarray_node', name='velarray_node', output='screen', parameters=['c...
Python
1
by_atom_or_bond_sum_expk = per_mol_sum_expk[batch] w = expk / (by_atom_or_bond_sum_expk) index_torch = batch.unsqueeze(1).repeat(1, preds.shape[1]) per_mol_preds = torch.zeros( n_mols, preds.shape[1], dtype=preds.dtype, device=preds.device ).scatter_reduce_(0, index...
Python
1
ink layer address that can be discovered using NDP. pub(crate) trait LinkLayerAddress: Copy + Clone + Debug { /// The length, in bytes, expected for the `LinkLayerAddress` const BYTES_LENGTH: usize; /// Returns the underlying bytes of a `LinkLayerAddress` fn bytes(&self) -> &[u8]; /// Attempts to c...
Rust
0
_with_broadcast_common(X, Y, dtype, gc, dc) @settings(max_examples=30, deadline=None) @given( K=st.integers(min_value=1, max_value=10), N=st.integers(min_value=1, max_value=10), **hu.gcs ) def test_numpy_batch_matmul_1d_2d(self, K, N, gc, dc): dtype = np.float32 ...
Python
1
s def test_parse_stb(self): ''' test parse_stb.py basicaly ''' script_loc = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../helper_scripts/parse_stb.py') out_loc = self.wd_loc + '/test.stb' cmd = "{0} --reverse -f {1} -o {2}".format(script_loc, ' '.join(self.genomes), out_loc) ...
Python
1
SSStyleDeclaration, _param_spec: glib::ffi::gpointer, f: glib::ffi::gpointer, ) where P: IsA<DOMCSSStyleDeclaration>, { let f: &F = &*(f as *const F); f(&DOMCSSStyleDeclaration::from_glib_borrow(this).unsafe_cast_ref()) } unsafe...
Rust
0
processing...") print(f"📊 Instruments: {len(instruments)}") print(f"⏰ Timeframes: {len(timeframes)}") print(f"🔍 Patterns: {len(patterns)}") exported_files = [] total_jobs = len(instruments) * len(timeframes) current_job = 0 for inst...
Python
1
# config.py import os # Kafka cluster configuration KAFKA_HOST = '<Hostname of your Kafka cluster>' KAFKA_SSL_PORT = '14863' # Only change this if you're using a different Kafka SSL port KAFKA_CERTS_PATH = 'certs' # Only change this if you're using a different certs path OPENAI_KEY = '<OPENAI API KEY>'
Python
1
gl_sys::GstGLSLStageClass, GLSLStageClass>) @extends gst::Object; match fn { get_type => || gst_gl_sys::gst_glsl_stage_get_type(), } } impl GLSLStage { pub fn new<P: IsA<GLContext>>(context: &P, type_: u32) -> GLSLStage { skip_assert_initialized!(); unsafe { from_glib_n...
Rust
0
tab['images'][i].replace('_ramp.png', '_raw.fits') ramp_file = tab['images'][i].replace('_ramp.png', '_ramp.dat') #sn_pop = mywfc3.inspect.check_background_SN(ramp_file=ramp_file, show=False) #pop_reads = np.asarray(np.unique(np.hstack((pop_reads, sn_pop))),dtype=int) #pop_reads = list...
Python
1
= " Player 1 starting position: 4 Player 2 starting position: 8 "; #[test] fn example_parse() { let actual = parse_input(EXAMPLE_INPUT.to_string()); let expected = [4, 8]; assert_eq!(actual, expected); } #[test] fn example_part1() { assert_eq!(p...
Rust
0
import scrapy import sqlite3 from scrapy.loader import ItemLoader from ..items import ScrapItem from w3lib.html import remove_tags from itemloaders.processors import TakeFirst, MapCompose from scrapy.exceptions import DropItem ##### spiders/scrapy_countries.py ##################################### class ScrapyCountri...
Python
1
=True).count()}") def import_wikipedia_summaries(self, topics, language='pt'): """Importa resumos da Wikipedia para tópicos específicos.""" import wikipediaapi wiki = wikipediaapi.Wikipedia(language) items = [] for topic in topics: try: page = w...
Python
1
height and a depth; depth here corresponds /// to the number of layers (the module documentation for [web_glitz::image] goes into more detail /// on layered image storage). A [Texture3D] defines a [TextureFormat] `F`: all image data stored in /// the texture is stored in this format. /// /// See [RenderingContext::crea...
Rust
0
from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QHBoxLayout, QLabel, QVBoxLayout, QRadioButton, QGroupBox # App app = QApplication([]) # Ventana principal: mainwin = QWidget() mainwin.resize(965, 476) mainwin.setWindowTitle("memory card") ##################################...
Python
1
metadata = { 'protocolName': 'Visby Test with Pooling p1000', 'author': 'Dipro <dipro@basisdx.org>, Chaz <chaz@opentrons.com>', 'source': 'Custom Protocol Request', 'apiLevel': '2.3' } def run(protocol): [mnt1000, poolVol, numVisbys, numPools] = get_values( # noqa: F821 'mnt1000', 'poolVol',...
Python
1
id, entries] line = f"{[int(node[0]), node[1], node[2]]}\n" f.write(line) print("R-tree written to file \"Rtree.txt\".\n") ############################################################# def main(): if len(sys.argv) != 3: print("Use: Assignment2_1.py <coords_file> <offsets_file...
Python
1
or3, pub normal: Vector3, pub local_x_axis: Vector3, pub radius_a: f32, pub radius_b: f32, } // NOTE do not flip the normal, it will mess up the rotation pub fn create_general_ring_instance_matrix(data: &GeneralRingInstanceMatrixInfo) -> Matrix4 { let local_y_axis: Vector3 = data.normal.cross(&data...
Rust
0
""" Configuration for Binance commission rates. This module contains settings for Binance commission rates with consideration for different VIP levels and payment options. """ # Standard fee rate for Binance VIP 0 (0.1%) standard_fee_rate = 0.001 # Discounted fee rate if using BNB for fees (25% discount, 0.075%) bnb...
Python
1
#!/usr/bin/env python3 """ LAB04 - System Monitoring Scripts with Python This script collects and displays real-time system metrics using the psutil library. It provides an overview of CPU, memory, disk, and network usage. Usage: python monitor.py """ # TODO: Import the necessary libraries # You'll need psutil f...
Python
1
rate) struct DeployGetter { #[data_size(skip)] effect_builder: Arc<CommonEffectBuilder>, #[cfg(test)] deploys: Arc<HashMap<DeployHash, Deploy>>, } impl DeployGetter { pub(crate) fn new(joiner_effect_builder: EffectBuilder<JoinerReactorEvent>) -> Self { let effect_builder = CommonEffectBuild...
Rust
0
datetime.moment, grain: datetime.grain.into(), precision: datetime.precision.into(), }), Output::DatetimeInterval(datetime_interval) => match datetime_interval.interval_kind { DatetimeIntervalKind::After(datetime) => { SlotValu...
Rust
0
if upper_start < length && upper_end <= length { // Range fits into the upper part OneOfThree::Second(upper_start..upper_end) } else { let lower_start = upper_start % length; let lower_end = upper_end % length; if lower_start < head && lower_end <= he...
Rust
0
ettawatt_per_square_meter: prefix!(zetta); "ZW/m²", "zettawatt per square meter", "zettawatts per square meter"; @exawatt_per_square_meter: prefix!(exa); "EW/m²", "exawatt per square meter", "exawatts per square meter"; @petawatt_per_square_meter: prefix!(peta); "PW/m²", ...
Rust
0
Default: None. training_config (BaseTrainerConfig): the training config to use if the sampler needs to be trained (e.g. flow based samplers). Default: None. callbacks (List[~pythae.trainers.training_callbacks.TrainingCallbacks]): A list of callbacks to u...
Python
1
'm>( &'m mut self, handle: Self::SocketHandle, buf: &'m mut [u8], ) -> Self::ReadFuture<'m>; type CloseFuture<'m>: Future<Output = Result<(), TcpError>> where Self: 'm; fn close<'m>(&'m mut self, handle: Self::SocketHandle) -> Self::CloseFuture<'m>; } use crate::format::...
Rust
0
# Copyright 2021 Tencent # SPDX-License-Identifier: BSD-3-Clause import torch import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self): super(Model, self).__init__() def forward(self, x, y, z, w): x = x * 2 - 1 y = y * 2 - 1 z = z * 2 - ...
Python
1
Self::Spi2Tx => 0b001, // Self::Spi3Rx => 14, // Self::Spi3Tx => 15, Self::I2c1Rx => 0b011, Self::I2c1Tx => 0b011, Self::I2c2Rx => 0b011, Self::I2c2Tx => 0b011, Self::I2c3Rx => 0b011, // Self::I2c3Tx => 21, ...
Rust
0
pt específico **variables: Variáveis para substituição no template Returns: Prompt formatado pronto para uso """ role_key = agent_role.value if role_key not in self.prompts: raise ValueError(f"Agente '{role_key}' não encontrado no...
Python
1
8FA976104B8BA8C6F85DCF9E4"] } "#; let v = serde_json::from_str::<ContractCall>(s).unwrap(); println!("{:?}", v); } fn assert_that_version_control_has_no_unstaged_changes() { let output = Command::new("git") .arg("status") .arg("--porcelain") .output() .unwrap(...
Rust
0
# Generated by Django 2.2.7 on 2019-11-28 13:10 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Aluno', fields=[ ...
Python
1
(|item| !matches!(item.unnamed(), UnnamedItem::Predicated(..))) .collect_vec(); assert_eq!(items.len(), fields.len()); let mut dt = TokenStream::new(); for (name, item) in zip(fields, items) { dt.extend(detokeniz...
Rust
0
# # Copyright (c) 2023 Airbyte, Inc., all rights reserved. # from .source import SourceWaiteraid __all__ = ["SourceWaiteraid"]
Python
1
# 25825 - [Job Advancement] Agent of Justige (AB 2nd job adv) ESKALADE_NPC_ID = 3000018 if chr.getLevel() >= 30 and chr.getJob() == 6500: sm.setSpeakerID(ESKALADE_NPC_ID) sm.sendNext("Looking pretty tough there, #h #.") else: sm.dispose() sm.setSpeakerID(ESKALADE_NPC_ID) sm.setPlayerAsSpeaker() sm.sendNe...
Python
1
Loop1, (false, true) => Loop::Loop2, (false, false) => Loop::Off, } } } } fn to_bytes(&self) -> Vec<u8> { let mut result: Vec<u8> = Vec::new(); result.extend(self.attack.to_bytes()); // When emitting decay1 an...
Rust
0
Self::new_unchecked(value) } } } impl Niche for std::num::NonZeroUsize { type Output = usize; #[inline] fn none() -> Self::Output { 0 } #[inline] fn is_none(value: &Self::Output) -> bool { *value == 0 } #[inline] fn into_some(value: Self) -> Self::Output { ...
Rust
0
import pytest from apps.banking.models import Currency pytestmark = [pytest.mark.django_db] @pytest.fixture(autouse=True) def course(factory): return factory.course(slug="ruloning-oboev", price=1900) @pytest.fixture def default_user_data(): return { "name": "Забой Шахтёров", "email": "zabo...
Python
1
n_file, 'r') as f: try: processed_scenes = json.load(f) except json.JSONDecodeError: processed_scenes = [] else: processed_scenes = [] # Append new scene if not already present if scene_dir not in pr...
Python
1
(new_dst) except OSError: pass raise os.rename(new_dst, dst) elif link_errno != 0: # Either link isn't supported, or the filesystem doesn't support # linking, or 'src' and 'dst' are on different filesystems. shutil.copy(src, dst) def ensure_d...
Python
1
] macro_rules! handle_option { [$value:expr => $handler:block] => { match $value { Some(some_value) => some_value, None => $handler } } } <filename>src/clash/flying.rs use specs::prelude::*; use super::*; use crate::atlas::prelude::*; pub fn flying_event(ecs: &mut World...
Rust
0
ig_policy_name @pytest.mark.slow def test_new_policy(get_module): a = np.arange(10) orig_policy_name = np.core.multiarray.get_handler_name(a) orig_policy = get_module.set_secret_data_policy() b = np.arange(10) assert np.core.multiarray.get_handler_name(b) == 'secret_data_allocator' # test a...
Python
1
""" 13. Faça um programa que peça dois números, base e expoente, calcule e mostre o primeiro número elevado ao segundo número. Não utilize a função de potência da linguagem. """ num_base = float(input("Digite a base: ")) num_expoente = int(input("Digite o expoente: ")) resultado = 1.0 for i in range(num_expoente):...
Python
1
an interface or an enumeration PossibleType { #[serde(rename = "type")] typ: &'a FullType, }, } //! Helpers to program the task state segment. //! See Intel 3a, Chapter 7, Section 7 /// In 64-bit mode the TSS holds information that is not /// directly related to the task-switch mechanism, /// ...
Rust
0
action(Box, [13], "Ext_no_face") geompy.MakeExtraction(Box, [18], "Ext_no_edge") geompy.MakeExtraction(Box, [16], "Ext_no_vertex") # CurvatureOnFace Cylinder_1 = geompy.MakeCylinderRH(100, 50, 'Cylinder_r100_h150') [Face_1,Face_2,Face_3] = geompy.ExtractShapes(Cylinder_1, geompy.ShapeType["FACE"], True, "Fac...
Python
1
import pygame import pandas as pd from tela import Tela from telafinal import TelaFinal telafinal = TelaFinal() class TelaVencedor(Tela): def __init__(self) -> None: super().__init__() def produzirTela(self) -> None: self.screen.fill(self.gray) # Função para salvar o nome do jogador ...
Python
1
train_3, 'visStrain_3') printTensor(visStrainRate_3, 'visStrain_3_t') out.write('\nAuxiliary variables (perturbed solution):\n') printTensor(strainPert, 'totalStrainPert') printTensor(strainRatePert, 'totalStrainPert_t') printTensor(visStrain_1Pert, 'visStrainPert_1') printTensor(visStrainRate_1Pert, 'visStrainPert_1_...
Python
1
j > 0 { print!(", "); } print!("{}^{}", sizes[j], k - j); j = k; } println!("]"); } // ============================================================================= // Return total read support, intended as a sort of checksum. // ====...
Rust
0
import os from speechbrain.dataio.dataio import read_audio from speechbrain.utils.logger import get_logger try: import pandas as pd except ImportError: err_msg = ( "The optional dependency pandas must be installed to run this recipe.\n" ) err_msg += "Install using `pip install pandas`.\n" ...
Python
1
fn scan_unknown() { let source = "{"; match scan_text(source, true) { Ok(tokens) => assert!(false), Err(err) => match err { ScanErr { kind: ScanErrKind::UnexpectedCharacter(c), location } => { assert_eq!(c, '{'); assert_eq!(location.line, 1); ...
Rust
0
=> 83, ExdDescriptors::Icon => 84, ExdDescriptors::CompassHeading => 85, ExdDescriptors::GpsHeading => 86, ExdDescriptors::GpsElevation => 87, ExdDescriptors::AnaerobicTrainingEffect => 88, ExdDescriptors::Course => 89, ExdDescriptors:...
Rust
0
.VISUAL, (3, 2), 'Reverse find a'), test_data('0bxx45', (4, 1), 'x', unittest.VISUAL, (4, 2), 'Reverse find a'), test_data('0xax45', (3, 1), 'x', unittest.VISUAL, (2, 4), 'Reverse find b'), ) class VisualMultipleLine(F, unittest.ViewTestCase): cases = ( test_data('012\n456', (0, 5), '2...
Python
1
logger .info (f'奖品:')#line:101 for OO00OOO0000OOOO0O in O00OO0O0O00O0OO0O .get ('data').get ('rewards'):#line:102 if OO00OOO0000OOOO0O ['rewardStock']>1 :#line:103 if OO00OOO0000OOOO0O ["inviteNum"]>OOOO0OO0O00O000OO .successCount :#line:104 ...
Python
1
(sqrt(abs((b)/(a)))))))if((sqrt(((abs(sqrt(a)))**(sqrt((a)**(a))))**((((b)+(b))**(sqrt(b)))*(((a)**(b))*(sqrt(a))))))>=((((square((b)+(a)))**(((b)*(a))+(sqrt(a))))/(square(sqrt(square(a)))))**((sqrt(sqrt((b)/(a))))*((((b)-(a))-(square(b)))-((sqrt(b))+((a)*(b)))))))else(((abs((((a)**(b))if((a)<=(a))else((b)*(a)))+(((b)*...
Python
1
ved {str(size)} bytes from target port {str(rport)} - loop {str(loop)}" ) print( f"{self.c.WHITE} [-] SSRC: {ssrc} - Timestamp: {timestamp} - Seq number: {seq}" ) ...
Python
1
# Generated by Django 5.2.5 on 2025-09-25 09:38 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('zip_app', '0001_initial'), ] operations = [ migrations.CreateModel( name='Orders', fields=[ ('field_...
Python
1
""" Евгения создала класс KgToPounds с параметром kg, куда передается определенное количество килограмм, а с помощью метода to_pounds() они переводятся в фунты. Чтобы закрыть доступ к переменной kg она реализовала методы set_kg() - для задания нового значения килограммов, get_kg() - для вывода текущего значения кг. Из-...
Python
1
import cmdstanpy import numpy as np import pandas from scipy import stats from scipy.stats import norm from scipy import integrate import arviz as az import logging from cmdstanpy.utils import get_logger get_logger().setLevel(logging.ERROR) import warnings warnings.filterwarnings('ignore') np.random.seed(123) model = ...
Python
1
#!/usr/bin/env python # coding=utf-8 #================================================================ # Copyright (C) 2019 Fisher. All rights reserved. # # 文件名称:user_based.py # 创 建 者:YuLianghua # 创建日期:2019年12月16日 # 描 述: # #================================================================ import math im...
Python
1
rned /// into a web app by using `constriction` in a WebAssembly module). /// /// ## Quick Start /// /// ### Installing `constriction` for Python /// /// ```bash /// pip install constriction~=0.2.1 /// ``` /// /// ### Hello, World /// /// You'll mostly use the `stream` submodule, which provides stream codes (like Range...
Rust
0
type Item = Result<Find>; fn next(&mut self) -> Option<Self::Item> { if self.next_address > ADDRESS_MAX { return None; } let address = self.next_address; let item = status(self.serial, address).map(|s| Find { address, status: s }); self.next_address += 1; ...
Rust
0
import math m , n = [int (x) for x in input().split()] s = 0.0 for i in range(m , n + 1, 1): s += pow(i, 2) s += 1/i print("sum = %.6f" % s)
Python
1
er="o" ) # Plots agent images. if image is not None: transform_data = ( Affine2D().rotate_deg_around(*(_xii, _yii), _pii / np.pi * 180) + plt.gca().transData ) plt.imshow( image, transform=transform_data, interpolation="none", origin="lower", extent=[...
Python
1
_acctount_info(&self) -> Result<(Vec<Wallet>)> { let payload: String = format!("{}", "{}"); let data = self.client.post_signed("account_infos".into(), payload)?; println!("data: {:?}", data); let wallets: Vec<Wallet> = from_str(data.as_str())?; Ok(wallets) } pub fn get_...
Rust
0
)(obj_data); ret_val } } pub fn build(&self) -> Self { self.clone() } } pub trait DragMoveEventTrait<'a> { #[inline] #[doc(hidden)] fn get_drag_move_event_obj_funcs(&self) -> (*const RUBase, *const RUDragMoveEventFuncs); } impl<'a> EventTrait<'a> for DragMoveEvent<'...
Rust
0
// If we didn't validate the .unpack file, ensure that we clean up anything // that might be leftover from a failed unpack if unpack_dir.exists() { std::fs::remove_dir_all(&unpack_dir) .with_context(|| format!("unable to remove invalid unpack dir '{}'", unpack_dir))?; ...
Rust
0
sh_str(&format!( "{} {} is {:.2} {}\n", value, unit, converted_value, converted_unit )); } } response } pub fn respond_to_msg(msg: &str) -> Option<String> { parse_input(msg).map(|units| assemble_response(&units)) } #[cfg(test)] mod tests { use super::*; use float_cmp::{approx_eq, F64Margin}; #[tes...
Rust
0
se { #ord } } } }, ) } #[test] fn variants_partly_empty() -> Result<()> { #[cfg(feature = "nightly")] let discriminant = quote! { let __self_disc = ::core::intrinsics::discriminant_value(self); let __other_disc = ::core::intrinsics::discriminant_value(__other); }; #[cfg(not(feature = "nigh...
Rust
0
{:x?}", read); loop {} } use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use crate::{NatureError, Result}; #[inline] pub fn generate_id<T: Hash>(value: &T) -> Result<u64> { let mut s = DefaultHasher::new(); value.hash(&mut s); Ok(s.finish()) } #[inline] pub fn id_from_...
Rust
0
LICENSE for details. // SPDX-License-Identifier: Apache-2.0 //! Implementations of [`crypto::sha256`] based on `ring`. use core::convert::Infallible; use ring::digest; use crate::crypto::sha256; #[cfg(doc)] use crate::crypto; /// A `ring`-based [`sha256::Builder`]. pub struct Builder { _priv: (), } impl Bui...
Rust
0
256 => ::std::option::Option::Some(EProtoAppType::k_EAppTypeConfig), 512 => ::std::option::Option::Some(EProtoAppType::k_EAppTypeHardware), 1024 => ::std::option::Option::Some(EProtoAppType::k_EAppTypeFranchise), 2048 => ::std::option::Option::Some(EProtoAppType::k_EAppT...
Rust
0
impl Clone for Rander { fn clone(&self) -> Rander { Rander::with_seed(self.gen_u64()) } } impl Rander { #[inline] fn gen_u32(&self) -> u32 { let s = self.0.get(); self.0.set( s.wrapping_mul(6364136223846793005) .wrapping_add(1442695040888963407), ...
Rust
0
import torch import torch.nn as nn import torch.nn.functional as F from collections import defaultdict def dice_loss(input_mask, cls_gt): num_objects = input_mask.shape[1] losses = [] for i in range(num_objects): mask = input_mask[:,i].flatten(start_dim=1) # background not in mask, so we ...
Python
1
elf, node: LogicalPlanNode) -> Set[str]: """ Collect and return the set of column identities from the given node. Args: node: The node from which to collect column identities. Returns: A set of column identities. """ identities = set() fo...
Python
1
me: aliases.get(p).unwrap().to_string(), }), ); }); participants }; // Construct the layout let mut layout = layout::Layout::new(); for participant in ordered_participants { layout.add_participant(participants.get(participant).unwrap().clone()); }...
Rust
0
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS // BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. use super::*; use libc::{c_int, c_void}; #[repr(...
Rust
0
import gradio as gr from PIL import Image import torch from utils.image_utils import preprocess_image from utils.model_definitions import RTX3060OptimizedModel from utils.knowledge_loader import get_knowledge_entry # --- 模型和常量定义 --- MODEL_PATH = 'pests/models/best_pest_model.pth' NUM_CLASSES = 3 CLASS_NAMES = ['玉米粘虫'...
Python
1
ductions' in d: o.user_introductions = d['user_introductions'] if 'valid_days_range_from' in d: o.valid_days_range_from = d['valid_days_range_from'] if 'valid_days_range_to' in d: o.valid_days_range_to = d['valid_days_range_to'] if 'valid_time_range_from' in d...
Python
1
data['tracker_ids'][t] = tracker_id_map[data['tracker_ids'][t]].astype(np.int) # Record overview statistics. data['num_tracker_dets'] = num_tracker_dets data['num_gt_dets'] = num_gt_dets data['num_tracker_ids'] = raw_data['num_tracker_ids'] data['num_gt_ids'] = raw_da...
Python
1
lf): return 'foo' class FigureManagerTemplate(FigureManagerBase): """ Wrap everything up into a window for the pylab interface For non interactive backends, the base class does all the work """ pass ######################################################################## # # Now just pro...
Python
1
use_real (bool, optional): If True, return real part and imaginary part separately. Otherwise, return complex numbers. theta_rescale_factor (float, optional): Rescale factor for theta. Defaults to 1.0. Returns: freqs_cis: Precomputed frequency tensor with com...
Python
1
""" Authors: Shubham Ugare. Copyright: Copyright (c) 2020 Microsoft Research Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, c...
Python
1
y_pred.append(0) else: error += 1 print(r['resp']) continue if r['ground_truth'] == '1': y_test.append(1) else: y_test.a...
Python
1
else None, "cv_folds_for_gs_group": CV_FOLDS_FOR_GRIDSEARCH_INTERNAL if USE_GRID_SEARCH_OPTIMIZATION else 0, "fixed_params_for_group": FIXED_CLASSIFIER_PARAMS_CONFIG if not USE_GRID_SEARCH_OPTIMIZATION else None, "loading_conditions_config": None, "cluster_threshold_config_intra_fold_gro...
Python
1
0: f32, marker_size1: f32, ) { data.push(marker_x0); data.push(marker_y0); data.push(marker_x1); data.push(marker_y1); data.push((marker_size0 / 2.0) as f32); data.push((marker_size1 / 2.0) as f32); data.push(a0 as f32); data.push(a1 as f32); data.push((current.stroke_color.r / 2...
Rust
0
def extract_rgba_from_viz(viz_color): if "a" in viz_color: return "rgba(%s, %s, %s, %s)" % ( viz_color["r"], viz_color["g"], viz_color["b"], viz_color["a"], ) return "rgba(%s, %s, %s)" % ( viz_color["r"], viz_color["g"], vi...
Python
1
1) print("End: make distance features") data['target'] = data['price'] * 1000 / data['landSize'] data['population'] = np.log(data['population']) data['density'] = np.log(data['density']) data['acreage'] = np.log(data['acreage']) print("Start: make nearest features") nearest_list = [] ...
Python
1
from __future__ import annotations from pathlib import Path import time filedir = Path(__file__).parent.resolve() VERIFICATION = filedir.joinpath("inputs/verification.txt") INPUT = filedir.joinpath("inputs/input.txt") # linked-list approach to maintain order class Stone: number: int next: Stone def __in...
Python
1