text
string
label_name
string
labels
int64
rlying value are /// intended to have saturating semantics. /// /// The underlying value can be retrieved through the `.0` index of the /// `Saturating` tuple. /// /// # Examples /// /// ``` /// #![feature(saturating_int_impl)] /// use std::num::Saturating; /// /// let max = Saturating(u32::MAX); /// let one = Saturati...
Rust
0
at16) >>> config = TeaBlockCacheTaylorConfig( ... step_start=50, ... step_end=950, ... block_cache_start=1, ... single_block_cache_start=1, ... taylor_max_order=1, ... taylor_first_enhance=1, ... current_timestep_callback=lambda: pipe._current_timestep, ....
Python
1
import json from collections import OrderedDict from augmentations.ctaugment import * class StorableCTAugment(CTAugment): def load_state_dict(self, state): for k in ["decay", "depth", "th", "rates"]: assert k in state, "{} not in {}".format(k, state.keys()) setattr(self, k, state[...
Python
1
"version": vname } for k in add_keys: data_imprint.update({k: version_data[k]}) # getting file path file = get_representation_path(representation).replace("\\", "/") with maintained_selection(): model_node['selected'].setValue(True) # c...
Python
1
CROBATCHSIZE, shuffle=True, num_workers=1, drop_last=True, ) val_loader = DataLoader( dataset=val_dataset, batch_size=MICROBATCHSIZE, num_workers=1, drop_last=True, ) test_loader = DataLoader( dataset=test_dataset, batch_size=MIC...
Python
1
ples, len: sa.len(), } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_regular() { let cases = [ (1, 10), (1, 25), (2, 8), (2, 9), (2, 10), (2, 25), (3, 24), (3, 25), ...
Rust
0
attr(self.aug_pil, str(name))(image, label) return image, label else: name=np.random.choice(list(self.augment_ways.keys())) image, label = getattr(self.aug_pil, str(name))(image, label) return image, label class ToTensor(object): # image label -> tensor, ima...
Python
1
ted() { Ok(Action::Destruction(destruction_action(r).await?)) } else { Ok(Action::Creation(creation_action(r).await?)) } } async fn creation_action(r: &ResourceInterface) -> Result<CreationAction> { if r.resource().status.is_none() { return Ok(CreationAction::Initialize); } ...
Rust
0
?; let sri = writer.commit().await.to_internal()?; entry_hash.insert(key, (sri, size, mode)); } std::mem::drop(entries); let (sri, mut reader) = ar .into_inner() .map_err(|_| Error::MiscError("Failed to get inner Read".into())) .to_internal()? .into_inner() ...
Rust
0
, ()); assert_eq!( vec![(2, &()), (1, &())], graph.neighbors(0).collect::<Vec<(usize, &())>>() ); assert_eq!( Vec::<(usize, &())>::new(), graph.neighbors(1).collect::<Vec<(usize, &())>>() ); } } <reponame>NiklasEi/ld49 use crate::loadin...
Rust
0
let kserd = Kserd::enc(&1).unwrap(); assert_eq!(kserd.ch(), None); } #[test] fn eq_unsigned_int() { macro_rules! t { ($t:ident) => { let kserd = Kserd::new_num(std::$t::MAX); assert_eq!(kserd.uint(), Some(std::$t::MAX as u128)); let kserd = Kserd::enc(&true).unwrap()...
Rust
0
import pandas as pd import matplotlib.pyplot as plt a=(1,2,3,4,5) b=(1,2,3,4,5) c=(0,4,8,10) d=(1,3,6,9) # plt.plot((1,2,3,4,5),(1,2,3,4,5),'r') # r == tipo cor da linha, -- == tipo fromatação da linha, o == pontos ligados da linha plt.plot(a,b,'r --o') plt.plot(c,d,'m--*') # plt.hist(a,b) # plt.scatter(a,b,'r--o')# ...
Python
1
pub stat: bool, /// Dry run #[structopt(long, parse(from_occurrences = toggle_bool))] pub dryrun: bool, } /// Install/Uninstall necessary files. #[derive(StructOpt)] pub struct InstallOpts { /// Install all necessary files to the user directory // TODO: give up for Option<Option<PathBuf>>, not work...
Rust
0
import matplotlib.pyplot as plt import pandas as pd import matplotlib.animation as animation print("Welcome to DroneFlightData Visualizer!") print("How would you like to enter the data?") print("1 - Enter data manually") print("2 - Load data from CSV file") choice = input("Enter your choice (1 or 2): ") if choice ==...
Python
1
remoteFile" , // "id": "AAMCBQADFQABYhDFzqLglD1zuaFAaQfwZXAvNBgAAmYNAALKlThS4z4c8Z142qQBAAdtAAMiBA" , // "unique_id": "AQADZg0AAsqVOFJy" , // "is_uploading_active": false , // "is_uploading_completed": true , // "uploaded_size": 20067 // } // } // } , //...
Rust
0
return session_data except Exception as e: self.logger.error(f"Database connection error: {e}") raise def change_password(self, user_id: int, current_password: str, new_password: str) -> dict: """현재 로그인된 사용자의 비밀번호를 변경합니다.""" try: with s...
Python
1
l { pub neighbors: Neighbors, pub black_trees: Trees, pub stacked_trees: Trees, } impl AppCell { pub fn neighbors(&self) -> &HashMap<Size, Neighbor> { &self.neighbors.neighbors } pub fn neighbors_mut(&mut self) -> &mut Neighbors { &mut self.neighbors } pub fn black_trees(&self) -> &HashMap<Strin...
Rust
0
"} # 创建实体,设置基本属性 create_query = f""" CREATE (e:__Entity__:{entity_data.type} {{ id: $id, name: $name, description: $description }}) RETURN e.id AS id """ params = { "id": entity_data.id, ...
Python
1
import cv2 import numpy as np import tensorflow as tf # Load pre-trained MobileNetV2 model for liveness detection model_path = 'path/to/mobilenetv2/model' liveness_model = tf.keras.models.load_model(model_path) # Load LBPH face recognizer face_recognizer = cv2.face.LBPHFaceRecognizer_create() face_recognizer.read('pa...
Python
1
import argparse import os import shutil from job import append_to_json def get_args(): parser = argparse.ArgumentParser(description='Submit a job to the queue') parser.add_argument('--src', required=True, help='The source directory to copy') parser.add_argument('--dst', required=True, help='The destinati...
Python
1
t isinstance(results, list) if isinstance(results[0], list): pass elif isinstance(results[0], tuple): results = [result[0] for result in results] else: raise TypeError('invalid type of prediction results') if isinstance(cfg.data.test, dict): cfg.data.test.test_mode = Tru...
Python
1
); assert_approx_eq!(vec.y(), 20.0); } #[test] fn test_div_assign() { let mut vec = Vec2::new(1.0, -4.0); vec /= -5.0; assert_approx_eq!(vec.x(), -0.2); assert_approx_eq!(vec.y(), 0.8); } #[test] fn test_dot_prod() { let vec_a = Vec2::new(1.0, ...
Rust
0
oytan/tutorial.html")) except Exception as e: showCritical("Error occured while accessing to the Internet.\n" "Please report this bug to the developers via GitHub.\n" "(%s)" % e) def _on_website(self): try: QDesktopServices.o...
Python
1
ON CONFLICT (project, type_id) DO UPDATE SET count = EXCLUDED.count ", pid, &type_ids, &counts ) .execute(&self.pool) .await .map(drop) .map_err(Error::DatabaseError) } } impl std...
Rust
0
otenv().ok(); env::var("DATABASE_URL").expect("Cant find DATABASE_URL!") }; static ref POOL: Pool<Sqlite> = block_on(create_sqlite_pool(&DB_ADDRESS)).expect("Can't connect to db!"); } #[derive(Debug, Error)] enum ApplicationError { #[error(transparent)] Queries(#[from] QueriesError), ...
Rust
0
for sample, nf_f, nc_f, msg in pbar: if nf_f: samples.append(sample) if msg: msgs.append(msg) nf += nf_f nc += nc_f pbar.desc = f"{desc} {nf} images, {nc} ...
Python
1
el_oscuro:', 'fr': ':femme_en_smoking_peau_foncée:', 'ja': ':タキシードの女性_濃い肌色:', 'ko': ':턱시도를_입은_여자_검은색_피부:', 'pt': ':mulher_de_smoking_pele_escura:', 'it': ':donna_in_smoking_carnagione_scura:', 'fa': ':زن_با_کت_و_شلوار_و_پاپیون_پوست_آبنوسی:', 'id': ':wanita_bertuks...
Python
1
_id)); let future = self.base.execute_val::<Vec<clash_v1::Player>>("clash-v1.getPlayersBySummoner", route_str, request); #[cfg(feature = "tracing")] let future = future.instrument(tracing::info_span!("clash-v1.getPlayersBySummoner")); future } /// Get team by ID. /// # Param...
Rust
0
ure (SCD) solution. #[macro_use] extern crate wedpr_l_macros; pub mod issuer; pub mod user; pub mod utils; pub mod verifier; // TODO: Add E2E tests for all SCD functions. // TODO: Add benches for all SCD functions. <reponame>nanaian/bgmtool pub mod voice; /// Encoder ([Bgm] -> .bin) pub mod en; /// Decoder (.bin -...
Rust
0
current_diff: Diff | None = None for diff in differences: if diff["generated"]["begin_index"] == current_generated_index: current_diff = diff break # current_diff が None でない場合、generated_phone から始まる差分がある if current_diff is not...
Python
1
update after tests complete. 'date': date_only_str, 'piiPrompt': pii_prompt, 'inProgress': True } try: file_exists = os.path.exists(csv_filename) with open(csv_filename, 'a', newline='', encoding='utf-8') as csvfile: fieldnames = ['testID', 'model', 'testSet'...
Python
1
Real Field with 53 bits of precision Inner product matrix: [0.000000000000000 -1.00000000000000] [ 1.00000000000000 0.000000000000000] sage: T = M.tangent_space(M.point(), base_ring=RR); T Tangent space at Point on the Standard symplectic space R2 ...
Python
1
(), ) })? .clone(); for i in 0..unresolved_shuffle.output_partition_count { if let Some(x) = p.get(&i) { relevant_locations.push(x.to_owned()); } else { relevant_locations.push(vec![]...
Rust
0
new_ucmd!().arg("-R").arg(FILE).run().stdout; let expected = at.read(FILE); let unexpected = new_ucmd!().arg("-R").arg(FILE).run().stdout; assert_ne!(result, expected); assert_ne!(result, unexpected); } #[test] fn test_random_shuffle_contains_two_runs_not_the_same() { // check to verify that two ...
Rust
0
rn schedule_message, conflict_matrix, links def calculate_conflicts(args): """ 计算冲突矩阵的子任务。 """ i_start, i_end, links, d_v1_v2_all = args N = len(links) conflict_matrix_part = np.zeros((N + 1, N + 1), dtype=int) for i in range(i_start, i_end + 1): for j in range(i + 1, N + 1): ...
Python
1
; //! use std::io::{Read, Write}; //! //! // spawn a cat process //! let mut process = PtyProcess::spawn(Command::new("cat")).expect("failed to spawn a process"); //! //! // write message to cat. //! process.write_all(b"hello cat\n").expect("failed to write"); //! //! // read what cat produced. //! let mut buf = vec![0...
Rust
0
try: p = self.prompt_formatter(p) except Exception: # pylint: disable=broad-except print_exception() self.settitle() return p def format_color(self, string, hide=False, force_string=False, **kwargs): """Formats the colors in a string. ``BaseShell``'s default...
Python
1
} }); }; local_ret } } // We're essentially a pointer already, or at least a set of pointers, so allow us to be used // directly as a Deref trait in higher-level structs: impl std::ops::Deref for ManyChannelMonitor { type Target = Self; fn deref(&self) -> &Self { self } } /// Calls the free function if one is...
Rust
0
modify--write-api).\n\nFor information about avaliable fields see [apbspppcexp0](apbspppcexp0) module"] pub type APBSPPPCEXP0 = crate::Reg<u32, _APBSPPPCEXP0>; #[allow(missing_docs)] #[doc(hidden)] pub struct _APBSPPPCEXP0; #[doc = "`read()` method returns [apbspppcexp0::R](apbspppcexp0::R) reader structure"] impl crat...
Rust
0
)); } } #[derive(Debug)] pub struct If { cond: Cond, then_label: Option<Label>, else_label: Option<Label>, } impl If { fn new(cond: Cond, then_label: Option<Label>, else_label: Option<Label>) -> Self { Self { cond, then_label, else_label, } }...
Rust
0
presentation of Pem-encoded data #[derive(PartialEq, Debug, Clone)] pub struct Pem { /// The tag extracted from the Pem-encoded data pub tag: String, /// The binary contents of the Pem-encoded data pub contents: Vec<u8>, } impl Pem { fn new_from_captures(caps: Captures) -> Result<Pem> { fn ...
Rust
0
t_start_x - input_start_x_pad) * scale output_end_x_tile = output_start_x_tile + input_tile_width * scale output_start_y_tile = (input_start_y - input_start_y_pad) * scale output_end_y_tile = output_start_y_tile + input_tile_height * scale # put tile into...
Python
1
bits: ::std::os::raw::c_uint); } extern "C" { /// @ingroup OPERANDS /// Set the unsigned immediate using a BYTE length. pub fn xed_operand_values_set_immediate_unsigned(p: ...
Rust
0
] lmp = lammps(lammps_name, cmd_args, comm) struc = bulk('Si', 'diamond', cubic=True) struc.set_tags([1]*len(struc)) parameters = ["mass * 1.0", "pair_style mliap model nn Si-snap/NN_weights.txt descriptor sna Si-snap/DescriptorParams.txt", "pair_coeff * * Si Si" ...
Python
1
] #[allow(non_snake_case)] pub extern "system" fn Java_net_wooga_uvm_UnityVersionManager_detectProjectVersion( env: JNIEnv, _class: JClass, path: JObject, ) -> jstring { jni_utils::get_path(&env, path) .and_then(|path| uvm_core::dectect_project_version(&path, Some(true)).map_err(|e| e.into())) ...
Rust
0
`*"] pub struct MINIDUMP_SYSTEM_INFO { pub ProcessorArchitecture: PROCESSOR_ARCHITECTURE, pub ProcessorLevel: u16, pub ProcessorRevision: u16, pub Anonymous1: MINIDUMP_SYSTEM_INFO_0, pub MajorVersion: u32, pub MinorVersion: u32, pub BuildNumber: u32, pub PlatformId: VER_PLATFORM, pub...
Rust
0
iffCompressionZIP = 0x00000006, WICTiffCompressionLZWHDifferencing = 0x00000007, WICTIFFCOMPRESSIONOPTION_FORCE_DWORD = CODEC_FORCE_DWORD, }} ENUM!{enum WICJpegYCrCbSubsamplingOption { WICJpegYCrCbSubsamplingDefault = 0x00000000, WICJpegYCrCbSubsampling420 = 0x00000001, WICJpegYCrCbSubsampling422 = ...
Rust
0
::Option; use std::option::Option::Some; use std::prelude::v1::Vec; use std::result::Result; use std::result::Result::{Err, Ok}; use std::string::String; mod model; mod util; use post_data::PostData; use std::clone::Clone; use std::convert::From; use std::sync::{Arc, Mutex}; const GLADE_SRC: &str = include_str!("gri...
Rust
0
let data_iter = lock.into_iter().map(|size| { let prev_count = pair_count; pair_count += size; prev_count }); vulkano::buffer::ImmutableBuffer::from_iter( data_iter, vulkano::buffer::BufferUsage::all(), ...
Rust
0
mapping[carry_cur] = rule.target break else: node1, node2, target = find_swap( 'OR', mapping[and_cur], mapping[extra_cur] ) mapping[carry_cur] = target swap_rules(mapping, node1, node2) swapped_nodes.extend([node1, ...
Python
1
#!/usr/bin/env python # Copyright 2025 Google LLC # # 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 ...
Python
1
, the flag indicates the type of the stored value. /// /// Currently, even though a struct that contains an optimized union is supported by the /// `JuliaStruct` macro, these fields can't be used from Rust. If you want to access the value, /// you can use `Value::get_field` which will essentially convert it to the gene...
Rust
0
Config, ) -> Result<(), DkgCreateDealingError> { if !is_eligible_dealer(self_node_id, config) { return Err(DkgCreateDealingError::NotADealer(NotADealerError { node_id: *self_node_id, })); } Ok(()) } fn csp_dealing<C: NiDkgCspClient>( s...
Rust
0
ack_in_place(&mut self) { let filled = match self { PackedNibbleCube::Unpacked(_) => return, PackedNibbleCube::EntirelyDark => NibbleCube::default(), PackedNibbleCube::EntirelyLit => { let mut data = NibbleCube::default(); data.fill(u4::MAX); data } }; *self = PackedNibbleCube::Unpacked...
Rust
0
impl<T: Load> LoadRef for T { type BlobDyn = T::Blob; type PtrClean = T::PtrClean; type Zone = T::Zone; fn load_ref_from_bytes<'a>(bytes: Bytes<'a, Self::BlobDyn>, zone: &Self::Zone) -> Result<MaybeValid<Ref<'a, Self>>, <Self::BlobDyn as BlobDyn>::DecodeBytesError> { ...
Rust
0
/// Alias for MANTISSA_RADIX. pub const RADIX: u128 = MANTISSA_RADIX; /// Shift to convert to and from an exponent base as a `u32`. pub const EXPONENT_BASE_SHIFT: i32 = 112; /// Mask to extract the exponent base: the base the exponent is raised to. pub const EXPONENT_BASE: u128 = 0xFF << EXPONENT_BASE_SHIFT; /// Shi...
Rust
0
in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit(); exit() elif event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN: showing = False screen.fill((100, 200, 180)) # NOTE: some sprites (like Sasquatch) accept dt; others ign...
Python
1
n_kwargs=plot_neuron_kwargs, with_cells=with_cells, cells_linear_density=cells_linear_density, cells_wire_plot=cells_wire_plot, figsize=figsize, random=random, ) if not video: Path(pdf_filename).parent.mkdir(parents=True, exist_ok=True) with PdfPages(pdf_f...
Python
1
nown_query_param() { let opts = "mysql://localhost/foo?bar=baz"; let _: Opts = opts.into(); } } use std::fmt; use std::panic::{RefUnwindSafe, UnwindSafe}; use memchr::{memchr, memchr2, memchr3}; /// A prefilter describes the behavior of fast literal scanners for quickly /// skipping past bytes in ...
Rust
0
PxBaseFlags, pub structgen_pad1: [u8; 4], pub userData: *mut std::ffi::c_void, } #[test] fn check_size_PxContactJoint() { assert_eq!(std::mem::size_of::<PxContactJoint>(), 24); } #[derive(Clone, Copy)] #[repr(C)] pub struct PxJacobianRow { pub linear0: PxVec3, pub linear1: PxVec3, pub ang...
Rust
0
builder.set_timeout_config(timeout_config); if let Some(sleep_impl) = sleep_impl { builder.set_sleep_impl(Some(sleep_impl)); } let client = builder.build(); Self { handle: std::sync::Arc::new(Handle { client, conf }), } } } impl Client< aws...
Rust
0
an expression, maybe tags and description _ => return Err(make_failure(input, Error::Syntax(pos.into()))), } let expr = arg_vec.remove(0).trim().to_string(); let mut tags_and_desc = arg_vec; for s in tags_and_desc.iter_mut() { *s = truncate_and_trim(s).map_err(|_| make_failure(input, Er...
Rust
0
cation_commands(commands).await?; } else { for guild_id in deploy.split(',') { if let Ok(guild_id) = guild_id.parse() { http.create_guild_application_commands(guild_id, commands).await?; } } } Ok(()) } <filename>twp/src/layer_parser.rs use super::frame_parser::decode_frame_offset; use super::types::{D...
Rust
0
e the notification search pub l1bitmap: [AtomicU64; 8], // one bit map to one Quark Container pub l2bitmap: [AtomicU64; BITMAP_COUNT], } pub const MTU: usize = 1500; pub const UDP_BUF_COUNT: usize = 512 * 1024; // 512K udp buff // udp buf, around 1516 bytes #[derive(Copy, Clone)] pub struct UDPBuf { ...
Rust
0
raw::c_void; #[doc = " Handle for image event handler functionality. Created by calling"] #[doc = " spinImageEventHandlerCreate(), which requires a call to spinImageEventHandlerDestroy()"] #[doc = " to destroy."] pub type spinImageEventHandler = *mut ::std::os::raw::c_void; #[doc = " Handle for arrival event handler fu...
Rust
0
b.usd" FFTAI_GR1T1_LOWER_LIMB_CFG.actuators = ( { "actuators": ImplicitActuatorCfg( joint_names_expr=[".*"], stiffness={ ".*_hip_roll": 114, ".*_hip_yaw": 86, ".*_hip_pitch": 229, ".*_knee_pitch": 229, "....
Python
1
tState::Released, } } } impl From<&ElementState> for WrapElementState { fn from(inp: &ElementState) -> Self { match inp { ElementState::Pressed => WrapElementState::Pressed, ElementState::Released => WrapElementState::Released, } } } <gh_stars>0 use std::ffi:...
Rust
0
ternal" ' 'href="/admindocs/views/myapp.views.Index/">myapp.views.Index</a></p>' ) self.assertHTMLEqual(parse_rst(source, "view"), rendered) def test_parse_rst_template_case_sensitive(self): source = ":template:`Index.html`" rendered = ( '<p><a class="referen...
Python
1
um_nanoseconds(), "execution": { "resolvers": self.resolves } })) } } <reponame>jeivardan/influxdb_iox use std::fs; use std::fs::File; use std::io::{BufReader, Read}; use std::path::Path; use assert_cmd::assert::Assert; use assert_cmd::Command; use predicates::prelud...
Rust
0
t UnmappedColumnError: # in the case of single table inheritance, there may be # columns on the mapped table intended for the subclass only. # the "unmapped" status of the subclass column on the # base class is a feature of the declarative module as of sql...
Python
1
fn try_add_tags_to_builder() { let v = vec![("field1", "value1"), ("field2", "value2")]; let point = Point::builder("test") .unwrap() .try_add_fields(v) .build() .unwrap(); assert_eq!( point.to_text_with_precision(None), r#...
Rust
0
": { "browserName": "chrome", "version": "latest", "platform": "ANY" }, "firefox": { "browserName": "firefox", "version": "latest", "platform": "ANY" }, "edge": { ...
Python
1
import numpy as np import pytest from PIL import Image @pytest.fixture def dice_image(): return np.array(Image.open("assets/demo_cube.png")) @pytest.fixture def dice_image_mono(dice_image): return dice_image.mean(axis=-1) @pytest.fixture def equirec_image(): return np.array(Image.open("assets/demo_equ...
Python
1
BaseModel types are only supported with Pydantic v2 - {text_format}") return pydantic.TypeAdapter(text_format).validate_json(text) raise TypeError(f"Unable to automatically parse response format type {text_format}") def get_input_tool_by_name(*, input_tools: Iterable[ToolParam], name: str) -> FunctionT...
Python
1
use hal::pac::Peripherals; use hal::prelude::*; use hal::timer::TimerCounter; use smart_leds::{hsv::RGB8, SmartLedsWrite}; use ws2812_timer_delay::Ws2812; #[entry] fn main() -> ! { let mut peripherals = Peripherals::take().unwrap(); let mut clocks = GenericClockController::with_internal_32kosc( perip...
Rust
0
f = open('day01/input.txt') txt = [i.strip() for i in f.readlines()] L = [] R = [] for line in txt: margaret, thatcher = line.split() L.append(int(margaret)) R.append(int(thatcher)) sum_ = 0 for i, j in zip(sorted(L), sorted(R)): sum_ += abs(i - j) print(sum_)
Python
1
orm_(self.block2[-1].weight, gain=1e-5) def forward(self, x, temb): h = self.block1(x) h += self.temb_proj(temb)[:, :, None, None] h = self.block2(h) h = h + self.shortcut(x) h = self.attn(h) return h class UNet(nn.Module): def __init__(self, T, ch, ch_mult, a...
Python
1
} fn log_err(self, level: Level, message: &str) -> Result<T, E> { self.map_err(|e| { log!(level, "{}: {:?}", message, e); e }) } result_log_impl_group!(trace, Level::Trace); result_log_impl_group!(debug, Level::Debug); result_log_impl_group!(info, Level:...
Rust
0
let current_queue_size = current_config.request_queue_size; let new_limits = new_config.request_limits; let new_queue_size = new_config.request_queue_size; app_state.config.store(Arc::new(new_config.clone())); app_state .account_info_request_limit .apply_limit(current_limits.account_i...
Rust
0
from kivy.animation import Animation from kivy.lang.builder import Builder from kivy.properties import BooleanProperty, NumericProperty, StringProperty Builder.load_string( """ <AKAnimationBehaviorBase>: canvas.before: PushMatrix Rotate: angle: root._angle origin: self.c...
Python
1
update nagger update check"); let ui = get_latest_sentrycli_release()?; if ui.have_version_info() { check.update_for_info(&ui); let mut f = fs::File::create(&path)?; serde_json::to_writer_pretty(&mut f, &check)?; f.write_all(b"\n")?; } } else ...
Rust
0
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import torch class Stage8(torch.nn.Module): def __init__(self): super(Stage8, self).__init__() self.layer5 = torch.nn.LSTM(2048, 1024) self.layer8 = torch.nn.Dropout(p=0.2) def forward(self, input1, input2, inpu...
Python
1
u64_reduce(0x8B52DBAC4316DF3C, 0xE6DD1B0B096BA49B, 0x45B50205A85D4930, 0xBCA014CCF49A96CF, 0x43EF77C96A70C64D), }, PointAffine { /* 16 */ x: GFp5::from_u64_reduce(0xD253F638008F64D9, 0x300911F4CF750079, 0xEBA4C0CCF84421F1, 0xD9A8EC0A382CC42A, 0xB2B4D66CAC8FDA35), u: GFp5::f...
Rust
0
table => { let mut t = TestHarness::<MemTableConstructor>::new(is_reversed, restart_interval); for (k, v) in $kv.clone() { t.add(k, v); } t.do_test(); ...
Rust
0
is caller and is not required let tree_id: T::TreeId = 0u32.into(); let manager = Managers::<T>::get(tree_id).unwrap(); assert_eq!(manager.required, false); assert_eq!(manager.account_id, caller.into()); } set_manager { let caller: T::AccountId = whitelisted_caller(); // Making an account id for new adm...
Rust
0
listeners.wait_for_scheduled_execution(job_name, cluster_id, node_type) # 8.1. Test Trained Model On Global Params metrics = handlers.test_model(job_name, cluster_id, node_type, strategy) # 8.2. Add Test Performance Metrics to PerfLog perflog.ad...
Python
1
<hb_aat_layout_feature_selector_info_t>())).enable as *const _ as usize }, 4usize, concat!( "Offset of field: ", stringify!(hb_aat_layout_feature_selector_info_t), "::", stringify!(enable) ) ); assert_eq!( un...
Rust
0
#Funcao para retornar os totais por item ou de totos do os itens e valores registrados import modulo_conexao as conexao def total(): dic=[ {"cod":"1","lanche":"xburguer","preco":10.90}, {"cod":"2","lanche":"xbacon ","preco":9.90}, {"cod":"3","lanche":"xsalada ","preco":9.90}, ...
Python
1
True, blank=True, related_name='assigned_reviews') # Review details review_reason = models.TextField() priority = models.CharField(max_length=20, choices=[ ('low', 'Low Priority'), ('medium', 'Medium Priority'), ('high', 'High Priority'), ('urgent', 'Urgent'), ], def...
Python
1
st::Jmp, nb), _ => unreachable!(), } } } struct VM { pub accumulator: i32, } impl VM { pub fn default() -> Self { Self { accumulator: 0 } } pub fn run(&mut self, code: &[Instruction]) -> bool { let mut visited = vec![false; code.len()]; let mut pc = 0; ...
Rust
0
rg = "my-org" token = "my-token" "#; let config: InfluxDBTestConfig = toml::from_str(&config).unwrap(); let _ = influxdb_settings(config.influxdb1_settings, config.influxdb2_settings).unwrap(); } #[test] fn test_influxdb1_test_write_uri() { let settings = InfluxDB1Settin...
Rust
0
""" requests.hooks ~~~~~~~~~~~~~~ This module provides the capabilities for the Requests hooks system. Available hooks: ``response``: The response generated from a Request. """ HOOKS = ["response"] def default_hooks(): return {event: [] for event in HOOKS} # TODO: response is the only one def dispatch_...
Python
1
(0x1F238, 'M', '申'), (0x1F239, 'M', '割'), (0x1F23A, 'M', '営'), (0x1F23B, 'M', '配'), (0x1F23C, 'X'), (0x1F240, 'M', '〔本〕'), (0x1F241, 'M', '〔三〕'), (0x1F242, 'M', '〔二〕'), (0x1F243, 'M', '〔安〕'), (0x1F244, 'M', '〔点〕'), (0x1F245, 'M', '〔打〕'), (0x1F246, 'M', '〔盗〕'), (0x1F247,...
Python
1
) -> Callable: """錯誤處理裝飾器""" def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except Exception as e: error_msg = f"操作失敗: {str(e)}" st.error(error_msg) logger.error(f"函數 {func.__name__} 執行失敗: {e}") logger.error(traceback.f...
Python
1
rsp = &[0x43, 0x03, 0x07, 0x18]; stream_request_response(&mut exec, &mut stream, &remote, cmd, rsp); let cmd = &[ 0x40, 0x03, 0x04, 0x08, // TxLabel 4, Signal, ACP (1) and INT (2) SEID 0x07, 0x02, // Media Codec (7), length 2 0x40, // Unknown Media Type, RFA 0x01, // Media Cod...
Rust
0
(meta: EditorMeta, ctx: &mut Context) { let file_uri = Url::from_file_path(&meta.buffile).unwrap(); let file_uri: String = file_uri.into(); let req_params = ExecuteCommandParams { command: "java.edit.organizeImports".to_string(), arguments: vec![serde_json::json!(file_uri)], ..Execu...
Rust
0
"Configuring CacheCollector on a {} minute timer", config::constants::CACHE_COLLECTOR_RUN_INTERVAL_SECS / 60 ); // runs five soft recycles, followed by one hard recycle. This pattern // is followed indefinitely. let f = timer .map_err(Into::<agent::Er...
Rust
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # @File : util_corpus.py # @Author: Hua Zhu # @Date : 2022/3/23 # @Desc : 处理来自MediaCloud的新闻语料数据,转换成合适的格式,用于训练词向量模型 import os import json import multiprocessing from multiprocessing import Pool import re from tqdm import tqdm import random import math import pickle from c...
Python
1
# coding=utf-8 import requests from core import printmodels from exploits import CVE_2017_9841PHPUnit r = '\033[31m' g = '\033[32m' y = '\033[33m' b = '\033[34m' m = '\033[35m' c = '\033[36m' w = '\033[37m' Headers = { "User-Agent": "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) " ...
Python
1
import matplotlib as mpl mpl.use("Agg") from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import matplotlib.cm as cm import numpy as np from matplotlib import rcParams rcParams['font.family'] = 'sans-serif' rcParams['font.sans-serif'] = 'Arial' rcParams['sa...
Python
1