text
string
label_name
string
labels
int64
from __future__ import annotations import pytest from pyupgrade._data import Settings from pyupgrade._main import _fix_plugins @pytest.mark.parametrize( ('s', 'expected'), ( pytest.param( 'import mock.mock\n' '\n' 'mock.mock.patch("func1")\n' 'mock.pat...
Python
1
ist): # 列表需要特殊处理,确保每个元素都可序列化 content_list = [] for item in result: if isinstance(item, dict): content_list.append(item) elif isinstance(item, str): content_list.append({"type": "text", "text": item}) ...
Python
1
CommandArgs) -> Result<OutputStream, ShellError> { let args = args.evaluate_once()?; let cmd_args = RangeArgs { range: args.req(0)?, }; let from = cmd_args.range.min_usize()?; let to = cmd_args.range.max_usize()?; if from > to { Ok(OutputStream::one(Value::nothing())) } el...
Rust
0
promedio_hidrica = calcular_promedio_generacion(potencia_hidrica,eventos_hidrica) # Visualizamos resultados print('\n*** Resultados Obtenidos ****') print(f'Potencia total generada: {potencia_generada:.2f}') print(f'Hidrica: Eventos: {eventos_hidrica}, potencia: {potencia_hidrica}, promedio {promedio_hidrica:.2f}') pr...
Python
1
} pub fn update_campaign(&mut self, campaign_id: CampaignId) { self.campaign_id = campaign_id; } } pub trait CreditInterface<AccountId, Balance> { fn get_credit_score(account_id: &AccountId) -> Option<u64>; fn pass_threshold(account_id: &AccountId) -> bool; fn slash_credit(account_id: ...
Rust
0
or interline spacing, is the logical amount of space to be reserved between the descent of one line of text and the ascent of the next line. # # \return The leading of the font. # def getLeading() -> float: pass ## # \brief # \param string # \return # def getWidth(string: s...
Python
1
List(lst) => { let list = lst.parse(&mut source)?; // Riff Lists can have many different forms, but WavReader only supports Info // lists. match &list.form { b"INFO" => metadata.push(read_info_chunk(&mut source, lis...
Rust
0
fault() { refund += (config.gas_sstore_set - config.gas_sload) as i64; } else { refund += (config.gas_sstore_reset - config.gas_sload) as i64; } } refund } } } else { if current != H256::default() && new == H256::default() { config.refund_sstore_clears } else { 0 } } } ...
Rust
0
from pqcrypto.sign.dilithium2 import generate_keypair, sign, verify # 1. Generate kunci publik & privat public_key, private_key = generate_keypair() # 2. Buat pesan untuk ditandatangani message = b"Transaksi Blockchain Quantum-Secure!" # 3. Tanda tangani pesan menggunakan Dilithium signature = sign(message, private_...
Python
1
import numpy as np import cv2 as cv # OpenCV Utility Class for Mouse Handling class Sketcher: def __init__(self, windowname, dests, colors_func): self.prev_pt = None self.windowname = windowname self.dests = dests self.colors_func = colors_func self.dirty = False sel...
Python
1
import sys #import time from typing import Optional import click from colorama import Fore, Style from fakes import GoStub, GoFake from base import GoBase from go import Go #print(sys.argv) #sidestr = sys.argv[1] #BOARDSIZE = int(sidestr) trygrid = [] #gotype = GoFake(BOARDSIZE,2, False) #players = 2 #for _ in range...
Python
1
et o = self.cmd.fetch_file(path); pb.finish_with_message(format!("Done: {}", &cmd_fmt)); o } } pub fn get_progress_bar(m: &MultiProgress) -> ProgressBar { let pb = m.add(ProgressBar::new(100)); pb.set_style( ProgressStyle::default_bar() .tick_strings(spinners::random())...
Rust
0
collapse_where_in(&mut q, true).unwrap(); assert_eq!(rewritten.0, 0); assert_eq!(rewritten.1.len(), 3); assert_eq!( q, nom_sql::parse_query("SELECT * FROM x WHERE AVG(y) = ?").unwrap() ); } #[test] fn noninterference() { let mut q = nom_sql::...
Rust
0
String::from("hello world")); /// ``` /// /// Downgrading from a mutable to an immutable reference: /// /// ``` /// # use sharded_slab::Pool; /// use std::{thread, sync::Arc}; /// /// let pool: Arc<Pool<String>> = Arc::new(Pool::new()); /// /// let mut value = pool.clone().create_owned().unwrap(); /// let key = value....
Rust
0
Value::number(2), Value::number(1), ] ) } } <gh_stars>0 /// Data necessary to print a progress report pub struct ProgressStatus { pub total_no: usize, pub processed_no: usize, } impl ProgressStatus { /// `more` hints how many elements are left to be processed aft...
Rust
0
# SPDX-FileCopyrightText: 2024 M5Stack Technology CO LTD # # SPDX-License-Identifier: MIT import os, sys, io import M5 from M5 import * from unit import * label0 = None label1 = None lorae220_0 = None lorae220_rssi = None lorae220_data = None def lorae220_0_receive_event(received_data, rssi): global label0, l...
Python
1
this directive once implemented. fn cache_override_v2_set( &mut self, req_handle: RequestHandle, tag: CacheOverrideTag, ttl: u32, stale_while_revalidate: u32, sk: &GuestPtr<[u8]>, ) -> Result<(), Error> { // For now, we ignore caching directives because w...
Rust
0
Uses the FRO HF at 48MHz. pub fn frohf_48mhz() -> Config { Config { xtal_freq: None, rtc_32k_present: None, mainclksela: MainClkSelA::fro_hf(FroHfOsc::Fro48Mhz), mainclkselb: MainClkSelB::mainclka, ahbclkdiv: AHBClkDiv::NotDivided, aud...
Rust
0
er as u64)); if matches!(self.stream.read(&mut local_header_buf), Ok(n) if n == local_header_buf.len()) { if let Some(local_header) = unsafe { LocalFileHeader::from_raw_ptr(&local_header_buf) } { file.file_data_offset = file_info.relative_offset_of...
Rust
0
("this fc weight is not for this model") def reset_parameters(self) -> None: for w_A in self.w_As: nn.init.kaiming_uniform_(w_A.weight, a=math.sqrt(5)) for w_B in self.w_Bs: nn.init.zeros_(w_B.weight) class LoRA_Depth_Anything_v2(LoRA): """Applies low-rank adaptation to...
Python
1
import os from pythonforandroid.recipe import Recipe from pythonforandroid.util import current_directory from pythonforandroid.logger import shprint from multiprocessing import cpu_count import sh class LibZBarRecipe(Recipe): version = '0.10' url = 'https://github.com/ZBar/ZBar/archive/{version}.zip' d...
Python
1
ox locations, sized [#obj,4]. labels: (tensor) class labels for each box, sized [#obj,]. ''' CLS_THRESH = 0.5 NMS_THRESH = 0.5 input_size = torch.Tensor([input_size,input_size]) if isinstance(input_size, int) \ else torch.Tensor(input_size) anchor_...
Python
1
n F.gumbel_softmax(logits, tau=0.003, hard=True, dim=dim, eps=1e-7) reward_model.softmax = gumbel_softmax post_suffix_str = "ASSISTANT: " post_suffix = tokenizer(post_suffix_str, return_tensors="pt").input_ids post_suffix = post_suffix.squeeze().to(DEVICE) post_suffix = post_suffix[1:] import ...
Python
1
MaxBound).1; } (min, max) } pub fn compute_box<P>(bs: &Bspline<P>) -> (P, P) where P: PointT { let num_cpts = bs.control_points().len(); let dim = P::dim(); let mut minp: P = P::splat(f64::MAX); let mut maxp: P = P::splat(f64::MIN); for i in 0..num_cpts { let lp = bs.control_p...
Rust
0
import numpy as np import math from itertools import chain import pickle from ..methods.node import * def lookup_node(elements, nodes, literals): elements = tuple(elements) el = nodes.get(elements) if not el: # For creating the circuit n = Node() n.elements = [] for e in e...
Python
1
mUri; use http::uri::{Scheme, Uri}; #[derive(Debug)] struct StringWrapper(String); impl TryFromUri for StringWrapper { fn build_with_base_uri(uri: Uri) -> Self { StringWrapper(uri.to_string()) } } macro_rules! test_from_value_fn_ok { ([$method: path]: $($f:...
Rust
0
self._tab.get::<flatbuffers::ForwardsUOffset<&str>>(HttpRequest::VT_REMOTE_ADDR, None) } #[inline] pub fn has_body(&self) -> bool { self._tab.get::<bool>(HttpRequest::VT_HAS_BODY, Some(false)).unwrap() } } pub struct HttpRequestArgs<'a> { pub id: u32, pub method: HttpMethod, pub url: Optio...
Rust
0
r( api_key=analyzer_config["openai"]["api_key"], model=analyzer_config["openai"]["model"], temperature=analyzer_config["openai"]["temperature"] ) # Setup and run bot logger.info("Starting bot...") await setup_bot(telegram_config, storage, analyzer) except Exception as e: logger.error(f"Error in ma...
Python
1
max(self.origin.y + self.size.height, other.origin.y + other.size.height)); Rect { origin: upper_left.clone(), size: Size2D(lower_right.x - upper_left.x, lower_right.y - upper_left.y) } } #[inline] pub fn translate(&s...
Rust
0
f.ctx.seq_mgr.next_sns1(&dst), Some(qos_ctrl) => self.ctx.seq_mgr.next_sns2(&dst, qos_ctrl.tid()), } as u16 ) }, mac::QosControl?: qos_ctrl, mac::LlcHdr: &data_writer::make_snap_llc_hdr(ether_type), ...
Rust
0
ut stream: W) -> Result<()> { for par in pars { writeln!( stream, " {{ \"{}\", ASSIGN_DIMEN, DIMEN_BASE + DIMEN_PAR__{}, xf_prim_init_none }}, \\", par.name.replace("_", ""), par.name.to_lowercase(), )?; } Ok(()) } pub mod b { struct B ...
Rust
0
"""Tests for dealing with binary request and response data.""" import requests from .fixtures import BIN_FILE_PATH, BIN_FILE_CONTENT, BIN_FILE_PATH_ARG from httpie.output.streams import BINARY_SUPPRESSED_NOTICE from .utils import MockEnvironment, http class TestBinaryRequestData: def test_binary_stdin(self, htt...
Python
1
# -*- coding: utf-8 -*- # # Picard, the next-generation MusicBrainz tagger # # Copyright (C) 2019-2022 Laurent Monin # Copyright (C) 2020 Philipp Wolfer # # This program 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 Fou...
Python
1
uzzyMapLookupResult>, Box<Error>> where F: Fn(u32) -> &'a str { let mut matches = Vec::<u32>::new(); let mut variant_ids: Vec<u64> = Vec::new(); if query.is_ascii() { self.find_matching_variants_ascii(query.as_bytes(), 0, edit_distance as usize, &self.fst.root(), 0, &mut variant_ids...
Rust
0
#!/usr/bin/python ## ## (C) 2007, 2008, 2013-2016 Muthiah Annamalai, ## Licensed under GPL Version 3 ## ## Interpreter for EXRS language import os, sys, string, inspect, codecs from .Interpreter import Interpreter, REPL, Lex, get_prog_name from .errors import ParseException, RuntimeException def exprs_eval(): la...
Python
1
'y' => Token { register_token: Some(2), value_token: None, }, 'z' => Token { register_token: Some(3), value_token: None, }, _ => panic!("Something went wrong"), ...
Rust
0
wait response.json() # 调试信息:打印完整的OTA响应 self.logger.debug( f"OTA服务器返回数据: " f"{json.dumps(response_data, indent=4, ensure_ascii=False)}" ) return response_data except asyncio.TimeoutE...
Python
1
"""Test Graph Database Chain.""" from typing import Any from langchain_community.chains.graph_qa.arangodb import ArangoGraphQAChain from langchain_community.graphs import ArangoGraph from langchain_community.graphs.arangodb_graph import get_arangodb_client from langchain_community.llms.openai import OpenAI def popu...
Python
1
value('int'): <1-65535> Ethernet segment local discriminator value ip_address('int',optional): A.B.C.D IP address of the peer , default value is None vc_id('str',optional): <1-4294967295> Enter VC ID value , default value is None encapsulation('str',optional): Data enca...
Python
1
e(([0.0], recall, [1.0])) mpre = np.concatenate(([1.0], precision, [0.0])) # Compute the precision envelope mpre = np.flip(np.maximum.accumulate(np.flip(mpre))) # Integrate area under curve method = 'interp' # methods: 'continuous', 'interp' if method == 'interp': x = np.linspace(0, 1...
Python
1
k(0) filename = f"attendance_export_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv" return send_file(mem, mimetype="text/csv", as_attachment=True, download_name=filename) @app.route("/student/<roll_no>/attendance", methods=["GET"]) def student_detail(roll_no): date_from = request.args.get("date_from") or ...
Python
1
atch_size) with torch.no_grad(): with torch.cuda.amp.autocast(enabled=self.fp16): outputs = self.pretrained_model.render(rays['rays_o'], rays['rays_d'], None, staged=True, bg_color=None, perturb=False, force_all_rays=True, **vars(self.opt)) images = ou...
Python
1
' try to assemble original name.') return parser def main(): import os from tabulate import tabulate import operator p = initialize_parser() args = p.parse_args() root = logging.getLogger() logging.basicConfig() if args.verbose: root.setLevel(logging.DEBU...
Python
1
str), ERself(&'a str), } const RNONE: &Reason<'_> = &Reason::new(None, Reason_::Rnone); impl<'a> Reason<'a> { pub const fn new(pos: Option<&'a Pos<'a>>, reason: Reason_<'a>) -> Self { Self { pos, reason } } pub const fn none() -> &'static Reason<'static> { RNONE } pub fn wit...
Rust
0
_, insns_cnt, if strict_alignment { 1 } else { 0 }, license.as_ptr(), libbpf_sys::KERNEL_VERSION, ptr::null_mut(), 0)) .map(|fd| Prog { fd }) } } /// Get a `Prog` obj...
Rust
0
p(|c| c.get(1).or_else(|| c.get(2))) .collect(); for number in matches { let number = number.as_str(); let number_int = number.parse().unwrap_or(0); let search = solved::search(number).await?; if let Some(problem) = search .problems .iter() ...
Rust
0
+ "\nTitles: %s" % video_titles) return # Generate output string out_string = "" for url, title in zip(video_urls, video_titles): if output_xargs: # Assume xargs calls curl out_string += "-o \"%s.mp4\"\n" % title.replace("/", "_") if auth_coo...
Python
1
): #输出结果 odd = 0 for e in brance: print(e, end = ('=' if odd == 0 else '∧')) odd = 1 - odd print("target =", target) def print_tree(Tree, stack = []): if (None == Tree): return if (None != Tree.result): print_brance(stack, Tree.resul...
Python
1
pub fn writeback_impulses(&self, joints_all: &mut [JointGraphEdge]) { let joint = &mut joints_all[self.joint_id].weight; if let JointParams::RevoluteJoint(revolute) = &mut joint.params { revolute.impulse = self.impulse; revolute.motor_impulse = self.motor_impulse; ...
Rust
0
etTransitionRule_TimeDefinition public enum ZoneOffsetTransitionRule_TimeDefinition ("java/time/zone/ZoneOffsetTransitionRule$TimeDefinition") extends crate::java::lang::Enum { /// [values](https://developer.android.com/reference/java/time/zone/ZoneOffsetTransitionRule.TimeDefinition.html#values()) ...
Rust
0
ey='%s: bytes sent (total)' % net_if, value=net_values.bytes_sent)) # diag_vals.append(KeyValue(key='%s: bytes recv (total)' % net_if, value=net_values.bytes_recv)) # diag_vals.append(KeyValue(key='%s: packets sent (total)' % net_if, value=net_values.packets_sent)) ...
Python
1
HwHeader(payload.to_vec()), NFULA_HWLEN => { PacketNla::HwHeaderLen(parse_u16_be(payload).context("invalid NFULA_HWLEN value")?) } _ => PacketNla::Other(DefaultNla::parse(buf)?), }; Ok(nla) } } use crate::logger::*; use crate::subtasks::collect_al...
Rust
0
from typing import Type import gradio as gr from swift.ui.base import BaseUI class Advanced(BaseUI): group = 'llm_train' locale_dict = { 'advanced_param': { 'label': { 'zh': '高级参数设置', 'en': 'Advanced settings' }, }, 'optim': {...
Python
1
} None => Err(io::Error::new( io::ErrorKind::InvalidData, "No matching IconType", )), } } let mut images_to_resize: Vec<(image::DynamicImage, u32, u32)> = vec![]; for icon_path in settings.icon_files() { let icon_path = icon_path?; let icon = image::open(&icon_path)?; ...
Rust
0
&str; 3] = ["header.gph", "footer.gph", ".reverse"]; /// Whether to print info!() messages to stdout. /// Defaults to true. static SHOW_INFO: AtomicBool = AtomicBool::new(true); /// Hide info! messages. fn hide_info() { SHOW_INFO.swap(false, AtomicOrdering::Relaxed); } /// Print status message to the server's st...
Rust
0
rid(True, linestyle='--', alpha=0.5) if example_tid in orf_df.index: orf_info = orf_df.loc[example_tid] ax1.axvspan(orf_info['cDNA coding start'], orf_info['cDNA coding end'], color='green', alpha=0.2, label='Annotated ORF') ax1.legend(loc='upper right') ...
Python
1
&self.ctype)?; } if !self.cform.is_empty() { os.write_string(12, &self.cform)?; } if !self.genkei.is_empty() { os.write_string(13, &self.genkei)?; } if !self.yomi.is_empty() { os.write_string(14, &self.yomi)?; } os.writ...
Rust
0
Iterates through range.unfiltered_range and check each block for changes of keys' values. fn query_storage_unfiltered( &self, range: &QueryStorageRange<Block>, keys: &[StorageKey], changes: &mut Vec<StorageChangeSet<Block::Hash>>, ) -> Result<()> { let mut last_state: HashMap<_, Option<_>> = Default::defau...
Rust
0
import unittest from unittest.mock import patch from app import app class TestFlaskParentalGuidanceRoute(unittest.TestCase): def setUp(self): # Set up the test client self.app = app.test_client() self.app.testing = True @patch('route_handlers.parent.get_parental_guidance.assess_activi...
Python
1
repr(C)] struct TcpMd5sig { ss_family: u16, ss: [u8; 126], _pad0: u16, keylen: u16, _pad1: u32, key: [u8; 80], } impl TcpMd5sig { fn new(addr: &IpAddr, password: String) -> TcpMd5sig { let mut ss = [0; 126]; let ss_family = match addr { std::net::IpAddr::V4(addr)...
Rust
0
pen(f'data_scrb\j_objs{datetime.now().strftime("(%m.%d,%H,%M)")}.json', "w", encoding='utf-8') as json_file: json.dump(objs, json_file, indent=4) except: print("not loaded") #_____________________________________DB_block________________________________________ def use_conn_config(): """rea...
Python
1
_MAX_ENUM: VkFramebufferCreateFlagBits = 2147483647; pub type VkFramebufferCreateFlagBits = ::std::os::raw::c_uint; pub type VkFramebufferCreateFlags = VkFlags; pub const VK_RENDER_PASS_CREATE_TRANSFORM_BIT_QCOM: VkRenderPassCreateFlagBits = 2; pub const VK_RENDER_PASS_CREATE_FLAG_BITS_MAX_ENUM: VkRenderPassCreateFlagB...
Rust
0
1 data['total_runtime'] = total_runtime update_data() threading.Thread(target=macro_loop, daemon=True).start() def change_pref(): global status old_status = status status = ahk.input_box(prompt="Enter the new status:", title="Changing Preference", width=265, height=125)...
Python
1
::album_artist_id)), ) .select(( song_id, song_title, artist_name, album_artist_name, album_name, track_number, disc_number, duration, get_song_path(), diesel::dsl::sql::<Bool>("case w...
Rust
0
record)?; } } gen_file.flush()?; Ok((gen_name, cds_name)) } #[cfg(test)] mod test_em { use super::*; use config::EqClass; fn test_ds() -> EqClassCounts { let mut counts = HashMap::new(); let eq_a = EqClass::from(vec![0]); let eq_ab = EqClass::from(vec![0, 1]); ...
Rust
0
class TaskFamily: @staticmethod def get_tasks() -> dict[str, dict]: return { "1": {"concept": "Existentialism", "prompt": "Explain the concept of existentialism and discuss its implications on human freedom and responsibility."}, "2": {"concept": "Utilitarianism", "prompt": "Expl...
Python
1
} let cc = cc as i64; let file_name = file_name.into(); let file_id = ObjectId::new(); let mut file_item_raw = doc! { "_id": file_id, "file_name": file_name, "count": 1i32 }; let is_stream = cc == buffer_size as i64; let (...
Rust
0
c_2BC') If( ( (Expr.PushReg, 0x1), (Expr.PushLong, 0x6), Expr.Equ, Expr.Return, ), 'loc_2D5', ) OP_99(0x00FE, 0x06, 0x07, 1350) Jump('loc_381') def _loc_2D5(): pass label('loc_2D5') If( ( (Expr....
Python
1
import json, time import os import pika import threading import traceback import requests, aiohttp from requests.packages.urllib3.exceptions import InsecureRequestWarning import random, socket, asyncio from concurrent.futures import ProcessPoolExecutor #import http.client from concurrent.futures import as_completed imp...
Python
1
import yfinance as yf import numpy as np _v412618_cache = {} def execute_trade(ticker: str, cash_balance: float, shares_held: int) -> str: if ticker not in _v412618_cache: _v412618_cache[ticker] = yf.download(ticker, period="90d", interval="1h", progress=False) df = _v412618_cache.get(ticker) if d...
Python
1
import bpy from .. common.common import * class SaveAndReloadOperator(bpy.types.Operator): """Save and Reload""" bl_idname = 'qm.save_and_reload' bl_label = 'Save and Reload' def execute(self, context): bpy.ops.wm.save_mainfile() bpy.ops.wm.revert_mainfile() return {'FINISHED'} class ReimportText...
Python
1
or $2 &read $1 &pad $5 &write $1 |0100 @on-reset ( -> ) ;hello-txt print-str BRK @print-str ( str* -- ) &loop LDAk .Console/write DEO INC2 LDAk ?&loop POP2 JMP2r @hello-txt "Hello, 20 "World! 0a 00 """, "yuck": """ (defwindow bar :monitor 0 :geometry (geometry :x "0%" ...
Python
1
ize, pub spending_structure: bitcoin::AddressType, pub bitcoins: bitcoin::Amount, //pub fungibles: HashMap<TransitionId, Vec<(AssetAmount, TransitionId)>> } /* #[derive(Clone, Serialize, Deserialize, Debug)] pub struct AssetAllocations { pub seals: HashMap<ContractId, Vec<rgb::fungible::Allocation>>, }...
Rust
0
docs', action='store_true', help='Build docs') parser.add_argument('--disable-swift', default=False, dest='swiftdisabled', action='store_true', help='Disable building of Swift extensions') args, unknown_args = parser.parse_known_args() if unknown_args: print("The following args are not recognized a...
Python
1
S_ID_FEATURE_SEQUOIA_CAM = 147, } // --------------------- Conversion impls --------------------- // impl Into<u8> for Feature { fn into(self) -> u8 { match self { Self::Common(_) => 0, Self::Ardrone3 => 1, Self::Minidrone => 2, Self::JumpingSumo(_) => 3, ...
Rust
0
nemonic::Vprolq,// EVEX_Vprolq_zmm_k1z_zmmm512b64_imm8 Mnemonic::Psrld,// Psrld_mm_imm8 Mnemonic::Psrld,// Psrld_xmm_imm8 Mnemonic::Vpsrld,// VEX_Vpsrld_xmm_xmm_imm8 Mnemonic::Vpsrld,// VEX_Vpsrld_ymm_ymm_imm8 Mnemonic::Vpsrld,// EVEX_Vpsrld_xmm_k1z_xmmm128b32_imm8 Mnemonic::Vpsrld,// EVEX_Vpsrld_ymm_k1z_ymmm256b...
Rust
0
{ 'name': 'SaaS Server Backup S3', 'version': '17.0.1.0.1', 'author': 'Salton Massally, Nicolas JEUDY', 'license': 'LGPL-3', 'category': 'SaaS', "support": "apps@it-projects.info", 'website': 'http://idtlabs.sl', 'external_dependencies': { 'python': [ 'boto', ...
Python
1
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ CineAIStudio 图标管理器 提供统一的图标加载和管理功能 """ import os from typing import Optional, Dict, Any from pathlib import Path from PyQt6.QtGui import QIcon from PyQt6.QtCore import QSize class IconManager: """图标管理器""" def __init__(self, icon_dir: Optional[str] = None):...
Python
1
SSAGE_CAN_REBUILD", "4"), ("(guint) SOUP_MESSAGE_CERTIFICATE_TRUSTED", "32"), ("(guint) SOUP_MESSAGE_CONTENT_DECODED", "16"), ("(guint) SOUP_MESSAGE_DO_NOT_USE_AUTH_CACHE", "512"), ("SOUP_MESSAGE_FIRST_PARTY", "first-party"), ("SOUP_MESSAGE_FLAGS", "flags"), ("(gint) SOUP_MESSAGE_HEADERS_MULTIPA...
Rust
0
found in this scope #[test] fn larger_can_hold_smaller() { let larger = Rectangle { length: 8, width: 7, }; let smaller = Rectangle { length: 5, width: 1, }; assert!(larger.can_hold(&smaller)); } #[test] fn s...
Rust
0
e.get(endian)); p.field_string( "Path", image.path_file_offset.get(endian), image.path(endian, data), ); p.field_hex("Pad", image.pad.get(endian)); }); if let Some(offset) = mappings.and_then(|mappings| image...
Rust
0
if rendererInstance: dependencies.append(rendererInstance) rendererIds.append(rendererId) calls = context.buildDependencyCallList( objId, rendererIds, "addRenderer", "removeRenderer" ) return { "parent": getReferenceId(parent), "id": objId, ...
Python
1
Returns `true` if it is a Virtual Machine virtualization. pub fn is_vm(&self) -> bool { match self { Virtualization::Kvm => true, Virtualization::Qemu => true, Virtualization::Bochs => true, Virtualization::Xen => true, Virtualization::Uml => true...
Rust
0
_t, gensig: *const c_void, best_deadline: *mut uint64_t, best_offset: *mut uint64_t, ) -> (); pub fn find_best_deadline_sse2( scoops: *mut c_void, nonce_count: uint64_t, gensig: *const c_void, ...
Rust
0
x = state[1] for i in range(100): x = x + 0.005 state = ruiwo.run_ptm_mode(DEV_ID, x, 0, 10, 3, 0) if state == False: print("Motor run failed.") exit(1) time.sleep(0.05) print("Motor position:",state[1]) # 等待用户输入 ...
Python
1
#, E[e0], E[e1], B[e1], B[e0], e0, e1 ) }, )?; write!(out, "\n}}\n")?; Ok(()) } fn write_swizzle_vec3a(out: &mut impl Write) -> Result<()> { const SIZE: usize = 3; write!( out, r#" use super::{{Vec2, Vec3A, Vec4}}; #[cfg(vec3a_f32)] use super:...
Rust
0
; } let rotation = actions.tile_rotation.as_ref().unwrap(); let mut tiles = query.0; let players = query.1; for player in players.iter() { for (mut tile, transform) in tiles.iter_mut() { if player.x == transform.x && player.y == transform.y { match rotation { ...
Rust
0
::ScanningToJoin{ cmd, .. } = &self.current { Some(cmd) } else { None } } fn matching_mlme_txn_id(&self, incoming_txn_id: u64) -> bool { match &self.current { ScanState::NotScanning => false, ScanState::ScanningToJoin { mlme_txn_id, .. } ...
Rust
0
state(tk.NORMAL) if data: for i, short in enumerate(data): # Format the datetime string for display published_dt = datetime.datetime.fromisoformat(short['published'].replace('Z', '+00:00')) published_str = publis...
Python
1
import random import re import time from datetime import datetime, timedelta import pytz from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.triggers.cron import CronTrigger from app.core.config import settings from app.core.event import eventmanager, Event from app.plugins import _Plug...
Python
1
import os from loguru import logger SPIQA_DIR = os.getenv("SPIQA_DIR", "./datasets/spiqa") WRITE_DIR = os.getenv("WRITE_DIR", "./output") BERT_MODEL_DIR = os.getenv("BERT_MODEL_DIR", "./models/bert-base-uncased") API_MODEL = os.getenv("API_MODEL", "qwen-vl-max-2025-08-13") CLIP_MODEL_PATH = os.getenv("CLIP_MODEL_PAT...
Python
1
for partition in partitions.into_iter() { match partition { Partition::VCHAR(word) => { let mut word = Word::try_from(word)?; if let Some(fws) = last_gap.take() { word.pad_left(fws); } ...
Rust
0
(Int64(53))); for i in 0..65519 { array.insert_at(16 + i, Int64(i as i64)); } assert_eq!(array.header(), ArrayHeader::Array16(65535)); assert_eq!(array.get(65534), Some(Int64(65518))); array.insert_at(32768, Int64(-42)); assert_eq!(array.header(), ArrayHeade...
Rust
0
ropsOrTitle : str, width: int, height: int): ... def CreateWindow(self, propsOrTitle : WindowProperties | str, width : int | None = None, height : int | None = None): if isinstance(propsOrTitle , WindowProperties): self._window = Window.CreateWindow(propsOrTitle) else: self....
Python
1
s to audit table ---") audit_utils.end_audit_log( bq_client_main, batch_id, input_gcs_path, table_attributes, header_gcs_path ) print(f"Pipeline completed successfully for batch_id: {str(batch_id)}") finally: # Clean up local Snowfakery output directory for the current b...
Python
1
d, lower for fuzzy matches "normalized_aliases": normalized_answers } ], } if bleu == 1: local_sem += 1 elif bleu < 1 and ...
Python
1
from heapq import heappop, heappush from collections import defaultdict, Counter, deque from functools import reduce, lru_cache import math import sys fin = open(sys.argv[1]) if len(sys.argv) > 1 else sys.stdin def bfs(x, y): poss = defaultdict(int) poss[(x, y)] = 1 ends = set() seen = set() queue = deque() ...
Python
1
import os import requests from django.conf import settings OPENROUTER_API_URL = "https://openrouter.ai/api/v1/chat/completions" class DeepSeekService: @staticmethod def get_response(messages): headers = { "Authorization": f"Bearer {settings.OPENROUTER_API_KEY}", "HTTP-Referer": ...
Python
1
tions() """Determines whether animations run or not.""" ESCAPE_DELAY: Final[float] = _get_environ_int("ESCDELAY", 100, minimum=1) / 1000.0 """The delay (in seconds) before reporting an escape key (not used if the extend key protocol is available).""" SLOW_THRESHOLD: int = _get_environ_int("TEXTUAL_SLOW_THRESHOLD", 50...
Python
1
in range(2010, 2025) if f'answers_{year}' in entry} elif bench_name == "Biomedical": return {f'objects_{year}': set(entry[f'objects_{year}']) for year in range(2020, 2025) if f'objects_{year}' in entry} elif bench_name == "General": return {f'objects_{year}': set(obj for obj_list in entry[f'obj...
Python
1