text
string
label_name
string
labels
int64
Coordinate { x: origin.x, y: new_diag.y, }, old_diag, )); } } } for rect in removed.iter_mut().chain(added.iter_mut()) { rect.map_coords_inplace(|&(x, y)| { ...
Rust
0
}], depth_stencil_attachment: None, }); render_pass.end_pass(); let _command_buffer = command_encoder.finish()?; Ok(instance) }); } #[test] fn submit_command_buffer() { vki::validate(|| { let (instance, _adapter, device) = support::init()?; ...
Rust
0
llis(1_000)); } /// Creates 2 different disconnected servers, mine a few blocks on one, connect /// them and check that the 2nd gets all the blocks #[test] fn simulate_full_sync() { util::init_test_logger(); // we actually set the chain_type in the ServerConfig below global::set_mining_mode(ChainTypes::AutomatedTe...
Rust
0
import frappe from typing import Optional class UserContextManager: """Manages user context for migration operations with proper fallback logic""" @staticmethod def get_migration_user() -> str: """Get appropriate user for migration operations with fallback logic""" try: # T...
Python
1
# http://www.python.org/dev/peps/pep-0396/ __version__ = '0.4.2'
Python
1
# Copyright (c) 2021 PaddlePaddle 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 appli...
Python
1
equest::TwoBytes(&mut buff); complex .on_port_read(PciRootComplex::PCI_CONFIG_DATA + 2, val, view) .unwrap(); assert_eq!(u16::from_be_bytes(buff), 0x29c0); } #[test] fn test_register_byte_read() { let mut complex = complex_ready_for_reg_read(0); let m...
Rust
0
from __future__ import annotations from typing import Any, Callable, Dict, Iterable, List, Optional, Union from subprocess import CalledProcessError from almond_cloud.config import CONFIG from clavier import sh import splatlog as logging LOG = logging.getLogger(__name__) TValue = Any GIT_CONFIG_PREFIX = "targets" ...
Python
1
for various formats. //! //! The `Stream` is treated as a single byte-stream to be compressed/decompressed, each item is a //! chunk of data from this byte-stream. There is not guaranteed to be a one-to-one relationship //! between chunks of data from the underlying stream and the resulting compressed/decompressed //!...
Rust
0
SAC去噪并获得局部网格内的特征点坐标(相对于整张图像的全局坐标) ## def _get_features_in_subframe(self, early_subframe, late_subframe, subframe_offset): ''' Helper method for _get_matched_features_and_homography. Track and return features that appear between the two given frames, eliminating outliers by applying ...
Python
1
11.0] ], [ [12.0, 12.0, 13.0, 14.0, 15.0, 15.0], [12.0, 12.0, 13.0, 14.0, 15.0, 15.0], [16.0, 16.0, 17.0, 18.0, 19.0, 19.0], [20.0, 20.0, 21.0, 22.0, 23.0, 23.0], [20.0, 20.0, 21.0, 22.0, 23.0, 23.0] ], ...
Rust
0
/// /// The spiral pattern looks like this: /// /// ```text /// 17 16 15 14 13 /// 18 5 4 3 12 /// 19 6 1 2 11 /// 20 7 8 9 10 /// 21 22 23---> ... /// ``` /// /// We take the number 1 to be at coordinate (0, 0), with the x-axis increasing to the right and /// the y-axis increasing upwards. ...
Rust
0
&[b"h2".to_vec()], Box::new(true), true, ), KeyhouseService::new(store), ) .await { error!("error starting server: {:?}", e); sleep(StdDuration::from_millis(3000)).await; std::process::exit(1); // TODO: find a way to panic in a thre...
Rust
0
(), DispatchError::InvalidSelector, ); } // Invalid call to `message` with unknown selector. { let mut input_bytes = Vec::new(); input_bytes.extend(selector_bytes!("unknown_selector")); assert_eq!( <<Contract as ContractConstructorDecoder>::Type ...
Rust
0
2VL and AVX512BW` /// /// `16/32/64-bit` EVEX_Vptestnmw_k_k1_ymm_ymmm256, /// `VPTESTNMW k2 {k1}, zmm2, zmm3/m512` /// /// `EVEX.512.F3.0F38.W1 26 /r` /// /// `AVX512BW` /// /// `16/32/64-bit` EVEX_Vptestnmw_k_k1_zmm_zmmm512, /// `VPTESTMD k2 {k1}, xmm2, xmm3/m128/m32bcst` /// /// `EVEX.128.66.0F38.W0 27 ...
Rust
0
ty = self.sources[sec as usize].ty; } } else { if self.sources[self.contents[i as usize]].seq == self.section { found1 = true; } } i -= 1; } if sec == ...
Rust
0
sine(&x,&y), 1.0, ulps=2)); } #[test] fn test_euclidean() { let x = [0.0,3.0]; let y = [4.0,0.0]; assert_eq!(distance::euclidean(&x,&y), 5.0); } #[test] fn test_euclideansq() { let x = [0.0,3.0]; let y = [4.0,0.0]; assert_eq!(distance::euclideansq(&x,&y), 25.0...
Rust
0
0..SIZE { for x in 0..SIZE { b[y][x] = ( ws[0] * a[y][(x+1)%SIZE] + ws[1] * a[y][(x+SIZE-1)%SIZE] + ws[2] * a[(y+1)%SIZE][x] + ws[3] * a[(y+SIZE-1)%SIZE][x] ) / 4.0; ...
Rust
0
///////////////////////////////////////////////////////////// // Sampling / interpolation /// IMPORTANT: source_min <= source_samplepoint < source_max /// dest_min < dest_max #[inline] pub fn sample_integer_upper_exclusive_floored( source_samplepoint: i32, source_min: i32, source_max: i32, d...
Rust
0
ch, args.epochs): if is_master(args): logging.info(f'Start epoch {epoch}') train_one_epoch(model, data, loss, epoch, optimizer, scaler, scheduler, dist_model, args, tb_writer=writer) completed_epoch = epoch + 1 if "t_cls" in data: for sub_data in data['t_cls']: ...
Python
1
#, "did you mean", ) } <gh_stars>0 use syntax::ast::Expr; use syntax::ast::ExprKind::*; pub trait ExprExt { fn is_location(&self) -> bool; } impl ExprExt for Expr { fn is_location(&self) -> bool { match self.node { Path(..) => true, Cast(ref expr, _) => expr.is_loca...
Rust
0
x = 0 while x < 5: print(x, end=" ") x += 1 print() # Starting from 0 to 10 for y in range(10): print(y, end=" ") print() # Starting from 2 to 6 # Note that 7 is not included for y in range(2, 7): print(y, end=" ") print() # Starting from 0 to 10 increasing by 2 for y in range(0, 10, 2): prin...
Python
1
from __future__ import annotations from .points import Point, MultiPointGeometry # noqa (API import) from .line import ( # noqa (API import) LineAxis0, LineAxis0Multi, LinesAxis1, LinesAxis1XConstant, LinesAxis1YConstant, LinesAxis1Ragged, LineAxis1Geometry, ) from .area import ( # noqa ...
Python
1
import tkinter as tk from tkinter import ttk from tabs.project_config import create_project_config_tab from tabs.author_control import create_author_control_tab from tabs.publish_control import create_publish_control_tab from tabs.dispatcher_control import create_dispatcher_control_tab def main(): root = tk.Tk() ...
Python
1
,TR/BL---C--BR/TL /// , |.\__ , . /// , | . \,_ . /// , | . , \_ . /// , | , \__ . /// , | , . \__ . /// TL._ | , . _.TR /// 'B._ |, . _.C' /// 'BL BR' pub struct DrawLines3dOptions { /// ...
Rust
0
class Card: # The suits of the cards suits = ["Carreau", "Coeur", "Pique", "Trèfle"] ranks = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] # 11: Valet, 12: Reine, 13: Roi, 14: As rank_names = {11: "Valet", 12: "Reine", 13: "Roi", 14: "As"} def __init__(self, suit, rank): self.suit = suit ...
Python
1
let accepted = rustix::net::accept(&listener).expect("accept"); let mut response = [0u8; 128]; let n = rustix::net::recv(&accepted, &mut response, RecvFlags::empty()).expect("recv"); // Not strictly required, but it makes the test simpler. assert_eq!(n, request.len()); assert_eq!(request, &res...
Rust
0
players = ['charles', 'martina', 'michael', 'florence', 'eli'] print("Here are the first three players on my team:") for player in players[:3]: print(player.title())
Python
1
) + &i.to_string(), vec![]); } // let mut main_shell = Vec::new(); for x in (0..360).step_by(6) { for y in (0..360).step_by(6) { let i = y * 240 + x; let xs = (x as f32).to_radians(); let ys = (y as f32).to_radians(); let v = spherical_to_cartesian(&v...
Rust
0
BitAndNz), Opcode::IfAndZ => Some(Operator::BitAndZ), Opcode::CaseEq => Some(Operator::Eq), Opcode::CaseOrEq => Some(Operator::Eq), Opcode::CaseAndEq => Some(Operator::Eq), Opcode::CaseNe => Some(Operator::Ne), Opcode::CaseLt ...
Rust
0
()).as_str().parse().unwrap(); let labels = hashmap!{ label_id => "A".to_string() }; metrics::registry().register_counter(world.metric_id, "01D3MT4JY1NZH2WW0347B9ZAS7", Some(labels)).unwrap();; }; when regex "01D3MT8KDP434DKZ6Y54C80BB0" | world, _matches, _step| { le...
Rust
0
se super::super::SkewTContext; use crate::{ analysis::{Intensity, PrecipTypeAlgorithm}, app::config::{Rgba, BLUE, GREEN, RED}, coords::ScreenCoords, gui::{Drawable, DrawingArgs, PlotContextExt}, }; use sounding_analysis::{self, PrecipType}; const PRECIP_BOX_SIZE: f64 = 0.07; impl SkewTContext { pu...
Rust
0
speed_temp = align.calculate_speed('template') speed_comp = align.calculate_speed('complement') # Make sure we can calculate speed using only what's in the # summary summary = fh.get_summary_data('Alignment_000') template_su...
Python
1
, next: AtomicPtr<FreeListElement<Node<Value>>>, } impl<Value: CtoSafe> Debug for Node<Value> { #[inline(always)] fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "Node<Value>") } } impl<Value: CtoSafe> CtoSafe for Node<Value> { #[inline(always)] fn cto_pool_opened(&mut self, cto_pool_arc: &CtoPoo...
Rust
0
while i < 20 { handles.push(thread::spawn(|| { let mut snd2 = Sound::new("res/shot.wav").expect("Error on Sound loading."); snd2.play(); while snd2.is_playing() {} })); i += 1; sleep(Duration::from_millis(150)); } // Wait until the last soun...
Rust
0
must be only numbers")), }) .collect() } /// Turns a Javascript Array into a `Vec<isize>` pub fn into_vec_isize(input: &js_sys::Array) -> Result<Vec<isize>, JsValue> { input .iter() .into_iter() .map(|x: JsValue| match x.as_f64() { Some(n) => Ok(n as isize), ...
Rust
0
w78.hertz(), 78_200); /// assert_eq!(FskBandwidth::Bw93.hertz(), 93_800); /// assert_eq!(FskBandwidth::Bw117.hertz(), 117_300); /// assert_eq!(FskBandwidth::Bw156.hertz(), 156_200); /// assert_eq!(FskBandwidth::Bw187.hertz(), 187_200); /// assert_eq!(FskBandwidth::Bw234.hertz(), 234_300); /// as...
Rust
0
va='bottom', fontsize=8, bbox=bbox_props ) # 2. PBR (주가순자산비율) 플롯 axes[1].plot(df.index, df['PBR'], color=PRIMARY_COLORS[1], linewidth=2.5) if KOREAN_FONT_PROP: axes[1].set_title("주가순자산비율 (PBR)", fontsize=12, loc='left', fontproperties=KOREAN_FONT_PROP) ...
Python
1
import re class SimpleTokenizer: def __init__(self, vocabulary): self.str_to_int = vocabulary self.int_to_str = {v: k for k, v in vocabulary.items()} def encode(self, text): parts = text.split('</s>') main_text = parts[0].lower() tokens = re.findall(r'\w+|[^\w\s]',...
Python
1
distance[goal[1], goal[0]] = 0 # assign zero to goal # create the appropriate distance matrix D if metric.lower() in ("manhattan", "cityblock"): # fmt: off D = np.array([ [ np.inf, 1, np.inf], [ 1, 0, 1], [ np.inf, 1, np...
Python
1
rti.RequestNewOrder.if_touched_condition', index=27, number=154453, type=14, cpp_type=8, label=1, has_default_value=False, default_value=1, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( ...
Python
1
width = "64")] fn leb_64_bit() { let mut buf = [0x55; 10]; let i = leb64((1 << 32) - 1, &mut buf); assert_eq!(buf[..i], [0xff, 0xff, 0xff, 0xff, 0xf]); buf.iter_mut().for_each(|b| *b = 0x55); let i = leb64((1 << 35) - 1, &mut buf); assert_eq!(buf[..i], [0xff, 0xff, ...
Rust
0
# In[ ]: from google.colab import drive drive.mount('/content/drive') # In[ ]: from google_drive_downloader import GoogleDriveDownloader as gdd url = 'https://drive.google.com/file/d/1ubvKLzBDe5i1acxgGUK6ObeNBYCKUS07/view?usp=sharing' gdd.download_file_from_google_drive(file_id = url,dest_path='./data.zip',unzip=...
Python
1
mask * 255) # convert from bool to [0, 255] black & white image processed_mask = post_process_mask(mask) # simple heuristics (connected components, etc.) filename = str(batch_id*batch_size+j).zfill(FILE_NAME_NUM_DIGITS) + mask_extension cv.imwr...
Python
1
k_opt: Option<sdl2::keyboard::Scancode>) { if let Some(sdlk) = sdlk_opt { if let Some(scancode) = sdlk_to_scancode(sdlk) { keyboard_print!("Released: scancode={:x}", scancode); self.io_queue.push_back(scancode | 0x80); cpu.queue_hw_interrupt(0x9); } } } pub fn bios_pump_keystrokes(&mut se...
Rust
0
DETECT_VALUES_PROMPT_V3 = """ You are given a natural language question and a list of schema items (table names or fully qualified column names). The question is a textual representation of some SQL query a database for which we have the schema items. Your goal is to find a list of literal values, entities, constants, ...
Python
1
ot(target_os = "fuchsia"))] starting_time: std::time::Instant, } impl MonotonicTime { pub fn new() -> MonotonicTime { #[cfg(target_os = "fuchsia")] let time = MonotonicTime {}; #[cfg(not(target_os = "fuchsia"))] let time = MonotonicTime { starting_time: std::time::Instant::now()...
Rust
0
# Copyright 2016 NTT DATA # 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 appl...
Python
1
s: for index, person_id in enumerate(identities): self.last_multi_kps3d[ person_id] = keypoints3d.get_keypoints()[0, index, ...].T if end_of_clip: self.last_multi_kps3d = dict...
Python
1
EQ, #[doc = "0x08 - Power Down Request Request from AUX for system to enter power down. When system is in power down there is limited current supply available and the clock source is set by AON_WUC:AUXCLK.PWR_DWN_SRC"] pub pwrdwnreq: PWRDWNREQ, #[doc = "0x0c - Power Down Acknowledgment"] pub pwrdwnack: ...
Rust
0
use_message.movement_x, MOUSE_X); assert_eq!(mouse_message.movement_y, MOUSE_Y); assert_eq!(mouse_message.phase, fidl_fuchsia_ui_input::PointerEventPhase::Down); assert_eq!(mouse_message.buttons, 2); // Button 2 was pressed } _ ...
Rust
0
in traj_eval_res: values[metric].append(float(traj_eval_res[metric])) means = {} variances = {} for metric in metrics: means[metric] = np.mean(values[metric]) if values[metric] else None variances[metric] = np.var(values[metric]) if values[metric] else None ...
Python
1
s = self._multi_metrics.prod(axis=0) comfort_multi_score = np.ones_like(multiplicate_metric_scores) speed_limit_score = np.ones_like(multiplicate_metric_scores) comfort_multi_score[ self._weighted_metrics[WeightedMetricIndex.COMFORTABLE] == 0 ] = 0.5 speed_limit_score...
Python
1
m_sa): cur_xyz, cur_features, cur_indices = self.SA_modules[i]( sa_xyz[i], sa_features[i]) sa_xyz.append(cur_xyz) sa_features.append(cur_features) sa_indices.append( torch.gather(sa_indices[-1], 1, cur_indices.long())) fp_xyz = [sa...
Python
1
val = prime_field::fmul(val.clone(), denominator_inv[4].clone() ); // res += val * coefficients[32]. res = prime_field::fadd(res.clone(), prime_field::fmul(val.clone(), /*coefficients[32]*/ ctx[map::MM_COEFFICIENTS+32].clone() ) ); } { // Constraint expression for memory/multi_column_perm/perm/init0: (memor...
Rust
0
# Copyright 2025 Dimensional Inc. # # 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 applicable law or agreed to in writ...
Python
1
import matplotlib import matplotlib.pyplot as pyplot x = range(1, 11) y = [3, 4, 6, 9, 11, 12, 10, 11, 14, 16] # Set the axes headings pyplot.ylabel('y values', fontsize=12) pyplot.xlabel('x values', fontsize=12) # Set the title pyplot.title("Sample Graph using MatPlotLib " + str(matplotlib.__version__)) # Configure...
Python
1
# -*- coding: utf-8 -*- #pylint: skip-file import os class CommonConfigs(object): def __init__(self, d_type): self.ROOT_PATH = os.getcwd() + "/" self.TRAINING_DATA_PATH = self.ROOT_PATH + d_type + "/train_set/" self.VALIDATE_DATA_PATH = self.ROOT_PATH + d_type + "/validate_set/" se...
Python
1
""" Tests that work on both the Python and C engines but do not have a specific classification into the other test modules. """ from io import StringIO import numpy as np import pytest from pandas import ( DataFrame, option_context, ) import pandas._testing as tm pytestmark = pytest.mark.filterwarnings( ...
Python
1
select! { user_event => match user_event { Some(e) => handle_user_event(e), None => bail!("Stream of events from SME unexpectedly ended"), }, new_fidl_client => match new_fidl_client { Some(c) => fidl_clients.add(serve_fidl_endpoint(A...
Rust
0
""" CEASIOMpy: Conceptual Aircraft Design Software Developed for CFS ENGINEERING, 1015 Lausanne, Switzerland Evaluation of the number of crew members expected for an unconventional aircraft. | Author : Stefano Piccini | Date of creation: 2018-12-19 """ # ============================================================...
Python
1
"""Deprecated Magic functions. """ from __future__ import print_function #----------------------------------------------------------------------------- # Copyright (c) 2012 The IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, dist...
Python
1
n /= 2; } ret } } /// An elliptic curve, where y^2 = x^3 + a*x + b (mod p). pub trait Curve: Clone + Eq + PartialEq + Debug { fn p() -> BigInt; fn a() -> BigInt; fn b() -> BigInt; } #[cfg(test)] mod tests { use super::*; use num_traits::Num; #[derive(Clone, Eq,...
Rust
0
); } impl Default for TPM2B_TEMPLATE { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::<Self>::uninit(); unsafe { ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); s.assume_init() } } } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct TPM2B_PRIVAT...
Rust
0
s { Rn: Rn as _, Rt: Rt as _, Rt2: Rt2 as _, imm7: imm7 as _, }); } None } pub const fn decode_ldst_immpost(d: u32) -> Option<InstructionKind> { ["Could not decode."][((d & 0x3b200c00) != 0x38000400) as usize]; let Rn = (d >> 5) & 0x1F; let Rt...
Rust
0
import numpy as np import cv2 from params import vpy, turn_slope, threshold, bandheight kernel = np.float32([-1, -1, -1, 2, 2, 2, -1, -1, -1]) camera_matrix = np.load("../../tools/camcal/camera_matrix.npy") dist_coeffs = np.load("../../tools/camcal/dist_coeffs.npy") camera_matrix[:2] /= 4. # for 640x480 def clas...
Python
1
"""Classes representing inbound messages.""" import asyncio from typing import Optional, Union from .receipt import MessageReceipt class InboundMessage: """Container class linking a message payload with its receipt details.""" def __init__( self, payload: Union[str, bytes], receipt:...
Python
1
n rs { let mut row = row?; let f1: String = row.next_try_into()?; let f2: Option<i32> = row.next_try_into()?; let f3: i32 = row.next_try_into()?; let f4: NaiveDateTime = row.next_try_into()?; debug!( "From {}, got line {}, {:?}, {}, {}", tablename,...
Rust
0
from collections import OrderedDict from json.tests import PyTest, CTest CASES = [ (u'/\\"\ucafe\ubabe\uab98\ufcde\ubcda\uef4a\x08\x0c\n\r\t`1~!@#$%^&*()_+-=[]{}|;:\',./<>?', '"/\\\\\\"\\ucafe\\ubabe\\uab98\\ufcde\\ubcda\\uef4a\\b\\f\\n\\r\\t`1~!@#$%^&*()_+-=[]{}|;:\',./<>?"'), (u'\u0123\u4567\u89ab\ucdef\uab...
Python
1
1) # 832 18 # Light field decoder using the gather geometric context lf_out = self.phi(coords) rgb = lf_out[..., :3] # Mask invalid regions (no epipolar line correspondence) to be white valid_mask = valid_mask.bool().any(dim=1).float() rgb = rgb * valid_mask[:...
Python
1
=> { args[1] = opts; } } } node.args = Some(args); } return node; } } return node.fold_children_with(self); } fn fold_member_expr(&mut self, mut node: ast::MemberExpr) -> ast::MemberExpr { node.obj = node.obj.fold_ch...
Rust
0
} else { let rest = 2020 - num1 - num2; if numbers.contains(&rest) { println!( "Found {0}, {1}, and {2} -> {0} * {1} * {2} = {3}", num1, num2, rest, num1 * num2 * rest ); exit(0) } } } } ...
Rust
0
g auf eine Kur") self.assertEqual(len(matches), 1) def test_no_embedding_wrong_pos(self): matches = self._get_matches(holmes_manager_with_embeddings, "hervorkommen") self.assertEqual(len(matches), 0) def test_no_embedding_subword_too_short(self): ...
Python
1
let _ = En2::<_>::V0("151571"); let _ = En2::<&str>::V1(false); let _ = En2::<&str>::V2(42u8); let _ = En2::<&str>::V3(|| 12u8); let _ = En3::<_>::V0("deadbeef"); let _ = En3::<&str>::V1(&true); let f1 = (1,); let f2 = (2,); let _ = En4::<()>::V0(&f1.0); let _ = En4::<()>::V1(&f2...
Rust
0
ead + Seek, { let header = Header::read_chunk(read)?; let chunks = header.chunk_identifiers(); if chunks.is_empty() { return Err( ErrorKind::Format(String::from("Embedding file does not contain chunks")).into(), ); } let metadata = if ...
Rust
0
import re from rich import print as rprint from datetime import datetime, timedelta import uuid import json import logging from cryptography.fernet import Fernet def create_task(pid): id = uuid.uuid4() name = input("Task title: ") desc = input("Task description: ") start = datetime.now() end = star...
Python
1
g.JointSamTrainer( name=args.name, save_root=args.save_root, train_loader=train_loader, val_loader=val_loader, model=model, optimizer=optimizer, device=device, lr_scheduler=scheduler, logger=sam_training.JointSamLogger, log_image_interval=1...
Python
1
-> &mut Self { self.0.bits(bits); self } } #[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [AP...
Rust
0
""" Tinman Cache Module """ from functools import wraps from logging import debug # Module wide dictionary to hold the cached values in local_cache = dict() def memoize_write(*args): # Append the value if the key exists, otherwise just set it if args[0].tinman_memoize_key in local_cache: debug('mem...
Python
1
he histogram of a given results") plot.set_defaults(callback=self.plot_command) plot.add_argument( "--file", "-f", dest="file", required=True, type=argparse.FileType('r'), help="File path of the flux benchmark data in CSV format") plot.add_argument( ...
Python
1
res.unwrap_or_revert(); } #[cfg(not(feature = "no_transfer_many_tokens"))] #[no_mangle] pub extern "C" fn transfer_many_tokens() { let sender: Key = get_caller(); let recipient: Key = runtime::get_named_arg("recipient"); let token_ids: Vec<TokenId> = runtime::get_named_arg("token_ids"); let mut co...
Rust
0
))? .into_json()?; if resp["error"].is_null() { println!("found: {}", resp["character_list"][0]["character_id"]); if resp["returned"] == 0 { Ok(None) } else { let quoted = resp["character_list"][0]["character_id"].to_string(); Ok(Some(quoted.unqu...
Rust
0
Scalar> = rnd_scalar_vec(values.len()); let (range_proof, commit) = create_rangeproof_l2(&values, &blindings, N_BITS, prove_range).unwrap(); let res = verify_rangeproof_l2(&range_proof, &commit, N_BITS); assert!(res.unwrap()); } #[test] fn test_rangeproof_roundtrip() { ...
Rust
0
bf16 (bool, optional): Whether to use BF16 precision. Defaults to False. Returns: The DeepSpeed config for evaluation. """ assert offload in {'none', 'parameter', 'optimizer', 'all'} with EVAL_TEMPLATE_FILE.open(mode='rt', encoding='utf-8') as f: eval_config = json.load(f) i...
Python
1
lor; pub mod token;<filename>tests/clock.rs<gh_stars>10-100 use howlong::{clock::*, Clock, Duration}; use std::thread; mod utils; macro_rules! test_clock { ($name: ident, $clock: ty) => { #[test] fn $name() { let ten_millis = Duration::from_millis(10); let start = <$clock>:...
Rust
0
mut sensor_type_traits, } impl Default for sensor_type_traits__bindgen_ty_1 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl Default for sensor_type_traits { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[repr(C)] pub struct sensor_notify_ev_ctx { pub...
Rust
0
ue_index + 1 seq.append(node.merge_with_index) else: seq.append(0) if len(node.coeff): node.coeff = (node.coeff - bz_pc_range[:2]) / dx[:2] node.coeff[0] = np.clip(node.coeff[0], 0, bz_nx[0]-1) node.coe...
Python
1
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. import math import torch import torch.fft import torch.nn as nn import torch.nn.functional as F class AFNO2D(nn.Module): """ hidden_size: channel dimension size num_blocks: how many blocks to use in the block diagonal weight matrices (higher...
Python
1
elf.title().cmp(&other.title())) } } impl Ord for Addon { fn cmp(&self, other: &Self) -> Ordering { self.title().cmp(&other.title()) } } impl Eq for Addon {} <filename>c2rust-ast-builder/src/lib.rs #![feature(rustc_private)] extern crate rustc; extern crate rustc_target; extern crate syntax; exter...
Rust
0
0, column=0, padx=10, pady=5) generar_disparadores_btn = tk.Button(frame_botones, text="Generar Disparadores", command=generar_disparadores_bd, bg='#839788', fg='white') generar_disparadores_btn.grid(row=0, column=1, padx=10, pady=5) eliminar_disparadores_btn = tk.Button(frame_botones, text="Eliminar Disparadores", com...
Python
1
edTranslation) # The locator does *not* get node collapsed because it has a cube # underneath it, so we should have a blank Xform for the shape. self._ValidateXformPrim(stage, '/LocatorParent/LocatorParentShape') expectedTranslation = Gf.Vec3d(-2.0, -3.0, -4.0) self._ValidateMe...
Python
1
置已加载") except Exception as e: logger.error(f"加载工作流设置失败: {e}") def reset_to_default(self): """重置到默认设置""" try: # 重置工作流选择 if self.workflow_combo.count() > 0: self.workflow_combo.setCurrentIndex(0) # 重...
Python
1
# lamda functions (extra study) # resource: https://www.freecodecamp.org/news/python-lambda-functions/ '''Syntax: lambda arguments: expression''' add = lambda a,b: a+b print(add(5,7)) # Map function '''Syntax: map(function, iterable)''' numbers = [1,2,3,4,5] square = list(map(lambda x: x**2, numbers)) print(squa...
Python
1
Int<Ul ^ Ur, B0>` impl<Ul: Unsigned, Ur: Unsigned> PrivateXor<UInt<Ur, B0>> for UInt<Ul, B0> where Ul: PrivateXor<Ur>, { type Output = UInt<PrivateXorOut<Ul, Ur>, B0>; #[inline] fn private_xor(self, rhs: UInt<Ur, B0>) -> Self::Output { UInt { msb: self.msb.private_xor(rhs.msb), ...
Rust
0
EAX], but 0 is a 4 bytes immediate. sink.put1(0x0F); sink.put1(0x1F); sink.put1(0x80); sink.put1(0x00); sink.put1(0x00); sink.put1(0x00); sink.put1(0x00...
Rust
0
# 2. homework - Nagy Norbert #user_inputs fict_name = input("Please type your character's name:").strip().capitalize() fict_age_days = 365 * int(input("Please add how many years old is your character:")) fict_experience = int(input("How many years experencie does your character have in Python programming?")) #extra w...
Python
1
do_steps(&values.1, 40) } #[cfg(test)] mod test { use std::io::Cursor; use super::*; const INPUT: &str = include_str!("test_input.txt"); fn input() -> Input { read_input(Cursor::new(INPUT)).unwrap() } #[test] fn test1() { assert_eq!(part1(&input()), 1588); } #[t...
Rust
0
url: url, merkle: String::from("0"), meta, contents: HashMap::new(), cms: HashMap::new(), } } /// Creates a package definition which maps a set of service names to a set /// of files in the package which represent components that provide that /// service. pub fn create_svc_pkg_def(...
Rust
0
_test] fn init_existing_repo() -> Result<()> { // Arrange git_init_and_set_current_path("test_repo_existing")?; assert_that!(Path::new("test_repo_existing")).exists(); git_commit("chore: test commit")?; // Act Command::cargo_bin("cog")? .arg("init") .arg("test_repo_existing") ...
Rust
0
eeze(1) # [bs*n_agents, 1, rnn_hidden_dim] batch_size = hidden_state.size(0) * hidden_state.size(1) hidden_state = hidden_state.view(1, batch_size, -1) gru_out, _ = self.gru(x, hidden_state) z, _, _ = self.encoder(gru_out) local_q = th.stack([mlp(gru_out[id, :, :]) ...
Python
1