text
string
label_name
string
labels
int64
!("value for key `{}` must be an f64", key) }; if range.contains_value(&value) { Ok(value) } else { err_fmt!("value `{}` for key `{}` exceeds range {:?}", value, key, range) } } /// Tries to parse a list of `NestedExtMeta` as name-value pairs of the given /// type. Err...
Rust
0
#[cfg(test)] use proptest::prelude::*; #[cfg(test)] proptest! { #[test] fn encrypted_ciphertext_roundtrip(ec in any::<EncryptedNote>()) { zebra_test::init(); let mut data = Vec::new(); ec.zcash_serialize(&mut data).expect("EncryptedNote should serialize"); let ec2 = Encrypt...
Rust
0
await, None); assert!(stream.is_terminated()); } #[fuchsia_async::run_singlethreaded(test)] async fn when_done_skips_closure_if_missing_complete() { let (send, recv) = oneshot::channel(); futures::pin_mut!(recv); let evil_stream = stream::iter(vec![GeneratorStat...
Rust
0
irection : VoxelAxis) -> T { match direction { VoxelAxis::PosiX => return self.upper.x, VoxelAxis::PosiY => return self.upper.y, VoxelAxis::PosiZ => return self.upper.z, VoxelAxis::NegaX => return self.lower.x, VoxelAxis::NegaY => return self.lower.y, ...
Rust
0
inar.grid(row=0, column=0, padx=(0, 5), pady=2, sticky="w") btn_iniciar = ctk.CTkButton(frame_botones, text="Start", command=iniciar_ejecucion_en_hilo, fg_color="#3A3A4D", hover_color="#276749") btn_iniciar.grid(row=0, column=1, padx=5, pady=2) btn_detener = ctk.CTkButton(frame_botones, text="Stop", command=detener_...
Python
1
t, ) { if let Some(var_44) = &input.fleet_arn { object.key("FleetArn").string(var_44); } if let Some(var_45) = &input.max_results { object.key("MaxResults").number( #[allow(clippy::useless_conversion)] smithy_types::Number::NegInt((*var_45).into()), ); } ...
Rust
0
atch[k] = batch[k].to('cuda', non_blocking=False) else: batch = batch.to('cuda', non_blocking=False) # Execute one training step clear_grad_flag = (step_inner == 0) update_param_flag = (step_inner == iter_size - 1) loss_dict = train_step_fn(st...
Python
1
# -*- coding: utf-8 -*- # Scrapy settings for MySpider project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # https://doc.scrapy.org/en/latest/topics/settings.html # https://doc.scrapy.org/en/latest/topi...
Python
1
filename(&$fn)}) }}; } macro_rules! rpt_push_fname { ($fn:expr) => {{ REPORTER.with(|log| {log.borrow_mut().push_filename(&$fn)}) }}; } macro_rules! rpt_pop_fname { () => {{ REPORTER.with(|log| {log.borrow_mut().pop_filename()}) }}; } macro_rules! rpt { ($id:expr, $node:expr, $txt:expr) => {{ REPORTER.wi...
Rust
0
batched_amrs = Batch.from_data_list(amrs) # concate batched_edge_index = batched_amrs.edge_index.to(device) amr_token_feats = amr_token_feats.permute(1,0,2) decoder_layer_preds = {} # bt (V+E)max h w, bt*head (V+E)max hw out_mask, out_box, _ = self.forward_refdecoder_hea...
Python
1
::VMemoryUse => { self.vmemoryuse_bytes.with_label_values(labels).set(value); }, rctl::Resource::Wallclock => { let inc = self.update_metric_book( name, &BookKept::Wallclock(value as u64) ...
Rust
0
let pkgfs = PkgfsRamdisk::builder() .blobfs(blobfs) .system_image_merkle(system_image_package.meta_far_merkle_root()) .start() .unwrap(); let d = pkgfs.root_dir().expect("getting pkgfs root dir"); assert_eq!(ls_simple(d.list_dir("packages/example").unwrap()).unwrap(), ["0"])...
Rust
0
fpvec_eq!(Matrix::eye(m), &u.t() * &u, 1e-5); // make sure input V is unitary assert_fpvec_eq!(Matrix::eye(n), &v * &v.t(), 1e-5); assert_fpvec_eq!(Matrix::eye(n), &v.t() * &v, 1e-5); let mut sigma = Matrix::zeros(m, n); for i in 0..m { for j in 0..n { ...
Rust
0
boundry.y + boundry.height as i32 - 4, 4, 4, ), ) .unwrap(); gfx.canvas .copy( &gfx.textures.tilemap, SdlRect::new(corner_rect.x() + 3, corner_rect.y(), 1, 4), SdlRec...
Rust
0
: [ c.get(2)?.as_str().parse().ok()?, c.get(3)?.as_str().parse().ok()?, c.get(4)?.as_str().parse().ok()?, ], }) }) }) .collect(); Program { ...
Rust
0
bounded_upper() -> TestProblem { let mut prob = Problem::new(); prob.add_var(2., Bound::Upper(0.), Some("x1".to_string())) .unwrap(); assert_unbounded!(prob) } pub fn one_variable_unbounded_free() -> TestProblem { let mut prob = Problem::new(); prob.add_var(2., Bound::Free, Some("x1".to_...
Rust
0
m_delay:min_len] else: non_stream_out = non_stream_out[shift:min_len - sum_delay] stream_out = stream_out[sum_delay + shift:] self.assertAllEqual(non_stream_out.shape, (31-sum_delay,)) self.assertAllClose(stream_out, non_stream_out) @parameterized.parameters(False, True) def test_delay_inter...
Python
1
OS calls return results in kilobytes.) let basemem = nvram_read(kclock::NVRAM_BASELO) as u32; let extmem = nvram_read(kclock::NVRAM_EXTLO) as u32; let ext16mem = (nvram_read(kclock::NVRAM_EXT16LO) as u32) * 64; let totalmem = if ext16mem > 0 { 16 * 1024 + ext16mem } else if extmem > 0 { ...
Rust
0
elf.id, 'planned_acceptance_flow_id': vals['planned_acceptance_flow_id'], 'amount': vals.get('amount', self.amount) }) elif 'amount' in vals and self.planned_acceptance_flow_id: distribution = self.env['project_budget.distri...
Python
1
#! /usr/bin/python # -*- coding: utf8 -*- from sklearn import datasets from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt import numpy as np from keras.datasets import mnist from keras.models import Model from keras.layers import Dense, Input mnist_data=datasets.load_digits() X_train...
Python
1
C, VAR_CONST, VAR_DISPATCH, }} pub const IMPLTYPEFLAG_FDEFAULT: DWORD = 0x1; pub const IMPLTYPEFLAG_FSOURCE: DWORD = 0x2; pub const IMPLTYPEFLAG_FRESTRICTED: DWORD = 0x4; pub const IMPLTYPEFLAG_FDEFAULTVTABLE: DWORD = 0x8; UNION!{union VARDESC_u { [usize; 1], oInst oInst_mut: ULONG, lpvarValue lpvar...
Rust
0
avedData::new(), forward_curves: HashMap::new(), vol_surfaces: HashMap::new() } } } impl Saveable for SavedPrefetch { fn as_any(&self) -> &Any { self } fn as_mut_any(&mut self) -> &mut Any { self } fn clear(&mut self) { self.saved_data.clear(); self.forward_curv...
Rust
0
_APPLICATION_NAME; use exec::executor::execute_external_command_for_output; use libs::process::SystemBinary; use libs::scm::{CheckoutError, ScmService, ScmUrl}; use std::collections::HashMap; pub fn build_service_map(sub_commands: &AvaliableCommands) -> HashMap<String, Box<ScmService>> { let mut result: HashMap<St...
Rust
0
') ph_count: int = 0 for bq_tag in blockquote_tags: ph_count += 1 ph_tag = cloze_scope.new_tag('blockquote') ph_tag['id'] = f'ph-{ph_count}' bq_tag.replace_with(ph_tag) # find all cloze-deletion, avoid including child tag, skip if empty clo...
Python
1
&DbfType::FloatingPoint => { write!(fmt, "DbfType::FloatingPoint") } &DbfType::Timestamp => { write!(fmt, "DbfType::Timestamp") } &DbfType::Double => { write!(fmt, "DbfType::Double") } &DbfType::Long => { write!(fmt, "DbfType::Long") } &DbfType::Unsupported =...
Rust
0
conn.execute( "INSERT INTO blocks (height, hash, time, sapling_tree) VALUES (?, ?, ?, ?)", &[ u32::from(height).to_sql()?, hash.0.to_sql()?, time.to_sql()?, sapling_tree.to_sql()?, ], )?; Ok(()) } #[cfg(test)] mod tests { use ...
Rust
0
from pathlib import Path import asyncio from db_models import Message from db_sdk import Database # path to this agent's database db_path = Path(__file__).parent / "RecvAgent_1.db" db = Database(db_path) async def main(): # Fetch all distinct client addresses rows = await Message.find(db) addresses = sort...
Python
1
from datetime import datetime import json import os data_file = 'admin/user_data.json' def load_data(): """Загружает данные профилей из файла.""" if not os.path.exists(data_file): return {"last_sent": {}, "channel_ids": []} # Если файла нет, возвращаем структуру по умолчанию try: with ope...
Python
1
ersions .last() .unwrap() .header .height, difficulty: stats.pow_difficulty, accepted: stats.num_accepted, rejected: stats.num_rejected, stale: stats.num_stale, }; let response = serde_json::to_value(&status).unwrap(); return Ok(response); } // Handle GETJOBTEMPLATE message fn handl...
Rust
0
scores.len(); } } fn calc_part_one(after: usize) -> Vec<usize> { let mut scores: Vec<usize> = vec![3, 7]; let mut positions = vec![0, 1]; while scores.len() < after + 10 { add_scores(&mut scores, &mut positions); } scores.iter().skip(after).take(10) .map(|v| *v) .colle...
Rust
0
cceptprob = logpprime - logp0 - (rprime.dot(&rprime) - r0.dot(&r0)) * half; let a = if logacceptprob > half.ln() { T::one() } else { -T::one() }; while a * logacceptprob > -a * two.ln() { epsilon = epsilon * two.powf(a); let a = leapfrog(theta0, &r0, &grad0, epsilon, fg...
Rust
0
eq!( "The feature `ipfsOnEthereumContracts` is used by the subgraph but it is not declared in the manifest.", error_msg ); }); } #[test] fn declared_ipfs_on_ethereum_contracts_feature_causes_no_errors() { const YAML: &str = " specVersion: 0.0.4 schema: file: /: /ipfs/Qmsch...
Rust
0
_tts_loading_status["message"] = "正在验证服务状态..." # 更新请求状态中的当前模型信息 fastapi_request.app.state.current_tts_model_id = model_id fastapi_request.app.state.current_tts_character_name = config.character_name # 更新状态为完成 _tts_loading_status["status"] = "completed" _tts_loading_stat...
Python
1
let shape = ndarray_ext::as_shape(&ctx.input(0)); ctx.append_output(self.arr_rng.bernoulli(shape.as_slice(), self.p)); } fn grad(&self, ctx: &mut crate::op::GradientContext<T>) { ctx.append_input_grad(None); } } impl<R: Rng, T: Float> op::Op<T> for Exponential<T, R> { fn compute(&self...
Rust
0
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
Python
1
import numpy as np def transform_snorkel_matrix_to_z_t(class_matrix: np.ndarray) -> [np.ndarray, np.ndarray]: """Takes a matrix in format used by e.g. Snorkel (https://github.com/snorkel-team/snorkel) and transforms it to z / t matrices. Format - class_matrix_ij = -1, iff the rule doesn't apply ...
Python
1
rshaller { ser: ::grpcio::pb_ser, de: ::grpcio::pb_de }, }; const METHOD_OBJECT_API_DELETE_OBJECTS: ::grpcio::Method<super::pfs::DeleteObjectsRequest, super::pfs::DeleteObjectsResponse> = ::grpcio::Method { ty: ::grpcio::MethodType::Unary, name: "/pfs.ObjectAPI/DeleteObjects", req_mar: ::grpcio::Marshaller...
Rust
0
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
Python
1
ctc2tc3((s cookielib.pyRVs    cCstd|j|jjzrttj|j_|_xL|j||D]8}|jj ||rUtd||j |qUqUWWd|jj XdS(sAExtract cookies from response, where allowable given th...
Python
1
ation, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the followi...
Rust
0
# ), dim=1) # in_degree = pyg_utils.degree(support_edge[1], num_nodes=mesh_pos.shape[0]) # out_degree = pyg_utils.degree(support_edge[0], num_nodes=mesh_pos.shape[0]) # node_degree = in_degree + out_degree # print("Degree max, mean ,min:", node_degree.max(), node_...
Python
1
len >= 8 { return ( start.add(8), len - 8, u64::from_le((start as *const u64).read_unaligned()), ); } let res = read_partial_u64(start, len); (start, 0, res) } #[inline] unsafe fn read_partial_u64(start: *const ...
Rust
0
Ouster tweaks to the theme to handle logo size, fonts, etc. html_css_files = [ 'css/ouster_rtd_tweaks.css', ] # -- Extension configuration ------------------------------------------------- # use both class and constructor docstrings autoclass_content = 'both' # do not alphabetize class members autodoc_member_orde...
Python
1
"""Base trait model for Coterie.""" from typing import Optional, TYPE_CHECKING from sqlalchemy import String, Integer, ForeignKey from sqlalchemy.orm import Mapped, mapped_column, relationship from .base import Base if TYPE_CHECKING: from .character import Character class Trait(Base): """Base class for char...
Python
1
characters as possible, excluding those that appear at the /// start of other inline parsers e.g. '$', '[' fn string(input: &str) -> IResult<&str, InlineContent> { const CHARS: &str = "@^~$["; map_res( take_while1(|chr: char| CHARS.contains(chr)), |res: &str| -> Result<InlineContent> { Ok(Inline...
Rust
0
(T::new(ComPtr::from_raw(shader))) }; let instances = if instances == std::ptr::null_mut() { None } else { let c_instances = Vec::from_raw_parts( &mut instances, instances_num as usize, instances_num as usize, );...
Rust
0
let k = device_state.get_keys(); if k.is_empty(){ enigo.key_sequence_parse("{+CTRL}c{-CTRL}"); break; } thread::sleep(ten_millis); ...
Rust
0
take(proof.public.len()).map(|l| l).collect(), &proof.public.iter().map(|s| -*s).collect(), ); let (mut sponge, digest_before_evaluations, o, _, p_eval, _, _) = proof.oracles::<DefaultFqSponge<TweedledeeParameters, PlonkSpongeConstants>, DefaultFrSponge<Fp, PlonkSpongeConstants>>(index, &p_comm)...
Rust
0
Serialization and deserialization support for sshkeys #[cfg(feature = "serde")] mod serde; pub use self::cert::{CertType, Certificate}; pub use self::error::{Error, Result}; pub use self::keytype::{KeyType, KeyTypeKind}; pub use self::pubkey::{ Curve, CurveKind, DsaPublicKey, EcdsaPublicKey, Ed25519PublicKey, Fin...
Rust
0
__ImageSpec_assign as OIIO_ImageSpec_assign; pub use c_imageio::OpenImageIO_v2_2__ImageInput_format_name as OIIO_ImageInput_format_name; pub use c_imageio::OpenImageIO_v2_2__ImageInput_geterror as OIIO_ImageInput_geterror; pub use c_imageio::OpenImageIO_v2_2_roi_union as OIIO_roi_union; pub use c_imageio::OpenImageIO_v...
Rust
0
fn dump(&self, out: &mut dyn io::Write) -> io::Result<()> { (**self).dump(out) } } impl<'a, T: Store + ?Sized> Store for Box<T> { type Size = T::Size; fn get(&self, page: PageId) -> &[u8] { (**self).get(page) } fn dump(&self, out: &mut dyn io::Write) -> io::Result<()> { (**self).dump(out) } } impl<'a...
Rust
0
ssageType], symbols: &[String], subscribe: bool, _configs: Option<&HashMap<String, String>>, ) -> Vec<String> { msg_types .iter() .map(|msg_type| msg_type_to_channel(*msg_type)) .flat_map(|channel| { symbols .iter() .map(|symbol| channe...
Rust
0
"""Error classes for SQLFlow.""" from typing import Any, Dict, List, Optional class SQLFlowError(Exception): """Base class for all SQLFlow errors.""" def __init__(self, message: str): """Initialize a SQLFlowError. Args: ---- message: Error message """ se...
Python
1
#*************************************************************************************** # Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences # Copyright (c) 2020-2021 Peng Cheng Laboratory # # XiangShan is licensed under Mulan PSL v2. # You can use this software according to the ter...
Python
1
None => break, // empty Some(x) => x, }; program.set(pc, Operation { op: OP_LOOP_END, ex: pc_jmp as u32 }); let mut op = program.get(pc_jmp); op.ex = pc as u32; program.set(pc_jmp, op); ...
Rust
0
mut OsRng, secp: &Secp256k1<All>, grin_core: &mut GrinCore, btc_core: &mut BitcoinCore, grin_tx: &mut GrinTx, ) -> Result<(), String> { set_local_chain_type(grin_core::global::ChainTypes::Testnet); println!("Starting setup phase MW"); slate.pub_slate.status = crate::enums::SwapStatus::SETUP;...
Rust
0
.entry(template.as_bytes()[0] as char).or_default() += 1; let max = counts.iter().max_by_key(|(_, i)| *i).unwrap().1; let min = counts.iter().min_by_key(|(_, i)| *i).unwrap().1; max - min } <filename>parser/src/syntaxes/type.rs use super::*; // type Person = { name : String, dead : Bool } // type Dog[T] = ...
Rust
0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models, _ from odoo.exceptions import UserError class PosConfig(models.Model): _inherit = 'pos.config' it_fiscal_printer_https = fields.Boolean(string='Use HTTPS') it_fiscal_printer_ip = fields.Char(strin...
Python
1
::HKDF_SHA256) } pub fn expand<E: Encode, L: KeyType>( salt: &HmacKey, info: &E, out_buf: &mut [u8], key_type: L, ) -> Result<()> { let encoded_info = info.encode(); ring::hkdf::Prk::new_less_safe(ring::hkdf::HKDF_SHA256, &salt.as_bytes()) .expand(&[&encoded_info], key_type)? ....
Rust
0
gacyRemoteDebuggerAuthenticate request must be sent first.', ) self.set_exit() return try: debug_options = vspd.parse_debug_options(args['debugOptions']) if self.__redirect_output: debug_options.add('RedirectOutput') if vs...
Python
1
_hz: u64) { pic::unmask(PIT_INTERRUPT_NUMBER); unsafe { // Reset the Programmable Interval Timer (PIT). outb( PIT_COMMAND_PORT, PIT_BINARY_OUTPUT | PIT_RATE_GENERATOR_MODE | PIT_LOBYTE_ACCESS | PIT_HIBYTE_ACCESS | PIT_CHANNEL0, ); // Calculate the reload value to count down (round it t...
Rust
0
bject_ids = draw_lines(stage, filepath, names=names, fill='#ff8000', transform=transform) for object_id in object_ids: stage.canvas.lower(object_id) stage.canvas.update() @clean_slate def icecream(stage): transform = T(scale=7.7, dx=-3000, dy=-2400) draw_coastline(stage, transform=transform) ...
Python
1
class Employee: # Class variable to count the number of employees employee_count = 0 def __init__(self, name, family, salary, department): # Instance variables self.name = name self.family = family self.salary = salary self.department = department # Incremen...
Python
1
let vesting_creator = ensure_signed(origin)?; // check the account is present in the storage ensure!(VestingAccount::<T>::contains_key(&vesting_creator, &uid), Error::<T>::VestingAccountDoesNotExist); // decode data let content: Vec<u8> = VestingAccount::<T>::get(vesting_creator.clone(), &uid); let in...
Rust
0
, 11, 9, 1, no, yes, 5, 9), $crate::sc!(29, 11, 9, 2, no, yes, 3, 9), $crate::sc!(30, 11, 9, 3, no, yes, 7, 9), $crate::sc!(31, 11, 9, 4, yes, yes, 1, 9), $crate::sc!(32, 12, 10, 1, no, yes, 5, no), $crate::sc!(33, 12, 10, 2, no, yes, 3, no), $crat...
Rust
0
_driver()) .add_system_set_to_stage(Stage::EndTurn, State::<TurnState>::get_driver()) // AwaitingInput .add_system_set_to_stage( Stage::BeforeCombat, SystemSet::on_update(TurnState::AwaitingInput).with_system(player_input), ) ...
Rust
0
oduct", price=100, is_active=True) # İlk ProductUpdateRequest yaradılır ProductUpdateRequest.objects.create( product=product, status=ProductUpdateRequest.PENDING, data={}, # boş dict əlavə edilir ) client = APIClient() client.force_authenticate(user=user) url = revers...
Python
1
ng_seed = seed_split.concat(); let mut rng = Xoshiro256StarStar::from_seed(rng_seed.try_into().unwrap()); let start_pos = ICoord::new( rng.gen_range(0..WORLD_SIZE / 10), rng.gen_range(0..WORLD_SIZE), ); let end_pos = ICoord::new( rng.gen_range(WORLD_SIZE * 9 / 10..WORLD_...
Rust
0
Outside if: {}", (&p - &r)); &p - &r } pub struct EdwardsPoint { pub X: [u64; 5], pub Y: [u64; 5], pub Z: [u64; 5], pub T: [u64; 5] } impl Debug for EdwardsPoint { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, " EdwardsPoint {{ ...
Rust
0
f cauhinh(idfb): run = requests.get(f'https://traodoisub.com/api/?fields=run&id={idfb}&access_token={tokentds}').json() if run.get('success'): print('', end='\r') else: print(run.get('error', 'Unknown error')) cookiefb=input(f'\033[1;97m[\033[1;91m❣\033[1;97m] \033[1;36m✈ \033[1;32mNhập Co...
Python
1
F00_0000,// Movntss_m32_xmm 0x0000_0037, 0x7F00_0000,// Movntsd_m64_xmm 0x0000_0037, 0x7900_0000,// Cvttps2pi_mm_xmmm64 0x0000_0037, 0x7A00_0000,// Cvttpd2pi_mm_xmmm128 0x0000_0037, 0x7900_0000,// Cvttss2si_r32_xmmm32 0x0000_0037, 0x7900_0000,// Cvttss2si_r64_xmmm32 0x0000_0037, 0x0F00_0001,// VEX_Vcvttss2si_r32_...
Rust
0
ileFound, } // The MIT License (MIT) // // Copyright (c) 2017 Doublify Technologies // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the...
Rust
0
le stats.register("std", np.std, axis=0) #@UndefinedVariable stats.register("min", np.min, axis=0) #@UndefinedVariable stats.register("max", np.max, axis=0) #@UndefinedVariable return stats _has_been_setup = False def _setup(self, refiner, ngen=NGEN, ngen_comm=NGEN_COMM, nswarms...
Python
1
uirqsel15; #[doc = "Output Selection for CPU Interrupt 16\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [cpuirqsel16](cpuirqsel16) module"] pub type CPUIRQSEL16 = crate::Reg<u32, _CPUIRQSEL16>; #[...
Rust
0
ct(color='blue') )) fig.add_trace(go.Scatter( x=daily_sales['sale_date'], y=daily_sales['net_profit'], mode='lines+markers', name='Profit', line=dict(color='green') )) fig.update_layout(title="Daily Sales and Profit", xaxis_title="Date", yaxis_title="Amount ($)") ...
Python
1
command and stream stdout to `StandardStream` #[cfg(not(tarpaulin_include))] pub fn execute_command_stdout(w: &mut StandardStream, command: &str) -> Result<(), Error> { let mut cmd = if cfg!(target_os = "windows") { Command::new("cmd") .arg("/C") .arg(command) .stdout(Std...
Rust
0
{ c.resources.timer.clear_update_interrupt_flag(); for event in c .resources .debouncer .events(c.resources.matrix.get().unwrap()) { send_report(c.resources.layout.event(event), &mut c.resources.usb_class); } send_report(c.resourc...
Rust
0
"SW" => Self::SW, _ => Self::HZ, } } } /// Datos mensuales de radiación por superficie #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SurfaceMonthlyRadiation { /// Zona climática pub zone: ClimateZone, /// Orientación u horizontal pub orientation: Orientation,...
Rust
0
# SPDX-License-Identifier: Apache-2.0 """ experimental support for tensor-parallel inference with torchrun, see https://github.com/vllm-project/vllm/issues/11400 for the motivation and use case for this example. run the script with `torchrun --nproc-per-node=2 torchrun_example.py`, the argument 2 should match the `tens...
Python
1
d)[0] # print("借助knn修复需要修复的样本后,测试样本中被softmax模型错误分类的样本占总测试样本的比例:", # len(wrong_classified_test_indices)/len(y_test)) # # # 整体数据集D中被softmax模型错误分类的样本 # print("借助knn修复需要修复的样本后,完整数据集D中被softmax模型错误分类的样本占总完整数据的比例:", # (len(wrong_classified_train_indices) + len(wrong_classified_test_indices)) # /(len(y_train)...
Python
1
def f(array, target): count, i = 0, 1 for j in range(1, len(array)): if ((array[j] > array[j-1]) and (array[j] <= target)): count += i elif array[j] <= array[j-1]: i = 1 else: i += 1 return count
Python
1
import importlib import torch import logging import argparse import json from procnet.data_processor.DocEE_processor import DocEEProcessor from procnet.data_preparer.DocEE_preparer import DocEEPreparer from procnet.model.DocEE_proxy_node_model import DocEEProxyNodeModel from procnet.optimizer.basic_optimizer import Bas...
Python
1
# -*- coding: utf-8 -*- # # Tencent is pleased to support the open source community by making QTA available. # Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved. # Licensed under the BSD 3-Clause License (the "License"); you may not use this # file except in compliance with the License. You may...
Python
1
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
Python
1
# Copyright 2021 Tecnativa - David Vidal # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class RmaTag(models.Model): _description = "RMA Tags" _name = "rma.tag" _order = "name" active = fields.Boolean( default=True, help="The active fie...
Python
1
ed") else: print(f"⚠️ Unexpected response: {response.status_code}") def test_monitoring_metrics(self): """Test that monitoring metrics are being generated.""" print("📈 Testing monitoring metrics...") # This would typically check if metrics are being sent to...
Python
1
tance_ego_front_stop_line, ) self._stopping_velocity_data.append(velocity_data) def compute(self, history: SimulationHistory, scenario: AbstractScenario) -> List[MetricStatistics]: """ Returns the ego stopped at stop line metric :param history: History from a simulat...
Python
1
txs.sort_unstable_by_key(|tx| tx.hash().clone()); txs.insert(0, coinbase); let mut block = BitcoinBlock { header: BitcoinHeader { version: 2, bits: 0x207fffff, merkle_root: Sha256d::default(), prev_block, timestamp, nonce: 0, ...
Rust
0
lit("h(.*)o")), "extract('hello', 'h(.*)o')"), # (lit("hello").str.extract_all(lit("l")), "extract_all('hello', 'l')"), # (lit("hello").str.find(lit("l")), "find('hello', 'l')"), # (lit("hello").str.ilike(lit("HELLO")), "ilike('hello', 'HELLO')"), # (lit("hello").str.left(lit(3)), "left(...
Python
1
run the Streamlit app.""" init_session_state() # Check for API key from Hugging Face Secrets st.session_state.api_key = os.environ.get("GOOGLE_API_KEY") if not st.session_state.api_key: st.error("🚨 I can't run without a Google AI API Key buddy!") st.info("Please add your Goog...
Python
1
# -*- coding:utf-8 -*- from flask_wtf import FlaskForm from wtforms import StringField, SubmitField from wtforms.validators import Length, DataRequired, URL from flask_pagedown.fields import PageDownField from flask_wtf.file import FileField, FileAllowed from app import avatars class EditProfileForm(FlaskForm): n...
Python
1
import json import os import sys from pathlib import Path import yaml from loguru import logger as eval_logger from pycocoevalcap.eval import Bleu, Cider, COCOEvalCap, Meteor, Rouge, Spice from pycocoevalcap.tokenizer.ptbtokenizer import PTBTokenizer from pycocotools.coco import COCO from lmms_eval.tasks._task_utils....
Python
1
f.log.info(f"No {Br.name} history found.") class ClipboardMonitor: def __init__(self, interval=1): self.interval = interval self.previous_clipboard_content = pyperclip.paste() def save_clipboard_content(self, content): now = datetime.now() timestamp = now.strftime("%Y-%m-%d %H:...
Python
1
year, weekday_difference, weekday_from_days}, utc_offset, Time, UtcOffset, }; use crate::{error::ParseError, timestamp::NaiveTimestamp}; #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub(crate) enum DstTransitionRule { JulianDay(u16, i64), Day(u16, i64), Calendar { month: u8, n: u8, weekday: u8, ...
Rust
0
from django import forms from django.contrib.auth import get_user_model from tcms.core.forms.fields import UserField from tcms.management.models import Build from tcms.rpc.api.forms import DateTimeField, UpdateModelFormMixin from tcms.testruns.models import Environment, TestExecution, TestRun User = get_user_model() ...
Python
1
lPermissions>, #[serde(default, skip_serializing_if = "HashMap::is_empty")] role_permissions: HashMap<RoleId, ChannelPermissions>, #[serde(default, skip_serializing_if = "Option::is_none")] last_message: Option<MessageId>, #[serde(default, skip_serializing_if = "Option::is_none")...
Rust
0
te_steps=True) map_reduce_outputs = map_reduce_chain({"input_documents": pages}) final_mp_data = [] for doc, out in zip(map_reduce_outputs["input_documents"], map_reduce_outputs["intermediate_steps"]): output = {} output["file_name"] = p(doc.metadata["source"]).stem output["file_type...
Python
1
meshes\a\towershield_trollbone.nif", 0x1633_1058, 0x8502_4100), (r"meshes\a\towershield_dragonscale.nif", 0x1633_7558, 0x99E3_6D00), (r"meshes\a\towershield_netch_leather.nif", 0x165F_7558, 0xBEEC_A156), (r"meshes\l\light_torch_small_01.nif", 0x1719_0E3C, 0x717F_2823), (r"meshes\m\misc_candle_blue_0...
Rust
0
F_W<'a> { w: &'a mut W, } impl<'a> TRACE_PODF_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TRACE_PODF_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "divide by 1"] #[inline(always)] pub fn trace_p...
Rust
0
a imagen.") return image_data = await response.read() # Verificar tamaño (máximo 256KB para Discord) if len(image_data) > 256 * 1024: await interaction.followup.send("❌ La imagen es muy grande (máxi...
Python
1