text
string
label_name
string
labels
int64
dt: DateTime<Utc>, ) -> Instruction { let mut account_metas = vec![ AccountMeta::new(*from, true), AccountMeta::new(*contract, false), ]; if from != to { account_metas.push(AccountMeta::new(*to, false)); } Instruction::new(id(), &BudgetInstruction::ApplyTimestamp(dt), ac...
Rust
0
import numpy as np import sys from gaussPDF import gaussPDF def GMR(Priors, Mu, Sigma, x, input, output): lo = np.size(output) nbData = np.size(x) nbVar = np.size(Mu, 0) nbStates = np.size(Sigma, 2) realmin = sys.float_info[3] Pxi = np.ndarray(shape=(nbData, nbStates)) x = np.reshape(x,(1,nb...
Python
1
_http_bench", "deno_core_single" res.insert( "core_http_json_ops".to_string(), core_http_json_ops(core_http_json_ops_exe)?, ); res.insert("hyper".to_string(), hyper_http(hyper_hello_exe)?); Ok(res) } fn run( server_cmd: &[&str], port: u16, env: Option<Vec<(String, String)>>, origin_cmd: Option...
Rust
0
.front_id != 0 { os.write_uint32(16, self.front_id)?; } if self.exec_local_flag != false { os.write_bool(17, self.exec_local_flag)?; } if self.lambda_existed != false { os.write_bool(18, self.lambda_existed)?; } if !self.bytecode.is_emp...
Rust
0
n_df_subjects) > 10: print(f"\n{Fore.CYAN}Training subject category prediction model...{Style.RESET_ALL}") print(f"Using {len(train_df_subjects)} records for training") subj_vectorizer, subj_model, subj_mlb = train_subject_model(train_df_subjects) # Predict missing subject categ...
Python
1
_uc(slice: &[BitBlock], nm: &[BitBlock], fm: &[BitBlock]) -> u64 { let nblocks = slice.len(); debug_assert_eq!(nm.len(), nblocks); debug_assert_eq!(fm.len(), nblocks); let ptr1 = slice.as_ptr() as *const __m256i; let ptr2 = nm.as_ptr() as *const __m256i; let ptr3 = fm.as_ptr() as *const __m256i...
Rust
0
load_context: &'a mut LoadContext, ) -> BoxedFuture<'a, Result<()>> { Box::pin(async move { load_asset(bytes, load_context).await }) } fn extensions(&self) -> &[&str] { &["ftl"] } } use crate::ast::{self, ASTNode}; use crate::class::{CharClass, CharRange}; use std::convert::{T...
Rust
0
from typing import TypedDict, List, Annotated import operator class ResearchState(TypedDict): task: dict initial_research: str sections: List[str] research_data: List[dict] human_feedback: str # Report layout title: str headers: dict date: str table_of_contents: str introdu...
Python
1
ts::Constraint::RelativeConstraint; use gouda::input::AnyKey::Letter; use crate::gui::{GameGui, game_gui_system, StageText, change_stage_text, GoldText, WoodText, StoneText}; use crate::main_menu::{MenuScreen, MainMenu, MainMenuButtonId, menu_mouse_system, SaveEvent, ResumeEvent, SettingsEvent}; use std::collections::H...
Rust
0
loan of mutable vec content granted here v[1] = 4; //~ ERROR assigning to mutable vec content prohibited due to outstanding loan } } fn takes_const_elt(_v: &const int, f: fn()) { f(); } fn has_mut_vec_and_tries_to_change_it() { let v = ~[mut 1, 2, 3]; do takes_const_elt(&const v[0]) { ...
Rust
0
: headers['Referer'] = brokerId return {'url': url, 'method': method, 'body': body, 'headers': headers} def handle_errors(self, httpCode: int, reason: str, url: str, method: str, headers: dict, body: str, response, requestHeaders, requestBody): if not response: return No...
Python
1
mut self) -> Result<u64> { self.refresh(false)?; Ok(self.used) } pub(crate) fn available(&mut self) -> Result<u64> { self.refresh(false)?; Ok(self.available) } } #[cfg(test)] mod tests { use super::DiskStatistics; use crate::config::Config; use std::path::PathB...
Rust
0
fn compute_strain_energy_density(&self, deformation_gradient: &MatrixN<T, D>) -> T; fn compute_stress_tensor(&self, deformation_gradient: &MatrixN<T, D>) -> MatrixN<T, D>; fn contract_stress_tensor_with( &self, deformation_gradient: &MatrixN<T, D>, a: &VectorN<T, D>, b: &Vect...
Rust
0
.unwrap(); self.render_ac_sample_data(&model.r, Rgb565::RED)?; self.render_ac_sample_data(&model.ir, Rgb565::BLUE)?; Ok(()) } pub fn render_ac_sample_data( &mut self, samples: &Max3012SampleData, color: Rgb565, ) -> Result<(), LcdError> { ...
Rust
0
lpha = np.clip(alpha, 0, 1) * 255. trimap = target[:, 1, :, :].squeeze().numpy() mask = np.equal(trimap, 128).astype(np.float32) alpha = (1 - mask) * trimap + mask * alpha gt_alpha = target[:, 0, :, :].squeeze().numpy() * 255. alpha.astype(np.uint8) gt_alpha.astype(np....
Python
1
the configuration. /// fn create_book_toml(path: &str, project_name: &str) -> Result<(),String> { let book_toml_fname = Path::new(&path).join(MDBOOK_BOOK_TOML); let book_toml_fname = book_toml_fname.to_str().unwrap(); let file = match fs::OpenOptions::new() .read(false) .write(true) ...
Rust
0
eMetaArch) ## Convert to cuda if is_distributed: meta_arch = torch.nn.SyncBatchNorm.convert_sync_batchnorm(meta_arch) meta_arch = torch.nn.parallel.DistributedDataParallel(meta_arch.cuda(), device_ids=[gpu], output_device=gpu) else: meta_arch = meta_arch.cuda() checkpoint_name =...
Python
1
t) > 2 and text[0] == "#" and text[-1] == "#": topic_list.append(text[1:-1]) if topic_list: topics = ",".join(topic_list) return topics def get_at_users(self, selector): """获取@用户""" a_list = selector.xpath("//a") at_users = "" at_list = []...
Python
1
with col3: if "Date" in df.columns: date_range = (df["Date"].max() - df["Date"].min()).days st.metric("日期範圍", f"{date_range} 天") with col4: if "Close" in df.columns: avg_price = df["Close"].mean() st.metric("平均價格", f"{avg_price:.2f}") # 顯示資料表...
Python
1
the occurrences of # active materials (materials number 3 and 4) my_objective_dict.add_objective(name="energy", maximize=False, tag=None, node_func=partial(count_occurrences, keys=[3, 4]), output_node_name="material") # Initializing a population of Soft...
Python
1
self.status_label.setText("含密图像加载失败") return def _on_save_stego_clicked(self): """保存含密图像""" # 检查是否有含密图像 if not hasattr(self, 'stego_image') or self.stego_image is None: QMessageBox.warning(self, "警告", "没有可用的含密图像") return # 打开文件对话框选择保存路径 ...
Python
1
}; count_insn(cx, "ret_undef"); return llvm::LLVMGetUndef(retty.to_ref()); } } pub fn add_span_comment(bcx: block, sp: span, text: &str) { let ccx = bcx.ccx(); if ccx.sess.asm_comments() { let s = fmt!("%s (%s)", text, ccx.sess.codemap.span_to_str(sp)); debug!("%s",...
Rust
0
= center_y - ring_level; self.check_tile_for_mine_for_animation( x, y, &mut mine_indices, &mut visited_tiles, &mut current_mines_in_ring, ); } ...
Rust
0
enumerate() { datasets.push( Dataset::default() .name(&line.label) .marker(symbols::Marker::Dot) .style(Style::default().fg(COLORS[i])) .data(&line.points) ); } Chart::new(datasets) .block( Block::de...
Rust
0
; charset=utf-8"), "json" => Some("application/json"), "wasm" => Some("application/wasm"), _ => None, }) { resp.headers_mut() .unwrap() .insert(CONTENT_TYPE, HeaderValue::from_static(content_type)); } } #![doc = include_str!("../README....
Rust
0
from tkinter import * from tkinter import messagebox import sys class HelloButton(Button): def __init__(self, root, **kwargs): super().__init__(root, text="Hello", command = self.comd, **kwargs) def comd(self): messagebox.showinfo("Hi", "Hello") class LeaveButton(Butt...
Python
1
from(socket)?; if resp { Ok(()) } else { Err(Error { exit_code: -1, msg: "".into(), show_msg: false, }) } } fn shutdown(socket: &UnixStream) -> Result<(), Error> { Req::Shutdown.write_to(socket)?; resp::read_from::<_, resp::Shutdown>(socke...
Rust
0
//! ``` //! //! After you have a `Renderer`, there's some other things you can try: //! //! - Draw some things using a `Material` and `Model`. One is provided by the //! `simple` module, but you can make your own. //! - Create a `Camera` and use it to move your view around //! - Create a `Scene` and traverse it whe...
Rust
0
ayon::prelude::*; lazy_static! { static ref HAYSTACK: Vec<[u32; 1]> = { let mut rng = XorShiftRng::from_seed([0, 1, 2, 3]); (0..10_000_000) .map(|_| { let mut result: [u32; 1] = [0; 1]; result[0] = rng.next_u32(); result }) ...
Rust
0
} } // return output Ok(Page::single(&view) .to_svg() .or_else(Fail::from)? .to_string()) } /// Create plot fn new_plot(values: Vec<Xy>, colour: Option<&String>, size: Option<&String>) -> Plot { Plot::new(values).point_style( PointStyle::new() .colou...
Rust
0
import os import subprocess from datetime import datetime import json # Current year to be used in file paths current_year = datetime.utcnow().strftime('%Y') current_date = datetime.utcnow().strftime('%Y-%m-%d') # Dictionary holding environments configuration environments = { 'private-sector': { 'access_k...
Python
1
store(5).unwrap(); assert!(slots.try_read(slots.capacity(), |_| 0).is_none()); } #[test] fn index_can_be_used_to_read_value() { let mut slots: Slots<_, 8> = Slots::new(); slots.store(5).unwrap(); slots.store(6).unwrap(); slots.store(7).unwrap(); assert_eq!(5, slots.try_read(7, |&w| w).unwrap...
Rust
0
f" but the following tokens" f" were specified as bad: {invalid_token_ids}." f" All token id values should be integers satisfying:" f" 0 <= token_id <= {tokenizer.max_token_id}.") @cached_property def sampling_type(self) -> SamplingType: if sel...
Python
1
from datetime import timedelta import pytest from django.core.management import call_command from django.utils import timezone from magiclink.models import MagicLink @pytest.mark.django_db def test_magiclink_clear_logins(): # Valid Magic Links for index in range(2): MagicLink.objects.create( ...
Python
1
ze_of::<grid::Partical>()); dbg!(size_of::<grid::Grid>()); //let mut fps = Vec::new(); 'running: loop { for event in event_pump.poll_iter() { match event { Event::Quit { .. } => break 'running, Event::MouseButtonDown { x, y, .. } => { ...
Rust
0
rad def main(): X = np.array([[0,0], [0,1], [1,0], [1,1]]) Y = np.array([[1], [1], [1], [0]]) nn = adaptiveLearningRate(2, [4], 1, 'default') nn.eta = 1e-4 Yhat = nn.forward(X) print("Current Prediction: ", Yhat) printAt = 100 for i in range(2000): Yhat = nn.forward(X) ...
Python
1
# Copyright (C) PyZMQ Developers # Distributed under the terms of the Modified BSD License. import time import pytest import zmq from zmq.tests import BaseZMQTestCase class TestDraftSockets(BaseZMQTestCase): def setUp(self): if not zmq.DRAFT_API: pytest.skip("draft api unavailable") ...
Python
1
)), _ => {} } } } pub struct VoxelWorldPlugin; impl Plugin for VoxelWorldPlugin { fn build(&self, app: &mut App) { const UPDATE_VISIBLE_CHUNKS_LABEL: &'static str = "update_visible_chunks"; const CREATE_CHUNKS_LABEL: &'static str = "create_chunks"; app .insert_resource(VoxelWorld::def...
Rust
0
8, 21, 47, 14, 83, 57, 27, 86, 6, 75, 65, 26, 96, 1, 94, 72, 51, 15, 40, 86, 89, 32, 36, 52, 58, 52, 58, 52, 39, 10, 18, 81, 56, 80, 49, 4, 59, 66, 53, 20, 71, 87, 25, 87, 34, 2, 37, 11, 67, 80, 96, 2, 13, 80, 75, 17, 9, 48, 70, 19, 24, 61, 23, 31, 7, 6, ...
Rust
0
params['vocab_size']` must be specified. * `hparams['vocab_file']` and `hparams['text_file']` can not be None at the same time. .. code-block:: python { "vocab_file": None, "text_file": None, "vocab_size": None, ...
Python
1
can consist only of ASCII /// Latin letters A-Z and a-z, underscores(_), and ASCII digits 0-9. /// For each label an AnnotationSpec is created which display_name /// becomes the label; AnnotationSpecs are given back in predictions. /// /// `INSTANCE_ID` /// : A positive integer that identifies a specific instanc...
Rust
0
#!/usr/bin/env python3 from decimal import Decimal from decimal import ROUND_HALF_UP # display a title print("The Invoice program") print() choice = "y" while choice == "y": # get user entry order_total = Decimal(input("Enter order total: ")) order_total = order_total.quantize(Decimal("1.00"), R...
Python
1
import os import time import pymapp import logging import pytest import sleepy_worker CONFIG_LOCATION = os.path.dirname(__file__) @pymapp.register_mapp_class(os.path.join(CONFIG_LOCATION, "config.json")) class MyTestApplication(pymapp.MApp): def __init__(self): self.a = 1 self.b = 2 @pymapp...
Python
1
ore details. #![warn(missing_docs)] #[cfg(test)] mod tests; use std::thread; use std::sync::mpsc::channel; //use std::thread::JoinHandle; use std::marker::{Send}; use std::sync::mpsc::{Sender, Receiver, TryRecvError}; /// A promise is a way of doing work in the background. The promises in /// this library have the ...
Rust
0
# Code generated by Lark OpenAPI. from typing import Any, Optional, Union, Dict, List, Set, IO, Callable, Type from lark_oapi.core.model import BaseRequest from lark_oapi.core.enum import HttpMethod, AccessTokenType from .query_user_task_remedy_request_body import QueryUserTaskRemedyRequestBody class QueryUserTaskRe...
Python
1
IndexedMerkleProof { index: _, count, merkle_proof, } = self; let mut hashes = merkle_proof.iter(); let raw_root = if let Some(leaf_hash) = hashes.next().cloned() { // Compute whether to hash left or right for the elements of the Merkle proof. ...
Rust
0
let mut v = vec!(0; Reader::min_size()); v.extend_from_slice(b"Hello, World!"); v[28] = (v.len() - Reader::min_size()) as u8; let lfh = Reader::new(&v).unwrap(); assert_eq!(lfh.extra_field(), Some(&b"Hello, World!"[..])); } #[test] fn reader_file_name_success_with_max_le...
Rust
0
#!/usr/bin/env python3 # @file so3_math.py # @author Junlong Jiang [jiangjunlong@mail.dlut.edu.cn] # Copyright (c) 2025 Junlong Jiang, all rights reserved import torch import numpy as np def vec2skew(v: torch.Tensor): """创建一个3x3的斜对称矩阵,对应于向量v的叉积操作""" zero = torch.zeros_like(v[0]) return torch.t...
Python
1
import torch import torch.nn as nn import torch.nn.functional as F class multi_view_depth_loss(nn.Module): def __init__(self, opt): super().__init__() self.opt = opt self.loss = nn.L1Loss() def single_loss(self, src_depth, tar_depth, K, src_RTs, tar_RTs, height, width): ...
Python
1
param_k.requires_grad = False teacher.eval() def ema_scheduler(start_decay=0.999, end_decay=0.9999, schedule_step=30000, current_step=0): assert start_decay <= 1 assert end_decay <= 1 assert current_step >= 0 gap = end_decay - start_decay if current_step >= schedule_step: return...
Python
1
"""NullablePhotos Revision ID: 2cea75ad840c Revises: 0f7d92e3888c Create Date: 2025-03-23 10:56:49.289920 """ from typing import Sequence, Union from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision: str = '2cea75ad840c' down_revi...
Python
1
# Copyright 2025 The HuggingFace Team. 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 applicabl...
Python
1
1, // end of x86_psll.i16x8 (I32) // 000a74: x86_psra.i16x8 (I32) // --> [Mp2fa#5e1] and stop 0x0137, 0x05e1, // end of x86_psra.i16x8 (I32) // 000a76: x86_psrl.i16x8 (I32) // --> [Mp2fa#5d1] and stop 0x0137, 0x05d1, // end of x86_psrl.i16x8 (I32) // 000a78: iabs.i32x4 (I32) ...
Rust
0
# # Copyright (C) 2010-2017 Samuel Abels # The MIT License (MIT) # # 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 rights to use, copy,...
Python
1
rng.gen(), MAX_GAS_PER_TX, rng.gen(), maturity, 0, rng.gen(), vec![], vec![], vec![], vec![], vec![], ) .validate_without_signature(block_height, &CONSENSUS_PARAMS) .err() .expect("Expected erroneous transaction"); ...
Rust
0
""" Preload PySNMP MIBs +++++++++++++++++++ Send a series of SNMP GETNEXT requests using the following options: * with SNMPv2c, community name "public" * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for all OIDs starting from 1.3.6 * with MIB lookup enabled * preload all Python MIB modules found in search p...
Python
1
from clarifai.rest import ClarifaiApp def recognize_vegetables(api_key, image_url): # Initialize the Clarifai application app = ClarifaiApp(api_key=api_key) # Use the general model for image recognition model = app.public_models.general_model # Predict concepts (vegetable names) in the image ...
Python
1
table = tabulate.tabulate(resultsList, headers=['#',] + headers, showindex='always', tablefmt='pretty') print(table) if args.first > 0: out(f'\n[+] Found {len(resultsList)} symbols meeting all the criterias (but shown only first {args.first} ones).\n') el...
Python
1
import pygame from player import Player from projectile import Projectile from enemy import Enemy pygame.init() pygame.display.set_caption('First Game') screen_width = 500 screen_length = 480 win = pygame.display.set_mode((screen_width,screen_length)) clock = pygame.time.Clock() bg = pygame.image.load('pygame_game\\re...
Python
1
eck!(2); check!(3); check!(4); check!(10); check!(100); check!(1456789); check!(12345678); check!(123456789); check!(17473551615); check!(1744073551615); check!(1744073709551615); check!(18446744073709551615); } #[bench] ...
Rust
0
mut PageTable) } /// Get a reference to a recursively-mapped Page Directory. pub unsafe fn get_pd(pdp_idx: usize, pd_idx: usize) -> &'static mut PageTable { let pd_addr = PD_RECURSIVE_BASE + (0x20_0000 * pdp_idx) + (0x1000 * pd_idx); &mut *(pd_addr as *mut PageTable) } /// Get a re...
Rust
0
from django.conf import settings from jinja2.ext import Extension from jinja2 import nodes def format_path_for_latex(path): path = path.replace("\\", "/") if not path.endswith("/"): path += "/" if getattr(settings, "LATEX_INTERPRETER", None) != "lualatex" and " " in path: path = '"' + path...
Python
1
from collections import deque def bfs(board, words): initial_board = "".join(["".join(row) for row in board]) queue = deque([(initial_board, "")]) visited = set([initial_board]) while queue: current_board, actions = queue.popleft() if current_board == "".join(words): retur...
Python
1
s the rightmost node in the tree, unless that node is blank (not yet input) in which case we render its left sibling. """ while True: if isinstance(expr, Node): if isinstance(expr.right, Const): if expr.right.value == "": return expr.left.value ...
Python
1
continue #Number of async non queue entries: 0 m = p15.match(line) if m: group = m.groupdict() krt_entry['krtq-async-non-q-count'] = group['krtq_async_non_q_count'] continue #Time until next queue run: 0 m =...
Python
1
:ident() $Ref:ident.$ref:ident()),*) => { $( impl_add_ops!($Op.$op(), $Op.$op() ; ; ); impl_add_ops!($Op.$op(), $Ref.$ref(); 'a; ); impl_add_ops!($Op.$op(), $Op.$op() ; ; 'b); impl_add_ops!($Op.$op(), $Ref.$ref(); 'a; 'b); )* } } macro_rules...
Rust
0
).shape == points.shape assert 'conn_000' in limbs.get_connection_names() assert 'part_000' in limbs.get_part_names() for i in range(connections.shape[0]): connections[i, :] += i limbs.set_connections(connections) # test by connection names conn_dict = limbs.get_connections_by_names() ...
Python
1
user_id: int): logger.info(f"Setting accepted rules in the database: {channel_id}, {user_id}") query = "INSERT INTO rules_accepted (channel_id, user_id) VALUES (%s, %s)" values = (channel_id, user_id) insert_query(connection, query, values) def get_accepted_rules(connection: PooledMySQLConnection | MyS...
Python
1
{ let got: Config = toml::from_str(indoc! {r#" tags = ["foo", "bar"] base_dir = "test" [targets.baz] [targets.qux] "#}) .unwrap(); assert_eq!( got, Config { tags: Some(hashset! {String::from("foo"), String::from("bar")}), base_dir: PathBuf::from("test"), work_dir: None, tar...
Rust
0
# pygame.math module # https://www.pygame.org/docs/ref/math.html # # Simple physics string # https://stackoverflow.com/questions/41862541/simple-physics-string/67749043#67749043 # # GitHub - PyGameExamplesAndAnswers - Draw 2D - Particles # https://github.com/Rabbid76/PyGameExamplesAndAnswers/blob/master/documentation/p...
Python
1
import heapq def shortest_path(matrix): # Convert matrix into graph graph = {} for i in range(len(matrix)): for j in range(len(matrix[i])): if matrix[i][j] != 'x': graph[(i, j)] = {} # Possible moves: up, down, left, right for x, y in [(0...
Python
1
teln!(w, "\tpub free: Option<extern \"C\" fn(this_arg: *mut c_void)>,").unwrap(); generated_fields.push(("free".to_owned(), None, None)); writeln!(w, "}}").unwrap(); macro_rules! impl_trait_for_c { ($t: expr, $impl_accessor: expr, $type_resolver: expr) => { for item in $t.items.iter() { match item { s...
Rust
0
op_from_pair!(HueRotate, i32); parse_op_from_pair!(Resize, (u32, u32)); parse_op_from_pair!(Unsharpen, (f32, i32)); parse_op_from_pair!(Filter3x3, [f32; 9]); macro_rules! parse_setenv_from_pair { ($env_item:tt, $ty:ty) => { #[allow(non_snake_case)] fn $env_item(pair: Pair<'_, Rule>) -> Result<Instr...
Rust
0
ile(check_gir_file)) => return run_check(&check_gir_file), Ok(RunKind::Config(cfg)) => cfg, Err(err) => return Err(err), }; cfg.check_disable_format(); let statistics = Profiler::new("Gir"); statistics.start_frame(); let watcher_total = statistics.enter("Total"); let mut libra...
Rust
0
er=product_request.requested_by.user, notification_content=requester_msg, related_request=product_request ) # Notify the receiver (confirmation to self) receiver_msg = f"You {product_request.status.lower()} the request for '{product_request.product.product_name}' from '{product_request.requ...
Python
1
y(self.zircon_process(), nohang).await? } WaitTarget::Pid(pid) => (pid, wait_child(self.zircon_process(), pid, nohang).await?), }; wstatus.write_if_not_null(code)?; Ok(pid as usize) } /// `sys_execve` executes the program referred to by `path` /// (see [linux...
Rust
0
import os import warnings # When Swagger performs OAuth2 in the browser, it will set # the request host + relative path as the redirect uri, causing a # uri mismatch if the oauth_redirect_uri is just the relative path # is set in the c.JupyterHub.services entry (as per default). # Therefore need to know the request ho...
Python
1
](struct.Dummy.html) slave logger. fn default() -> Self { Self { inner: ArcSwap::from(Arc::new(Box::new(Dummy) as Box<dyn Log>)), } } } /// A global [`Reroute`](struct.Reroute.html) object. /// /// This one is manipulated by the global functions: /// /// * [`init`](fn.init.html) ///...
Rust
0
/// largest cutoff diameter of potentials in `Interactions` maximum_cutoff: Option<f64>, } impl Resize { /// Create a new `Resize` move, with target pressure `pressure` and maximum /// displacement of `delta`. pub fn new(pressure: f64, delta: f64) -> Resize { assert!(delta > 0.0, "delta mu...
Rust
0
ms = BlockImportParams::new(BlockOrigin::File, new_header); params.post_digests.push(item); params.body = Some(new_body); params.intermediates.insert( Cow::from(INTERMEDIATE_KEY), Box::new(BabeIntermediate::<Block> { epoch_descriptor }) as Box<dyn Any>, ); params.fork_choice = Some(ForkCho...
Rust
0
ning is end. Args: state_key: The key of state in `self.t`. Returns: bool ''' # As a rule, the learning can not be stopped. x, y = state_key end_point_tuple = np.where(self.__map_arr == self.__end_point_label) end_point_x_arr, end_poin...
Python
1
s.verify(public_key, input) { Some(pos) } else { None } } pub fn to_verifiable_output(&self, public_key: &PublicKey, input: &[u8]) -> Option<OutputSeed> { if self.verify(public_key, input) { Some(self.u.clone()) } else { None ...
Rust
0
latest", "centos", "unstable/scylla/branch-2025.3/rpm/centos/latest/scylla.repo"), ("branch-2025.3:latest", "ubuntu", "unstable/scylla/branch-2025.3/deb/unified/latest/scylladb-2025.3/scylla.list"), ("branch-2025.3:latest", "debian", "unstable/scylla/branch-2025.3/deb/unified/latest/scylladb-2025.3/scylla.list"...
Python
1
h.insert("Lodsd_EAX_m32", Code::Lodsd_EAX_m32); h.insert("Lodsq_RAX_m64", Code::Lodsq_RAX_m64); h.insert("Scasb_AL_m8", Code::Scasb_AL_m8); h.insert("Scasw_AX_m16", Code::Scasw_AX_m16); h.insert("Scasd_EAX_m32", Code::Scasd_EAX_m32); h.insert("Scasq_RAX_m64", Code::Scasq_RAX_m64); h.insert("Mov_r8_imm8", Co...
Rust
0
, ForwardF32, CONTEXT32, CONTEXT64}; use crate::vector::{AvxF32x8, AvxF64x4}; #[target_feature(enable = "avx")] unsafe fn target_forward_f32x8( hap: &[u8], rs: &[u8], q: &[u8], i: &[u8], d: &[u8], c: &[u8], ) -> f32 { let v = AvxF32x8::new_uncheck...
Rust
0
ked into the Unix ancillary data format. #[inline] pub fn encoded_size(&self) -> usize { match self { Self::FileDescriptors(fds) => Self::encoded_size_of_file_descriptors(fds.len()), #[cfg(any(doc, not(any(target_os = "macos", target_os = "ios",)),))] Self::Credential...
Rust
0
pdate values taking precedence. Args: base: The base dictionary to merge into update: The dictionary with values to merge in (takes precedence) Returns: A new dictionary with deeply merged values """ result = copy.deepcopy(base) for key, value in update.items(): if...
Python
1
= "freopen$UNIX2003" )] pub fn freopen( filename: *const c_char, mode: *const c_char, file: *mut FILE, ) -> *mut FILE; pub fn fflush(file: *mut FILE) -> c_int; pub fn fclose(file: *mut FILE) -> c_int; pub fn remove(filename: *const c_char) -> c_int; pub fn rename(old...
Rust
0
e('%Y-%m-%dT%H:%M:%S') # workflow_node.setAttribute('current_step_launch_time', t) # workflow_node.setAttribute('percentageComplete', '100.0') # try: # workflow_node.removeAttribute('current_step_id') # except xml.dom.NotFoundErr: # pass # try: # ...
Python
1
HEX_STR = set(['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']) def find_all_freed_indexes(pattern:str): ''' 查找pattern中*出现的全部索引 ''' indexes = [] for i in range(32): if pattern[i] == '*': indexes.append(i) return indexes def pattern2ipv6s_6graph(pattern,se...
Python
1
ct: &[], tag: [0x70c7123f, 0xc819aa06, 0x0ed2d3c1, 0x59b6ea41], }, Gcm { key: [0x281a570b, 0x1e8f265e, 0xe09303ec, 0xae0cc46d], iv: [0x8c2941f7, 0x3cf8713a, 0xd5bc13df], pt: &[], aad: &[], ct: &[], tag: [0xa42e5e5f, 0x6fb00a9f, 0x1206b302, 0xedbfd...
Rust
0
# sort three num count=0 print 'please input three num for sort' while count <3: print 'please input num%d'%(count+1) input=raw_input('num%d='%(count+1)) if input.isdigit()==False: print 'input error, not a num' continue count+=1 if count==1: num1=input #print 'num1 is',num1 elif count==2: num2=inpu...
Python
1
ateScore(m): if _fscores is None: readFragmentScores() # fragment score fp = rdMolDescriptors.GetMorganFingerprint(m, 2) # <- 2 is the *radius* of the circular fingerprint fps = fp.GetNonzeroElements() score1 = 0. nf = 0 for bitId, v i...
Python
1
cribers: Vec<&Addr<WSClient>> = self .bbox_subscriptions .iter() .filter(|(_, bbox)| bbox.contains(position.longitude, position.latitude)) .map(|(addr, _)| addr) .filter(|addr| id_subscribers.map_or(true, |list| !list.contains(addr))) ...
Rust
0
ZE, ) .map_err(Error::ProtectVm)?; } for (vcpu_id, vcpu) in vcpus.iter().enumerate() { use_pmu &= vcpu.init_pmu(AARCH64_PMU_IRQ as u64 + 16).is_ok(); if has_pvtime { vcpu.init_pvtime(AARCH64_PVTIME_IPA_START + (vcpu_id as u64 * AARCH64_PVT...
Rust
0
self.bits = bits; self } #[doc = "Bit 0 - DMA Transfer Enable"] #[inline(always)] pub fn usb_dmactl6_enable(&mut self) -> _USB_DMACTL6_ENABLEW { _USB_DMACTL6_ENABLEW { w: self } } #[doc = "Bit 1 - DMA Direction"] #[inline(always)] pub fn usb_dmactl6_dir(&mut self) -> ...
Rust
0
# portalocker.py - Cross-platform (posix/nt) API for flock-style file locking. # Requires python 1.5.2 or better. """Cross-platform (posix/nt) API for flock-style file locking. Synopsis: import portalocker file = open("somefile", "r+") portalocker.lock(file, portalocker.LOCK_EX) file.seek...
Python
1
} fn changed(self: Rc<Self>) { self.inner.clone().changed(); } } /// A handle returned by [`use_atom`]. /// /// This type dereferences to `T` and has a `set` method to set value for current state. pub struct UseAtomHandle<T> where T: Atom, { inner: UseSliceHandle<AtomSlice<T>>, } impl<T> UseA...
Rust
0
def get_dummy_components(self): prior = self.dummy_prior prior_text_encoder = self.dummy_prior_text_encoder scheduler = DDPMWuerstchenScheduler() tokenizer = self.dummy_tokenizer text_encoder = self.dummy_text_encoder decoder = self.dummy_decoder vqgan = self.dummy_vqgan components = {'t...
Python
1
_id print(f"Tokenizer未设置pad_token,已自动设为eos_token_id: {tokenizer.eos_token_id}") # 2. 准备输入数据 print(f"正在准备 {NUM_CONCURRENT_REQUESTS} 路并发输入数据...") prompts_batch = generate_prompt_batch(tokenizer, TARGET_PROMPT_TOKENS, NUM_CONCURRENT_REQUESTS) # 对整个批次进行分词 # 注意:HuggingFace的padding默认是向右填充(paddin...
Python
1