text
string
label_name
string
labels
int64
parser } pub(crate) fn qemu_internal_line_parser<I>() -> impl Parser<Input = I, Output = ()> where I: Stream<Item = char>, I::Error: ParseError<I::Item, I::Range, I::Position>, { let parser = skip_until(newline()).skip(newline()); parser } #[cfg(test)] mod test { use super::*; #[test] f...
Rust
0
#[serde(rename_all = "kebab-case")] pub struct RustBuildMetaSummary { /// The target directory for Rust artifacts. pub target_directory: Utf8PathBuf, /// Base output directories, relative to the target directory. pub base_output_directories: BTreeSet<Utf8PathBuf>, /// Linked paths, relative to th...
Rust
0
2_bindings::BOOL_VEC2 | gles2_bindings::FLOAT_VEC2 => 8, gles2_bindings::INT_VEC3 | gles2_bindings::BOOL_VEC3 | gles2_bindings::FLOAT_VEC3 | gles2_bindings::INT_VEC4 | gles2_bindings::BOOL_VEC4 | gles2_bindings::FLOAT_VEC4 => 16, gles2_bindings::FLOAT_MAT2 => 32, ...
Rust
0
# Animation du chemin trouvé for case in chemin: fenetre.blit(image_fond, (0, 0)) pygame.draw.rect(fenetre, NOIR, (MARGE_X, MARGE_Y, LARGEUR, HAUTEUR)) for ligne in copie_grille_jeu: for case_grille in ligne: case...
Python
1
= Path::new("res").join("fixtures").join(filename); println!("loading fixture from {:?}", fixture); let mut file = File::open(fixture).expect("error opening fixture file!"); let mut contents = vec![]; file.read_to_end(&mut contents).expect("error reading fixture file!"); contents } use crate::stora...
Rust
0
import matplotlib.pyplot as plt import pandas as pd # Data for the first plot data1 = { "Local epoch": list(range(1, 13)), "Average S1(f)": [0.012132, 0.01213, 0.0121, 0.01209,0.012084, 0.012066, 0.012062, 0.01206, 0.012058, 0.012056, 0.012052, 0.012012], "Average S2(f)": [0.011642, 0.01162,0.011602, 0.011...
Python
1
# -*- coding: utf-8 -*- # # test_parameter_apply.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the Li...
Python
1
from aiogram import types from utils.admin_utils import is_admin from services.channel_service import ChannelService from .listing import list_channels async def toggle_channel(callback: types.CallbackQuery): """Переключение статуса канала (включен/выключен)""" if not is_admin(callback.from_user.id): a...
Python
1
int; pub type u8_0 = libc::c_uchar; static mut sigma: [libc::c_char; 16] = [101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]; static mut tau: [libc::c_char; 16] = [101, 120, 112, 97, 110, 100, 32, 49, 54, 45, 98, 121, 116, 101, 32, 107]; pub unsafe extern "C" fn chacha_keysetup(mut x: *...
Rust
0
from matplotlib import pyplot as plt import numpy as np import shap from lib.models.base import BaseClassifier from lib.path import ModelAnalysisPath def analyze_shap_summary(shap_values, X, path: ModelAnalysisPath): output = path.get_path(f"shap_summary.png") print(f"SHAP summary plot saved to {output}") ...
Python
1
""" 游戏引擎模块,负责处理游戏逻辑 """ import json import random import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from config.llm_config import SYSTEM_PROMPTS, AGE_STAGES, BACKGROUND_TYPES, ATTRIBUTE_NAMES from server.llm_client import LLMClient class GameEngine: """ 游戏引擎类,完...
Python
1
ceipts(header) } fn is_known_block(hash: bp_eth_poa::H256) -> bool { BridgeRialtoPoA::is_known_block(hash) } } impl bp_eth_poa::KovanHeaderApi<Block> for Runtime { fn best_block() -> (u64, bp_eth_poa::H256) { let best_block = BridgeKovan::best_block(); (best_block.number, best_block.hash) } fn...
Rust
0
from typing import List """ TIME: 139ms (Beats 74.86%) MEMORY: 18.14MB (Beats 69.14%) NOTE: This legit took me less than 10 minutes. I am telling you, I am just goated 🐐. """ class Solution: def numSimilarGroups(self, strs: List[str]) -> int: n = len(strs) parent = list(range(n)) rank =...
Python
1
# ===================================================================== # EJERCICIO 77: Clase Alumno # --------------------------------------------------------------------- # Crear la clase Alumno co los atributos: # • __nombre # • __nota # El constructor inicializa ambos valores por parametro. # Metodos: # • aprobado:...
Python
1
f, &mut output_offset); *input_buf_ptr = (*input_buf_ptr).offset(input_offset as isize); *output_buf_ptr = (*output_buf_ptr).offset(output_offset as isize); *available_in -= input_offset; *available_out -= output_offset; *state = BroccoliState::from(bro_catli); ret } #[no_mangle] pub unsafe extern fn Brocc...
Rust
0
s.insert((Position { x: 4.0, y: 5.0 },)); for (_, (mut velocity,)) in ecs.query::<(W<Velocity>,)>() { velocity.x = 0.0; } for (_, (position, velocity)) in ecs.query::<(R<Position>, R<Velocity>)>() { assert_ne!(position.x, 0.0); assert_ne!(position.y, 0.0); ...
Rust
0
#!/usr/bin/env python3 import numpy as np import matplotlib matplotlib.use("Agg") from matplotlib import pyplot as plt matplotlib.style.use("../../../tools/stylesheets/mnras.mplstyle") # read in file evals = np.loadtxt("eigenvals.txt") n_points = int(np.sqrt(evals.shape[0]) + 0.5) evals = evals.reshape((n_points,...
Python
1
# /bin/python import os import numpy as np from fedn.utils.helpers.helpers import get_helper HELPER_MODULE = "numpyhelper" ARRAY_SIZE_FACTOR = float(os.environ.get("FEDN_ARRAY_SIZE_FACTOR", 1)) # 144 MB * ARRAY_SIZE_FACTOR ARRAY_SIZE = int(20000000 * ARRAY_SIZE_FACTOR) def save_model(weights, out_path): """Sa...
Python
1
import unittest from borb.pdf import PDF, SmartArt from borb.pdf.document import Document from borb.pdf.page import Page from borb.pdf.page_layout.page_layout import PageLayout from borb.pdf.page_layout.single_column_layout import SingleColumnLayout class TestHorizontalEquation(unittest.TestCase): def test_hori...
Python
1
import ctypes from ctypes import ( c_int, c_uint, c_longlong, c_ushort, c_byte, c_char, c_char_p, c_double, c_void_p, POINTER, Structure, byref, ) from enum import Enum import ctypes.util import os import sys import platform def load_libidh(): # 当前包目录 lib_dir = ...
Python
1
# Modified version of # Configuration/StandardSequences/python/SimIdeal_cff.py import FWCore.ParameterSet.Config as cms # CMSSW/Geant4 interface from SimG4Core.Configuration.SimG4Core_cff import * # rename g4SimHits so we can reuse the module label for neutron simhits collection g4SimHitsNeutrons = g4SimHits.clone()...
Python
1
ExtendedPoliciesMessage, KerbQueryS4U2ProxyCacheMessage, }} pub type PKERB_PROTOCOL_MESSAGE_TYPE = *mut KERB_PROTOCOL_MESSAGE_TYPE; STRUCT! {struct KERB_QUERY_TKT_CACHE_REQUEST { MessageType: KERB_PROTOCOL_MESSAGE_TYPE, LogonId: LUID, }} pub type PKERB_QUERY_TKT_CACHE_REQUEST = *mut KERB_QUERY_TKT_CACHE_REQ...
Rust
0
Two {} impl From<One> for Two { fn from(_: One) -> Self { Two {} } } pub enum SimpleMachineCommand {} fn main() { // state enum exists with both states let _ = SimpleMachineState::One(One {}); let _ = SimpleMachineState::Two(Two {}); // Event enum exists let _ = SimpleMachineEvent...
Rust
0
img_gt, img_lq = augment([img_gt, img_lq], self.opt['use_hflip'], self.opt['use_rot']) # BGR to RGB, HWC to CHW, numpy to tensor img_gt, img_lq = img2tensor([img_gt, img_lq], bgr2rgb=True, float32=True) # normalize if self.mean is not None or self.std is not None: normaliz...
Python
1
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Sep 5 15:11:05 2024 @author: bioinfo """ # List # Lists are used to store multiple items in a single variable. # Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with ...
Python
1
from PyObjCTools.TestSupport import TestCase, min_os_level import objc import Network nw_ethernet_channel_state_changed_handler_t = b"v@@" nw_ethernet_channel_receive_handler_t = b"v@" + objc._C_USHT + b"n[6t]n[6t]" nw_ethernet_channel_send_completion_t = b"v@" class TestEtherChannel(TestCase): def test_constan...
Python
1
# Generated by Django 3.0 on 2022-10-17 20:17 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Test', fields=[ ('id', models.AutoField(auto_...
Python
1
ags if tag not in unwanted_tags] updated_tags += new_tags if updated_tags != in_info_tags: del info["Tag"] for tag in updated_tags: info.add_header("Tag", tag) if definitely_not_purelib: info["Root-Is-Purelib"] = "False" logger.info("Changed wheel typ...
Python
1
" SHIFT = "shift" TRISECT = "trisect" TRISEGMENT = "trisegment" BETWEEN_BOUND = "between_bound" # Complete figure constructions ISO_TRIANGLE_VERTEX = "iso_triangle_vertex" ISO_TRIANGLE_VERTEX_ANGLE = "iso_triangle_vertex_angle" EQ_TRIANGLE = "eq_triangle" ISO_TRAPEZOID2 = "iso_trape...
Python
1
t() //! } //! }, //! _ => () //! } //! # Ok::<(), quiche::h3::Error>(()) //! ``` //! //! [`quiche`]: https://github.com/cloudflare/quiche/ //! [test]: struct.Http3Test.html //! [`Http3Test`]: struct.Http3Test.html //! [`Http3Assert`]: struct.Http3Assert.html //! [`Http3req`]: struct.Http3Req.html //! [`...
Rust
0
import argparse import sys import yt # hard-coded parameters (in code units) field = 'particle_mass' proj_axis = 'z' center = [0.5, 0.5, 0.5] width_x = 1.0e-2 width_y = 1.0e-2 width_z = 1.0e-2 colormap = 'arbre' dpi = 150 # load the command-line parameters parser = argparse.ArgumentParser( descr...
Python
1
이름이 여기서 설정되었습니다", _ => "The class was previously named here", } define_msg! { pub CannotNameUnknownClass<'a> { cls: Slot<'a> }: "ko" => "`{cls}` 타입이 하나의 클래스로 정해지지 않았기 때문에 이름을 설정할 수 없습니다", _ => "The type `{cls}` cannot be resolved to a single class so cannot be named", } define_msg! { pub NoCtor: ...
Rust
0
clientID"; let private_key = "<KEY>; assert_eq!( "chaRF2hTJKOScPr-RQCEhZbSzIE=", sign_url(path_and_query, private_key).unwrap() ); } #[test] fn test_build_normal_url() { let query = Query { id: "1".to_string(), origin: Coord::n...
Rust
0
def SessionExpireTime(self): return self._SessionExpireTime @SessionExpireTime.setter def SessionExpireTime(self, SessionExpireTime): self._SessionExpireTime = SessionExpireTime @property def HealthCheck(self): return self._HealthCheck @HealthCheck.setter def Healt...
Python
1
PrimitiveTypeInfo::Empty), Lang::Select([consequent, alternative, _]) => { // Get from operands let consequenttpe = eg[*consequent] .data .clone() .expect("Missing operand type") .tpe; ...
Rust
0
str = "http://www.itunes.com/dtds/podcast-1.0.dtd"; fn parse_image(map: &mut HashMap<String, Vec<Extension>>) -> Option<String> { let mut element = match map.remove("image").map(|mut v| v.remove(0)) { Some(element) => element, None => return None, }; element.attrs.remove("href") } fn par...
Rust
0
LOCK_REG_SPEC>`"] pub type SPINLOCK_LOCK_REG = crate::Reg<spinlock_lock_reg::SPINLOCK_LOCK_REG_SPEC>; #[doc = "Spinlock Register"] pub mod spinlock_lock_reg; use crate::error::Result; use crate::podman_service::PodmanService; use crate::system::parameter_types::{EventsParameter, EventsParameterStreamingQuery}; use crat...
Rust
0
e A - Italy": "soccer_italy_serie_a", "J League": "soccer_japan_j_league", "K League 1": "soccer_korea_kleague1", "League of Ireland": "soccer_league_of_ireland", "Liga MX": "soccer_mexico_ligamx", "Dutch Eredivisie": "soccer_netherlands_eredivisie", "Eliteserien - Norway...
Python
1
fruit="orange" for j in fruit: print(j)
Python
1
et[j1][indexB] = partBs[i] subset[j1][-1] += 1 subset[j1][-2] += candidate[partBs[i].astype(int), 2] + connection_all[k][i][2] # if find no partA in the subset, create a new subset elif not found and k < 17: row = -1 * ...
Python
1
import re from django.contrib.admin.templatetags.admin_list import ( result_headers, result_hidden_fields, results ) from django.template import Library EXTRACT_URL = re.compile(r'href="(.*?)"') register = Library() @register.inclusion_tag("admin/documents/document/change_list_results.html") def resul...
Python
1
} } mod errors { error_chain! { types { Error, ErrorKind, ChainErr, Result; } links { ::konane::errors::Error, ::konane::errors::ErrorKind, Game; } foreign_links { ::clap::Error, Clap, "clap error"; ::uuid::ParseError, UUIDParse, "UUID parse error"; ::std::io::Err...
Rust
0
# *-* coding: utf-8 *-* import logging from importlib_metadata import entry_points from dialog.settings import Settings from fastapi import FastAPI from fastapi.staticfiles import StaticFiles from fastapi.middleware.cors import CORSMiddleware from dialog.routers import api_router, open_ai_api_router, add_model_router...
Python
1
k layer, ex. conv layer), one layer may contain more than one residual block Args: block: block type, basic block or bottle neck block out_channels: output depth channel number of this layer num_blocks: how many blocks per layer stride: the stride of the ...
Python
1
(true)) .arg(Arg::with_name("true_char") .short("t") .long("true_char") .takes_value(true) .help("the true character displayed. be extra spooky")) .arg(Arg::with_name("false_char") .short("f") .long("fa...
Rust
0
# Copyright (c) 2021 PaddlePaddle Authors. 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 required by app...
Python
1
# -*- coding: utf-8 -*- # author: timor from notices.serializers import * from common.views import ModelViewSet, JsonResponse from common import status from collections import OrderedDict from rest_framework.decorators import action class NoticeViewSet(ModelViewSet): queryset = MailBot.objects.all() serializ...
Python
1
ctions = parse_actions(gt_domain) gt_actions = {k:{'params': self._preprocess([f"{p.symbol}" for p in v.parameters]), 'preconds':self._preprocess([x.strip() for x in str(v.precondition)[1:-1].split('and')]), 'effect':self._preprocess([str(x) for x in v.eff...
Python
1
Channels::new(in_channels, out_channels, source1); let source3 = PausableAudio::new(paused.clone(), out_channels, source2); mixer.add(source3); while mixer.is_playing() { sleep(Duration::from_millis(1000)); paused.set(!paused.get()); } } <filename>src/api/ieee488.rs use crate::format::{parse, into...
Rust
0
Lexeme::January, Lexeme::Num(1), Lexeme::Comma, Lexeme::Num(2010), Lexeme::Num(5), Lexeme::Colon, Lexeme::Num(0) ]), Lexeme::lex_line(input)); } #[test] fn test_unknown_token() { let input = "Hello World".to_string(); assert!(Lexeme::lex_line(input).is_err...
Rust
0
record = get_value::<SubnetListRecord>(&registry, make_subnet_list_record_key().as_bytes()) .await; assert_eq!(subnet_list_record, initial_subnet_list_record); Ok(()) }); } #[test] fn test_a_canister_other_than_the_proposals_canister_cannot_create_a_subnet() { local...
Rust
0
item) class StripeChargeMixin(object): """ Provides a property `stripe_charge` that returns a stripe charge instance. Your class must have an attribute `stripe_charge_id` (method or property) to provide the invoice id for the returned instance. """ def _get_stripe_charge(self): return...
Python
1
_translation_xyz(0.0, 0.0, 0.0); let sprite = SpriteRender::new(sprite_sheet.clone(), 0); world.push((transform, sprite, Transparent, Named("reference".into()))) } // Initialize a sprite as a reference point fn init_screen_reference_sprite(world: &mut World, sprite_sheet: &Handle<SpriteSheet>) -> Entity { ...
Rust
0
""" 모델 학습 및 추론에 유용한 여러 함수들을 정의 """ import pickle as pickle import torch import random import numpy as np def set_seed(seed:int = 42): torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) # if use multi-GPU torch.backends.cudnn.deterministic = True torch.backends.c...
Python
1
:from_str_radix(cols[0], 16).unwrap())); } return flag } pub fn lesbian() -> String { let mut flag: String = "\n".to_string(); let cols: Vec<&str> = vec!["A60061", "B95594", "D162A8", "E5ADD1", "C64D53", "8C1801"]; for col in cols { for _ in 0..3 { flag = forma...
Rust
0
move(pth+"/backgroundszip.zip") print("Downloading fonts.. (6.94MB)") fontz = requests.get("https://github.com/goglesquirmintontheiii/streamdeck-plus-software/raw/main/fonts.zip").content print("Saving fonts..") with open(pth+"/fontszip.zip", "wb") as f: f.write(fontz) print("Unzipping..") ...
Python
1
""" A wrapper that unrolls the second (time) dimension of a tensor into the first (batch) dimension, applies some other ``Module``, and then rolls the time dimension back up. """ import torch class TimeDistributed(torch.nn.Module): """ Given an input shaped like ``(batch_size, time_steps, [rest])`` and a ``M...
Python
1
().as_mut().unwrap().data as *mut std::ffi::c_void, std::mem::size_of::<T>() * slice.len(), std::mem::transmute::<&mut u64, *mut *const std::ffi::c_void>(owner), flags, std::mem::transmute::<extern fn(*mut T, &CopyData<T>), extern fn(*mut std::ffi::c_void, *mut std::ffi::...
Rust
0
ain # connect use domain if len(sys.argv) > 1: ip = sys.argv[1] else: ip = "46.134.208.94" ip = "2001:ee0:3203:a::12" print("Usage: check_ip.py [ip] [top_domain] [wait_time=0]") print("test ip:%s" % ip) if len(sys.argv) > 2: top_domain = sys.argv[2] e...
Python
1
0.9877535827147117, 0.9708627248497483, 0.9655170378370462, 0.9655170378370462, 0.9405186291064791, 0.9060295822713065, 0.8951147997010394, 0.8951147997010394, 0.8654018683927851, ...
Python
1
} mod get_thread_id { use super::*; #[tokio::test] #[cfg(feature = "general_test")] async fn ack_fails_with_incorrect_thread_id() { let _setup = SetupMocks::init(); let routing_keys: Vec<String> = vec!("verkey123".into());...
Rust
0
c fn does_pkg_exist(pkg_name: &str) -> Result<AurResponse, reqwest::Error> { let resp: AurResponse = reqwest::get(pkg_name) .await? .json::<AurResponse>() .await?; Ok(resp) } } use std::ops::Range; use syntect::{ highlighting::{ FontStyle, HighlightState, Highlig...
Rust
0
app.after(7000, versionLabel.destroy) except Exception as e : print(f'Error in update logic: {e}') if allowedUpdates == True: app.after(250, lambda: CheckForUpdates(current_ver)) buttonStart.configure(state="normal", command= startButton) buttonStartDodge.configure(state="normal", command=dodge...
Python
1
in the histogram fn buckets(&self) -> usize; } pub struct Config { min: usize, max: usize, precision: usize, window: Option<Duration>, } impl Config { pub fn new(min: usize, max: usize, precision: usize, window: Option<Duration>) -> Self { Self { min, max, ...
Rust
0
Criterion; extern crate curve25519_dalek; use curve25519_dalek::ristretto::CompressedRistretto; use curve25519_dalek::scalar::Scalar; extern crate merlin; use merlin::Transcript; extern crate rand; use rand::Rng; /* K-SHUFFLE GADGET SPECIFICATION: Represents a permutation of a list of `k` scalars `{x_i}` into a li...
Rust
0
cpu.step_n(50); assert_eq!(0xFF, cpu.registers.A); assert_eq!(true, cpu.flags.sign); } #[test] fn INTEGRATION_CPU_cmp_does_branch_on_accumulator_less_than_memory_bcc() { let asm = " LDA #$0F CMP #$FF BCC LESS LDA #$02 JMP END LESS: LDA #$01 END ...
Rust
0
e_to_missing_secret_key( &epoch3_nodes, dkg_id0, &env )); // Further DKGs can be run after removing an earlier key let config4 = RandomNiDkgConfig::reshare(transcript3, 1..=2, max_subnet_size); let (_transcript4, dkg_id4, epoch4_nodes) = r...
Rust
0
StreamResponseFail(Arc<ctx::http::Response>, StreamResponseFail), StreamResponseEnd(Arc<ctx::http::Response>, StreamResponseEnd), } #[derive(Clone, Debug)] pub struct TransportClose { /// Indicates that the transport was closed without error. // TODO include details. pub clean: bool, pub durat...
Rust
0
s = connections started = True started = False pe.tocsin.signal(pe.SIG_ENGINE_READY).listen(ready) engine = pe.PacketEngine() connections = pe.connect.Connections(engine) engine.receive_handler = self._make_receive_handler( connections.receive_handler) ...
Python
1
ow_size=window_size, shift=(i % 2 == 1), offset_range_factor=offset_range_factor, dw_ks=dw_ks, ) for i in range(align_depth)]) self.apply(init_weights) self.apply(init_deform_weights) def forward(self, q, kv, grid=None): """ ...
Python
1
TRY_FAILURE_SUM.load(Ordering::Relaxed), 0); stats.increment_publish_failed(1); assert_eq!(KAFKA_PUBLISH_SUCCESS_SUM.load(Ordering::Relaxed), 1); assert_eq!(KAFKA_PUBLISH_RETRY_SUM.load(Ordering::Relaxed), 1); assert_eq!(KAFKA_PUBLISH_FAILURE_SUM.load(Ordering::Relaxed), 1); ass...
Rust
0
d", 16).unwrap() ); let simple_map_write_with_part_struct_func_arg_key = functions .iter() .find(|v| v["name"].as_str().unwrap() == "simpleMapWriteWithPartStructFuncArgKey6") .unwrap() .as_object() .unwrap(); let simple_map_write_with_...
Rust
0
pub fn account_token_mint_burn_allowed(acc: &T::AccountId) -> bool { const ALLOWED_ROLES_MASK: u8 = INVESTOR_ROLE_MASK | ISSUER_ROLE_MASK; AccountRegistry::<T>::get(acc).roles & ALLOWED_ROLES_MASK != 0 } /// <pre> /// Method: balance_everusd(acc: &T::AccountId) -> EverUSDBalance //...
Rust
0
#! usr/bin/env python3 # -*- coding:utf-8 -*- """ @Author:Kaiyin Zhou """ import tensorflow as tf def top_k_logits(logits, k): if k == 0: return logits else: values, indices = tf.math.top_k(logits, k=k) min_values = tf.expand_dims(values[:, -1], -1) # 这个用法好,可以按元素判断并做修改 ...
Python
1
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
Python
1
Mode::Mixed) { let logger: Box<dyn SharedLogger> = term_logger; combined.push(logger); } CombinedLogger::init(combined).unwrap(); } LOGGER.get_or_init(move || _initializer(file_path.into())); } <filename>futures_examples/src/main.rs //! `main.rs` //!```no_run //!...
Rust
0
2d { self.ptr } pub(crate) unsafe fn as_raw_mut(&self) -> *mut futhark_i64_2d { self.ptr as *mut futhark_i64_2d } pub(crate) unsafe fn from_ptr<T>(ctx: T, ptr: *const futhark_i64_2d) -> Self where T: Into<*mut bindings::futhark_context>, { let ctx = ctx.into(); ...
Rust
0
### weight_manager.py ### """ This module manages weights assigned to security-related variables. Users can specify weights for each variable to calculate the security index. """ from rich.console import Console from rich.theme import Theme import geopandas as gpd import pandas as pd # Define the theme custom_theme = ...
Python
1
<T>>) -> T { let mut avg_loss = T::zero(); for (input, truth) in inputs.iter().zip(truths.iter()) { let pred = self.predict(input).unwrap(); avg_loss += self.loss.call(&pred, &truth).unwrap(); } avg_loss / T::from(inputs.len()).unwrap() } fn train_once(&mu...
Rust
0
</div> </div> <div class="form-actions"> <button type="submit" class="btn btn-primary"> 💾 保存配置 </button> <button typ...
Python
1
""" materialize.py Factory class defining functions for instantiating various Training Strategies, supporting different VLMs, backbones, and strategy configurations. """ from typing import Callable, Optional import torch from prismatic.models.vlms import PrismaticVLM from prismatic.training.strategies import FSDPSt...
Python
1
# -*- coding: utf-8 -*- # @Time : 2025-5-28 # @Author : 程序员NEO # @FileName: example.py # @Software: VSCode # @Email : it666@linux.do # @Github : https://github.com/BNTang # @Description: 18-Python-函数-闭包-小案例 """ 闭包的应用场景案例:根据不同配置信息生成不同的分割线函数 闭包的标准格式: 1. 外部函数接收参数 2. 内部函数使用外部函数的变量/参数 3. 外部函数返回内部函数 4. 内部函数及其引用的外部环...
Python
1
e ({}, {}) expected in re-serialized result", key, value ) } for (key, value) in looped.clone() { let original_val = original.get(&key); ...
Rust
0
--repetitions", "--non-words", "--escape", "--with-surrogates", TEST_CASE, ]); grex.assert().success().stdout(predicate::eq( "^I\\W{7}36\\Wand\\W\\u{663}\\Wand\\W(?:y\\u{306}){2}\\Wand\\W{4}$\n", )); ...
Rust
0
id(row=0, column=1, padx=5, pady=5) ttk.Button(buttons_frame, text="Export", command=export_info, style="TButton").grid(row=0, column=2, padx=5, pady=5) ttk.Button(buttons_frame, text="Contact dev", command=contact_dev, style="TButton").grid(row=0, column=3, padx=5, pady=5) # Output Text Box output_text = tk.Text(main...
Python
1
Str; #[test] fn build_and_install() { let temp_dir = tempfile::tempdir().expect("temporary directory"); let library = Build::new().out_dir(&temp_dir).build(); assert!(library.prefix().join("include/themis/themis.h").exists()); assert!(library.prefix().join("lib/pkgconfig/libthe...
Rust
0
nfo(f"脚本结束执行时间: {end_time}") logging.info(f"总执行时间: {end_time - start_time}") logging.info(f"成功处理的数据块: {successful_chunks}/{end_chunk - start_chunk + 1}") except Exception as e: logging.critical(f"脚本执行过程中发生未捕获的异常: {e}") import traceback logging.critical(traceback.format_e...
Python
1
mpl<'a, R: 'a + ParserSource> StartNode<'a, R> { /// Creates a new `StartNode`. pub(crate) fn new(parser: &'a mut Parser<R>) -> Self { Self { parser } } /// Returns the node name. pub fn name(&self) -> &str { self.parser.current_node_name() } /// Returns node attributes rea...
Rust
0
import gradio as gr from transformers import pipeline import numpy as np import sys model = sys.argv[1] transcriber = pipeline("automatic-speech-recognition", model=model) def transcribe(stream, new_chunk): sr, y = new_chunk y = y.astype(np.float32) y /= np.max(np.abs(y)) if stream is not None: ...
Python
1
); assert_eq!(tmp_buffer.len(), 0); decrypted_buffer.extend(&*decrypted); buffer = &decrypted_buffer[skip_start..]; original_buffer = &decrypted_buffer; } let (signature, buffer) = buffer.split_at(3); let version = match (signature[0], signature[1], signature[2]) { (...
Rust
0
and s[inp + 1] in hex_numbers: ch = chr(int(s[inp:inp+2], 16)) inp += 2 odata.append(ch) else: odata.append('=') elif header and s[inp] == '_': odata.append(' ') inp += 1 else: odata.append(s[...
Python
1
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class Expense(models.Model): _inherit = "hr.expense" sale_order_id = fields.Many2one('sale.order', compute='_compute_sale_order_id', store=True, string='Customer to Reinvoi...
Python
1
# Code generated by Lark OpenAPI. import lark_oapi as lark from lark_oapi.api.hire.v1 import * def main(): # 创建client client = lark.Client.builder() \ .app_id(lark.APP_ID) \ .app_secret(lark.APP_SECRET) \ .log_level(lark.LogLevel.DEBUG) \ .build() # 构造请求对象 request: Cr...
Python
1
import cv2 import os import json import sys import warnings import numpy as np import torch import traceback from diffusers import StableDiffusion3ControlNetPipeline from diffusers.models import SD3ControlNetModel from PIL import Image from tqdm import tqdm warnings.filterwarnings("ignore") def image_generation(promp...
Python
1
import numpy as np try: import mpmath except ImportError: pass def mpmath_wrightomega(x): return mpmath.lambertw(mpmath.exp(x), mpmath.mpf('-0.5')) def wrightomega_series_error(x): series = x desired = mpmath_wrightomega(x) return abs(series - desired) / desired def wrightomega_exp_error(...
Python
1
(stderr); set_errno(Errno(ENOENT)); perror(cstr!(std::env::current_exe().unwrap().to_str().unwrap())); } } <reponame>SpringQL/SpringQL<filename>springql-core/src/stream_engine/autonomous_executor/task/sink_task.rs // This file is part of https://github.com/SpringQL/SpringQL which is licensed under M...
Rust
0
est_phys_addr: region.start_addr().raw_value(), memory_size: region.len() as u64, // It's safe to unwrap because the guest address is valid. userspace_addr: guest_memory.get_host_address(region.start_addr()).unwrap() as u64, ...
Rust
0
# =============================================== # ✧ Simple Windows Keylogger in Python ✧ # =============================================== from pynput.keyboard import Key, Listener import ctypes import tkinter as tk from tkinter import messagebox SPECIAL_KEYS = { Key.space: " ", Key.enter: "[ENTER]", ...
Python
1
).err).msg_code = crate::cderror_h::JERR_PPM_OUTOFRANGE as libc::c_int; Some( (*(*cinfo).err) .error_exit .expect("non-null function pointer"), ) .expect("non-null function pointer")( cinfo as crate::jpeglib_h::j...
Rust
0
EL0, look in `thread`'s executable file and (when implemented) its swap file. // For EL1, we can use this opportunity to identity-map a new read-write page, which should reduce the size of the // kernel's page tables and speed up the boot process. MmuIss::FS_TRANSLATION_LEVEL_0 ...
Rust
0