text
string
label_name
string
labels
int64
import io from pathlib import Path from typing import Union import fitz # PyMuPDF from pdf2image import convert_from_bytes from PIL import Image import pytesseract class CADPDFExtractor: def __init__(self, ocr_if_empty: bool = True, ocr_lang: str = "eng"): self.ocr_if_empty = ocr_if_empty self.ocr...
Python
1
order = decode_hex("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); assert_eq!( SecretKey::parse_slice(&group_order).err().unwrap(), Error::InvalidSecretKey ); } #[test] fn test_hkdf() { let text = b"secret"; let h = H...
Rust
0
from mani_skill import ASSET_DIR, PACKAGE_ASSET_DIR from mani_skill.envs.scene import ManiSkillScene from mani_skill.utils import sapien_utils from mani_skill.utils.geometry.trimesh_utils import ( get_articulation_meshes, merge_meshes, ) from mani_skill.utils.io_utils import load_json PARTNET_MOBILITY = None ...
Python
1
from django.shortcuts import render, redirect from .forms import FormularioContacto from django.core.mail import EmailMessage # Create your views here. def contacto(request): formulario_contacto=FormularioContacto() if request.method=="POST": formulario_contacto=FormularioContacto(data=request.POST)...
Python
1
lace('Chemistry', 'Chem', regex=False) .str.replace('scored ', '', regex=False) ) numeric_df = numeric_df.rename(columns={ 'SAT Total_x': 'SAT Total', '% students rec. general ed settings Special Ed Teacher Support Services (SETSS)': '% students rec. SETSS', '% students rec. Integrated Co-Teaching (ICT)...
Python
1
"download".into(), ) .await .measure()?; let mut conn = ctx .get_conn() .await .error(AppErrorKind::DbConnAcquisitionFailed)?; let recordings = crate::db::recording::RecordingListQuery::new(webinar.id()) .execute(&mut conn) .await ...
Rust
0
); pixel += 9 * getElementAtFloat(gCurrentFrame, x + 1, y - 1); pixel += 12 * getElementAtFloat(gCurrentFrame, x - 1, y); pixel += 15 * getElementAtFloat(gCurrentFrame, x, y); pixel += 12 * getElementAtFloat(gCurrentFrame, x + 1, y); pixel += 9 * getElementAtFloat(gCurrentFrame...
Rust
0
from Console.Console import Console from Library.Library import Library from Console.Data import getBooks, getUsers if __name__ == "__main__": lib: Library = Library.getLibrary() books = getBooks() users = getUsers() for book in books: lib.addBookByDict(book) for user in users: l...
Python
1
:read" ], "role": "manager", "can_switch_companies": True, "accessible_modules": [ "dashboard", "invoicing", "accounting", "hrm", "reports" ] } return succ...
Python
1
rmed. """ _check_str(command_string) self.run = shlex.split(command_string) def _validate_type(self): """Private method to ensure that the type field is set to inspection.""" if self._type != "inspection": raise securesystemslib.exceptions.FormatError( ...
Python
1
T> { &self.row } } impl<'a, T: 'a> DerefMut for RowMut<'a, T> { fn deref_mut(&mut self) -> &mut MatrixSliceMut<'a, T> { &mut self.row } } impl<'a, T: 'a> Deref for Column<'a, T> { type Target = MatrixSlice<'a, T>; fn deref(&self) -> &MatrixSlice<'a, T> { &self.col } }...
Rust
0
-> Vec<AlterEnum> { Vec::new() } /// If this returns `true`, the differ will generate /// SqlMigrationStep::RedefineIndex steps instead of /// SqlMigrationStep::AlterIndex. fn can_alter_index(&self) -> bool { true } /// Returns true only if the database can cope with an op...
Rust
0
KEY")?, &var("BITMEX_SECRET")?); let resp = rt.block_on(bm.post_order(PostOrderRequest { symbol: "XBTUSD".to_string(), ord_type: Some(OrdType::StopLimit), stop_px: Some(7000.), price: Some(7100.), order_qty: Some(-1.), text: Some("Shine".into()), ..Default::d...
Rust
0
ion function # to the embeddings since they are pre-activation. num_units = 100 fc = slim.fully_connected(tf.nn.relu(embeddings), num_units) # Add a classifier layer at the end, consisting of parallel logistic # classifiers, one per class. This allows for multi-class tasks. logits =...
Python
1
(), depth_in, strip_in_name.as_ptr(), strip_in, background_in_name.as_ptr(), background_in, page_height_in_name.as_ptr(), page_height_in, NULL, ); utils::result( vips_op_response, util...
Rust
0
forests: Vec<Forest> = Vec::with_capacity(nforests); for _ in 0..nforests { let mut trees = Vec::with_capacity(forest_size); for _ in 0..forest_size { let mut nodes = Vec::with_capacity(splits_count); for _ in 0..splits_count { nodes.p...
Rust
0
ert([0, 0], 1.0); sm.insert([9, 9], 10.0); sm.insert([4, 3], 0.25); sm.insert([0, 8], 0.125); sm.insert([8, 0], 0.125); let sm_bin: AIJMatrixBinary = sm.into(); sm_bin .print_to_petsc_binary_file("./test_output/test.bin") .unwrap(); } #[...
Rust
0
c_call!(BLOCK_FOR_GC_METHOD_OFFSET, tls); } } fn spawn_worker_thread(tls: VMThread, ctx: Option<Box<GCWorker<JikesRVM>>>) { let ctx_ptr = if let Some(r) = ctx { Box::into_raw(r) } else { std::ptr::null_mut() }; unsafe { jtoc_call!(SPAW...
Rust
0
def energy_conversion(from_type, to_type, value): """ Converts energy units from one type to another. Parameters: - from_type (str): The unit to convert from. - to_type (str): The unit to convert to. - value (float): The numeric value to convert. Supported units: - joule - ...
Python
1
reateTime") self._Port = params.get("Port") self._HasDockerfile = params.get("HasDockerfile") self._Dockerfile = params.get("Dockerfile") self._BuildDir = params.get("BuildDir") self._LogType = params.get("LogType") self._LogSetId = params.get("LogSetId") self._Lo...
Python
1
help="Batch size for LLM. If None, will be populated using LLM_NAME_TO_BATCH_SIZE", ) parser.add_argument( "--llm_dtype", type=str, default=None, choices=[None, "float32", "float64", "float16", "bfloat16"], help="Data type for LLM. If None, will be populated using L...
Python
1
import sys print(""" This script will download and process a large amount of crow audio data. It requires over 30 GB of disk space and will take several hours to complete. Each audio file will be downloaded, denoised, segmented, embedded, and classified. Files that are already processed will be skipped. Are you ready...
Python
1
(true); performance.run_from(&music_time::MusicTime::new(4, 3, 5), 0); } _ => assert!(false, "Cannot create performance engine"), } assert_eq!(my_state.beat_interval_count, 44); assert_eq!(my_state.current_time, music_time::MusicTime::new(5, 4, 8)); } } <reponame>DasIch/distracing #![a...
Rust
0
line) } } }; }; } /// The options for [`use_plic!`]. pub trait PlicOptions { /// The base address of PLIC's memory-mapped registers. const PLIC_BASE: usize; /// The maximum (highest) interrupt priority supported by the PLIC /// implementation. const MAX_PRIO...
Rust
0
); assert_eq!( unsafe { &(*(::std::ptr::null::<character_set>())).csname as *const _ as usize }, 8usize, concat!("Offset of field: ", stringify!(character_set), "::", stringify!(csname)) ); assert_eq!( unsafe { &(*(::std::ptr::null::<character_set>())).name as *const _ as...
Rust
0
#!/usr/bin/python3 import os import sys import base64 sys.path.append(os.path.join("%(install_dir)s", 'setup_app/pylib')) from pyDes import * saltFn = "%(configFolder)s/salt" f = open(saltFn) salt_property = f.read() f.close() key = salt_property.split("=")[1].strip() def obscure(data=""): engine = triple_des(...
Python
1
"""Example of using shearlet coefficients for signal separation. In this example we define the shearlet transform S, the wavelet transform W and use them to separate a signal according to min_{w,s} ||W(w)||_1 + a ||S(s)||_1 + b ||w + s - x||_2^2 Here we expect the shearlet coefficients to contain the edges, and...
Python
1
16 { match chr { 'a' => 0x07, 'b' => 0x08, 'n' => 0x0A, 'r' => 0x0D, 't' => 0x09, '\\' => 0x5C, '\'' => 0x27, '\"' => 0x22, '?' => 0x3F, _ => 0, } } <filename>schemes/example/src/main.rs extern crate syscall; use std::fs::File; use...
Rust
0
ender = profiler_cuda.decorate(gaussiansplatting_render) # --- test --- # s = 1000 s = 5 # image_size = (512, 512, 3) image_size = (511, 511, 3) # image_size = (256, 512, 3) # image_size = (256, 256, 3) sigmas = 0.999*torch.rand(s, 3).to(torch.float32).to("cuda") sigmas[:,:2] = 5*...
Python
1
ength path_changed = False path_scalings = get_normalized_path_scaling(q_shortened) low_point, high_point = sorted(np.random.random(2)) q_low, idx_low = get_configuration_from_normalized_path_scaling( q_shortened, path_scalings, low_point ) q_high, idx_high =...
Python
1
ranch for j in parent.children: if j != i: branches.append(j) print(branches) !python -m spacy download en_core_web_trf nlp_trf = spacy.load("en_core_web_trf") doc = nlp_trf(articles[313]['body']) displacy.render(doc, style="ent", jupyter=True) display(sent.text) from t...
Python
1
cuda() coord[0::2] *= width coord[1::2] *= height coord[0] -= coord[2] / 2 coord[1] -= coord[3] / 2 IoU_det = computeIoU(ref_box, coord) num_val += 1 if IoU_det >= 0.5: correct_val_d += 1 eval_result = {'score': correct_val_d / num_val} fo...
Python
1
// Executed Command: // ./target/release/composable // benchmark // --chain=picasso-dev // --execution=wasm // --wasm-execution=compiled // --pallet=frame_system // --extrinsic=* // --steps=5 // --repeat=2 // --raw // --output=./runtime/picasso/src/weights #![allow(unused_parens)] #![allow(unused_imports)] use sp_st...
Rust
0
: *mut crate::sctp6_usrreq::icmp6_filter, pub inp6_cksum: libc::c_int, pub inp6_hops: libc::c_short, } #[repr(C)] #[derive(Copy, Clone)] pub struct C2RustUnnamed_177 { pub inp4_ip_tos: u_char, pub inp4_options: *mut mbuf, pub inp4_moptions: *mut ip_moptions, } /* * XXX The defines for inc_* are ha...
Rust
0
import json import pickle import socket import struct import time from FunctionMod import * G = ecp.generator() # socke配置 NodeA = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = ('127.0.0.1', 123) NodeA.connect(server_address) # 获取注册信息 client_type = "A" deltT = 1.0 sk_A = secrets.token_bytes(32...
Python
1
)?; computer.value_of('b').ok_or(Error::BadInput) } #[cfg(test)] mod tests { use super::*; const INPUT: &str = include_str!("test-input.txt"); #[test] fn test_example_program() { let mut computer = Computer::from_str(INPUT).unwrap(); computer.run().unwrap(); assert_eq!(com...
Rust
0
; let label = unsafe{ String::from_utf8_lossy(CStr::from_ptr((*config_value).label.as_ptr()).to_bytes()) }; // let mut value = String::from(""); let widget_type = unsafe{ (*config_value).widget_type }; match widge...
Rust
0
Ok(read_len) } } impl Write for ByteBuffer { fn write(&mut self, buf: &[u8]) -> Result<usize> { self.write_bytes(buf); Ok(buf.len()) } fn flush(&mut self) -> Result<()> { Ok(()) } } impl std::fmt::Debug for ByteBuffer { fn fmt(&self, f: &mut std::fmt::Formatter)...
Rust
0
>>> problem_dict1 = { >>> "fit_func": fitness_function, >>> "lb": [-10, -15, -4, -2, -8], >>> "ub": [10, 15, 12, 8, 20], >>> "minmax": "min", >>> } >>> >>> epoch = 1000 >>> pop_size = 50 >>> ST = 0.8 >>> PD = 0.2 >>> SD = 0.1 >>> model = OriginalSSA(epoch,...
Python
1
1.INC"), ("Simple_CoK_M2", simple_cokriging_markII, [neighbourhood1, { "primary_data": sck_primary, "secondary_data": sck_secondary, "grid": grid, "correlation_coef": 0.97}], "current//RESULT_SCK_MARK_2.INC", "SCK_MARK_2", "fixed/RESULT_SCK_MARK_2.INC"), ("SIS_LVM", sis_simulation, [{"prop": multi_ik_prop, "g...
Python
1
from datetime import datetime from typing import ( NamedTuple, Callable, List, TypeVar, Any, Type, TYPE_CHECKING, Optional, ) if TYPE_CHECKING: from mercapi import Mercapi RM = TypeVar("RM", bound="ResponseModel") T = TypeVar("T") ExtractorDef = Callable[[dict], Optional[T]] clas...
Python
1
OwnerType::new() } fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT; descriptor.get(|| { let mut fields = ::std::vec::Vec::new(); f...
Rust
0
ption( status_code=status.HTTP_404_NOT_FOUND, detail='Benchmark does not exists' ) # Check if user has CONTENT_CREATE rights in the specified group await check_group_permissions(db_handler, user, publish_in, [RIGHT.BENCHMARK_CREATE]) try: # Create the update dictionary ...
Python
1
_AES_128_CBC_SHA256, EcdhePskWithAes256CbcSha384 = TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384, EcdhePskWithNullSha = TLS_ECDHE_PSK_WITH_NULL_SHA, EcdhePskWithNullSha256 = TLS_ECDHE_PSK_WITH_NULL_SHA256, EcdhePskWithNullSha384 = TLS_ECDHE_PSK_WITH_NULL_SHA384, EcdheEcdsaWithCamellia128...
Rust
0
# Copyright (c) 2021 The University of Manchester # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
Python
1
ment) return element else: logging.warning( "[RANDOM] used but path '%s' did not resolve to a non-empty array.", path_before ) return None else: ...
Python
1
self.mir.source_info(borrow.reserve_location).span } // Retrieve type of a place for the current MIR representation fn retrieve_type_for_place(&self, place: &Place<'tcx>) -> Option<ty::Ty> { match place { Place::Local(local) => { let local = &self.mir.local_decls...
Rust
0
n, m=map(int, input().split()) s=set() count=0 for i in range(n): s.add(input()) for _ in range(m): t=input() if t in s: count+=1 print(count)
Python
1
print('\nFeatures') print(batch.features.dtype, batch.features.shape) print('\nLabels') print(batch.labels.dtype, batch.labels.shape) print('\nAugment Scales') print(batch.scales.dtype, batch.scales.shape) print('\nAugment Rotations') ...
Python
1
ignorables", ), "uni82A6_uE0100" ); } #[test] fn cmap_1_003() { assert_eq!( shape( "tests/fonts/text-rendering-tests/TestCMAP14.otf", "\u{82A6}\u{E0101}", "--ned --remove-default-ignorables", ), "uni82A6_uE0101" ); } #[test] fn cm...
Rust
0
import datetime from typing import Any from autowsgr.constants.image_templates import IMG from autowsgr.game.game_operation import get_ship from autowsgr.timer import Timer from autowsgr.utils.api_image import absolute_to_relative, crop_image, match_nearest_index from autowsgr.utils.time import get_eta, str2time # 开...
Python
1
_hash, "backup_path": str(backup_path), "timestamp": datetime.now(UTC).isoformat() + "Z" } print(f"✅ {agent_file.name}: {original_size}B → {new_size}B ({compression_ratio:.1f}% reduction)") return result except Excepti...
Python
1
fn clone(&self) -> Self { *self } } #[doc = "*Required features: `\"Win32_NetworkManagement_QoS\"`*"] pub const QOS_QUERYFLOW_FRESH: u32 = 1u32; #[doc = "*Required features: `\"Win32_NetworkManagement_QoS\"`*"] pub type QOS_QUERY_FLOW = i32; #[doc = "*Required features: `\"Win32_NetworkManagement_QoS\"`...
Rust
0
assert_eq!(paths.val[0].1.root(&config), paths::root()); assert_eq!(paths.val[1].0, "cli"); assert_eq!(paths.val[1].1.root(&config), somedir); } #[cargo_test] fn enforces_format() { // These dotted key expressions should all be fine. let config = ConfigBuilder::new() .config_arg("a=true") ...
Rust
0
, 500.0) } } impl<'a> Entity for Sun<'a> { fn init(&mut self, _ctx: &mut pantheon::context::Context) { // @TODO //ctx.gfx_context.light_uniforms.light_color = self.light_color; } fn update(&mut self, _ctx: &mut pantheon::context::Context) { /* if self.rotating { ...
Rust
0
- start_time) / 100 * 1000 # Time fused operations start_time = time.time() for _ in range(100): _ = fused_matmul_activation(a_mat, b_mat, "relu") torch.cuda.synchronize() fused_matmul_time = (time.time() - start_time) / 100 * 1000 # Calculate speedup matmul_speedup = sepa...
Python
1
array(&key[1..9])) < prune_to_block }); for (key, _val) in block_iter { batch.delete(key)?; } batch.commit()?; Ok(()) } } impl<S: Store, BS: Store> CkbBalanceExtension<S, BS> { pub fn new( store: S, indexer: Arc<Indexer<BS>>, _n...
Rust
0
_balance: BalanceDTO, pool: &web::Data<Pool>) -> Result<(), ServiceError> { match Balance::insert(new_balance, &pool.get().unwrap()) { Ok(_) => Ok(()), Err(_) => Err(ServiceError::new(StatusCode::INTERNAL_SERVER_ERROR, constants::MESSAGE_CAN_NOT_INSERT_DATA.to_string())), } } pub fn delete(id: ...
Rust
0
tTask, WorkerCommand.IO_TEST: TestIOTask, WorkerCommand.CATALOG_CLEANUP: CatalogCleanupTask, WorkerCommand.DEVELOPMENT_DATASET_CREATE: DevelopmentDatasetCreateTask, WorkerCommand.DEVELOPMENT_DATASET_DELETE: DevelopmentDatasetDeleteTask, WorkerCommand.DEVELOPMENT_DATASET_ADD_TABLES: DevelopmentDatase...
Python
1
len: read_size, }; let req = ReadVirtualMemoryRequest { conn_id: conn_id.to_string(), pid: pid, base_offsets: false, reads: vec![entry], }; let phys_entry = ReadPhysicalMemoryEntryRequest { addr: address, len: read_size, }; let phys_req = ReadPhysi...
Rust
0
} }; } #[doc(hidden)] #[macro_export] macro_rules! __priv_usize_const { ($value:literal) => { pub const __USIZE_CONST: $crate::__::usize = $value; }; } if_rust_1_46!{ /// Counts the amount of token trees passed to this macro, /// passing the amount to an (optional) callback macro. //...
Rust
0
two vertices, /// or if the curve is continuous (i.e. connects to itself), the edge could /// be defined by the whole curve, and have no bounding vertices. pub curve: LocalForm<Curve<D>, Curve<3>>, /// Access the vertices that bound the edge on the curve /// /// If there are no such vertices, ...
Rust
0
tag("\""), opt(escaped_transform( none_of("\\\""), '\\', alt((tag("\\"), tag("\""))), )), tag("\""), ), |data| TextString { data: data.unwrap_or_default(), bitwidth: IntegerWidth::Unkn...
Rust
0
f not specified, less than one // or higher than what the device supports, the number of items is // determined by the // device. #[yaserde(prefix = "tdc", rename = "Limit")] pub limit: Option<i32>, // Start returning entries from this start reference. If not specified, // entries shall sta...
Rust
0
Frames Transmitted Register"] pub mod tbft1518; #[doc = "GTBFT1518 register accessor: an alias for `Reg<GTBFT1518_SPEC>`"] pub type GTBFT1518 = crate::Reg<gtbft1518::GTBFT1518_SPEC>; #[doc = "Greater Than 1518 Byte Frames Transmitted Register"] pub mod gtbft1518; #[doc = "TUR register accessor: an alias for `Reg<TUR_S...
Rust
0
d() .map(|x| x.shorthand().map(|x| x.to_string())) .unwrap_or(None) } } /// get current repository git branch. /// /// When current repository exists git folder. /// /// It's use default feature.This function try use [git2] crates get current branch. /// If not use git2 feature,then try use...
Rust
0
); } let create_infos = vec![create_info]; let pipelines = device.create_graphics_pipelines(None, &create_infos, None) .map_err(|(e, _)| e)?; Ok((layout, pipelines[0].clone())) } <reponame>richardeoin/thermocouple //! Utilities for running unit tests. #[allow(unused_macros)] /// Run ...
Rust
0
acronym|address|applet|area|audioscope|b|base|basefront|bdo|bgsound|big|blackface|blink|blockquote|body|bq|br|button|caption|center|cite|code|col|colgroup|comment|dd|del|dfn|dir|div|dl|dt|em|embed|fieldset|fn|font|form|frame|frameset|h1|head", "ver": "OWASP_CRS/3.2.0", "type": "ModSecurity: Warning", ...
Python
1
RES_CAPACITY: usize, const URC_CAPACITY: usize, > where Tx: embedded_hal::serial::nb::Write<u8>, CLK: fugit_timer::Timer<TIMER_HZ>, U: UrcMatcher, D: Digester, { serial_tx: Tx, timer: CLK, config: Config, custom_urc_matcher: U, custom_digester: D, } impl< Tx, T,...
Rust
0
l)) => { model.page = Page::init(url, &model.guides); let title = match model.page { Page::Guide { guide, .. } => format!("{} - {}", guide.menu_title, TITLE_SUFFIX), Page::NotFound => format!("404 - {}", TIT...
Rust
0
esponse( status=status.HTTP_422_UNPROCESSABLE_ENTITY, data={ "code": 1, "message": "Checksum address validation failed", "arguments": [address], }, ) ordering = self.get_ordering_parameter() ...
Python
1
ED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CO...
Rust
0
# Copyright (C) 2014-2025 CEA, EDF # # This library 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 2.1 of the License, or (at your option) any later version. # # This library is distr...
Python
1
: i32 = create_topic_args .value_of("replication_factor") .unwrap() .parse() .expect("invalid replication-factor value"); let metadata = kafky_client.get_metadata(None)?; let existent_topic_names: Vec<String> = metadata.topic_names...
Rust
0
] { &self.0 } } impl PrivateKey { /// takes the given raw bytes and perform some modifications to normalize /// it properly to a Private Key. /// pub fn from_bytes(bytes: [u8; PRIVATEKEY_SIZE]) -> Self { PrivateKey(bytes) } pub fn from_slice(bytes: &[u8]) -> Result<Self> { ...
Rust
0
} } // Add the given set of data pub fn with_data(self, data: Vec<yul::Data>) -> Runtime { Runtime { data, ..self } } /// Generate the top level YUL object pub fn to_yul(&self) -> yul::Object { let all_statements = [self.functions.clone(), self.test_statements.clone()].conca...
Rust
0
rts.append(pybel.Smarts('[#9]')) smarts.append(pybel.Smarts('[#17]')) smarts.append(pybel.Smarts('[#35]')) smarts.append(pybel.Smarts('[#53]')) # count atoms present, final element will be used for number of rings atm_cnt = np.zeros((len(smarts)+1)) # atomic and molecular diffusion volume increments (Ta...
Python
1
{ let (c1, c2) = session_channel(); ts.push(spawn(move || { client_handler(c2); })); tx = tx.sel2().send(c1).zero(); } tx.sel1().close(); let count = server(rx); for t in ts { let _ = t.join(); } println!("Handled {} connections", count); } us...
Rust
0
use std::fmt; use common; use common::AocResultType; use common::AocResult; use std::collections::BTreeSet; #[derive(Debug)] struct Replacer { replaced: Vec<u8>, replacement: Vec<u8>, } impl Replacer { fn new(spec: &str) -> Option<Replacer> { let tokens: Vec<&str> = spec.split(" => ").collect(); ...
Rust
0
import numpy as np from time import sleep def regression(X,Y,learning_rate,episodes): X=np.array(X) Y=np.array(Y) features=len(X[0]) weights=np.zeros(features) bias=0 for episode in range(episodes): for _ in range(len(X)): index=np.random.randint(0,len(X)) x_in...
Python
1
рекомендаций по\n" "улучшению состояния здоровья\n" "на основе введённых\n" "показателей.")) self.label_2.setText(_translate("MainDownload", "Авторы приложения не несут ответсвенности за Ваше здоровье. \n" "Обязательно проконсультируйтесь с врачом.")) def center(self, window): # Получаем геомет...
Python
1
import argparse from style import Style,TreeStyle, RectangleStyle from visitor import IVisitor, Visitor def main(): # 创建style对象 style_td = TreeStyle("test.json", "default") style_tp = TreeStyle("test.json", "pokerface") style_rd = RectangleStyle("test.json", "default") style_rp = RectangleStyle(...
Python
1
as *const _ as usize }, 80usize, concat!( "Offset of field: ", stringify!(GFSDK_SSAO_InputNormalData_D3D12), "::", stringify!(FullResNormalTextureSRV) ) ); } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct GFSDK_SSAO_...
Rust
0
MAPPING_ZH_TW_COMMON_TRANSLATION_ERROR = { '創建': '建立', # create '代碼': '程式碼', # code '信息': '資訊', # information '模塊': '模組', # module '標誌': '旗標', # flag '異常': '例外', # exception '解釋器': '直譯器', # interpreter '頭文件': '標頭檔', # header '對象': '物件', # objetc '支持': '支援', # support ...
Python
1
nt` to the field"] #[inline(always)] pub fn variant(self, variant: STBIEN_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "The standard transmit buffer interrupt generation is disabled."] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(STBIEN_A::VALUE1) ...
Rust
0
# routes/category.py from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException from sqlalchemy.orm import Session from app.core.db import get_db from app.models import PymeTrust from app.schemas import UserProfile import time router = APIRouter() @router.post("/recalculate/{ruc}") def recalculate_trust_s...
Python
1
epare("") { Err(PgWrongTransaction) => {} Err(r) => panic!("Unexpected error {}", r), Ok(_) => panic!("Unexpected success"), } match trans.transaction() { Err(PgWrongTransaction) => {} Err(r) => panic!("Unexpected error {}", r), Ok(_) => panic!("Unexpected success...
Rust
0
r.forward_bots(&world_guard).await.unwrap(); drop(world_guard); // free the read guard let bots_forward_finished = Instant::now() - start; // forbid other threads from sending more inputs // let tick_intents = gather_inputs(&mut input_bus, bot_intents); tokio::spawn( ...
Rust
0
bill_file.write(f"Total Price: ${total_amt:.2f}\n") elif dairy_product=="buttermilk": quantity=int(input("Enter how many packs of Buttermilk's you want : ")) original_amt=buttermilk*quantity gst_amt=(original_amt*gst_rate)/100 discount_amt=(discou...
Python
1
r non-overlapping. // // In effect, a range trie is building a DFA from a sequence of arbitrary // byte ranges. But it uses an algoritm custom tailored to its input, so it // is not as costly as traditional DFA construction. While it is still quite // a bit more costly than the forward's case (which only needs Daciuk's...
Rust
0
access rights (not even read) which is then locked (`mlock`'d). #[cfg_attr(not(any(target_os = "android", target_os = "linux")), allow(unused_variables))] #[inline(always)] pub fn new(length: usize, allocate_in_first_2Gb: bool, ignore_mlock_failure: bool) -> Result<Self, ExecutableAnonymousMemoryMapCreationError> {...
Rust
0
#!/usr/bin/env python3 # Copyright (C) 2019 Checkmk GmbH - License: GNU General Public License v2 # This file is part of Checkmk (https://checkmk.com). It is subject to the terms and # conditions defined in the file COPYING, which is part of this source code package. from collections.abc import Mapping from cmk.rule...
Python
1
else: print(f"请求 {id_value} 失败: {e}") return None, id_value, alias return None, id_value, alias def crawl_websites( self, ids_list: List[Union[str, Tuple[str, str]]], request_interval: int = CONFIG["REQUEST_INTERVAL"], ) -> Tuple[D...
Python
1
e::ptr::null::<playdate_sound_source>())).setFinishCallback as *const _ as usize }, 12usize, concat!( "Offset of field: ", stringify!(playdate_sound_source), "::", stringify!(setFinishCallback) ) ); } #[repr(C)] #[derive...
Rust
0
from timeit import timeit import numpy as np def row_major_mean(np_mat: np.ndarray, mean_idx=[]): if len(mean_idx) == 0: mean_idx = slice(None) return 1000*timeit(lambda: np_mat[:,mean_idx].mean(axis=0), number=10) / 10 def col_major_mean(np_mat: np.ndarray, mean_idx=[]): if len(mean_idx) == 0: ...
Python
1
compatible ordering operator."] #[doc = " We prefer to set eqop/sortop/nulls_first to match any ORDER BY item that"] #[doc = " the query presents for the same tlist item. If there is none, we just"] #[doc = " use the default ordering op for the datatype."] #[doc = ""] #[doc = " If the tlist item's type has a hash opc...
Rust
0
Feedforward matrix \ /// dx: Statespace size \ /// du: control input size \ #[derive(Debug, Clone, PartialEq)] pub struct LTISystem { pub A: DMatrix<f32>, pub B: DMatrix<f32>, pub C: DMatrix<f32>, pub D: DMatrix<f32>, pub dx: usize, pub du: usize, } impl LTISystem { pub fn new(A: DMatrix<f...
Rust
0
pub defs: HashMap<ConcType, EnumDef>, } impl EnumDefs { pub fn get_enum_def(&mut self, ty: ConcType) -> &mut EnumDef { self.defs.entry(ty).or_insert_with(Default::default) } } impl EnumDef { pub fn get_variant_index(&mut self, ty: ConcType) -> usize { let id = self.variants.len(); ...
Rust
0
le<()> { spawn(move || { println!("Starting HTTP server on {}", self.sock_addr); let path_regex = Regex::new(r"^/([^/]+)$|^/private/([^/]+)$").unwrap(); let tx_mutex = Mutex::new(tx); let server = Server::http(move |req: Request, mut res: Response| { ...
Rust
0
cation=self.device) # 处理权重键名 state_dict = OrderedDict() for k, v in checkpoint.items(): if k.startswith('encoder.'): k = k.replace('encoder.', '') if k.startswith('blocks.'): continue state_dict[k] = v ...
Python
1