text
string
label_name
string
labels
int64
.unwrap()) .map_err(|_| StatusCode::OutOfGas)?; let value = u256_from_slice(&state.memory[region.offset..region.offset + region.size.get()]); state.stack.push(value); Ok(()) } #[inline(always)] pub(crate) fn mstore(state: &mut ExecutionState) -> Result<(), StatusCode> { let index = state.sta...
Rust
0
.unwrap_or_default() } } impl Default for CountersigningWorkspace { fn default() -> Self { Self::new() } } #[cfg(test)] mod tests { use arbitrary::Arbitrary; use super::*; #[test] /// Test that a session of 5 headers is complete when /// the expiry time is in the fu...
Rust
0
one job = qmm.simulate(config, res_depletion_time, simulation_config) # Get the simulated samples samples = job.get_simulated_samples() # Plot the simulated samples samples.con1.plot() # Get the waveform report object waveform_report = job.get_simulated_waveform_report() # Cast the wavef...
Python
1
hs.len(){ if utils::check_if_path_exist(&paths[i]) == true{ if utils::check_if_file(&paths[i]) == 1 { fs::remove_dir_all(&paths[i]).expect("Failded to delete dir"); if (mode == 2) || (mode == 1){ println!("{}: {}", paint("Deleted dir").with(Color::Green), paths[i]); } }else if utils::check_if_f...
Rust
0
the client has ``websocket_ping_timeout`` seconds to # respond. If no response is received within this period, the connection will be # closed from the server side. # Default: 0 # c.ServerApp.websocket_ping_interval = 0 ## Configure the websocket ping timeout in seconds. # # See ``websocket_ping_interval`` for ...
Python
1
pub type Polygon = ewkb::Polygon; pub type MultiPoint = ewkb::MultiPoint; pub type MultiLineString = ewkb::MultiLineString; pub type MultiPolygon = ewkb::MultiPolygon; pub type GeometryCollection = ewkb::GeometryCollection; /// Generic Geometry Data Type #[derive(Debug)] pub enum GeometryType { Point(Point), ...
Rust
0
described here: // https://en.wikipedia.org/wiki/Rounding#Round_half_to_even #![feature(core_intrinsics)] use std::intrinsics::nearbyintf32; #[kani::proof] fn test_one() { let one = 1.0; let result = unsafe { nearbyintf32(one) }; assert!(result == 1.0); } #[kani::proof] fn test_one_frac() { let one_f...
Rust
0
import cv2 import argparse from ultralytics import YOLO import supervision as sv import numpy as np ZONE_POLYGON = np.array([ [0, 0], [0.5, 0], [0.5, 1], [0, 1] ]) def parse_arguments() -> argparse.Namespace: parser = argparse.ArgumentParser(description="YOLOv8 live") parser.add_argument( ...
Python
1
import numpy as np from nuplan.common.maps.maps_datatypes import SemanticMapLayer from nuplan.common.actor_state.state_representation import StateSE2 from nuplan.common.maps.nuplan_map.lane import NuPlanLane from nuplan.common.maps.maps_datatypes import TrafficLightStatusType from nuplan.planning.metrics.utils.state_e...
Python
1
} cmp::Ordering::Equal => { // this is the last fragmented message, need to return the whole reassembled message self.total_size = 0; self.data.append(&mut data); Some(self.data.drain(..).collect()) } ...
Rust
0
use structopt::StructOpt; mod feed; mod upload; #[derive(Debug, StructOpt)] #[structopt(about = "audiobook to podcast tool")] enum Opt { Feed { #[structopt(short, long)] title: String, #[structopt(short, long)] region: String, #[structopt(short, long)] bucket: Strin...
Rust
0
eaders) response.raise_for_status() user_data = response.json() return user_data['id'] if __name__ == "__main__": # this will be changed. access token will be passed from main.py in the production. import dotenv dotenv.load_dotenv() access_token = os.getenv("OSU_ACCESS_TOKEN", "") if ...
Python
1
不存在,请检查名称是否正确') def Write_Flash_Page(Page_add, data_w, Page_num): # 往Flash指定页写入256B数据 # 先把数据传输完成 hex_use = bytearray() # 空数组 for i in range(0, 64): # 256字节数据分为64个指令 hex_use.append(4) # 多次写入Flash hex_use.append(i) # 低位地址 hex_use.append(data_w[i * 4 + 0]) # Data0 hex_us...
Python
1
= Keyrom::new(); let mut keyloc = KeyLoc::SelfSignPub; // start from the self-sign key first, then work your way to less secure options loop { match keyloc { KeyLoc::SelfSignPub => { if !keyrom.key_is_zero(KeyLoc::SelfSignPub) { // self-signing key takes priority ...
Rust
0
len(); let mut ysize = 1; parse_row(first_row, &mut map, ysize - 1); for r in map_rows.iter().skip(1) { let row = r.trim(); ensure!( xsize == row.len(), "ERROR: Wrong size of the row. Expected {} but was {}.", xsize, row.len() ); ...
Rust
0
: num }; unsafe { conv.f1 &= 0x7fffffff; return conv.f2; } } pub fn pow2(num: f32) -> f32 { num * num } fn min(first: f32, second: f32) -> f32 { if first < second { first } else { second } } fn max(first: f32, second: f32) -> f32 { if first > second { first } else { second } }<rep...
Rust
0
# ================================================================================== # # Copyright (c) 2020 Samsung Electronics Co., Ltd. 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 obta...
Python
1
(bit_width <= 64); debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); debug_assert!((bit_offset + (bit_width as usize)) / 8 <= self.storage.as_ref().len()); for i in 0..(bit_width as usize) { let mask = 1 << i; let val_bit_is_set = val & mask...
Rust
0
delay to increase chance of race conditions # Start multiple threads threads = [] for i in range(5): thread = threading.Thread(target=log_errors, args=(i,)) threads.append(thread) thread.start() # ...
Python
1
#Dependencies import SimpleITK as sitk reader = sitk.ImageFileReader() reader.SetImageIO("MetaImageIO") import numpy as np #Import funtcions from transforms.py #rom transforms import mri_transforms, array_transforms import mri_transforms, array_transforms #Here resampling and any other 3D pre-processing are applied b...
Python
1
import re from contextlib import contextmanager from typing import Iterator, Dict, Iterable, Tuple, List from allennlp.models import Model from qdecomp_with_dependency_graphs.utils.helpers import rgetattr, rsetattr @contextmanager def capture_model_internals(model: Model, module_regex: str = ".*") -> Iterator[dict]...
Python
1
"pastedText": ":_pomuSmall9cm:" } }, "4,2": { "State": 0, "States": [ { "FFamily": "", "FSize": "12", "FStyle": "", "FUnderline": "off", "Image": ""...
Rust
0
def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) if __name__ == "__main__": print("Program Deret Fibonacci") n = int(input("Masukkan jumlah elemen Fibonacci yang ingin dihitung: ")) print(f"Deret Fibonacci hingg...
Python
1
.footer-center, .footer-right { text-align: left; } } </style> </head> <body> <nav class="navbar"> <img src="logo.svg" alt="logo" class="logo" onclick="window.location.href='index.py'"> <ul class="nav-links"> <li><a href="index.py">HOME</a></li> <li><a href="all-doctors.py">ALL DO...
Python
1
} fn set_position<P: Into<Vector3f>>(&mut self, position: P) { unsafe { ffi::sfSound_setPosition(self.sound, position.into().raw()) } } fn set_relative_to_listener(&mut self, relative: bool) { unsafe { ffi::sfSound_setRelativeToListener(self.sound, sfBool::from_bool(relative)) } } fn...
Rust
0
} } rpass.draw(0..4, 0..self.vertices); } encoder.finish() } pub fn update_buffer( &mut self, vertices: Vec<Vertex>, device: &wgpu::Device, queue: &wgpu::Queue, ) { self.vertices = vertices.len() as u32; let data: &[u...
Rust
0
import turtle import json def draw_from_json(json_file): # Configurar turtle screen = turtle.Screen() screen.bgcolor("black") screen.setup(800, 800) t = turtle.Turtle() t.hideturtle() t.speed(0) screen.tracer(0) # Cargar regiones with open(json_file) as f: regions =...
Python
1
let hash_of_zero = <T as system::Trait>::Hashing::hash_of(&0); let zero_balance = <T::Balance as As<u64>>::sa(0); let cat = Kitty { id: random_hash, dna: random_hash, price: zero_balance, gen: 0, }; <KittyOwner<T>>::insert(&ra...
Rust
0
use super::*; pub struct StandardRenderStrategy; impl AnyPixelRenderStrategy for StandardRenderStrategy { fn render_pixel( &self, scene: &Scene, canvas_x: UnitInterval, canvas_y: UnitInterval, pixel_width: f64, pixel_height: f64, ...
Rust
0
-> u8 { if c == '#' { 1 } else { 0 } } let (algorithm, image) = input.split_once("\n\n").unwrap(); let lookup = algorithm.chars().map(convert).collect_vec(); assert_eq!(512, lookup.len()); let lines = image.lines().collect_vec(); let pixels = li...
Rust
0
#!/usr/bin/env python3 import os import time from BUZZWatch.raspberry_pi_code.hardware_layer.sensors import ( read_dht22_indoor, read_dht22_outdoor, read_weight ) from BUZZWatch.raspberry_pi_code.services.api.thingspeak import ThingSpeakAPI def test_thingspeak_connection(): """Test ThingSpeak connecti...
Python
1
ColumnCatalog::new(1, DataTypeKind::Int(None).not_null().to_column("b".into())), ], false, ) .unwrap(); let sql = " insert into t values (1, 1); insert into t (a) values (1); insert into t values (1);"; let ...
Rust
0
'generic': 15.0 # GHz, 通用Ka波段 } return frequency_allocations.get(constellation.lower(), 15.0) def _get_official_satellite_eirp(self, constellation: str) -> float: """✅ Grade B: 基於公開技術文件的衛星EIRP""" # 基於官方文件和技術規格書 official_eirp = { 'starlink': 42.0, # dBW,...
Python
1
and stop 0x0195, 0x7081, // end of icmp_imm.i32 (I32) // end of icmp_imm.i32 (I64) // 000215: iconst.i32 (I64) // --> [RexOp1pu_id#b8] 0x0010, 0x00b8, // --> [Op1pu_id#b8] 0x000e, 0x00b8, // stop unless inst_predicate_1 0x1001, // --> [RexOp1u_id_z#31] 0x001c, 0x0031, ...
Rust
0
path_deltas: &str, channel: &mut C, rng: &mut RNG, ) -> Result< ( CrtBundle<fancy_garbling::Wire>, CrtBundle<fancy_garbling::Wire>, ), Error, > { let mut gb = Garbler::<C, RNG, OtSender>::new(channel.clone(), RNG::from_seed(rng....
Rust
0
os::raw::c_int; use std::sync::atomic::Ordering; use super::{ffi, wrap_egl_call, Error, MakeCurrentError}; use crate::backend::allocator::Format as DrmFormat; use crate::backend::egl::display::{EGLDisplay, PixelFormat}; use crate::backend::egl::EGLSurface; use slog::{info, o, trace}; /// EGL context for rendering #[...
Rust
0
n KeybdKey::Type::F10; case 0x45: return KeybdKey::Type::NumLock; case 0x46: return KeybdKey::Type::ScrollLock; case 0x3a: return KeybdKey::Type::CapsLock; case 0x2a: return KeybdKey::Type::LShift; case 0x36: return KeybdKey::Type::RShift; case 0x1d: ...
Rust
0
train_loader = torch.utils.data.DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=2, drop_last=False) test_loader = torch.utils.data.DataLoader(testset, batch_size=batch_size, shuffle=False, num_workers=2, ...
Python
1
logger.warning("⚠️ Error processing rank data for product #%s: %s. Data: %s", product_idx, e, rank_data) product.relevance_score = None # Ensure score is None if parsing fails product.relevance_explanation = "Error processing ranking data." else: lo...
Python
1
#!/usr/bin/env python import sys from vtkmodules.vtkCommonCore import vtkPoints from vtkmodules.vtkCommonDataModel import ( vtkCellArray, vtkPolyData, ) from vtkmodules.vtkRenderingCore import ( vtkActor, vtkCellPicker, vtkHardwarePicker, vtkPolyDataMapper, vtkRenderWindow, vtkRenderWind...
Python
1
INPUT D1 130 IF X=X1 AND Y=Y1 AND D=D1 THEN GOTO 300 140 PRINT "SHOT WAS "; 150 IF Y1>Y THEN PRINT "NORTH"; 160 IF Y1<Y THEN PRINT "SOUTH"; 170 IF X1>X THEN PRINT "EAST"; 180 IF X1<X THEN PRINT "WEST"; 190 PRINT 200 IF D1>D THEN PRINT "TOO FAR" 210 IF D1<D THEN PRINT "NOT FAR ENOUGH" 220 NEXT I 230 PRINT "YOUR TIME HAS...
Rust
0
program) self.assertEqual(rv, program) # missing PATH: test os.confstr("CS_PATH") and os.defpath with test_support.EnvironmentVarGuard() as env: env.pop('PATH', None) # without confstr with unittest.mock.patch('distutils.s...
Python
1
device = A.values.device scalar_dtype = A.scalar_type r = wp.zeros_like(b) p = wp.zeros_like(b) Ap = wp.zeros_like(b) if use_diag_precond: A_diag = bsr_get_diag(A) z = wp.zeros_like(b) if A.block_shape == (1, 1): precond_kernel = _bsr_cg_solve_scalar_diag_...
Python
1
ub fn setup_with_drop_closure( mut server: ::grpcio::Server, drop_closure: Option<Box<dyn FnOnce()>>, ) -> Self { let (start_sender, start_receiver) = mpsc::channel(); let (stop_sender, stop_receiver) = mpsc::channel(); let handle = Self { stop_sender, ...
Rust
0
: usize = BLOOM_OFFSET - magic::HEADER_SIZE; const FANOUT_OFFSET : usize = magic::HEADER_SIZE + 8; const BLOOM_OFFSET : usize = FANOUT_OFFSET + FANOUT_SIZE; // calculate the file offset from where the hashes are stored fn offset_hashes(bloom_size: u32) -> u64 { magic::HEADER_SIZE as u64 + 8 + FANOUT_SIZE as u64 ...
Rust
0
cube(a, username), } } fn find_cube( &self, address: &CUBEApiUrl, username: Option<&Username>, ) -> Option<&SavedCubeAuth> { for cube in &self.cubes { if address == &cube.address { if let Some(given_username) = username { ...
Rust
0
ect = UpdatedFANOVA( X=trials_df.drop("value", axis="columns", inplace=False), Y=trials_df["value"], config_space=config_space, **fanova_kwargs) # Set cutoffs / percentile if study.direction == optuna.study.StudyDirection.MAXIMIZE: lower_cutoff = ...
Python
1
info( "{:<45} {:<10} {:<10} {:<10}".format( "Trend_Name", "Percentile", "Limit", "Actual" ) ) for trend_name, trend_values in trend_dict.items(): if "thresholds" in trend_values: for threshold_item in trend_values["thresholds"]: formatted_result_st...
Python
1
self.have_temp = true; } if self.data.len() == 10 && self.data[9].0 < 10 && self.data[9].0 + self.data[9].1 == 10 && self.have_temp{ self.data.push((self.temp,0)); self.have_temp = false; } Ok(()) } pub fn score(&self) ->Result<u64,()>{ if !self.s...
Rust
0
tamp < val && *payer.key != candy_machine.authority { return Err(ErrorCode::CandyMachineNotLive.into()); } } } Ok(()) } pub fn assert_owned_by(account: &AccountInfo, owner: &Pubkey) -> ProgramResult { if account.owner != owner { Err(ErrorCode::IncorrectOwner.int...
Rust
0
from PIL import Image from modules import shared, sd_models from sd_bmab.base.context import Context from sd_bmab.base.processorbase import ProcessorBase base_sd_model = None def change_model(name): if name is None: return info = sd_models.get_closet_checkpoint_match(name) if info is None: print(f'Unknown...
Python
1
.body(body.to_string()); Ok(self.goose_send(request_builder, None).await?) } /// A helper to make a named `POST` request of a path and collect relevant metrics. /// Automatically prepends the correct host. Naming a request only affects collected /// metrics. /// /// Calls to `user.post...
Rust
0
ributes = HashMap<String, ObjectRef>; pub struct ComplexObject { class: TypeRef, attributes: Attributes, } impl ComplexObject { pub fn new(class: TypeRef) -> Self { Self { class: class.clone(), attributes: HashMap::new() } } } impl Object for ComplexObject { fn class(&self) -> &TypeRef { ...
Rust
0
get(url.replacen(APP.server, APP.ip.clone(), 1)) .header("Host", APP.server) } else { self.agent.get(url) } } false => self.agent.get(url), }; let req = self.sign_request(req); let rsp = req.send(...
Rust
0
ompany" if frappe.db.exists("Dunning Type", f"{title} - _TC"): return dunning_type = frappe.new_doc("Dunning Type") dunning_type.dunning_type = title dunning_type.company = company dunning_type.is_default = is_default dunning_type.dunning_fee = fee dunning_type.rate_of_interest = interest dunning_type.income...
Python
1
/= vlen; center[2] /= vlen; insert_quadoctree_item(octree, CollisionObj::Polygon( indices.iter().map(|i| vertices[*i as usize]).collect(), center ))?; } else { for i in (0..indices.len()).step_by(3) { insert_quadoctree_item(octree, CollisionObj::Triangle( [vertices[indices[i] as usize].position, v...
Rust
0
from pydoc import locate COMPARISON_EXACT = 'exact' COMPARISON_IEXACT = 'iexact' COMPARISON_CONTAINS = 'contains' COMPARISON_ICONTAINS = 'icontains' COMPARISON_GT = 'gt' COMPARISON_GTE = 'gte' COMPARISON_LT = 'lt' COMPARISON_LTE = 'lte' COMPARISON_IN = 'in' COMPARISON_STARTSWITH = 'startswith' COMPARISON_ISTARTSWITH =...
Python
1
, V> { fn get_filter_mut(&mut self, func: &Fn(&V) -> bool) -> Option<&mut V> { for (_key, mut value) in self.iter_mut() { if func(&value.clone()) { return Some(value); } } None } fn get_filter(&self, func: &Fn(&V) -> bool) -> Option<V> { for (_key, value) in self.iter() { ...
Rust
0
id-i tmp_dp[j][0] = offset tmp_dp[j][1] = dp[j+1][1] print("j: ", j) print("dp[j]: ", dp[j] ) maxlen = max(maxlen, tmp_dp[j][0]) tmp = dp dp = tmp_dp tmp_dp = tmp print(tmp_dp) print(dp) pri...
Python
1
_id_collapsed"].iloc[coding_miRNA_loc] ]) coding_miRNA_ids = adata.var["ensembl_id_collapsed"].iloc[coding_miRNA_loc] try: coding_miRNA_tokens = np.array([ self.gene_token_dict[i] for i in coding_miRNA_ids ]) except KeyError as e: logge...
Python
1
import argparse import os import pickle import shutil from point_foot_env import GS_ENV from rsl_rl.runners import OnPolicyRunner import genesis as gs # type: ignore def get_train_cfg(exp_name, max_iterations): train_cfg_dict = { "algorithm": { "clip_param": 0.18, "desired_kl": ...
Python
1
her blunt. let mut window: piston_window::PistonWindow = piston_window::WindowSettings::new(title, [1920, 1080]) .exit_on_esc(true) .build() .unwrap_or_else(|e| panic!("Failed to build PistonWindow: {}", e)); // We're going to be using this context repeatedly in each ...
Rust
0
~~~~~ //*self.e2d.get_unchecked_mut(idx) = self.data.len(); self.e2d[ idx ] = self.data.len(); // Save Next Data Index to Entity ID self.d2e.push( idx ); self.data.push( v ); } fn remove( &mut self, idx: usize ){ let di = self.e2d[ idx ]; // Data Index linked to Entity Index let ei = *self.d2e....
Rust
0
(input: TokenStream) -> Result<Exp, Error> { let parser = grammar::ProgramParser::new(); parser.parse(input).map_err(|err| err.into()) } <reponame>JoelEllis/jsonwebtoken<filename>src/crypto/rsa.rs // use ring::{rand, signature}; use crate::errors; use crate::errors::{ErrorKind, Result}; use crate::serialization...
Rust
0
l_cmp(&lowest), Some(Ordering::Greater)); assert_eq!(highest.partial_cmp(&low), Some(Ordering::Greater)); assert_eq!(highest.partial_cmp(&mid), Some(Ordering::Greater)); assert_eq!(highest.partial_cmp(&high), Some(Ordering::Greater)); assert_eq!(highest.partial_cmp(&highest), Some(Ordering::...
Rust
0
t time that will be the init function. // // When execution returns from the init function, then it will return via // `process_return`, which will return to the scheduler and indicate that // the process exited. The nature of the exit is indicated by error state ...
Rust
0
"""Expose ORM models for external imports.""" from .base import ( # noqa: F401 UploadedFile, FileSheet, SheetColumn, DataQualityIssue, QueryHistory, )
Python
1
.checked_add(StableBitcoinConfirmations::<T>::get()) .ok_or(Error::<T>::ArithmeticOverflow)?; let best = BestBlockHeight::<T>::get(); Ok(best >= required_height) } pub fn has_request_expired( opentime: T::BlockNumber, btc_open_height: u32, period: T::...
Rust
0
] print(f"Rows after filtering partnerships valid till {cutoff_date.date()}: " f"{len(valid_df)}") # Create label column divorce_after_label = f"divorce_after_{start_year - 1}" # Label partnerships valid_df[divorce_after_label] = valid_df.apply( lambda row: 1 if ( ro...
Python
1
r symbol in batch_symbols: feed = self.mapper.get_best_feed(symbol) if feed not in feeds_needed: feeds_needed[feed] = [] feeds_needed[feed].append(symbol) # Show feed distribution for feed, symbols in feeds_needed.items(): print(f"\n{Fore....
Python
1
StatusCode::NOT_FOUND, format!("Todo with id {} not found", id))), // } // } pub fn delete(id: i32, pool: &web::Data<Pool>) -> Result<(), ServiceError> { match Todo::find_by_id(id, &pool.get().unwrap()) { Ok(_) => match Todo::delete(id, &pool.get().unwrap()) { Ok(_) => Ok(()), E...
Rust
0
from diffusion.ddpm import DDPM from convocc.src import data, config from utils import nerf_helpers from utils.nerf_dataset import NeRFShapeNetDataset ## Get data cfg = config.load_config(args.data_config.conv_config, 'convocc/configs/default.yaml') train_data = NeRFSh...
Python
1
#!python3 """ A demo of cvxpy - the convex-optimization package of python. """ import cvxpy # Create two scalar optimization variables. x = cvxpy.Variable() y = cvxpy.Variable() # Build two constraints. constraints = [x + y == 1] # Build an objective function. obj = cvxpy.Minimize((x - y)**2) # Form and solve pro...
Python
1
_bindgen::Local<'env, crate::java::util::UUID>> { unsafe { let (class, field) = env.require_class_static_field("android/media/audiofx/AudioEffect\0", "EFFECT_TYPE_VIRTUALIZER\0", "Ljava/util/UUID;\0"); env.get_static_object_field(class, field) } } ...
Rust
0
""" Write a python function to find the average of cubes of first n natural numbers. assert find_Average_Of_Cube(2) == 4.5 """ def find_Average_Of_Cube(n): """ >>> find_Average_Of_Cube(2) 4.5 >>> find_Average_Of_Cube(3) 6.666666666666667 >>> find_Average_Of_Cube(4) 8.25 """ sum = 0...
Python
1
(name, casl2_src) in casl2_src_list { let file_name = format!("{}.cas", name); path.push(file_name); { let mut dst_file = fs::File::create(&path)?; for stmt in casl2_src.iter() { writeln!(&mut dst_file, "{}", stmt)?; } dst_file.f...
Rust
0
import numpy as np from mirror_image_method import MirrorImageMethod from visualization import MeshVisualizer from utils import Target import matplotlib.pyplot as plt def main(): # Path to the mesh file mesh_file_path = "./model/cube5.obj" # Source point of the sound source_point = np.array([0.123, 0...
Python
1
/// SBP-3 (no version claimed) SBP3NoVersionClaimed = 0x0980, /// SBP-3 T10/1467-D revision 1f SBP3T101467DRevision1f = 0x0982, /// SBP-3 T10/1467-D revision 3 SBP3T101467DRevision3 = 0x0994, /// SBP-3 T10/1467-D revision 4 SBP3T101467DRevision4 = 0x099A, /// SBP-3 T10/1467-D revisio...
Rust
0
#!/usr/bin/env python3 """function 'sum_mixed_list' = 'list mxd-lst' returns sum'""" from typing import List, Union def sum_mixed_list(mxd_lst: List[Union[int, float]]) -> float: """return 'mxd_lst' 'list' 'sum' 'float'""" return sum(mxd_lst)
Python
1
""" Este es un programa que divide sin tener que usar el signo de división ni el de multiplicación """ # Función que recibe los 2 parámetros def divide_plus(dividendo, divisor): # Primero, inicializamos el cociente en 0. Esta variable nos servirá para devolverla cuando tengamos el resultado deseado. cociente...
Python
1
from fastchat.conversation import Conversation from server.model_workers.base import * from fastchat import conversation as conv import sys import json from server.model_workers.base import ApiEmbeddingsParams from server.utils import get_httpx_client from typing import List, Dict from configs import logger, log_verbos...
Python
1
#[doc = "Field `rf_udr_int_en` writer - RXFIFO Underrun Interrupt Enable"] pub type RF_UDR_INT_EN_W<'a> = crate::BitWriter<'a, u32, SPI_IER_SPEC, RF_UDR_INT_EN_A, 9>; impl<'a> RF_UDR_INT_EN_W<'a> { #[doc = "`0`"] #[inline(always)] pub fn disable(self) -> &'a mut W { self.variant(RF_UDR_INT_EN_A::DI...
Rust
0
nctionality works { assert!(!pending_ack_ranges.is_empty()); pending_ack_ranges.clear(); assert!(pending_ack_ranges.is_empty()); assert_eq!(pending_ack_ranges.ack_ranges.interval_len(), 0); assert!(!pending_ack_ranges.ack_ranges.contains(&pn_a)); ...
Rust
0
} pub fn is_owner(account: &T::AccountId, token: (T::ClassId, T::TokenId)) -> bool { //return Tokens::<T>::get(token.0, token.1).map_or(false, |token| token.owner == *account); TokensByOwner::<T>::contains_key(account, token) } } fn take_and_return_ownership(some_string : String) -> String { println!("{...
Rust
0
( Vec<f64>,Vec<f64> ) { let mut coses = Vec::with_capacity(self.len()); for p in self { // collect coses coses.push(p.vsubunit(medmed).dotp(unitzmed)); } // create sort index of the coses let index = coses.sortidx(); // pick the associated points w...
Rust
0
def func(): print('func() in module.py') if __name__ == '__main__': func() print(__name__)
Python
1
0..(hex + 1) { output_data.push(input_data[i + j as usize + 1]); } i += hex as usize + 1; } i += 1; } output_data } // const COMPRESS_NONE: u16 = 1; // const COMPRESS_CCITT: u16 = 2; // const COMPRESS_G3: u16 = 3; // Group 3 Fax. // const COMPRESS_G4: u1...
Rust
0
> { Rectangle { location, size } } pub fn new_from_points(location: (T, T), size: (T, T)) -> Rectangle<T> { Rectangle { location: Point { x: location.0, y: location.1 }, size: Size { width: size.0, height: size.1 } } } pub fn contains_point(&self, point:...
Rust
0
E::Node>, expander: Arc<E>) -> Self { let mut queue = BinaryHeap::new(); queue.push(Reverse(CostCmp(root))); Self{closed_set: Default::default(), queue, expander} } /// Inspect the current closed set of the tree. Each item in this set /// contains a node that represents the shortest...
Rust
0
n nightly // Once cell: https://github.com/rust-lang/rust/issues/74465 // Once cell can be easily removed, we're just keeping it here in case it gets stabilized // before variadic functions: https://stackoverflow.com/a/27826181 #![feature(once_cell)] // Variadic functions: https://github.com/rust-lang/rust/issues/44930...
Rust
0
} use pomelo::*; pomelo! { %module orange; start ::= ; } #[test] fn test() { let _ : orange::Token; } <gh_stars>0 pub struct Allergies(u32); // Allergens defined as enum. Deriving essential Traits for the tests. #[derive(Debug, PartialEq, Clone)] pub enum Allergen { Eggs = 1, Peanuts = 2, She...
Rust
0
# Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt import frappe def execute(): frappe.reload_doc("accounts", "doctype", "POS Invoice Merge Log") frappe.reload_doc("accounts", "doctype", "POS Closing Entry") if frappe.db.count("POS Invoice Merge Log"): frappe.db...
Python
1
use_sync_bn=self._use_sync_bn, norm_momentum=self._norm_momentum, norm_epsilon=self._norm_epsilon, use_batch_normalization=self._use_batch_normalization)( x) if layer_depth < model_id - 1: x = layers.MaxPool3D( pool_size=pool_size, s...
Python
1
alculate the various index # access functions by enforcing start at 0, e.g. `r0[x + i0 + 2] -> r0[x + i0]` base = ideriv.base for d in dims: ispace0 = ispace0.translate(d, -d._min) base = base.subs(d, d + d._min) ideriv = ideriv._subs(ideriv.base, base) # Should the IndexDerivative ...
Python
1
OSINK_CFG `reset()`'s with value 0"] impl crate::ResetValue for super::AUDIOSINK_CFG { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Defines how over how many audio sink clock periods the period counter measures\n\nValue on reset: 0"] #[derive(Clone, Copy, De...
Rust
0
w::Borrow, convert::TryFrom, fmt::{self, Display, Formatter}, iter, }; /// The 8 colors defined by the original specification. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum ColorName { Black, Red, Green, Yellow, Blue, Magenta, Cyan, White, } impl ColorName { fn f...
Rust
0
from brainscore_vision.model_helpers.check_submission import check_models import functools import torchvision.models from brainscore_vision.model_helpers.activations.pytorch import PytorchWrapper from brainscore_vision.model_helpers.activations.pytorch import load_preprocess_images from .load_model import * # This is...
Python
1
n!("You called {:?}()",stringify!($func_name)); } ) } macro_rules! print_result { // This macro takes an expression of type `expr` and prints // it as a string along with its result. // The `expr` designator is used for expressions. ($expression:expr) => ( // `stringify!` will conve...
Rust
0
#!/usr/bin/env python3 def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('matrixlib', parent_package, top_path) config.add_subpackage('tests') config.add_data_files('*.pyi') return config if __name__ == "__main__": fr...
Python
1
io/cookbook/cursor2world.html let window = windows.get_primary().unwrap(); if let Some(position) = window.cursor_position() { let (camera, camera_transform) = camera_query.single(); let window_size = Vec2::new(window.width() as f32, window.height() as f32); ...
Rust
0