text
string
label_name
string
labels
int64
>>, hovered_snap_point: Res<HoveredSnapPoint>, mut draggables: Query<(Entity, &Draggable, &Dragged, &mut Transform), With<Interactable>>, mut commands: Commands, ) { // Ignore non-mouse click events // XXX: Eventually we'll want to map this more dynamically to enable controller remaps if !mouse_...
Rust
0
str.parse::<u32>().unwrap(); let digit_count = (words.len() as f64).log(base as f64).ceil() as usize; let mut digits = vec![1u32; digit_count]; for word in words.iter() { // Print dice rolls. for d in 0..digit_count { print!("{}", digits[digit_count - 1 -...
Rust
0
"a1"], )?; Ok(()) } } <gh_stars>1-10 use std::io; use std::io::Read; use std::fs::File; //fn read_username_from_file() ->Result<String,io:: Error>{ // let f = File::open("123.txt"); // let mut f= match f{ // Ok(file) =>file, // Err(error) =>return Err(error), // }; // // ...
Rust
0
defined on line 4 | 3 | alias foo := bar | ^^^ ", status: EXIT_FAILURE, } test! { name: alias_show, justfile: "foo:\n bar\nalias f := foo", args: ("--show", "f"), stdout: " alias f := foo foo: bar ", } test! { name: alias_show_missing_target, justfile: "alia...
Rust
0
pub duid: String, /// Offered PASA Availability of Scheduled generator DUID for the day. pub pasaavailability: Option<rust_decimal::Decimal>, #[serde(with = "crate::mms_datetime_opt")] pub latest_offer_datetime: Option<chrono::NaiveDateTime>, #[serde(with = "crate::mms_datetime_opt")] pub l...
Rust
0
as usize; fast = nums[nums[fast] as usize] as usize; } fast = 0; while slow != fast { slow = nums[slow] as usize; fast = nums[fast] as usize; } slow as i32 } } use std::cmp::{max, min}; use std::option::Option; use plonky2_util::{log2_st...
Rust
0
Serialize}; use sqlx::{postgres::PgConnection, Row}; #[derive(Serialize, Deserialize, Clone, Debug)] pub struct PlayerPagination { #[serde(default, deserialize_with = "non_nullable")] #[serde(rename = "before")] pub before_id: Option<i32>, #[serde(default, deserialize_with = "non_nullable")] #[se...
Rust
0
t any(command.startswith(cmd) for cmd in allowed_commands): return jsonify({ "status": "error", "message": f"Command not allowed. Allowed commands: {', '.join(allowed_commands)}" }), 400 result = execute_command(command) return jsonify({ "status": "success", ...
Python
1
#!/usr/bin/env python3 # Usage: reverse.py <zone_filename>... # # This demo script will load in all of the zones specified by the # filenames on the command line, find all the A RRs in them, and # construct a reverse mapping table that maps each IP address used to # the list of names mapping to that address. The tabl...
Python
1
dbypass(&mut self) -> _RXDBYPASSW { _RXDBYPASSW { w: self } } } <reponame>ferristseng/rust-tfidf // Copyright 2016 rust-tfidf Developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource...
Rust
0
frm_dms(0, 0, 0.42665) + y) + t*angle::deg_frm_dms(0, 0, 0.041833)))).to_radians(); let A = old_dec.cos() * (old_asc + xi).sin(); let B = theta.cos() * old_dec.cos() * (old_asc + xi).cos() - theta.sin() * old_dec.sin(); let C = theta.sin() * old_dec.cos(...
Rust
0
# # simple unpacker/deobfuscator for scripts messed up with # javascriptobfuscator.com # # written by Einar Lielmanis <einar@jsbeautifier.org> # rewritten in Python by Stefano Sanfilippo <a.little.coder@gmail.com> # # Will always return valid javascript: if `detect()` is false, `code` is # returned, unmodified....
Python
1
index_pos) = (data.head.pos, data.index.pos); let head_val = pass_msg!(data.head.accept(self)?); let list = match head_val.get_type() { ValueType::Vector => head_val.to_list(head_pos)?.borrow().clone(), ValueType::Str => head_val.to_str(head_pos)?.chars().map(|c| Str::new(c.to_string())).collect(), typ =>...
Rust
0
InvalidAODataWrite: ::std::os::raw::c_int = -200561; pub const DAQmxErrorWaitUntilDoneDoesNotIndicateDone: ::std::os::raw::c_int = -200560; pub const DAQmxErrorMultiChanTypesInTask: ::std::os::raw::c_int = -200559; pub const DAQmxErrorMultiDevsInTask: ::std::os::raw::c_int = -200558; pub const DAQmxErrorCannotSetPr...
Rust
0
COM, projected to xy for i, layer in enumerate(tower.block_info): blocks[i, :] = [t is not None for t in layer] return np.concatenate( ([tower.height()], COMs.flatten(), blocks.flatten(), ) ) BASIC_FEATURESIZE = 1 + INITIAL_SIZE*3*2 + INITIAL_SIZE*3*3 max_mod = ...
Python
1
println!("\nSetting sweep mode to logarithm:\n{}", command); } let inbuf: Vec<u8> = command.as_bytes().to_vec(); let mut outbuf: Vec<u8> = (0..SET_SWEEP_MODE_RES_LEN).collect(); if !port.mock { port.port.as_mut().unwrap().write(&inbuf[..])?; port.port.as_mut().unwrap().read(&mut outbuf[..])?; } let res = ...
Rust
0
rd<'a, Shard<T>> { let mut h = crate::FastHashBuilder::default().build_hasher(); elem.hash(&mut h); // Hash a little extra, so that the hash here is distinct from the one // used within the individual shard. SHARD_COUNT.hash(&mut h); let shard_index = h.finish() as usize ...
Rust
0
); let mut line = shape2d::Line::new(points, color, 1); line.draw(&mut canvas); line.transform(Transform::ShearX(0.0, 0.0, 1.2)); line.draw(&mut canvas); save_image(Canvas::to_photon(&canvas), "tests/outputs/canvas_line_ShearX.png"); } #[test] fn test_line_shear_y() { let mut canvas = Canvas::ne...
Rust
0
AObj: usize) -> TAnchors; pub fn ToolBar_SetAnchors(AObj: usize, AValue: TAnchors); pub fn ToolBar_GetAutoSize(AObj: usize) -> bool; pub fn ToolBar_SetAutoSize(AObj: usize, AValue: bool); pub fn ToolBar_GetBorderWidth(AObj: usize) -> i32; pub fn ToolBar_SetBorderWidth(AObj: usize, AValue: i32); pub fn ToolB...
Rust
0
logger.info(f" 图片file: {getattr(quoted_comp, 'file', 'N/A')}") logger.info(f" 图片url: {getattr(quoted_comp, 'url', 'N/A')}") logger.info(f" 图片所有属性: {quoted_comp.__dict__}") else: logger.info("引用消息链为空") ...
Python
1
the names of the metrics, and the values are corresponding results. """ # NOTICE: don't access `self.results` from the method. `self.results` # are a list of results from multiple batch, while the input `results` # are the collected results. # concat target =...
Python
1
best_eval = {} for metric in args.metric_types.split(','): for log_key in best_log.keys(): if metric in log_key: best_eval[metric] = best_log[log_key] break f.write('LeCaRDv2 Best Test Record: '+str(Test_results)+'\n') # 写入LeCaRD的测试结果 f.write('L...
Python
1
found_description_start = True break else: # These lines are part of the description block description_lines.insert(0, raw_lines[k].strip()) if found_description_start and description_lines: ...
Python
1
"))] pub unsafe fn mmap( addr: *mut u8, len: usize, prot: u64, flags: u64, fd: u64, offset: i64, ) -> Result<*mut u8, MmapError> { let addr = addr as i64; let out_addr: i64; let err: i64; asm!( r" // Make a syscall, using the parameters in the registers s...
Rust
0
pub TransitionState: VDS_TRANSITION_STATE, pub ulFlags: u32, pub ulStripeSize: u32, pub sRebuildPriority: i16, } impl ::core::marker::Copy for VDS_LUN_PLEX_PROP {} impl ::core::clone::Clone for VDS_LUN_PLEX_PROP { fn clone(&self) -> Self { *self } } #[doc = "*Required features: `\"Win32...
Rust
0
{i += gaussian_filter.len()} else {i+= 1;} out_px +=1; } Ok(output) } fn edge_detection_no_bs(img: &Vec<LWE>, w: &usize, h: &usize, sk: &LWESecretKey) -> Result<Vec<(LWE, LWE)>, CryptoAPIError> { println!("Executing Edge Detection"); let mut output = Vec::<(LWE, LWE)>::new(); let sobel_filter = [[-1, 0, 1]...
Rust
0
rror { reason: format!("Pattern did not match {}", segment), })?; let tx_name = caps[1].to_string(); let auditor = Party::try_from((&caps[2], PartyKind::Auditor))?; Ok(Self { tx_id, tx_name, auditor, }) } } /// Human readable f...
Rust
0
gerador_senhas,width=590,height=220) fr_generate3.pack(padx=5,pady=5) nb_pass = ctk.CTkTabview(master=fr_generate3, width=580, height=210) nb_pass.place(x=5,y=5) nb_pass.add("Password") # add tab at the end #tabview.set("Password") fr_generate3_a=ctk.CTkFrame(master=nb_pass.tab("Password")) fr_generate3_a.place(x=5...
Python
1
(None, Some(case)); } let mut child_cases: Vec<Case> = Vec::new(); let mut child_suites: Vec<Suite> = Vec::new(); for c in &node.children { let (child_suite, child_case) = third_pass(c, false); match child_case { Some(case) => { child_cases.push(case); ...
Rust
0
fn cpy(&mut self, mode: AddrMode) { let addr = self.operand_addr(mode); let v = self.fetch_operand(addr, mode); self.cmp(self.y(), v); } /// Branch if carry set fn bcs(&mut self, _mode: AddrMode) { self.branch(self.p.contains(Flags::C)); } /// Branch if carry cl...
Rust
0
er_info: try: c_info["resource_id"] = r_id container_name = get_container_name(c_info) c_id = process_container(c_info, container_name) if c_info["software_name"]: s_id = proc...
Python
1
return Llm(model, tokenizer, points.pythia(pythia_id)) def llama2( llama_id: Llama2Id, device: torch.device, use_half_precision: bool, ) -> Llm[LlamaForCausalLM, PreTrainedTokenizerFast]: dtype = torch.bfloat16 if use_half_precision else torch.float32 model = AutoModelForCausalLM.from_pretraine...
Python
1
(); // const N_ELEMENTS: usize = 1000; // for i in 0..N_ELEMENTS { // v.push(i); // } // b.iter(|| { // let mut acc = 0; // for i in 0..N_ELEMENTS { // acc += v[i]; // } // acc // }); // } #[derive(thiserror::Error, Debug)] pub enum SystemServiceE...
Rust
0
com/reference/android/content/res/Configuration.html#UI_MODE_NIGHT_MASK) pub const UI_MODE_NIGHT_MASK : i32 = 48; /// public static final [UI_MODE_NIGHT_NO](https://developer.android.com/reference/android/content/res/Configuration.html#UI_MODE_NIGHT_NO) pub const UI_MODE_NIGHT_NO : i32 = 16; ...
Rust
0
true), cmd::arg("priv-key", "the private key in WIF/hex").required(true), cmd::arg("compressed", "Whether the corresponding pk is compressed") .required(false) .default_value("true"), cmd::opt("raw-stdout", "output the raw bytes of the result to stdout") .short("r") .required(false), cmd::opt("outpu...
Rust
0
from trunklucator import WebUI title = "News classification" news_titles = [ "Half of all older adults are worried about dementia, survey says", "Telus invests $500,000 to bring wireless service to First Nation’s community in B.C.", "Asteroid Bigger Than the Eiffel Tower Approaching Earth at 20 Times the ...
Python
1
::new( ErrorKind::Other, "Failed get_pull_requests", ))) } let json = response.json::<ResponseRoot>().await?; for pull_request_node in json.data.viewer.pullRequests.nodes { pull_requests.push(pull_request_node) } end_cursor...
Rust
0
builder.set_text_large_type(" ".to_owned()); } else { builder.set_text_large_type(self.items.join("\n")); } if let Some(ref doc_path) = self.doc_path { let doc_url = format!("https://doc.rust-lang.org/{}", doc_path); builder.set_quicklook_url(doc_url.clon...
Rust
0
## @auther: pp ## @date: 2024/10/15 20:31 ## @description: import os from src.utils.utility import Utility work_space = os.getcwd() raw_imdb_tar = os.path.join(work_space, 'data', 'raw', 'imdb', 'aclImdb_v1.tar.gz') processed_imdb_dir = os.path.join(work_space, 'data', 'processed', 'imdb') # 解压imdb.tar.gz Utility....
Python
1
DamageSystem, "damage", &["melee_combat", "use_item"]) .with(ParticleSpawnSystem, "particle", &["damage"]) .build(); SysRunner { dispatcher } } pub fn run(&mut self, ecs: &mut World) { self.dispatcher.dispatch(ecs); ecs.maintain(); } } //! Provides the `Ins...
Rust
0
import os import ament_index_python.packages from launch import LaunchDescription from launch_ros.actions import ComposableNodeContainer from launch_ros.descriptions import ComposableNode import yaml def generate_launch_description(): share_dir = ament_index_python.packages.get_package_share_directory('kobuki_...
Python
1
import numpy as np import argparse, os, sys if __name__ == '__main__': parser = argparse.ArgumentParser(description='') parser.add_argument('--ltc_npy', type=str, help='') parser.add_argument('--amp_npy', type=str, help='') parser.add_argument('--output', type=str, help='Output text file') args = p...
Python
1
t bs2: [bool; S] = random_bool_initialization(); for i in 0..bs1.len() { let b1 = bs1[i]; let b2 = bs2[i]; let nand = !(b1 && b2); let c1 = tlwe.encrypt(b1); let c2 = tlwe.encrypt(b2); let c = homnand(c1, c2, sk); let msg = tlwe.decrypt(c); count +=...
Rust
0
5, 2, 3, 4), Greater); assert_eq!(cmp2(5, 5, 5, 4), Greater); } #[test] fn test_int_totaleq() { assert!(5.equals(&5)); assert!(!2.equals(&17)); } #[test] fn test_ordering_order() { assert!(Less < Equal); assert_eq!(Greater.cmp(&Less), Greater); } ...
Rust
0
, like Gecko) Firefox/58.0.1", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:54.0) Gecko/20100101 Firefox/58.0", "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:52.59.12) Gecko/20160044 Firefox/52.59.12", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:46.0) Gecko/20120121 Firefox/46.0", "Mozilla/5.0 (Windows NT 10.0; WOW64;...
Rust
0
import os import time import numpy as np import torch from torch import nn from butterfly_factor import butterfly_factor_mult_intermediate # from butterfly import Block2x2DiagProduct # from test_factor_multiply import twiddle_list_concat exps = np.arange(6, 14) sizes = 1 << exps batch_size = 256 ntrials = [100000...
Python
1
f.__dict__.items(): if key.startswith("_"): continue try: dict_data[key] = pickle.dumps(value) except Exception as e: user_system_log.warn("context.{} can not pickle", key) return pickle.dumps(dict_data) def set_state(self,...
Python
1
ff_file: ANNOTATION.parse().unwrap(), panel_file: PANEL.parse().unwrap(), reference_file: REF.parse().unwrap(), padding: 100, outdir: PathBuf::from(outdir.path()), match_len: 5, ..Build::default() }; let result = builder.run(); ...
Rust
0
"Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // Th...
Rust
0
stacks = [[], ['Blue', 'Blue', 'Green', 'Red'], [], ['Green', 'Red', 'Yellow', 'Yellow'], [], ['Green', 'Red', 'Blue', 'Yellow']] costs = {0: 3, 1: 5, 2: 1, 3: 6, 4: 7, 5: 4} min_cost = float('inf') best_moves = [] def is_valid_move(src, dest): if not src or (dest and src[-1] != dest[-1]): return False ...
Python
1
# ------------------------------------------------------------------ # Copyright (c) 2023 PyInstaller Development Team. # # This file is distributed under the terms of the GNU General Public # License (version 2.0 or later). # # The full license is available in LICENSE, distributed with # this software. # # SPDX-Licens...
Python
1
ding='VALID') layers['pool5_r'] = tf.reshape(layers['pool5'], [-1, 2048]) with tf.name_scope('fc1000'): layers['fc1000'] = fully_connected( layers['pool5_r'], weights['fc1000']['weights'], weights['fc1000']['biases']) layers['prob'] = tf.nn.softmax(layers['fc1000']) return ...
Python
1
_mm256_unpackhi_epi16(coeffs_abs, _mm256_setzero_si256()), ), log_tx_scale, ), ), coeffs, ); _mm256_store_si256(rcoeffs_ptr as *mut _, rcoeffs); // Only use a dc quantizer for the first iteration quants = quants_ac; coeffs_ptr = coeffs_ptr.add(st...
Rust
0
, /// `LOOPE rel8` /// /// `a16 o32 E1 cb` /// /// `386+` /// /// `16/32-bit` Loope_rel8_32_CX = 665, /// `LOOPE rel8` /// /// `a32 o16 E1 cb` /// /// `386+` /// /// `16/32/64-bit` Loope_rel8_16_ECX = 666, /// `LOOPE rel8` /// /// `a32 o32 E1 cb` /// /// `386+` /// /// `16/32-bit` Loope_rel8_32_...
Rust
0
"Accelerate config": f"{accelerate_config_str}", "PyTorch version (GPU?)": f"{pt_version} ({pt_cuda_available})", "Tensorflow version (GPU?)": f"{tf_version} ({tf_cuda_available})", "Flax version (CPU?/GPU?/TPU?)": f"{flax_version} ({jax_backend})", "Jax version"...
Python
1
ter window when running program. """ screen_width = app.winfo_screenwidth() screen_height = app.winfo_screenheight() x_position = (screen_width - width) // 2 y_position = (screen_height - height) // 2 app.geometry(f"{width}x{height}+{x_position}+{y_position}") def open_log(): """ Opens the lo...
Python
1
#author: Peter Okma import xml.etree.ElementTree as et class Feedback(): """Feeback used by Alfred Script Filter Usage: fb = Feedback() fb.add_item('Hello', 'World') fb.add_item('Foo', 'Bar') print(fb) """ def __init__(self): self.feedback = et.Element('items...
Python
1
ix("global::").unwrap_or(l).len() < 8) || matches!((i, next), (Instruction::RTS, Instruction::Label(lbl)) if !(lbl.starts_with("if") || lbl.starts_with("for") || lbl.starts_with("while"))) || matches!((i, next), (Instruction::FCB(_), Instruction::Label(_))) || matches!((i, next), (Instruction::Label(_), Instru...
Rust
0
"""GUI layouts Organize GUI controls using folders, tabs, and nested structures for better user experience. **Features:** * :meth:`viser.GuiApi.add_folder` for grouping related controls * :meth:`viser.GuiApi.add_tab_group` and :meth:`viser.GuiTabGroupHandle.add_tab` for tabbed interfaces * Nested folder hierarchies ...
Python
1
} } } <filename>src/invert_tree.rs //! # 226. 翻转二叉树 //! //! 难度 简单 //! //! 翻转一棵二叉树。 //! //! ## 示例: //! //! 输入: //! ```text //! 4 //! / \ //! 2 7 //! / \ / \ //! 1 3 6 9 //! ``` //! //! 输出: //! ```text //! 4 //! / \ //! 7 2 //! / \ / \ //! 9 6 3 1 //! ``` //! //! ##...
Rust
0
score = coherence_result.value * 10 depth_of_analysis_score = depth_of_analysis_result.value * 10 # Calculate overall score as average of all four metrics overall_score = ( logical_reasoning_score + factual_accuracy_score + coherence_score + depth_of_analysis_score ...
Python
1
from ..utils import * from .graderregistry import CYaRonGraders from .mismatch import TextMismatch @CYaRonGraders.grader("NOIPStyle") def noipstyle(content, std): content_lines = strtolines(content.replace('\r\n', '\n')) std_lines = strtolines(std.replace('\r\n', '\n')) if len(content_lines) != len(std_li...
Python
1
F, D> { ArgminParam(&self.0 - &other.0) } } impl<F: Float, D: Dimension> ArgminAdd<ArgminParam<F, D>, ArgminParam<F, D>> for ArgminParam<F, D> { fn add(&self, other: &ArgminParam<F, D>) -> ArgminParam<F, D> { ArgminParam(&self.0 + &other.0) } } impl<F: Float, D: Dimension> ArgminDot<Argmin...
Rust
0
e): if overwrite: shutil.rmtree(output_dir) os.makedirs(output_dir) if not os.path.exists(output_dir): os.makedirs(output_dir) abs_op_contents = {} file_contents = collections.defaultdict(list) all_schemas = onnx.defs.get_all_schemas_with_history() for schema in all_schemas: since_version = ...
Python
1
import torch.utils.data as data from PIL import Image import torchvision.transforms as transforms import numpy as np import random class BaseDataset(data.Dataset): def __init__(self): super(BaseDataset, self).__init__() def name(self): return 'BaseDataset' def initialize(self, opt): ...
Python
1
T: Clone> Clone for LinkedList<T> { fn clone(&self) -> Self { self.iter().cloned().collect() } } impl<'a, T> IntoIterator for &'a LinkedList<T> { type Item = &'a T; type IntoIter = Iter<'a, T>; fn into_iter(self) -> Iter<'a, T> { self.iter() } } impl<'a, T> IntoIterator for &'a mut LinkedL...
Rust
0
o_run /// # extern crate hyper; /// # extern crate hyper_rustls; /// # extern crate google_photoslibrary1 as photoslibrary1; /// use photoslibrary1::api::AddEnrichmentToAlbumRequest; /// # async fn dox() { /// # use std::default::Default; /// # use photoslibrary1::{PhotosLibrary, oauth2, hyper, hyper_rustls}; /// /// ...
Rust
0
Returns: Tuple of (optimized_messages, context_usage, optimization_info) """ # Initial analysis context_usage = self.analyze_context_usage(messages, search_results_tokens) optimization_info = {'sliding_applied': False} # Check if we need to apply slid...
Python
1
use pallet::*; #[cfg(test)] mod mock; #[cfg(test)] mod tests; type BalanceOf<T> = <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance; pub const MINIMUM_LIQUIDITY: u128 = 1000; // 10**3; #[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug, MaxEncodedLen, TypeInfo)] pub ...
Rust
0
asterizer error") print("means3D_final:", means3D_final.shape) print("means2D:", means2D.shape) print("shs_final:", shs_final.shape) print("opacity:", opacity.shape) print("cov3D_precomp:", cov3D_precomp.shape) import pdb ; pdb.set_trace() # Those Gaussians that were...
Python
1
ew(GFF_FILE, GffType::GFF3); for (i, r) in reader.records().enumerate() { let record = r.unwrap(); assert_eq!(record.seqname(), seqname[i]); assert_eq!(record.source(), source[i]); assert_eq!(record.feature_type(), feature_type[i]); assert_eq!(*record....
Rust
0
:5659").unwrap(); backend.set_compression(compression); let logger = Logger::new(Box::new(backend)).expect("Should create with success"); log_message_characters_benchmark(logger, group) } fn log_compression_gzip_benchmark(c: &mut Criterion) { for level in 1..=12 { let compression = MessageCom...
Rust
0
@cached_property def summary(self) -> SummaryResourceWithStreamingResponse: return SummaryResourceWithStreamingResponse(self._leaked_credentials.summary) @cached_property def timeseries_groups(self) -> TimeseriesGroupsResourceWithStreamingResponse: return TimeseriesGroupsResourceWithStrea...
Python
1
.spawn_bundle(camera::DollyCameraBundle::new()) .insert_bundle(PickingCameraBundle::default()); let theta = std::f32::consts::FRAC_PI_4; let light_transform = Mat4::from_euler(EulerRot::ZYX, 0.0, std::f32::consts::FRAC_PI_4, -theta); commands.spawn_bundle(DirectionalLightBundle { transf...
Rust
0
ct::<Vec<_>>(); let next_authorities = queued_validators.map(|(_account, k)| (k, 1)).collect::<Vec<_>>(); Self::enact_epoch_change(authorities, next_authorities) } fn on_disabled(i: usize) { Self::deposit_consensus(ConsensusLog::OnDisabled(i as u32)) } } // compute randomness for a new epoch. rho is the co...
Rust
0
; while i < 18 { let (new_l, new_r) = self.encrypt(l ^ next_u32_wrap(salt, &mut salt_pos), r ^ next_u32_wrap(salt, &mut salt_pos)); l = new_l; r = new_r; self.p[i] = l; self.p[i+1] = r; i += 2 } for i in 0..4 { l...
Rust
0
esponse(404) self.end_headers() self.wfile.write('not found'.encode('utf8')) def handle_GET(self): """ Overwrite this method to handle a GET request. The default action is to respond with "error 404 (not found)". """ self.send_response(404) self.end_h...
Python
1
# get cdist wrapper cdist_fn = getattr(_distance_wrap, "cdist_%s_%s_wrap" % (metric_name, typ)) cdist_fn(XA, XB, dm, **kwargs) return dm elif mstr.startswith("test_"): if mstr in _TEST_METRICS: dm = cdist(XA, XB, ...
Python
1
; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PacketData { pub token: PrefixedCoin, pub sender: Signer, pub receiver: Signer, } impl TryFrom<RawPacketData> for PacketData { type Error = Error; fn try_from(raw_pkt_data: RawPacketData) -> Result<Self, Self::Error> { ...
Rust
0
from sqlalchemy import Column, String, Float, DateTime, BigInteger, PrimaryKeyConstraint from infrastructure.db.db_manager import Base class IntradayOhlcv(Base): """ OHLCV 원시 데이터를 저장하는 테이블. 분봉(1m, 5m, 15m, 1h)과 일봉(1d) 데이터를 모두 저장합니다. 데이터의 '단일 진실 공급원(Single Source of Truth)' 역할을 합니다. """ __tabl...
Python
1
from aiogram import Router, F from aiogram.enums import ParseMode from aiogram.fsm.context import FSMContext from aiogram.fsm.state import State, StatesGroup from aiogram.types import CallbackQuery, Message from loguru import logger from utils import validate_excel_date from .get_all_data_to_excel_func import get_all_...
Python
1
; let renderer_builder = skulpin::RendererBuilder::new() .app_name(CString::new("Skulpin Example App").unwrap()) .use_vulkan_debug_layer(true); atelier_legion_demo::app::App::run( example_app, LogicalSize::new(900, 600), renderer_builder, ); } // Generated from defin...
Rust
0
ps >= self.neg_iou_thr[0]) & (max_overlaps < self.neg_iou_thr[1])] = 0 # 3. assign positive: above positive IoU threshold pos_inds = max_overlaps >= self.pos_iou_thr assigned_gt_inds[pos_inds] = argmax_overlaps[pos_inds] + 1 if self.match_low_quality: ...
Python
1
y two. // This will give us the amount to shift right by, selecting the correct two attribute bits. let x_component = v & 0b10; let y_component = (v >> 4) & 0b100; let shift = (y_component | x_component) as usize; let palette_nibble = (attr_byte >> shift) & 0b11; // Retu...
Rust
0
import time from AutoEncoder import * from CutTarget import cut_target_from_image, apply_mask from ImagePreProcessing import * from ImageTools import * # 计算两个图像之间的结构相似性指数(SSIM) def calculate_ssim(img1, img2): C1 = (0.01 * 255) ** 2 C2 = (0.03 * 255) ** 2 img1 = img1.astype(np.float64) img2 = img2.ast...
Python
1
nue except phonenumbers.NumberParseException: print(Colors.red + "Could not parse the number. Please enter a valid number.") input("Press Enter to return to the main menu.") continue def bing_search(query): query = urllib.parse.quote(query) url = f...
Python
1
total_seconds = update_interval.scenario_start.elapsed().as_secs_f32(); let new_rotation = ROTATION_DEG_PER_S * total_seconds; // Translation on z to be in the clipped space (between -w and w) and camera in front of the cube let z_translation: cgmath::Matrix4<f32> = cgmath::Matrix4:...
Rust
0
05; pub const HCI_PIN_OR_KEY_MISSING: i32 = 0x06; pub const HCI_MEMORY_FULL: i32 = 0x07; pub const HCI_CONNECTION_TIMEOUT: i32 = 0x08; pub const HCI_MAX_NUMBER_OF_CONNECTIONS: i32 = 0x09; pub const HCI_MAX_NUMBER_OF_SCO_CONNECTIONS: i32 = 0x0a; pub const HCI_ACL_CONNECTION_EXISTS: i32 = 0x0b; pub const HCI_COMMAND_DISA...
Rust
0
let mut list = SimpleLinkedList::new(); for i in item { list.push(i.clone()); } list } } impl<T> Into<Vec<T>> for SimpleLinkedList<T> { let l: int32 = 32; fn into(mut self) -> Vec<T> { let mut vec = Vec::new(); while let Some(data) = self.pop() { ...
Rust
0
for it,i in tqdm(enumerate(masks_option)): mask = [int(a) for a in "{0:b}".format(i)] # batch_tokens_masked = batch_tokens.clone() for m,pos in zip(mask, positions): if m == 1: input_tokens[it, 0, 1+mapp...
Python
1
goodmem_client.models.retrieve_memory_request import RetrieveMemoryRequest from goodmem_client.models.retrieved_item import RetrievedItem from goodmem_client.models.sentence_chunking_configuration import SentenceChunkingConfiguration from goodmem_client.models.separator_keep_strategy import SeparatorKeepStrategy from ...
Python
1
: u8, pub repulse_direction: u8, pub repulse_chunk_x: u8, pub repulse_chunk_y: u8, } #[repr(C)] pub struct UnitPath { pub path: *mut c_void, pub path_frame: u8, pub pathing_flags: u8, pub _unk106: u8, pub _unk107: u8, pub collision_points: [u16; 0x4], } #[repr(C)] pub struct PointA...
Rust
0
icate_pushdown::PredicatePushdown), // Lifts the information `!isnull(col)` Box::new(crate::nonnullable::NonNullable), // Lifts the information `col = literal` // TODO (#6613): this also tries to lift `!isnull(col)` but ...
Rust
0
[21] v+=flag[25] s.add(v == 628) v=-150 v+=flag[17] v+=flag[10] v+=flag[15] v+=flag[21] s.add(v == 174) v=-31 v+=flag[2] v+=flag[13] v+=flag[5] v+=flag[2] s.add(v == 420) v=-101 v+=flag[10] v+=flag[17] v+=flag[23] v+=flag[5] s.add(v == 272) v=-194 v+=flag[0] v+=flag[7] v+=flag[0] s.add(v == 33) v=-319 v+=flag[12] ...
Python
1
anaged by the inserter (usually the Perseus interface). However, this will change radically when Sycamore's /// proposals for fine-grained reactivity are stabilized. #[derive(Default, Clone)] pub struct GlobalState { /// A map of type IDs to anything, allowing one storage of each type (each type is intended to a pr...
Rust
0
::Value, E> where E: de::Error, { let result_level: LevelFilterWrapper = match value { "TRACE" => LevelFilterWrapper(LevelFilter::TRACE), "DEBUG" => LevelFilterWrapper(LevelFilter::DEBUG), "INFO" => LevelFilterWrapper(LevelFilter::INFO), "WARN" => LevelFilterWrapper(LevelFilter::WARN), ...
Rust
0
# Copyright 2017-2019 EPAM Systems, Inc. (https://www.epam.com/) # # 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 appli...
Python
1
l_type(Base): class Table(Base, table=True): id: int = Field(primary_key=True) x: decimal.Decimal y: decimal.Decimal = Field(max_digits=4, decimal_places=2) z: Annotated[decimal.Decimal, Field(max_digits=4, decimal_places=2)] columns = inspect(Table).columns assert type(colu...
Python
1
record(&["client", "available", "held", "total", "locked"])?; for (client_id, account) in storage.iter() { let total_amt = account.available.add(account.held)?; let client = format!("{}", client_id); let available = format!("{}", account.available); let held = format!("{}", account.h...
Rust
0
l_one_image(pred, predn, path, names, im) def on_val_end(self): # Callback runs on val end if self.wandb: files = sorted(self.save_dir.glob('val*.jpg')) self.wandb.log({"Validation": [wandb.Image(str(f), caption=f.name) for f in files]}) def on_fit_epoch_end(self, vals,...
Python
1