text
string
label_name
string
labels
int64
"setup": "設定", "youtube_back": "返回", "youtube_forward": "前往", "download_mp3": "mp3", "download_mp4": "mp4", "youtubeMp3": "以 mp3 格式下載音訊", "youtubeMp4": "以 mp4 格式下載視訊", "youtube_mp3": "轉換為 mp3", "youtube_mp4": "轉換為 mp4", "youtube_address": "輸入 YouTube 網址:", "youtube_copy": "複製現...
Python
1
x_vec[1]); let green = utils::map_hex(hex_vec[2]) * 16 + utils::map_hex(hex_vec[3]); let blue = utils::map_hex(hex_vec[4]) * 16 + utils::map_hex(hex_vec[5]); Ok(Self { red, green, blue, }) } } #[cfg(test)] mod test { use super::*; #[test] fn from_hex_string() { ...
Rust
0
response = json.loads(body) model = models.DescribeFirmwareTaskResponse() model._deserialize(response["Response"]) return model except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise Tenc...
Python
1
n(&Self) + 'static>( &self, f: F, ) -> SignalHandlerId; } impl<O: IsA<FileChooserRequest>> FileChooserRequestExt for O { fn cancel(&self) { unsafe { ffi::webkit_file_chooser_request_cancel(self.as_ref().to_glib_none().0); } } fn get_mime_types(&self) -> Vec<...
Rust
0
# class Person: # country = "India" # def __init__(self,fn,ln,rollNo,age): # self.firstName = fn # self.lastName = ln # self.rollNo = rollNo # self.age = age # # instance method # def displayName(self): # print(self.firstName + self.lastName) # def update...
Python
1
Rsync::from_str( "rsync://host/module/\ $%&'()*+,-./0123456789:;=\ ABCDEFGHIJKLMNOPQRSTUVWXYZ_\ abcdefghijklmnopqrstuvwxyz~" ).is_ok() ); } #[test] fn rsync_from_str() { assert!(Rsync::from_str("").is_e...
Rust
0
()); } if trait_to_duplicate.is_some() { self.player_dna .simplified .insert(self.selected_gene + 1, trait_to_duplicate.unwrap()); self.decrease_charge...
Rust
0
type(ty, visited_ty)) { return ControlFlow::Continue(()); } trace!("exploring local {:?} with {:?}", self.local, ty); self.ty_stack.push(ty); match ty.kind() { _ if ty.is_box() => { self.place_stack.push(ProjectionElem::Deref); self.visit_ty(ty.boxed_ty()); sel...
Rust
0
ach": state_files.lxd_pro_config_file.write( state_files.LXDProConfig(guest_attach=LXDGuestAttachEnum.OFF) ) setattr(cfg, args.key, None) return 0 show_subcommand = ProCommand( "show", help=messages.CLI_CONFIG_SHOW_DESC, description=messages.CLI_CONFIG_SHOW_DESC, a...
Python
1
import platform import re from itertools import chain from verspec.loose import Version, Specifier, SpecifierSet, InvalidSpecifier from verspec.python import PythonVersion, PythonSpecifier, PythonSpecifierSet from .app_version import version as bfg_version from .exceptions import VersionError from .iterutils import it...
Python
1
/// use lcov::Reader; /// use lcov::reader::Error as ReadError; /// use lcov::record::ParseRecordError; /// let mut reader = Reader::new("FOO:1,2".as_bytes()); /// assert_matches!(reader.next(), Some(Err(ReadError::ParseRecord(1, ParseRecordError::UnknownRecord)))); /// # } /// ``` #[error("...
Rust
0
tree.insert(GeneralKey::key_from(val), val, &guard); } })); } for h in handlers.into_iter() { h.join().unwrap(); } let guard = crossbeam_epoch::pin(); for v in key_space.iter() { let val = tree.get(&GeneralKey::key_from(*v), &guard).unwrap(); ...
Rust
0
p)) self.conv = SSConv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=True, in_channels_ranges=('0', '1'), out_channels_ranges=self.dropout_ins[-1]) self.bn = SSBatchNorm2d(64, features_ranges=self.dropout_ins[-1]) self.relu = nn.ReLU(inplace=True)...
Python
1
} fn const_zero(typ: wasm::syntax::ValType) -> wasm::syntax::Const { use wasm::syntax::*; match typ { ValType::I32 => Const::I32(0), ValType::I64 => Const::I64(0), ValType::F32 => Const::F32(0.), ValType::F64 => Const::F64(0.), } } fn check_parametrics(rng: &mut rng::Rng, ...
Rust
0
"Reader of field `CAREF`"] pub type CAREF_R = crate::R<u8, CAREF_A>; impl CAREF_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CAREF_A { match self.bits { 0 => CAREF_A::CAREF_0, 1 => CAREF_A::CAREF_1, 2 => CAREF_A::CAREF_...
Rust
0
Remove(RemoveKind::File)), event( "rename.txt", FileEventKind::Modify(ModifyKind::Name(RenameMode::Any)), ), event( "modify.txt", FileEventKind::Modify(ModifyKind::Data(DataChange::Any)), ), event("any.txt", FileEventKind::Any), ]; assert_eq!( summarise_events_to_env(&events), HashMap::from(...
Rust
0
# Copyright 2020-2021,2024-2025 Ivan Yelizariev <https://twitter.com/yelizariev> # Copyright 2020-2021 Denis Mudarisov <https://github.com/trojikman> # Copyright 2021 Ilya Ilchenko <https://github.com/mentalko> # License MIT (https://opensource.org/licenses/MIT). { "name": "Sync 🪬 Studio", "summary": """Join ...
Python
1
mt::Formatter) -> fmt::Result { f.write_str("DragIcon") } } use std::fs; use crate::config; use crate::result::*; pub fn run() -> Result<()> { let mut removed_any = false; let path = config::access_token_path(); if path.exists() { fs::remove_file(&path)?; log::trace!("removed ...
Rust
0
_iter)?; if market.data.borrow()[0] != 0 { msg!("Market account is already initialized."); return Err(ProgramError::InvalidAccountData); } Ok(Self { market, clock_sysvar, oracle, admin, vault, }) } ...
Rust
0
either express or implied. // See the License for the specific language governing permissions and // limitations under the License. extern crate test_bin; use std::fs; use tempfile; const TEXT: &str = " Ah! well a-day! what evil looks Had I from old and young! Instead of the cross, the Albatross About my neck was hu...
Rust
0
# Copyright (c) 2017, Frappe and Contributors # License: GNU General Public License v3. See license.txt import frappe def execute(): frappe.db.sql( """ DELETE FROM `tabProperty Setter` WHERE doc_type in ('Sales Invoice', 'Purchase Invoice', 'Payment Entry') AND field_name = 'cost_center' AND property = '...
Python
1
from django.contrib import admin from api.models import Meal, Rating # Register your models here. class MealAdmin(admin.ModelAdmin): list_display = ('name', 'date') search_fields = ('name', 'date') list_filter = ('date', 'name') ordering = ('-date',) class RatingAdmin(admin.ModelAdmin): list_displ...
Python
1
1]) def test_user_defined_words_can_override_built_in_operators(self): self.assertEqual(evaluate([": + * ;", "3 4 +"]), [12]) def test_user_defined_words_can_use_different_words_with_the_same_name(self): self.assertEqual( evaluate([": foo 5 ;", ": bar foo ;", ": foo 6 ;", "bar foo"...
Python
1
from __future__ import absolute_import, division, print_function, with_statement from tornado.test.util import unittest class ImportTest(unittest.TestCase): def test_import_everything(self): # Some of our modules are not otherwise tested. Import them # all (unless they have external dependencies)...
Python
1
(); // spawns `baz` onto the task scheduler // `baz` has higher priority than `foo` so it immediately preempts `foo` c.spawn.baz().unwrap(); hprintln!("foo - end").unwrap(); } #[task] fn bar(_: bar::Context) { hprintln!("bar").unwrap(); debug::exit(debug::...
Rust
0
"simd")] fn bench_euclidean_distance_simd(bencher: &mut Bencher) { let a = &BENCH_ARRAY_1; let b = &BENCH_ARRAY_2; bencher.iter(|| euclidean_distance_simd(a, b)); } #[bench] fn bench_dot_product_no_simd(bencher: &mut Bencher) { let a = &B...
Rust
0
from .. import Provider as BankProvider class Provider(BankProvider): """Implement bank provider for ``fa_IR`` locale.""" bban_format = "IR########################" country_code = "IR" swift_bank_codes = ( "BEGN", "KESH", "BKMN", "BKBP", "CIYB", "BTOS",...
Python
1
# -*- coding: utf-8 -*- # # (c) 2018 Alberto Planas <aplanas@gmail.com> # # This file is part of KManga. # # KManga 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 3 of the License, or # (at you...
Python
1
son(player.clone())), // None => Err(ActixAnyhowError::from(anyhow!("player not found"))), // } // } // // // #[get("/players")] // pub async fn all_players( // world: web::Data<Arc<FactorioWorld>>, // ) -> Result<Json<Vec<FactorioPlayer>>, ActixAnyhowError> { // let mut all_players: Vec<FactorioPla...
Rust
0
> { #![allow(clippy::useless_conversion)] // fails to compile otherwise let ret = unsafe { syscall((SYS_setns as i32).into(), fd, nstype) }; if ret < 0 { let e = errno(); info!( LOGGER.0, "setns(); error, could not call SYS_setns for fd: {} and nstype: {}; errno: {}",...
Rust
0
| (A >> 7) // Affected Flags: Z (res), N (res), H (res), C (set|res) // Remarks: Carry is set if bit 7 is set, otherwise it is reset. // Timing: Instant. pub fn rlca(cpu: &mut Cpu) { cpu.regs.f = Flag::empty(); cpu.regs.f.set(Flag::C, cpu.regs.a >= 0x80); cpu.regs.a = (cpu.regs.a << 1) | (cpu.regs.a >> 7)...
Rust
0
v as i64); } // Noether blob file discardable ratio if let Some(v) = engine.get_property_int_causet(handle, LMDB_TITANDB_DISCARDABLE_RATIO_LE0_FILE) { STORE_ENGINE_TITANDB_BLOB_FILE_DISCARDABLE_RATIO_VEC .with_label_values(&[name, causet, "le0"]) ...
Rust
0
self.chainToAtomIndices = self.chainToAtomIndices[:chainCount + 1] self.chainToGroupIndices = self.chainToGroupIndices[:chainCount + 1] self.num_atoms = atomCount self.num_groups = groupCount self.num_chains = chainCount def chain_to_entity_index(...
Python
1
let epoch = atomic_epoch.load(Relaxed); assert_eq!(epoch.into_inner(), 0); } #[test] fn atomic_epoch_cas() { let atomic_epoch = AtomicEpoch::new(); let epoch = atomic_epoch.load(Relaxed); let prev = atomic_epoch.compare_and_swap(Epoch::new(), epoch + 1, Relaxed); as...
Rust
0
_grids.grids) grids_centers = mol_grids.grids_centers for grid_i,grid_i_index in zip(mol_grids.grids,range(num_grids)): #Dimensions : grid_i,grid_j,rad,ang,coordinates number_points = grid_i.number_points n_r,n_l = np.shape(grid_i.xyz_coords)[1:] xyz_coords = grid_i.xyz_coords....
Python
1
ppend(true) .create(true) .open(path)?; f.write_all(contents)?; Ok(()) })() .chain_err(|| format!("failed to write `{}`", path.display()))?; Ok(()) } pub fn mtime(path: &Path) -> CargoResult<FileTime> { let meta = fs::metadata(path).chain_err(|| format!("failed ...
Rust
0
# Pyrogram - Telegram MTProto API Client Library for Python # Copyright (C) 2017-present Dan <https://github.com/delivrance> # # This file is part of Pyrogram. # # Pyrogram 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 F...
Python
1
}) } None => Err(AgentError::from("Signing Error: No Valid Keys")) } } } /// Fetch the list of serial numbers for the connected Yubikeys /// The return from this function must be freed by the caller because we can no longer track it /// once we return #[no_mangle] pub extern fn l...
Rust
0
widgets = [first, previous, next, last, play, pause] self.bind_links(widgets) for widget in widgets: widget.SetBackgroundColour(wx.Colour(*BACKGROUND)) sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.AddSpacer(10) sizer.Add(first, 0, wx.TOP|wx.BOTTOM, 5) sizer...
Python
1
ket, CloseBracket, Pipe, Hash, Dollar, Zero, OpenBrace, CloseBrace, Arrow, Underscore, Slash, Exclam, And, Newline, } impl ControlChar { pub fn try_from_char(c: char) -> Option<ControlChar> { use self::ControlChar::*; match c { '.' => ...
Rust
0
str document, # type: Any *options, # type: AnalyzeDocumentSearchIndexOptions **kwargs # type: Dict[str, Any] ) -> Deferred[Dict[str, Any]]: super().analyze_document(index_name, document, *options, **kwargs) ...
Python
1
i * d["y"]) ), }, prefix="result_p_ux_uy", ) } solver = ppsci.solver.Solver( model, output_dir=cfg.output_dir, equation=equation, geom=geom, validator=validator, visualizer=visualizer, pretrained_model_path=...
Python
1
pkgname = "go-bootstrap" pkgver = "1.24.0" pkgrel = 0 # just in case depends = ["!go"] pkgdesc = "Go programming language bootstrap toolchain" license = "BSD-3-Clause" url = "https://go.dev" options = ["!strip", "!scanrundeps", "!lintstatic", "foreignelf", "execstack"] match self.profile().goarch: case "arm64": ...
Python
1
def __init__(self, vit_model='eva_clip_g', q_former_model= 'https://storage.googleapis.com/sfr-vision-language-research/LAVIS/models/BLIP2/blip2_pretrained_flant5xxl.pth' , img_size=224, drop_path_rate=0, use_grad_checkpoint=False, vit_precision='fp16', freeze_vit=True, has_qformer=True, freeze_qformer ...
Python
1
), { 'user_id': application.user_id, 'schedule_interview_id': schedule_interview.id }).first() if existing_applicant: user = db.query(User).filter(User.id == application.user_id).first() user...
Python
1
.len()].iter().all(|v| *v == 0xff), true, "Writing a non-erased area" ); data[offset..offset + buf.len()].copy_from_slice(&buf); responder.send(&mut Ok(())).unwrap(); ...
Rust
0
/// This is usually constructed for you using the the fluent builder returned by /// [`update_studio`](crate::client::Client::update_studio). /// /// See [`crate::client::fluent_builders::UpdateStudio`] for more details about the operation. #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct...
Rust
0
from typing import ( Type, ) from eth.rlp.blocks import BaseBlock from eth.vm.forks.constantinople import ( ConstantinopleVM, ) from eth.vm.state import BaseState from .blocks import IstanbulBlock from .headers import ( compute_istanbul_difficulty, configure_istanbul_header, create_istanbul_header...
Python
1
emp_dir: trees_file = temp_dir / "edit_trees.bin" trees.to_disk(trees_file) trees2 = trees2.from_disk(trees_file) # Verify that the nodes did not change. assert len(trees) == len(trees2) for i in range(len(trees)): assert trees.tree_to_str(i) == trees2.tree_to_str(i) # ...
Python
1
"""Gmail tools.""" from typing import TYPE_CHECKING, Any from langchain._api import create_importer if TYPE_CHECKING: from langchain_community.tools import ( GmailCreateDraft, GmailGetMessage, GmailGetThread, GmailSearch, GmailSendMessage, ) # Create a way to dynamica...
Python
1
let devices = prepare_devices(adapters); let mut ways = vec![0; devices.len()]; ways[0] = 1; for i in 1..devices.len() { let lower_limit = if i < 4 { 0 } else { i - 4 }; for j in (lower_limit..i).rev() { if devices[i] - devices[j] < 4 { ways[i] += ways[j]; ...
Rust
0
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
Python
1
ime}; pub(crate) static TRACER: AtomicLazyCell<Tracer> = AtomicLazyCell::NONE; pub(crate) struct Tracer { pub sampler: Box<dyn Sample + Sync + Send>, pub reporter: Box<dyn Report + Sync + Send>, pub local_endpoint: Endpoint, } /// Initializes the global tracer. /// /// The tracer can only be initialized ...
Rust
0
equations = { '1' : """dw_dot.i.Omega(m.rho, v, ddu) + dw_lin_elastic.i.Omega(m.C, v, u) - dw_piezo_coupling.i.Omega(m.e, v, p) = 0""", '2' : """dw_piezo_coupling.i.Omega(m.e, u, q) + dw_diffusion.i.Omega(m.kappa, q, p) - de_s...
Python
1
import streamlit as st from agents import Agent, AsyncOpenAI, OpenAIChatCompletionsModel, RunConfig, Runner from dotenv import load_dotenv, find_dotenv import os import nest_asyncio # Allow nested loops for Streamlit compatibility nest_asyncio.apply() # Load API key load_dotenv(find_dotenv()) gemini_api_key = os.gete...
Python
1
ffi::gdk_keymap_get_default()) } } #[doc(alias = "gdk_keymap_get_for_display")] pub fn for_display(display: &Display) -> Option<Keymap> { skip_assert_initialized!(); unsafe { from_glib_none(ffi::gdk_keymap_get_for_display(display.to_glib_none().0)) } } pub fn connect_direction_chan...
Rust
0
) # Display compact source list for filename, pages in sources_by_file.items(): if "N/A" not in pages: pages_str = ", ".join([f"p.{p}" for p in sorted(set(pages)) if p != "N/A"]) st.caption(f"📄 {fil...
Python
1
""" Logging configuration for the application. """ import logging import os import sys from datetime import datetime from typing import Dict, Any from app.config import get_settings class CustomFormatter(logging.Formatter): """Custom formatter adding colors to the logs.""" grey = "\x1b[38;20m" yello...
Python
1
dth { let dp = Point::new(dx + x, dy + y); let sp = Point::new(sx + x, sy + y); unsafe { dest.set_pixel_unchecked( dp, f(self.get_pixel_unchecked(sp), dest.get_pixel_unchecked(dp)), );...
Rust
0
::_110 } #[doc = "Checks if the value of the field is `_111`"] #[inline(always)] pub fn is_111(&self) -> bool { *self == IDHIT_A::_111 } } #[doc = "Identifier Acceptance Mode\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum IDAM_A { #[doc = "0: Two 32-...
Rust
0
PI_2: Decimal = Decimal::TWO_PI; /// -π pub const PI_MINUS: Decimal = dec!(-3.1415926535897932384626433833); /// -2π pub const PI_2_MINUS: Decimal = dec!(-6.2831853071795864769252867666); /// π/2 pub const PI_FRACT_2: Decimal = Decimal::HALF_PI; /// π/3 pub const PI_FRACT_3: Decimal = de...
Rust
0
#!/usr/bin/python # -*- coding: utf-8 -*- # # Developed by Shangchen Zhou <shangchenzhou@gmail.com> import os import utils.network_utils as net_utils from losses.losses import * from losses.metrics import * from time import time def mkdir(path): if not os.path.isdir(path): mkdir(os.path.split(path)[0]) ...
Python
1
let mut buffer = [0u8; 800]; //let mut number_of_bytes; match socket.recv(&mut buffer){ Ok(t) => { let state = deserialize::<GameState>(&buffer).expect("cannot crack ze coode"); if state.time.elapsed().unwrap() > readout_time.elapsed(){ return false; ...
Rust
0
# Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt import frappe from frappe import _ from frappe.query_builder.functions import Sum def execute(filters=None): columns = get_columns() data = get_data(filters) return columns, data def get_column...
Python
1
a = str(input('Введите пароль: ')) if len(a) < 8: print('Пароль не может содержать меньше восьми символов') if len(a) < 8: print('Пароль не может содержать меньше восьми символов') b = str(input('Повторите пароль: ')) if a == b: print('Пароль принят') else: print('Пароль не принят')
Python
1
s the first argument (known as source), and where to start looking /// for the line othertongue (inlined or not) as the second argument (known as the offset). /// /// ## Notes /// If there is no valid raw token found, it will return invalid raw token along with the probably /// last index checked. /// /// ## Examples /...
Rust
0
####################################################################### # Copyright (c) 2019-present, Blosc Development Team <blosc@blosc.org> # All rights reserved. # # This source code is licensed under a BSD-style license (found in the # LICENSE file in the root directory of this source tree) #######################...
Python
1
".to_string())); } #[test] pub fn last() { let text = "{{ list | last }}"; let options : LiquidOptions = Default::default(); let template = parse(&text, options).unwrap(); // array of numbers let mut data = Context::new(); data.set_val("list", Value::Array(vec![Value::Num(12f32), Value::Num(1...
Rust
0
#! /usr/bin/env python # import matplotlib.pyplot as plt import numpy as np DATA_DIR = 'data' USE_LOG = True fig, ax = plt.subplots(2, 1, figsize=(8, 6), constrained_layout=True) #ax =[ax] ax[0].set_title('Effective Area / System Temperature') hf = np.loadtxt(f'{DATA_DIR}/AeTsys_HF.dat', delimiter=',') ax[0].fill_bet...
Python
1
image_score(parse_image(input::puzzle_input(), 25, 6))); } type Layer = Vec<Vec<u32>>; type Image = Vec<Layer>; fn parse_image(input: &str, width: usize, height: usize) -> Image { let digits: Vec<u32> = input .chars() .map(|c| c.to_digit(10).unwrap()) .collect(); let layer_size = width * height; let mut lay...
Rust
0
, type = 'string', help = 'make rtconfig.h from config file.') AddOption('--global-macros', dest = 'global-macros', type = 'string', help = 'attach global macros in the project. '+\ 'e.g. scons --global-config=RT_USING_X...
Python
1
_enum_doc_attributes, } } pub(crate) fn display(&self, attrs: &[Attribute]) -> Result<Option<Display>> { let displaydoc_attr = attrs.iter().find(|attr| attr.path.is_ident("displaydoc")); if let Some(displaydoc_attr) = displaydoc_attr { let lit = displaydoc_attr ...
Rust
0
import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname), encoding='utf').read() setup( name="ULTRA", version="0.2.0", author="Qingyao Ai", author_email="aiqingyao@gmail.com", description=("TODO"), license="BSD", ...
Python
1
""" ./allure-pytest/examples/label/bdd/dynamic_bdd_label.rst """ import pytest from hamcrest import assert_that from tests.allure_pytest.pytest_runner import AllurePytestRunner from allure_commons_test.report import has_test_case from allure_commons_test.label import has_feature, has_epic, has_story def test_dynami...
Python
1
new().unwrap(); /// let local = task::LocalSet::new(); /// local.block_on(&rt, async { /// let join = task::spawn_local(async { /// let blocking_result = task::block_in_place(|| { /// // ... /// }); /// // ... /// }); /// join.await.unw...
Rust
0
_to[0], shape_to[-1] if a_to == 2 * a_from and z_to == z_from: var_to.assign(expand_1_axis(var_from_np, epsilon=epsilon, axis=0)) return if a_to == a_from and z_to == 2 * z_from: var_to.assign(expand_1_axis(var_from_np, epsilon=epsilon, axis=-1)) return if a_to == 2 * a_from and z_to == 2 * z_f...
Python
1
self .q_func .evaluate(s) .unwrap() .into_iter() .map(|v| { let v = (v / tau).exp(); z += v; v }) .collect(); ws.iter().map(|w| w / z).collect() } } #[cfg(test)] mod tests ...
Rust
0
slot.hash(state); self.finalized_checkpoint.hash(state); let headers: Vec<PendingShardHeader> = VariableList::into(self.current_epoch_pending_shard_headers.clone()); headers.hash(state); } } impl BeaconState { pub fn root(&self) -> Root { root(&self) } pub f...
Rust
0
use error::Error; const B: usize = 60; const F: usize = 30; pub type Word = u64; pub type Count = u32; pub type Bit = usize; pub struct Encoder<W> { inner: W, out_buf: u8, out_bits: usize, out_pending: usize, range: Word, low: Word, } impl<W: Write> Encoder<W> { pub fn new(wr...
Rust
0
! Mult(u64, u64), //! Result(u64), //! } //! //! lucet_hostcalls! { //! #[no_mangle] //! pub unsafe extern "C" fn hostcall_factorials( //! &mut vmctx, //! n: u64, //! ) -> u64 { //! fn fact(vmctx: &mut Vmctx, n: u64) -> u64 { //! let result = if n <= 1 { //! ...
Rust
0
attention_scores = torch.randn(batch_size, num_heads, seq_len, seq_len) masked_scores = causal_mask(attention_scores) print(f"因果掩码前形状: {attention_scores.shape}") print(f"因果掩码后形状: {masked_scores.shape}") # 测试RoPE rope = RotaryPositionalEncoding(d_model) x_rope = rope(x) print(f"RoPE输入...
Python
1
v[0]).")?; if args.len() != 1 { eprintln!("Usage:"); eprintln!(" {} <errno number | errno identifier>", exe_name); return Err("Invalid command line arguments".into()); }; let num_or_id = args.next().expect("Logic error: no num_or_id"); let result = if let Ok(num) = num_or_...
Rust
0
import sys sys.stdin = open('input.txt') ''' 시간 초과 발생 순열을 구하면 풀 수 있을 것 같지만... -> 실제로 풀 수는 있다. 그러나 만능인줄 알았던 itertools 마저... 엄청난 순열의 경우의 수는 견디지 못했다. ''' import itertools def cal(num1, num2, oper_idx): if oper_idx == 0: return num1 + num2 if oper_idx == 1: return num1 - num2 if o...
Python
1
Option<String>, //! #[serde(rename = "lastName")] //! pub last_name: String, //! } //! //! #[tokio::main] //! async fn main() -> Result<(), Box<dyn Error>> { //! let client = couch_rs::Client::new(DB_HOST, "admin", "password")?; //! let db = client.db(TEST_DB).await?; //! let find_all = FindQuery::...
Rust
0
strength: {}] ", input_map.get_action_strength("MOVE_BACKWARD_PLYR2") ); } if input_map.is_action_active("QUIT_APP_PLYR2") { println!("Player 2 Quiting..."); app_exit_events.send(AppExit); } // PLAYER 3 if input_map.is_action_active("BACK_PLYR3") { prin...
Rust
0
load_sfn_template(BaseTemplate.JSON_PATH_ARRAY_ACCESS) template["States"]["EntryState"]["Parameters"]["item.$"] = json_path_string definition = json.dumps(template) exec_input = json.dumps({"items": [{"item_key": i} for i in range(11)]}) create_and_record_execution( aws_clie...
Python
1
# Copyright 2017 Denis Leemann, Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models class CrmTeam(models.Model): _inherit = "crm.team" manual_delivery = fields.Boolean( help="If enabled, the deliveries are not created at SO confirmation....
Python
1
@require_torch_accelerator def test_from_pretrained_accelerate(self): model, _ = UNet2DModel.from_pretrained('fusing/unet-ldm-dummy-update', output_loading_info=True) model.to(torch_device) image = model(**self.dummy_input).sample assert image is not None, 'Make sure output is not None'
Python
1
its: u8, pub num_ref_idx_l0_default_active_minus1: u8, pub num_ref_idx_l1_default_active_minus1: u8, pub init_qp_minus26: i8, pub diff_cu_qp_delta_depth: u8, pub pps_cb_qp_offset: i8, pub pps_cr_qp_offset: i8, pub num_tile_columns_minus1: u8, pub num_tile_rows_minus1: u8, pub column_...
Rust
0
# Copyright (C) 2023-present The Project Contributors # # 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
void; pub type KeySpline = *mut ::core::ffi::c_void; #[repr(C)] #[doc = "*Required features: `\"UI_Xaml_Media_Animation\"`, `\"Foundation\"`*"] #[cfg(feature = "Foundation")] pub struct KeyTime { pub TimeSpan: super::super::super::super::Foundation::TimeSpan, } #[cfg(feature = "Foundation")] impl ::core::marker::Co...
Rust
0
0.29, 0.02, 0.01, ], f_shwith300: [ 0.0, 0.08, 0.25, 0.44, 0.57, 0.56, 0.62, 0.56, 0.35, 0.12, 0.0, 0.0, ], f_shwith500: [ 0.0, 0.0, 0.03, 0.18, 0.33, 0.35, 0.41, 0.28, 0.16, 0.01, 0.0, 0.0, ], }, SurfaceMonthlyRadiation { zone: B2c, ...
Rust
0
# -*- coding=utf-8 -*- from outwiker.core.htmlformatter import HtmlFormatter from outwiker.core.cssclasses import CSS_ERROR, CSS_IMAGE def test_image_no_common_classes(): content = 'image.png' formatter = HtmlFormatter() expected = f'<img class="{CSS_IMAGE}" src="{content}" />' assert formatter.imag...
Python
1
) -> &'static ::protobuf::reflect::MessageDescriptor { Self::descriptor_static() } fn new() -> AnnounceMessageDataList { AnnounceMessageDataList::new() } fn default_instance() -> &'static AnnounceMessageDataList { static instance: ::protobuf::rt::LazyV2<AnnounceMessageDataList>...
Rust
0
f" Error: Path {path_id} not explored by {self.username}.") # Example Usage: # user1 = User("u001", "Wanderer_7") # user2 = User("u002", "StarGazer_Prime") # echo1_user1 = user1.submit_echo("The quiet despair of a lost crop.", ["loss", "agriculture", "rural"]) # echo1_user1.set_signature(EmotionalSignature("Sorrow",...
Python
1
insert into codes ( id, date, used, user_id, code ) values ( $1, $2, $3, $4, $5 ) ", ) .bind(&code_id.to_string()) .bind(&now) .bind(false) .bind(&user_id.to_string()) .bind(&code) .execute(db.borrow_mut()) .await?; if let Some(smtp_transport) = app_state.smtp_tran...
Rust
0
.blit_color(&frame.geometry_buffer, &frame.default_framebuffer); } RenderSource::Shadowmap => { spot.gfx .renderer .blit_depth(&frame.shadow_buffer, &frame.default_framebuffer); } } // Render GUI ...
Rust
0
raft_txid; mod raft_types; mod table_info; mod table_reply; #[cfg(test)] mod cluster_test; #[cfg(test)] mod match_seq_test; use async_trait::async_trait; use tokio::sync::Mutex; use crate::cluster::{GetCompressor, GetConnection, ResponseCache}; use crate::error; use crate::frame::traits::AsBytes; use crate::frame::F...
Rust
0
(num, american)) .collect() }; static ref DWIM_STR_TO_NUMBER: DwimMap = { let mut map = DwimMap::new(); // TODO: add systematic names, alternative spellings for &(num, sym, american) in SPECIAL_NAMES { map.insert(sym, num); map.insert(american, ...
Rust
0
import time import tvm from flextensor.utils import Config from flextensor.task import Task from flextensor.scheduler import schedule, schedule_with_config from flextensor.measure import _evaluate def test(): # create an empty task but has the correct key we want task = Task("yolo1", None, (1, 3, 448, 448, 6...
Python
1