text
string
label_name
string
labels
int64
NE_SEC` constant. fn elapsed_time(&self) -> u64; /// One second in the instant units. const ONE_SEC: u64; } /// A new-type wrapper for std Instants and Metered's [Instant](trait.Instant.html) trait that /// measures time in milliseconds. #[derive(Debug, Clone)] pub struct StdInstant(std::time::Instant); i...
Rust
0
import sys if len(sys.argv) != 2: print("Provide points") sys.exit(1) points = sys.argv[1] l = points.split(",") paired = [(l[i], l[i+1]) for i in range(0, len(l), 2)] print(',\n'.join(f"{lat},{lon}" for lat,lon in paired))
Python
1
def save_model_card(args, repo_id: str, images=None, repo_folder=None): img_str = '' if len(images) > 0: image_grid = make_image_grid(images, 1, len(args.validation_prompts)) image_grid.save(os.path.join(repo_folder, 'val_imgs_grid.png')) img_str += '![val_imgs_grid](./val_imgs_grid.png)...
Python
1
""" Custom exceptions for the Discord bot, providing a structured error hierarchy. """ class BotBaseException(Exception): """Base exception for all custom exceptions in this bot.""" pass class ConfigurationError(BotBaseException): """Raised for errors in bot configuration, like missing keys or invalid ...
Python
1
l=[22,31,3,41,5,63,4] print(l) m=l.copy() # l and m both are same list m[0]=0 print(m) # again print l
Python
1
: Status = num::FromPrimitive::from_u8(s).unwrap(); Output{status, pressure, temperature} } // it's not safe to use I2C bus from different treads and therefore this driver is not // tread-safe either. // This should not be necessary since the actual implementations for I2C should not implement Sync // but I don't...
Rust
0
# 导入jieba模块,用于中文分词 import jieba # 导入matplotlib,用于生成2D图形 import matplotlib.pyplot as plt # 导入wordcount,用于制作词云图 from wordcloud import WordCloud, STOPWORDS # 获取所有个性签名 signatures = [] with open('friends.txt', mode='r', encoding='utf-8') as f: rows = f.readlines() for row in rows: signature = row.split(',')...
Python
1
= value else: attrs[(None, name)] = value return (_base.ELEMENT, namespace, self.filter.fromXmlName(tag), attrs, len(node) > 0 or node.text) def getFirstChild(self, node): assert not isinstance(node, tuple), "Text nodes have no children" ...
Python
1
self.rproof_pmmr .rewind(out_pos_rew, height as u32) .map_err(&Error::SumTreeErr)?; self.kernel_pmmr .rewind(kern_pos_rew, height as u32) .map_err(&Error::SumTreeErr)?; self.dump(true); Ok(()) } /// Current root hashes and sums (if applicable) for the UTXO, range proof /// and kernel sum trees. ...
Rust
0
calculates a new signature without knowledge of the key let forge_msg = b";admin=true"; // copy the original message and padding, without the secret key // represents info available to the attacker let mut full_forge_msg = orig_msg.to_vec(); let mut msg_padding = isha1::Sha1::pad_message(&full_ms...
Rust
0
rint(concat1) with tf.variable_scope('refine0'): concat0 = _refine( inp=concat1, num_outputs=32, features_direct=conv0_1, data_format=data_format, ) print(concat0) with tf.vari...
Python
1
prog).pos + 1, mode1, &mut err); let param2 = get(prog, (*prog).pos + 2, mode2, &mut err); let val = param1 * param2; set(prog, (*prog).pos + 3, mode3, val, &mut err); (*prog).pos += 4; }, 3 => { // input if (*input).read_pos < (*input).buff.len() { let input_val = (*input).buff[(*input)....
Rust
0
// /// # Arguments /// * `namespace` - A string that holds the namespace for the job /// * `queue` - A string that holds the queue name fn size(&self, namespace: String, queue: String) -> Result<u64, io::Error>; /// Destroy the queue /// /// # Arguments /// * `namespace` - A string that...
Rust
0
ET_HIGH; #[doc = "`read()` method returns [setup_packet_high::R](setup_packet_high::R) reader structure"] impl crate::Readable for SETUP_PACKET_HIGH {} #[doc = "`write(|w| ..)` method takes [setup_packet_high::W](setup_packet_high::W) writer structure"] impl crate::Writable for SETUP_PACKET_HIGH {} #[doc = "Bytes 4-7 o...
Rust
0
efault(); // when pool.import( TrustedOperation { data: vec![5u8], bytes: 1, hash: 5, priority: 5u64, valid_till: 64u64, requires: vec![vec![0]], provides: vec![], propagate: true, source: Source...
Rust
0
world, delta_time) } } pub fn delta_time(&self) -> f32 { unsafe { let stats = ecs_get_world_info(self.world).as_ref().unwrap(); stats.delta_time } } /** Signal application should quit. * After calling this operation, the next call to progress() returns false. */ pub fn quit(&self) { ...
Rust
0
{ assert!(cat.category_id < 16); // make sure category 0 is "unfiled" if cat.category_id == 0 { assert_eq!(cat.name_try_str().ok(), Some("Unfiled")); } } } // Test record iteration for (_idx, (rec_hdr, rec_data)) in (0..).zip(database.records.iter()) { assert_eq!(rec_data.len(), rec_hdr.data_l...
Rust
0
db.remove(key); match r { Ok(_) => Ok(()), Err(err) => Err(KvError::IoError(err.to_string())), } } fn max_key(&self) -> Result<Vec<u8>, KvError> { let last = self.db.last(); match last { Ok(last) => match last { Some((key, _)) ...
Rust
0
from fastapi import APIRouter, Depends, HTTPException, status from sqlmodel.ext.asyncio.session import AsyncSession from backend.app.api.routes.auth.deps import CurrentUser from backend.app.api.services.profile import create_user_profile from backend.app.core.db import get_session from backend.app.core.logging import ...
Python
1
#!/usr/bin/env python3 """ Sage 注入流程测试脚本 测试完整的记忆注入功能:向量索引、召回、重排、上下文压缩 """ import os import json import subprocess import sys import time from pathlib import Path def test_sage_injection(): """测试完整的 Sage 注入流程""" print("🚀 开始测试 Sage 记忆注入功能...") # 测试用例 test_cases = [ { "name...
Python
1
n v: #0f0;\ \n w: lime;\ \n x: rgba(0, 255, 0, 0.5);\ \n y: lime;\ \n z: #00ff01;\ \n}\ \nd {\ \n q: 1px solid silver;\ \n r: 1px solid #ddd;\ \n s: 1px solid green;\ \n t: 1px solid #00FF00;\ \n v: 1px solid #0f0;\ ...
Rust
0
et b = (x & 0xff) as u8; writer.write_u8(b)?; x >>= 8; } Ok(x) } fn update(x: u32, freq_i: u32, cfreq_i: u32) -> u32 { (x / freq_i) * 0x1000 + cfreq_i + (x % freq_i) } #[cfg(test)] mod tests { use super::*; #[test] fn test_rans_encode_with_order_0() -> io::Result<()> { ...
Rust
0
ary, Rare, Enchanted, Common, } let prize_list = [Prize::Legendary, Prize::Rare, Prize::Enchanted, Prize::Common]; // available prizes let slice = &prize_list; let weights = [1, 5, 15, 30]; // a scale of chance of picking each kind of prize let n = 1000000; let mut counter = [0usize; 4]; for _ in 0..n {...
Rust
0
from django import forms from .models import Projeto, Atividade # Classe ProjetoForm class ProjetoForm(forms.ModelForm): class Meta: model = Projeto exclude = ['usuario'] fiels = '__all__' def __init__(self, *args, **kwargs): # Função __init__ que herda de forms.ModelForm ...
Python
1
ipt = driver.find_element(By::Id("IdInput")).await?; id_ipt.send_keys(id).await?; let pw_btn = driver .find_element(By::XPath( "/html/body/div/div/div[2]/div/div/fieldset/ul/li[2]/input[2]", )) .await?; pw_btn.click().await?; let pw_ipt = driver.find_element(By::Id(...
Rust
0
mean_FID) # print("mean_KID_mean : ", mean_KID_mean * 100) # print("mean_KID_stddev : ", mean_KID_stddev * 100) fake_images_path = './vggface1way3shotNEW/test/' # mean_fid(fake_images_path) #### calculating the IS from whole dataset inception_score(fake_images_path) #### calculating the FIS from each categor...
Python
1
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models, api class ResConfigSettings(models.TransientModel): _inherit = 'res.config.settings' # pos.config fields pos_adyen_ask_customer_for_tip = fields.Boolean(compute='_compute_p...
Python
1
import time import random from pyrogram import Client, filters CMD = ["/", "."] @Client.on_message(filters.command("alive", CMD)) async def check_alive(_, message): await message.reply_text("𝖡𝗎𝖽𝖽𝗒 𝖨𝖺𝗆 𝖠𝗅𝗂𝗏𝖾 :) 𝖧𝗂𝗍 /start \n\n𝖧𝗂𝗍 /help 𝖥𝗈𝗋 𝖧𝖾𝗅𝗉 ;)\n\n\n𝖧𝗂𝗍 /ping 𝖳𝗈 𝖢𝗁𝖾𝖼𝗄 𝖡𝗈𝗍 ...
Python
1
t Some(reserved) = self.reserved_word_map.get(&val) { ret.append(&mut reserved.clone()); } let chars = val.chars(); let mut normal = String::new(); for mut ch in chars { if ch.is_ascii_alphabetic() { ch = ch.to_ascii_uppercase(); } ...
Rust
0
import pcobra # garantiza rutas para submódulos from unittest.mock import MagicMock, patch import pytest from ia import analizador_agix def test_generar_sugerencias_variable_descriptiva(): """Verifica que se retorne la sugerencia adecuada.""" instancia_falsa = MagicMock() instancia_falsa.select_best_mo...
Python
1
1], categories=[3, 2, 1], ordered=True, dtype='category') If the mapping is not one-to-one an :class:`~pandas.Index` is returned: >>> idx.map({'a': 'first', 'b': 'second', 'c': 'first'}) Index(['first', 'second', 'first'], dtype='object') If a `dict` is used, ...
Python
1
_to_pool(test_source(), tx.clone(), true, &header) .unwrap(); assert_eq!(write_pool.total_size(), 5); assert!(write_pool.stempool.is_empty()); } // Now check we can correctly deaggregate a multi-kernel tx based on current // contents of the txpool. // We will do this be adding a new tx to the pool ...
Rust
0
} fn main() -> Result<(), Box<dyn std::error::Error>> { let app = clparse::parse_command_line(); let app_matches = app.get_matches(); let (sub_command, sub_matches) = app_matches.subcommand(); let matches = sub_matches.unwrap_or_else(|| { clparse::parse_command_line().print_help().unwrap(); ...
Rust
0
: String = match tweet["id"].clone() { JsonValue::String(s) => s.to_string(), JsonValue::Number(n) => me(JsonValue::Number(n).clone()), _ => panic!("Invalid JSON"), }; let date: String = tweet["date"].clone().try_into().unwrap(); let username: String = tweet["...
Rust
0
mbourg Lv, // Latvia Ly, // Libya Ma, // Morocco Mc, // Monaco Md, // Moldova, Republic of Me, // Montenegro Mf, // Saint Martin (French part) Mg, // Madagascar Mh, // Marshall Islands Mk, // North Macedonia Ml, // Mali Mm, // Myanmar Mn, // Mongolia Mo, // Macao ...
Rust
0
oad_image(&mut images, ENEMY_LASER_SPRITE), //explosion: texture_atlases.add(texture_atlas), //}); } /* fn my_cursor_system( // need to get window dimensions wnds: Res<Windows>, // query to get camera transform q_camera: Query<&Transform, With<MainCamera>> ) { // get the primary window...
Rust
0
), fuc.FefferyFullscreen( id='task-mgmt-table-add-modal-editor-fullscreen', targetId='task-mgmt-table-add-modal-editor-mount-target', ), ...
Python
1
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. try: pass except ModuleNotFoundError: pass from torchtitan.config_manager import JobConfig as BaseJob...
Python
1
service::password_reset_init(&context, &email).into_json() } #[allow(clippy::needless_pass_by_value)] #[post("/password-reset/finish", format = "json", data = "<password_reset>")] fn password_reset_finish( password_reset: Json<PasswordWithResetToken>, context: UnauthContext, ) -> JsonResult<()> { service:...
Rust
0
# Code automatically generated from OptiMUS # Problem type: MIP # Problem description ''' A company can build two types of butcher shops: small shops that produce HotDogsPerSmallShop hot dogs per day and require WorkersPerSmallShop workers each, and large shops that produce HotDogsPerLargeShop hot dogs per day...
Python
1
1, }) } #[test] fn roundtrip_CMGT_asimdmisc_Z() { assert_eq!(Instruction::CMGT_asimdmisc_Z { Q: 1, size: 3, Rn: 31, Rd: 31, }.encode().decode(), Instruction::CMGT_asimdmisc_Z { Q: 1, size: 3, Rn: 31, Rd: 31, }) } #[test] fn roundtrip_CMEQ_asimdmisc_Z() { assert_eq!(Instruction::CMEQ_asimdmisc_Z...
Rust
0
configuration. pub fn enable( mut device: D, config: UartConfig, frequency: Hertz, ) -> Result<UartPeripheral<Enabled, D>, Error> { let effective_baudrate = configure_baudrate(&mut device, &config.baudrate, &frequency)?; // Enable the UART, both TX and RX device....
Rust
0
def replace_word(): str = "Hi i am Aafrith" word_to_replace = input("Enter the word to replace: ") new_word = input("Enter the new word: ") print(str.replace(word_to_replace, new_word)) replace_word()
Python
1
1 => self.y, 2 => self.z, _ => panic!("Swizzle index y out of range {:?}", idx_y), }; let z = match idx_z { 0 => self.x, 1 => self.y, 2 => self.z, _ => p...
Rust
0
alue> { self.params .iter() .rev() .find(|&&param| name == param.0) .map(|&(_, value)| value) } } impl<'a> WriteParams<'a> for MediaType<'a> { fn set_param<'n: 'a, 'v: 'a>(&mut self, name: Name<'n>, value: Value<'v>) { self.remove_params(name); ...
Rust
0
cation', 999968) power_improvement = (enh_power / trad_power) if trad_power > 0 else float('inf') print(f"✅ Power Allocation Improvement: {power_improvement:.0f}x") print(f"✅ Advanced Methods Impact:") print(f" - Traditional: {trad_power:.0f} kW allocated") pr...
Python
1
); } if let Some(x) = args.name { builder.add_name(x); } if let Some(x) = args.pos { builder.add_pos(x); } builder.add_hp(args.hp); builder.add_mana(args.mana); builder.add_equipped_type(args.equipped_type); builder.add_color(args.color); builder.finish() } pub const V...
Rust
0
{Pipeline, Exchange}; use timely::dataflow::operators::Operator; use timely::progress::Antichain; use differential_dataflow::{ExchangeData, Collection, AsCollection, Hashable}; use differential_dataflow::difference::{Semigroup}; use differential_dataflow::lattice::Lattice; use differential_dataflow::operators::arrange...
Rust
0
_subcommand) .subcommand(generate_completions_subcommand) .subcommand(infer_schema_subcommand) .setting(AppSettings::SubcommandRequiredElseHelp) } fn migration_dir_arg<'a, 'b>() -> Arg<'a, 'b> { Arg::with_name("MIGRATION_DIRECTORY") .long("migration-dir") .help( ...
Rust
0
mod utils; pub type Args = std::iter::Peekable<std::iter::Skip<std::env::Args>>; pub mod prelude { pub use { ::anyhow::{self, anyhow, bail, Context as _, Result}, log::{debug, error, info, trace, warn}, owo_colors::OwoColorize as _, }; } // Built-in deps // External deps use num::{rat...
Rust
0
rval = rhs.evaluate(); if rval == 0 { 0 } else { lhs.evaluate() / rval } } } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_add_expression() { let add_expr = ArithmeticExpre...
Rust
0
collections: &mut std::collections::HashMap<Plan<Self::Value>, Collection<S, Vec<Self::Value>, Diff>>, arrangements: &mut TraceManager<Self::Value>, ) -> Collection<S, Vec<Self::Value>, Diff> { let expressions = self.expressions.clone(); // TODO: re-use `tuple` allocation. self...
Rust
0
vendor_prefix: VendorPrefix::empty(), declarations: DeclarationBlock { important_declarations: vec![], declarations: vec![ Property::Custom(CustomProperty { name: "--ltr".into(), value: $ltr.into() }), Pr...
Rust
0
ption::Option::None; } pub fn has_appid(&self) -> bool { self.appid.is_some() } // Param is passed by value, moved pub fn set_appid(&mut self, v: u32) { self.appid = ::std::option::Option::Some(v); } // optional uint32 depotid = 2; pub fn get_depotid(&self) -> u32 { ...
Rust
0
a d@sNdZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl m Z m Z dZ ejZdad+ddZdd Zd d Zd d ZddZddZddZddZedejZddZGdddeZGdddeeZ Gddde!eZ"Gdd d e#eZ$Gd!d"d"eZ%Gd#d$d$e%Z&e&Z'd%...
Python
1
] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `SENSITIVE_REGION_PMS_CONSTRAIN_WORLD_0_AREA_6`"] pub type SENSITIVE_REGION_PMS_CONSTRAIN_WORLD_0_AREA_6_R = crate::R<u8, u8>; #[doc = "Write proxy for field `SENSITIVE_REGION_PMS_CONSTRAIN_WORLD_0_AREA_6`"] pub struct SENSITIVE_REGION_PM...
Rust
0
self.main_widgets["risk_chart"].clear() # Reload y_axis after clearing self.main_widgets["ohlc_chart"].addItem(self.y_value_label_forex, ignoreBounds = True) self.main_widgets["risk_chart"].addItem(self.y_value_label_risk, ignoreBounds = True) def show(self): self.main_widg...
Python
1
from tkinter import * from datetime import datetime import threading # Create the main window root = Tk() root.title("Digital Clock") root.geometry("380x150") root.resizable(False, False) root.config(bg="#2a2a2a") def update_time(): now = datetime.now() # Get the current time current_time = now.strftime...
Python
1
IntoNodes; use std::rc::Rc; #[allow(clippy::module_name_repetitions, clippy::type_complexity)] pub struct AppCfg<Ms, Mdl, INodes> where Ms: 'static, Mdl: 'static, INodes: IntoNodes<Ms>, { pub(crate) document: web_sys::Document, pub(crate) mount_point: web_sys::Element, pub(crate) update: Box<dy...
Rust
0
X64) => format!("{}-win64", project.title), (Platform::Windows, Bitness::X86) => format!("{}-win32", project.title), (Platform::MacOs, _) => format!("{}-macos", project.title), } } /// Get a platform-specific path to the app cache directory where LÖVE is stored. pub fn get_love_version_path( ve...
Rust
0
tate::Login> { #[tracing::instrument(skip(self))] pub async fn logout(self) -> Result<Session<state::Start>> { let mut logout_uri = reqwest::Url::parse(&self.login_uri).unwrap(); logout_uri.set_query(Some("op=logout")); info!("Logging out of Symphony..."); self.client...
Rust
0
ule.ms_deform_attn_forward( value, value_spatial_shapes, value_level_start_index, sampling_locations, attention_weights, im2col_step=ctx.im2col_step) ctx.save_for_backward(value, value_spatial_shapes, value_lev...
Python
1
} match client_node.trust_new_interval().await { Ok(_) => (), Err(ClientNodeError::NotConnected) => return, Err(e) => panic!("unexpected error {}", e), }; if !client_node.connected() { ...
Rust
0
v(&[smol(1), smol(3)]), // (11) Three facet bits (one beeg one smol). 0b1011 => av(&[beeg(0), smol(3)]), // (12) Two adjacent facet bits (one beeg triangle). 0b1100 => av(&[beeg(2)]), // (13) Three facet bits (one beeg one smol). 0b1101 => av(&[bee...
Rust
0
fn _mm512_abs_epi32(a: __m512i) -> __m512i { let a = a.as_i32x16(); // all-0 is a properly initialized i32x16 let zero: i32x16 = mem::zeroed(); let sub = simd_sub(zero, a); let cmp: i32x16 = simd_gt(a, zero); transmute(simd_select(cmp, a, sub)) } /// Computes the absolute value of packed 32-bit...
Rust
0
1-1-1.lib"#); static ARM64_API_MS_WIN_DX_D3DKMT_L1_1_0: &[u8] = include_bytes!(r#"../libs\arm64/api-ms-win-dx-d3dkmt-l1-1-0.lib"#); static ARM64_API_MS_WIN_GAMING_DEVICEINFORMATION_L1_1_0: &[u8] = include_bytes!(r#"../libs\arm64/api-ms-win-gaming-deviceinformation-l1-1-0.lib"#); static ARM64_API_MS_WIN_GAMING_EXPANDEDR...
Rust
0
_AFRL7W { w: self } } #[doc = "Bits 24:27 - Alternate function selection for port x bit y (y = 0..7)"] #[inline(always)] pub fn afrl6(&mut self) -> _AFRL6W { _AFRL6W { w: self } } #[doc = "Bits 20:23 - Alternate function selection for port x bit y (y = 0..7)"] #[inline(alway...
Rust
0
(&self) -> u8 { self.0 } pub fn minus_one(&self) -> Arity { Arity(self.0 - 1) } pub fn plus_one(&self) -> Arity { Arity(self.0 + 1) } } pub(crate) type JumpOffset = u16; use crate::vm::{ new_handle, DefinitionError, Module, ModuleLimitError, ObjClosure, ObjFn, Symbol,...
Rust
0
If n_steps not specified, derive from target_rollout import math n_steps_float = args.target_rollout / args.num_envs # Round up to nearest multiple of 8 for efficiency args.n_steps = math.ceil(n_steps_float / 8) * 8 print(f"n_steps not provided. Derived from target_rollout: {args...
Python
1
from dataclasses import Field from typing import TYPE_CHECKING, TypeVar from pypika import functions from pypika.dialects import RedshiftQuery from pypika.enums import Dialects from pypika.queries import QueryBuilder from pypika.terms import Term from weaverbird.backends.pypika_translator.dialects import SQLDialect f...
Python
1
Register (chid = 23)"] pub mod cda23; #[doc = "CNDA23 register accessor: an alias for `Reg<CNDA23_SPEC>`"] pub type CNDA23 = crate::Reg<cnda23::CNDA23_SPEC>; #[doc = "Channel Next Descriptor Address Register (chid = 23)"] pub mod cnda23; #[doc = "CNDC23 register accessor: an alias for `Reg<CNDC23_SPEC>`"] pub type CND...
Rust
0
id = i['id'] link = i['link'] chuyen(link, may) cache = tds.cache(id, 'TIKTOK_FOLLOW_CACHE') if cache != True: tg=datetime.now().strftime('%H:%M:%S') hien = f'{vang}[{red}X{vang}] {red}| {lam}{tg} {red}| {vang}FOLLOW {red}| {trang}{id} {red}|'; print(hien, end = '\...
Python
1
(ClassIdOf, TokenIdOf), } /// The module configuration trait. pub trait Config: system::Config + orml_nft::Config { type Event: From<Event<Self>> + Into<<Self as frame_system::Config>::Event>; /// Wallet Transfer Handler type Transfer: OnTransferHandler<Self::AccountId, Self::ClassId, Self::TokenId>; ...
Rust
0
d('颁'): 'bān', ord('颂'): 'sòng', ord('翁'): 'wēng', ord('胰'): 'yí', ord('脆'): 'cuì', ord('脂'): 'zhī', ord('胸'): 'xiōng', ord('脐'): 'qí', ord('胶'): 'jiāo', ord('脑'): 'nǎo', ord('脓'): 'nóng', ord('逛'): 'guàng', ord('狸'): 'lí', ord('狼'): 'láng', ord('卿'): 'qīng', ...
Python
1
"), include_str!("shaders/quartic.glsl"), include_str!("shaders/portal.glsl"), include_str!("shaders/fragment.glsl"), ); fn as_f32_array(v: &[f32]) -> js_sys::Float32Array { let memory_buffer = wasm_bindgen::memory() .dyn_into::<js_sys::WebAssembly::Memory>() .unwrap_throw() .bu...
Rust
0
state. Peer should be connected. let _ = exec.run_until_stalled(&mut futures::future::pending::<()>()); assert!(peer_handle.is_connected()); // Shouldn't be able to send data over the old channel. match remote.as_ref().write(&[0; 1]) { Err(zx::Status::PEER_CLOSED) => {} ...
Rust
0
Edit { pos: 11, kind: EditKind::Insert("123"), }, ); assert_eq!(text.as_str(), "abcd\r\nefg\r\n123hijklm\r\nno"); assert_eq!( doc_lines(lines), vec![doc_line(0), doc_line(6), dirty_doc_line(11), doc_line(22)] ); } #[test] fn insert_at_start() { let (mut tex...
Rust
0
imestamp): self.print_log("====================================================","restore") self.print_log("开始恢复插件数据","restore") self.print_log("如迁移机器未绑定宝塔用户并升级为专业版或企业版,将会出现插件还原失败等情况", "restore") restore_path=self.base_path + "/{timestamp}_restore/plugin".format(timestamp=timest...
Python
1
num_days if discounted_profit > 0: lower_bound = discount_rate else: upper_bound = discount_rate return discount_rate if __name__ == "__main__": # 设置参数 num_simulations = 1000 num_days = 180 initial_price = 100 drift = 0.05 volati...
Python
1
&Aabb3<f32>) -> bool { true && aabb1.min.x < aabb2.max.x && aabb1.min.y < aabb2.max.y && aabb1.min.z < aabb2.max.z && aabb2.min.x < aabb1.max.x && aabb2.min.y < aabb1.max.y && aabb2.min.z < aabb1.max.z } fn contains(aabb1: &Aabb3<f32>, aabb2: &Aabb3<f32>) -> bool { true && aabb1.min.x <= aabb2.min.x...
Rust
0
""" Test CSS loaders """ from django.conf import settings from django.test import TestCase from django.test import override_settings from django_inlinecss.css_loaders import StaticfilesFinderCSSLoader from django_inlinecss.css_loaders import StaticfilesStorageCSSLoader @override_settings(STATICFILES_DIRS=[settings....
Python
1
current_kbtype = getattr(self.cnfg, 'override_kbtype', 'Auto-Adapt') try: target_index = self.keyboard_types.index(current_kbtype) if self.keyboard_type_dropdown.get_selected() != target_index: debug(f"Updating keyboard type dropdown to {curren...
Python
1
def generate_recommendations(analysis_summary): recommendations = [] # Example logic for generating recommendations based on analysis summary if analysis_summary['risk_score'] > 7: recommendations.append("Consider reducing high-risk assets in your portfolio.") if analysis_summary['diversif...
Python
1
"AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use cgmath::matrix::*; use cgmath::vector::*; use test::Bencher; pub mod matrix2 { use cgmath::matrix::*; use cg...
Rust
0
em == "pop") and (ins.op1 in target): mod_type = "pop" mod_addr = ins.ea target = None break if target != None: target = target[0] return (target, mod_type, mod_addr) target = choose_backtrace_target(Scre...
Python
1
: Span, doit: bool) -> ast::ItemKind { match i { ItemKind::Mod(m) => { println!("is a mod"); ItemKind::Mod(self.mutate_mod(ecx, m)) }, ItemKind::Fn(decl, unsafety, abi, generics, body) => { if !doit { return ItemKind::Fn(decl, unsafety, abi, generics, body) ...
Rust
0
aTeX files. List of tuples # (source start file, target name, title, author, document class [howto/manual]). latex_documents = [ ('index', 'GrapeFruit.tex', 'GrapeFruit Documentation', 'Xavier Basty <xbasty@gmail.com>', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # th...
Python
1
""" Classifies: CHEBI:57643 1,2-diacyl-sn-glycero-3-phosphocholine """ """ Classifies: 1,2-diacyl-sn-glycero-3-phosphocholine Defined as: The conjugate base of a 1,2-diacyl-sn-glycero-3-phosphocholine compound formed by deprotonation of the phosphate OH group. """ from rdkit import Chem from rdkit.Chem import rdMolDe...
Python
1
01, 0x01, 0x01, 0x01, 0x01, 0x01, ]; let mut init_map_mutation = InitMapMutation::new(); let reader = StreamReader::new(&map_bytes); init_map_mutation.deserialize(&reader); assert_eq!(init_map_mutation.data, map_bytes); } #[test] fn serialize() { let map_byt...
Rust
0
("3k4/8/8/8/8/8/2n/K6q/N w - - 45 56", Square::B1, false), ]; for (bug_str, sq, expected) in &cases { let board = BughouseBoard::from_str(bug_str).unwrap(); let bb = BitBoard::from_square(*sq); assert!(board.blocks_check(bb) == *expected); } }...
Rust
0
# -*- coding: utf-8 -*- # @Time : 2020/12/19 # @Author : Lart Pang # @GitHub : https://github.com/lartpang import functools from datetime import datetime class TimeRecoder: __slots__ = ["_start_time", "_has_start"] def __init__(self): self._start_time = datetime.now() self._has_start = ...
Python
1
hb_var_int_t() { assert_eq!(::std::mem::size_of::<_hb_var_int_t>() , 4usize); assert_eq!(::std::mem::align_of::<_hb_var_int_t>() , 4usize); } impl Clone for _hb_var_int_t { fn clone(&self) -> Self { *self } } pub type hb_var_int_t = _hb_var_int_t; pub type hb_tag_t = u32; extern "C" { pub fn hb_tag_from...
Rust
0
from random import randrange import re def test_compare_contacts_on_homepage(app): index = randrange(len(app.contact.get_contact_list())) contact_from_home_page = app.contact.get_contact_list()[index] contact_from_edit_page = app.contact.get_contact_info_from_edit_page(index) assert contact_from_home_p...
Python
1
import requests import os # Base URL of your API BASE_URL = 'http://127.0.0.1:8088' # Change this to match your server def upload_single_excel(excel_file_path): """ Upload a single Excel file """ url = f'{BASE_URL}/api/import/' # Ensure file exists if not os.path.exists(excel_file_path):...
Python
1
True if edit_button: if original_jar is None: st.error("Please select a JAR file first.") else: # 重置完成状态 st.session_state.edit_completed = False # 创建步骤显示区域 step_container = st.container() with step_container: ...
Python
1
# -*- coding: utf-8 -*- from .upsample_initializer import UpsamplingDeconvWeight from .matting_link import MattingLink from .laplacian import matting_laplacian from .fcn8s import FCN8s from .fcn8s_matting import FCN8sMatting # logging from logging import getLogger, NullHandler logger = getLogger(__name__) logger.add...
Python
1
email = input("Enter your email address: ").strip().lower() UserName = email[:email.index("@")].capitalize() WebSite = email[email.index("@")+1:email.index(".")] Domain = email[email.index(".")+1:] print(f"Your User Name Is: {UserName}") print(f"Email Service Provider Is: {WebSite}") print(f"Top Level Domain Is : {Dom...
Python
1
faces.push(value); } // GNDX check_for_tag(offset, "GNDX")?; let vertex_groups_count = src.gread_with::<u32>(offset, ctx)?; let mut vertex_groups = Vec::new(); for _ in 0..vertex_groups_count { let value = src.gread_with::<VertexGroup>(offset, ctx)...
Rust
0
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse from alipay.aop.api.domain.SupervisionBillInfo import SupervisionBillInfo class AlipayEbppIndustrySupervisionBillBatchqueryResponse(AlipayResponse): def __init__(self): super(Alipa...
Python
1
e key file must /// not require a passphrase (e.g. was created with the `-nodes` option on /// openssl). NB: There is a bug/behaviour in Mac OS X that prevents opening /// unencrypted key files. pub fn load_from_pem_files<P: AsRef<Path>, Q: AsRef<Path>>( cert_file: P, key_file: Q, ) ...
Rust
0