text
string
label_name
string
labels
int64
import cv2 import numpy as np def _resize_and_pad(frame: np.ndarray, target_width: int, target_height: int) -> np.ndarray: """ Resize an image to fit into a target frame while maintaining aspect ratio, and pad with black pixels to match the exact target size. Parameters: frame (np.ndarray): T...
Python
1
aded. best_model = tuner.get_best_models()[0] best_model.score(x, y) def test_sklearn_real_data(tmp_path): tuner = keras_tuner.SklearnTuner( oracle=keras_tuner.oracles.BayesianOptimizationOracle( objective=keras_tuner.Objective("score", "max"), max_trials=10 ), hypermod...
Python
1
or_flg; use crate::arg_and_help; pub use std::fs::File; pub use std::io::{BufReader, Read}; use kanaria::{string::UCSStr, utils::ConvertTarget}; pub use regex::Regex; use error_flg::*; use arg_and_help::{ARG_PAT_NAME, ARG_PAT_FIRST_INITIAL, ARG_PAT_LAST_INITIAL, ARG_PAT_CATEGORIES, ARG_PAT_TEL_TYPE}; #[deri...
Rust
0
; i += len as usize; } assert_eq!(wtr.n_raw_bytes(), i as u64); assert!(src[..i] == wtr[..i]); Ok(()) } #[test] #[ignore = "expensive"] fn lmd() -> crate::Result<()> { let pad = Seq::new(Rng::new(0)).take(0x0100).collect::<Vec<_>>(); let src =...
Rust
0
# Copyright (C) 2018, 2019, 2020 Dominic O'Kane from financepy.products.bonds.bond_mortgage import BondMortgageTypes from financepy.products.bonds.bond_mortgage import BondMortgage from financepy.utils.date import Date principal = 130000 start_dt = Date(23, 2, 2018) end_dt = start_dt.add_tenor("10Y") mortgage = Bond...
Python
1
import logging from flask import Blueprint, Response from app.services.helper_service import ( get_data, get_feature_names, get_model_results, get_training_progress, get_available_models, get_class_names, ) helper_service_bp = Blueprint("helper_service", __name__) logger = logging.getLogger(__n...
Python
1
er as f64; Ok(Number { integer, float }) } fn oper_lt(_idx_expr: usize, nums: &[Number]) -> Result<Number, ExprError> { let lhs = nums[0]; let rhs = nums[1]; let integer = (lhs.integer < rhs.integer) as u64; let float = (lhs.float < rhs.float) as u64 as f64; Ok(Number { integer, float }) } fn ...
Rust
0
import _init_paths import os from lib.test.evaluation import get_dataset import shutil trackers = [] # dataset_name = 'uav' dataset_name = 'nfs' root_dir = "/data/sda/v-yanbi/iccv21/STARK_Latest/Stark" base_dir = os.path.join(root_dir, "test/tracking_results/TransT_N2") dataset = get_dataset(dataset_name) for x in d...
Python
1
sample']['last_step_size'], num_steps=train_config['sample']['num_sampling_steps'], ) return sample_fn def get_latents(train_config: dict, device='cpu'): from utils.data_utils import get_latent_stats_from_local latent_mean, latent_std = get_latent_stats_from_local(path='pretrains/vavae/...
Python
1
""" Current user settings stored in UserSettings. Storing a global dict to allow for db-less access, they're global settings, after all. They're written to at load (or when the settings change). """ from lute.models.setting import UserSetting # The current user settings, key/value dict. current_settings = {} # Cur...
Python
1
/stackoverflow.com/a/46635398/5435443 CursorIcon::Help => Cursor::Undocumented("_helpCursor"), CursorIcon::ZoomIn => Cursor::Undocumented("_zoomInCursor"), CursorIcon::ZoomOut => Cursor::Undocumented("_zoomOutCursor"), CursorIcon::NeResize => Cursor::Undocumented("_window...
Rust
0
"""Main page with simplified interface""" return render_template('simple_index.html') @app.route('/api/predict', methods=['POST']) def predict_current(): """Simplified prediction API""" try: data = request.json # Make prediction prediction = predictor.predict(data) ...
Python
1
_eq!(node_index, decoded.unwrap()); } } } #[macro_use] extern crate criterion; use criterion::{Criterion, Fun}; use rand::distributions::{Distribution, Standard}; use rand::prelude::*; use unroll::unroll_for_loops; static SEED: [u8; 32] = [3; 32]; const N: usize = 5; #[inline] fn make_random_prod_pair() ...
Rust
0
from django.db import models from django.contrib.auth.models import User from django.utils import timezone class Author(models.Model): fullname = models.CharField(max_length=200) born_date = models.DateField() born_location = models.CharField(max_length=1502, default='Default Location') description = m...
Python
1
"""Pipette assembly qc."""
Python
1
Clear for RawNebulaCertificate { fn clear(&mut self) { self.Details.clear(); self.Signature.clear(); self.unknown_fields.clear(); } } impl ::std::fmt::Debug for RawNebulaCertificate { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { ::protobuf::text_f...
Rust
0
an additional instance is requested, the code will panic in runtime. /// Hence, obtaining indexes from a `Fork` functions similarly to [`RefCell::borrow_mut()`]. /// /// For example the code below will panic at runtime. /// /// ```rust,should_panic /// # use exonum_merkledb::{access::CopyAccessExt, TemporaryDB, ListIn...
Rust
0
import requests import json import re import bleach from collections import Counter from rating.models import Profession from .word_filter import words_filter from easyoffer.settings import HEADERS from .models import Search, Skill, KeyWord from datetime import datetime def get_link(url): print('Start – get_link...
Python
1
on } } } impl<'a> Codegen<'a> for Pass<'a> { fn codegen(&self, state: &mut CodegenState<'a>) { state.add_token("pass"); self.semicolon.codegen(state); } } impl<'a> Inflate<'a> for Pass<'a> { fn inflate(mut self, config: &Config<'a>) -> Result<Self> { self.semicolon = self.semicol...
Rust
0
attacker commander /// * `commander_rhs` - The defender commander /// /// # Returns /// /// * `result` - A FightResult structure containing the result /// * `moves_lhs` - Logged moves of the attacker, if requested. None if not. /// * `moves_rhs` - Logged moves of...
Rust
0
, 'mt': 'Każak', 'my': 'ကာဇာချ', 'mzn': 'قزاقی', 'nb': 'kasakhisk', 'ne': 'काजाख', 'nl': 'Kazachs', 'nn': 'kasakhisk', 'no': 'kasakhisk', 'nqo': 'ߞߖ߭ߊߞߌߞߊ߲', 'or': 'କାଜାକ୍', 'pa': 'ਕਜ਼ਾਖ਼', 'pa-Guru': 'ਕਜ਼ਾਖ਼', 'pcm': 'Kazák Lángwej', 'pl': 'kazachski', 'ps': 'قازق', 'pt': 'cazaque', 'qu': 'Kazajo Simi', 'rm': 'casac',...
Python
1
import argparse from marltoolkit.envs.smacv1 import SMACWrapperEnv from marltoolkit.envs.vec_env import SubprocVecEnv def make_vec_env( env_id: str, map_name: str, num_train_envs: int = 10, num_test_envs: int = 10, **kwargs, ): def make_env(): if env_id == 'SMAC-v1': env ...
Python
1
from .exact_str_match import ExactStrMatch class SimpleStrMatch: """Basic string matching, without spaces or hyphens.""" @staticmethod def match(response, correct_answer: str) -> int: """Simple string match between response and correct_answer.""" if not isinstance(response, str): ...
Python
1
(), |_, _| (), |_| ()); print_category(&category); assert_eq!(2, category.objects.len()); assert_eq!(4, category.morphisms.len()); assert_eq!(2, category.equalities.len()); } fn print_category<O: Debug, M: Debug, E: Debug>(category: &Category<O, M, E>) { println!("\n----- Category -----"); pri...
Rust
0
_select! { signal.recv() -> signal => { // println!("received signal: {:?}", signal); // we capture SIGINT or SIGTERM so we can turn cursor back on println!("\x1b[?25h"); io::stdout().flush().unwrap(); let count_up = *count_up_seconds2.lock().unwrap(...
Rust
0
) hr = set_mute_func(endpoint, False, None) if hr < 0: raise ctypes.WinError(hr) _mic_muted = False except Exception as e: raise RuntimeError(f"無法取消靜音麥克風: {e}") def is_mic_blocked(): """ 檢查麥克風是否被阻擋(靜音) 返回 : True 表示被阻擋(靜音...
Python
1
M: 1, Q: 1, Rd: 22, Rm: 0, Rn: 20, size: 2 } ); } #[test] fn test_fmls() { // fmls v6.4s, v2.4s, v0.4s assert_eq!( decode_root_unwrap(0x4EA0CC46), InstructionKind::FMLSAsimdsameOnly { Q: 1, Rd: 6...
Rust
0
if tag.identifier == identifier { return Some(current_tag as u64); } current_tag = tag.next as *const StivaleTagHeader; } None } pub fn command_line(&self) -> Option<&'static StivaleCommandLineTag> { self.get_tag(0xe5e76a1b4597a781) ...
Rust
0
def myfunction () : print("Hello") print("Bye ") myfunction()
Python
1
i64> for QVariant { fn into(self) -> i64 { let p = self.raw; unsafe { cpp!([ p as "QVariant*"] -> i64 as "long long" { return p->toLongLong(); }) } } } impl Into<f64> for QVariant { fn into(self) -> f64 { let p = self.raw; unsafe { ...
Rust
0
.setup().await?; self.verify().await?; println!(); let mut rng = rand::thread_rng(); let customers = rand::distributions::Uniform::from(1..=self.customers as i64); let transfers = futures::stream::iter( std::iter::from_fn(|| Some((customers.sample(&mut rng), customer...
Rust
0
16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, ); assert_eq!(r, e); } #[simd_test = "avx2"] unsafe fn _mm256_adds_epi8() { #[cfg_attr(rustfmt, rustfmt_skip)] let a = i8x32::new( 0, 1,...
Rust
0
import locale import sys import pytest __all__ = ['fail_on_ascii'] locale_encoding = ( locale.getencoding() if sys.version_info >= (3, 11) else locale.getpreferredencoding(False) ) is_ascii = locale_encoding == 'ANSI_X3.4-1968' fail_on_ascii = pytest.mark.xfail(is_ascii, reason="Test fails in this local...
Python
1
import numpy as np from numba import njit @njit def percolation(GRID, water: float, dt: int) -> float: """Percolate melt water through the snow- and firn pack. Bucket method (Bartelt & Lehning, 2002). Args: GRID (Grid): Glacier data structure. water: Melt water at the surface, [|m w.e.| ...
Python
1
").await?; add_edges(relation_id, object_id_a, &[object_id_b]).await?; sleep(Duration::from_secs(1)).await; // async insert let view_data = materialize_view(view, &[schema_a, schema_b]).await?; assert_eq!(view_data.rows.len(), 0); Ok(()) } #[tokio::test] async fn should_return_no_results_when_ed...
Rust
0
import streamlit as st import os import openai import json import glob from openai import OpenAI from sklearn.metrics.pairwise import cosine_similarity from typing import List import numpy as np # Set up OpenAI client client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) # Load or compute embeddings @st.cache_data(sho...
Python
1
""" Created on 20250601 """ import sys import logging import pandas as pd sys.path.extend(['../..', '.']) import kis_auth as ka from inquire_time_fuopchartprice import inquire_time_fuopchartprice # 로깅 설정 logging.basicConfig(level=logging.INFO) ######################################################################...
Python
1
my_name = "Lehi" # If statement if my_name == "Pikachu": print ("This is not Lehi") # Nested If statement if my_name == "Lehi": print("ah, maybe it is you Lehi") # Elif statement elif my_name == "Dave": print("Ahh Lehi, you are not a Pokémon") # Else statement else: print("you must be the c...
Python
1
rocopy::{AsBytes, FromBytes, Unaligned, U16, U32, U64}; pub use mm0_util::u32_as_usize; pub use {parser::*, ty::*, write::*}; /// The maximum number of bound variables supported by the MMB format. pub const MAX_BOUND_VARS: usize = 55; /// Constants used in the MMB specification. pub mod cmd { /// `MM0B_MAGIC = "MM...
Rust
0
"""Configure Synology DSM tests.""" from collections.abc import Generator from unittest.mock import AsyncMock, patch import pytest from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component @pytest.fixture def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Moc...
Python
1
"index": "序号", "stockcode": "证券代码", "stockname": "证券名称", "newweight": "最新权重", "beginningdate": "计入日期", }, inplace=True, ) temp_df = temp_df[ [ "序号", "证券代码", "证券名称", "最新权重", "计入日期",...
Python
1
elf, BootInfoFrameAllocator}; let phys_mem_offset = VirtAddr::new(boot_info.physical_memory_offset); let mut mapper = unsafe { memory::init(phys_mem_offset) }; let mut frame_allocator = unsafe { BootInfoFrameAllocator::init(&boot_info.memory_map) }; allocator::init_heap(&mut mapper, &mut f...
Rust
0
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # 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 applicable law o...
Python
1
ount: u32, ) -> DispatchResultWithPostInfo { let acc = ensure_signed(origin)?; let mut state = <NominatorState2<T>>::get(&acc).ok_or(Error::<T>::NominatorDNE)?; ensure!(!state.is_leaving(), Error::<T>::NominatorAlreadyLeaving); ensure!( nomination_count >= (state.nominations.0.len() as u32), Error...
Rust
0
from functools import partial from typing import Tuple from io import StringIO import torch from torch.nn.functional import interpolate as interp import numpy as np def model_count(model): return sum(p.numel() for p in model.parameters()) class mesh_convertor(object): ''' Class for fine/coarse mesh ...
Python
1
2]= (result[-2] or '-') tc_results.append(result) if i > 0 and i >= max_repeat_print: continue if num_tests > 1: if combine_repeats: result[0] += f'_avg' else: result[0] += f'_{i}' if not combine_repeats or i==0: fil...
Python
1
def verbalize_age_gender(generation, gender): if generation == "GenZ" and gender == "male": perspective = "un giovane uomo della generazione Z" elif generation == "GenZ" and gender == "female": perspective = "una giovane donna della generazione Z" elif generation == "GenY" and gende...
Python
1
urn_off(self, **kwargs: Any) -> None: """Turn the switch off.""" loop: asyncio.AbstractEventLoop = asyncio.get_event_loop() await loop.run_in_executor( None, self._vue.update_outlet, self.coordinator.data[self._device_gid], False, ) ...
Python
1
_size=message_byte_size) # Test groups. # (2 * 1) bytes for begin and end tags, plus message_byte_size. self.assertEqual(2 + message_byte_size, wire_format.GroupByteSize(1, mock_message)) # (2 * 2) bytes for begin and end tags, plus message_byte_size. self.assertEqual(4 + messag...
Python
1
class Solution: def findScore(self, nums: List[int]) -> int: d = {} min_heap = [(i, index) for index, i in enumerate(nums)] heapq.heapify(min_heap) s = 0 while len(d) < len(nums): cur = heapq.heappop(min_heap) ind = cur[1] if ind not in d:...
Python
1
add_argument('--engine', type=str, default="MTE", help='The path of engine') parser.add_argument('--series', type=str, default="h7", help='The series of gd32,f4 or h7') parser.add_argument('--conf_thr', type=float, default=0.3, ...
Python
1
from STTools import * def getNestingChains(arg, chain=None): node = arg[1] if node.trigger == None: # reached protein level return [chain] else: if chain == None: chain = arg[0][0] + ":" + node.type else: chain += "-" + arg[0][0] + ":" + node.type chains ...
Python
1
CLKPLL_SDM_FLAG_R::new(((self.bits >> 28) & 0x01) != 0) } #[doc = "Bits 24:25"] #[inline(always)] pub fn clkpll_dither_sel(&self) -> CLKPLL_DITHER_SEL_R { CLKPLL_DITHER_SEL_R::new(((self.bits >> 24) & 0x03) as u8) } #[doc = "Bits 0:23"] #[inline(always)] pub fn clkpll_sdmin(&...
Rust
0
_i64(); validator.push_value(dst); if validator.reachable() { builder.current_block_mut().body.push(f(dst, src.unwrap())); } } fn make_i32_load<F>(f: F, memarg: MemoryImmediate, builder: &mut SsaFuncBuilder, validator: &mut Validator, alloc: &mut SsaVarAlloc) where F: FnOnce(MemoryImmediate, T...
Rust
0
import numpy as np from pathlib import Path from scipy.ndimage import gaussian_filter def load_and_combine_batches(processed_dir, split): """ 加载并合并指定 split 的所有批次数据。 """ # 获取所有批次的文件 batch_files = sorted(processed_dir.glob(f"{split}_batch_*.npz")) if not batch_files: raise FileNotFoundErr...
Python
1
import pytz import time import requests import threading from datetime import datetime, timedelta from typing import Any, List, Dict, Tuple, Optional from urllib.parse import urljoin from urllib3.util.retry import Retry from requests.adapters import HTTPAdapter from apscheduler.schedulers.background import BackgroundS...
Python
1
# Copyright 2022 Digital Brain Laboratory, Yan Song and He jiang # 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 applic...
Python
1
# def greet(): # print("good morning") # print("have a nice day") # # greet() # def add(x,y): # total = a+b # return total # sum = add(10,20) # print(sum) # def add(x,y): # total = x+y # return total # print(add(10,20)) # def add(x,y): # total = x+y # return total # num1 =int(input("e...
Python
1
addString = tempString tempFileMemory = workingFileMemory[:rightParen - 1] + addString + workingFileMemory[rightParen - 1:] rightParen += len(addString) var2 += len(addString) workingFileMemory = tempFileMemory #print workingFileMemory[leftParen:rightPare...
Python
1
# Generated by h2py from /usr/include/sys/cdio.h CDROM_LBA = 0x01 CDROM_MSF = 0x02 CDROM_DATA_TRACK = 0x04 CDROM_LEADOUT = 0xAA CDROM_AUDIO_INVALID = 0x00 CDROM_AUDIO_PLAY = 0x11 CDROM_AUDIO_PAUSED = 0x12 CDROM_AUDIO_COMPLETED = 0x13 CDROM_AUDIO_ERROR = 0x14 CDROM_AUDIO_NO_STATUS = 0x15 CDROM_DA_NO_SUBCODE = 0x00 CDROM...
Python
1
A6,// EVEX_Vfmaddsub213pd_zmm_k1z_zmm_zmmm512b64_er 0x4414_00A7,// VEX_Vfmsubadd213ps_xmm_xmm_xmmm128 0x4514_00A7,// VEX_Vfmsubadd213ps_ymm_ymm_ymmm256 0x4454_00A7,// VEX_Vfmsubadd213pd_xmm_xmm_xmmm128 0x4554_00A7,// VEX_Vfmsubadd213pd_ymm_ymm_ymmm256 0x4414_00A7,// EVEX_Vfmsubadd213ps_xmm_k1z_xmm_xmmm128b32 0x45...
Rust
0
o stop using self.interpreter and use API on # ModuleState instead. Modules should stop using this class and instead use # ModuleObject base class. class ExtensionModule(NewExtensionModule): def __init__(self, interpreter: 'Interpreter') -> None: super().__init__() self.interpreter = interpreter cl...
Python
1
"input_fit": _input_fit_schema, "input_predict": _input_predict_schema, "output_predict": _output_predict_schema, }, } MultiTaskLassoCV = make_operator(_MultiTaskLassoCVImpl, _combined_schemas) if lale.operators.sklearn_version >= version.Version("1.2"): # old: https://scikit-learn.org/1.1/...
Python
1
cy+halfh)) W2, H2 = img.size if verbose: print(f' - adding {path} with resolution {W1}x{H1} --> {W2}x{H2}') # @MODIFIED imgs.append( { 'img': ImgNorm(img)[None], 'true_shape': np.int32([img.size[::-1]]), 'idx': len(...
Python
1
audio_data(&array_buffer) .map_err(LoadSoundError::WebAudio)?; let value = JsFuture::from(promise) .await .map_err(LoadSoundError::WebAudio)?; assert!(value.is_instance_of::<AudioBuffer>()); value.dyn_into().unwrap() }; ...
Rust
0
(nFeat, nDenselayer, growthRate)) block2_1.append(RWDB(nFeat, nDenselayer, growthRate)) block2_2.append(RWDB(nFeat, nDenselayer, growthRate)) block2_3.append(RWDB(nFeat, nDenselayer, growthRate)) block3_1.append(RWDB(nFeat, nDenselayer, growthRate)) block3_2.a...
Python
1
", e), Error::InvalidDnsName(n) => write!(f, "invalid DNS name: {}", n), Error::__Nonexhaustive => f.write_str("__Nonexhaustive") } } } impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { Error::Io(...
Rust
0
7) / COTP() / COTP_TCP_Data() / S7COMM(param_length=8) / S7COMM_Ack() / S7COMM_Job() / S7COMM_Job_Connect() )) def run(self): if self._is_llc_: print "Server is starting in LLC mode..." self.reply_enu...
Python
1
uman-sciences': True, 'c_natural-sciences': True, 'c_mathematics': True, } def aggregation(self): return { "acc": mean, '2022': mean, 'languages': mean, 'human-sciences': mean, 'natural-sciences': mean, ...
Python
1
from saved_settings.basics import basic_fix from saved_settings.vd_single_frame_fx import vd_basic, res18_la def slow_bs(args): args['batch_size'] = 64 args['test_batch_size'] = 32 args['test_no_frames'] = 5 args['kNN_val'] = 10 args['fre_filter'] = 50000 args['fre_cache_filter'] = 5000 ar...
Python
1
""" 排除项管理器 单例模式,全局唯一实例 """ _init_content = """.git __pycache__ .idea """ class ExcludeManager: def __init__(self): # 用户初始化输入的东西,可以看成是.gitignore文件的内容 self.user_input_content = _init_content # 是否开启局部排除 self.is_local_exclude = True # 是否开启全局排除 self.is_global_exclude =...
Python
1
def task1(): class Restaurant: def __init__(self, restaurant_name, cuisine_type): self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type def describe_restaurant(self): print(f'Ресторан {self.restaurant_name}: {self.cuisine_type} кухня') d...
Python
1
hMap::new(), children: vec![], }))], }))], }))], } ); } #[test] fn de_tree_has_parallel_tag_children() { assert_eq!( Tree::de("<div><div></div><div></div></div>".into()).unwrap(), Tree { pre: None, ...
Rust
0
# # SPDX-License-Identifier: LGPL-3.0-or-later # Copyright (c) 2024-2025, QUEENS contributors. # # This file is part of QUEENS. # # QUEENS is free software: you can redistribute it and/or modify it under the terms of the GNU # Lesser General Public License as published by the Free Software Foundation, either version 3 ...
Python
1
")); assert!(Glob::new("a%b%c?").matches("aabcc")); assert!(!Glob::new("a%b%c?").matches("acb")); } // #[test] // fn test_file_glob() -> io::Result<()> { // let mut out: Vec<String> = Vec::new(); // glob_files("C*", Path::new("."), &mut out)?; // assert_eq!(out, vec!["Car...
Rust
0
del, task=task, is_recurring=True) # We create a monthly recurrence pattern = ifcopenshell.api.sequence.assign_recurrence_pattern(model, parent=work_time, recurrence_type="MONTHLY_BY_DAY_OF_MONTH") # Specifically, the maintenance task must occur every 6 months ifcopenshell....
Python
1
import numpy as np file = open("inputs/in2.txt") part1 = 0 part2 = 0 for line in file: my_dict = {} game = int(line.split(":")[0][5:]) info = line.strip().split(" ", 2)[2].split(";") my_dict.update({game: []}) for reveals in info: for reveal in reveals.split(","): my_dict[game...
Python
1
import uuid from pydantic import BaseModel from app.constants import DetectionItemType class DetectionItemCreate(BaseModel): origin_file: str type: DetectionItemType detection_id: uuid.UUID class DetectionItemBase(DetectionItemCreate): id: uuid.UUID predict_file: str | None classes: str | ...
Python
1
iw => { f.write_str(format!("Sraiw").as_str()) } Srl => { f.write_str(format!("Srl").as_str()) } Srlw => { f.write_str(format!("Srlw").as_str()) } Srli => { f.write_str(format!("Srli").as_str()) } Srliw => { f.write_str(format!("Srliw").as_str()) } Sub => { f....
Rust
0
_W { IPS0_W { w: self } } #[doc = "Bit 2 - Inter-Processor Signal Interrupt Enable for CPU 1"] #[inline(always)] pub fn ips1(&mut self) -> IPS1_W { IPS1_W { w: self } } } // constant string with the valid characters of Poop v1.0 const CHARACTERS: &str = "0123456789abcdefghijklmnopqrs...
Rust
0
d by the future pub fn join(self) -> T { while self.task_core.future.is_some() { unsafe { self.task_core.runtime.as_mut().run_once(); } } self.result.take().expect("No Result") } } impl<'t, T> Drop for JoinHandle<'t, T> { fn drop(&mut self) { ...
Rust
0
{ pub fn cudnnRNNBackwardDataEx( handle: cudnnHandle_t, rnnDesc: cudnnRNNDescriptor_t, yDesc: cudnnRNNDataDescriptor_t, y: *const ::libc::c_void, dyDesc: cudnnRNNDataDescriptor_t, dy: *const ::libc::c_void, dcDesc: cudnnRNNDataDescriptor_t, dcAttn: *c...
Rust
0
several passes. // In first pass we collect information about the chars and store their // raw bitmap data. It gives us max character height and summary width // of all characters. let chars_len = needed_chars.len(); let mut chars_info = HashMap::with_capacity(chars_len); ...
Rust
0
import torch from quaterion.loss import TripletLoss class TestTripletLoss: embeddings = torch.Tensor( [ [0.0, -1.0, 0.5], [0.1, 2.0, 0.5], [0.0, 0.3, 0.2], [1.0, 0.0, 0.9], [1.2, -1.2, 0.01], [-0.7, 0.0, 1.5], ] ) gr...
Python
1
= 0: return 1.0 if nodes else 0.0 # 计算提取的实体覆盖率 extracted_entities = len(nodes) coverage = min(extracted_entities / text_entities, 1.0) # 考虑关系提取 relationship_bonus = min(len(relationships) / max(len(nodes), 1), 0.3) ...
Python
1
eta = None else: eta = self.calc_eta(start, time.time(), ctx.data_len - ctx.resume_len, byte_counter - ctx.resume_len) self._hook_progress({ 'status': 'downloading', 'downloaded_bytes': byte_counter, ...
Python
1
Self { server, thread: Some(thread), stop: s, } } pub fn req_addr(&self) -> SocketAddr { self.server.addrs()[0] } pub fn stream_addr(&self) -> SocketAddr { self.server.addrs()[1] } fn respond(id: &[u8]) -> Result<zmq::Messa...
Rust
0
(self.ptr.as_ptr()) } } } impl Clone for ForeignLooper { fn clone(&self) -> Self { unsafe { ffi::ALooper_acquire(self.ptr.as_ptr()); Self { ptr: self.ptr } } } } impl ForeignLooper { /// Returns the looper associated with the current thread, if any. #[inline...
Rust
0
(1); } // Program args are the ones that come after the program name, so // collect those to be later used when the program is run. // NOTICE: THIS CODE MAY BE REPLACED LATER, AS IT IS NOT APPARENTLY // NECESSARY! let program_args: Vec<String> = args[2..args.len()].to_vec(); let mut sys...
Rust
0
# You are given a string s. # We define the mirror of a letter in the English alphabet as its corresponding letter when the alphabet is reversed. For example, the mirror of 'a' is 'z', and the mirror of 'y' is 'b'. # Initially, all characters in the string s are unmarked. # You start with a score of 0, and you perfo...
Python
1
from openai import OpenAI import json import os api_key_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "apikey.json") with open(api_key_path, 'r', encoding='utf-8') as f: api_key_data = json.load(f) api_key = api_key_data.get("api_key") client = OpenAI( api_key = api_key, base_url="ht...
Python
1
pub mod particle_system; pub mod pivot; pub mod rigidbody; pub mod sound; pub mod sprite; pub mod terrain; pub mod transform; pub mod variable; pub mod visibility; use crate::{ animation::{machine::container::AnimationMachineContainer, AnimationContainer}, core::{ algebra::Vector2, color::Color...
Rust
0
rotate_z(theta: Float) -> Self { let r = theta.to_radians(); let sin_theta = r.sin(); let cos_theta = r.cos(); let m = Matrix4x4::new( cos_theta, -sin_theta, 0.0, 0.0, sin_theta, cos_theta, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, ...
Rust
0
\"QPvivo_2015_11_10_1targetmethod\", filter: \"\", peaks: [], parent: [], children: [] }"); } #[test] fn equality_record_test() { let x = mgf_33450(); let y = mgf_33450(); let z = mgf_empty(); assert_eq!(x, y); assert_ne!(x, z); assert_ne!(y, z); } ...
Rust
0
######################################################################## # File name: get_external_services.py # This file is part of: aioxmpp # # LICENSE # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as # published by the Free Sof...
Python
1
eaderFormat { /// No header (for example, the header is 0 bytes in length) NoHeader, /// Type 1 log header Type1LogHeader, /// A value unknown to this standard, check the raw value None, } impl From<u8> for HeaderFormatData { fn from(raw: u8) -> Self { HeaderFormatData { ...
Rust
0
>, pub capabilities: Option<Vec<&'a str>>, } #[derive(Debug, Deserialize, PartialEq)] pub enum TerminusDurability { None, Configuration, UnsettledState, } impl Default for TerminusDurability { fn default() -> Self { TerminusDurability::None } } impl Serialize for TerminusDurability { ...
Rust
0
_mask); b_feature_map.mobility += N_MOB_SCORE[mobility_mask.count_ones() as usize]; b_feature_map.weak_king_attack_count += (wk_ring_mask & mov_mask).count_ones() as i32; b_feature_map.weak_king_attack_count += (bitmask.n_attack_masks[state.wk_index] & mov_mask).count_on...
Rust
0
hen Jan 1 is a Sunday) // - <NAME> Jr. Day (3rd Monday in January, only after 1998) // - Lincoln's Birthday (February 12th, only before 1954) // - Washington's Birthday (February 22nd, before 1971 with rule change in // 1964) // - Washington's Birthday (aka President's Day, 3rd Monday in February, // after 1970) //...
Rust
0
# Docstring with no newline def foobar(foor, bar={}): """ """
Python
1