text
string
label_name
string
labels
int64
1 { arg_vals[0].clone() } else { values::Tuple::new(arg_vals) as Value }; (funcs[fun_name].run)(arg) } } } //! Actix web juniper example //! //! A simple example integrating juniper in actix-web extern crate serde; extern crate serde_json;...
Rust
0
import threading import cv2 from deepface import DeepFace import os # Make sure model storage path exists model_path = os.path.join(os.getcwd(), "deepface_models") os.makedirs(model_path, exist_ok=True) # Preload the model to avoid "no model found" error DeepFace.build_model("Facenet") # You can use "VGG-Face", "Arc...
Python
1
.wait_for_disconnect() else: self.sync_with_ping() raw_mempool = node.getrawmempool() if success: # Check that all txs are now in the mempool for tx in txs: assert tx.hash in raw_mempool, "{} not found in mempool".f...
Python
1
WriteSetTrie}; use crate::write::TxStateUpdate; use alloc::format; #[cfg(feature = "cache_hash")] use crossbeam_utils::atomic::AtomicCell; use serde::{Deserialize, Serialize}; use slimchain_common::{ basic::{account_data_to_digest, Address, Nonce, StateKey, H256}, collections::HashMap, digest::Digestible, ...
Rust
0
== 0 { cpu.status.insert(CPUStatus::ZERO); } else { cpu.status.remove(CPUStatus::ZERO); } } pub fn update_neg_flag(cpu: &mut CPU, flag: u8) { if flag & 0b1000_0000 != 0 { cpu.status.insert(CPUStatus::NEGATIVE); } else { cpu.status.remove(CPUStatus::NEGATIVE); } } p...
Rust
0
trace(&self, witness: &Witness) -> TraceTable { let mut trace = TraceTable::new(TRACE_LENGTH, TRACE_WIDTH); // compute g^H(m) * Q let hm = U256::from(&self.hash); scalar_mult(&mut trace, &GENERATOR, &hm, 0, 0, false); let g_hm_q_x = trace[(255, 3)].clone(); let g_hm_q_y...
Rust
0
if _ssCount is None: _ssCount = [ 0 ] # Setting this to a mutable list so that the callers can read the changed value. TODO improve this comment commandList = _tokenizeCommandStr(commandStr) # Carry out each command. originalPAUSE = PAUSE _runCommandList(commandList, _ssCo...
Python
1
Options::new() .create(false) .write(true) .read(true) .open("_test/data_test_1.pico") .unwrap(); let mut pico = Pico::open(file).unwrap(); let mut data = [0u8; 20]; assert_eq!(pico.get(0, &mut data).unwr...
Rust
0
from __future__ import annotations from collections.abc import Callable from typing import Any from plain.packages import packages_registry from plain.runtime import settings from plain.utils.functional import LazyObject from plain.utils.module_loading import import_string from .environments import DefaultEnvironmen...
Python
1
pub fn feed<T>( feeder: &dyn BusFeeder, format: SerializationFormat, data: T) where T: Serialize, { Self::feed_bytes_or_error(feeder, super::encode_response(format, &data)); } pub fn feed_or_error<T>( feeder: &dyn BusFeeder, format: Serializ...
Rust
0
E user_id=? AND coin_id=? ORDER BY created ASC", (self.id, coin_id.unwrap()), )? }; let mut states: Vec<UserCoin> = vec![]; for row in ret { match row { Ok(row) => { let (id, coin_id, amount, created): (i64, String, f64...
Rust
0
stringify!(dwBitCount_CmpSize) ) ); assert_eq!( unsafe { &(*(::std::ptr::null::<_TMPQBetTable>())).dwBitCount_FlagIndex as *const _ as usize }, 60usize, concat!( "Offset of field: ", stringify!(_TMPQBetTable), "...
Rust
0
self.log( "Restricted step satisfies trust radius of " f"{self.trust_radius:.6f}" ) self.log( f"Micro-cycles converged in cycle {mu:02d} with " f"alpha={alpha:.6f}!" ) ...
Python
1
""" test_provider_9.py Simple test script for Provider 9 (Azure OpenAI) chat completions via the local API endpoint. """ import os from openai import OpenAI from dotenv import load_dotenv import sys import logging # Configure logging logging.basicConfig(level=logging.INFO) log = logging.getLogger(__name__) # Get th...
Python
1
page text content") with patch.object(browser, "_ensure_page_async", return_value=mock_page): return await browser._runner.submit.call_args[0][0]() mock_runner.submit.return_value = "Name: John Smith\nML Engineer with 5 years at Google" # Act result = browser.read_...
Python
1
opcodes.set_opcodes(op_names, ops_by_name, disabled_ops) def get_script_engine_class(): return stack.get_script_engine() def set_script_engine_class(cls): return stack.set_script_engine(cls) def set_to_preset(name): """Reset chainparams to the preset name.""" global active_preset # Will throw an...
Python
1
name="📝 Comandos Principais", value=( "`/castigo` - Informações completas do sistema\n" "`/abrir_castigo` - Inicia um novo castigo\n" "`/cancelar_castigo` - Cancela a criação" ), inline=False ) embed.add_field( name="⚙️ Comandos de Admin",...
Python
1
> { syslog::init_with_tags(&["bt-mgr"]).expect("Can't init logger"); fx_log_info!("Starting bt-mgr..."); let mut executor = fasync::Executor::new().context("Error creating executor")?; let launcher = Launcher::new() .context("Failed to open launcher service") .unwrap(); let btgap = ...
Rust
0
rs.pet_target_id and (global_vars.pet_bahavior == PetBehavior.Guard or global_vars.pet_bahavior == PetBehavior.Fight): GLOBAL_CACHE.Party.Pets.SetPetBehavior(PetBehavior.Fight, global_vars.owner_target_id) #ActionQueueManager().AddAction("ACTION", Party.Pets.SetPetBehavior, PetBehavior.Fight, global_var...
Python
1
import pytest import numpy as np from pathlib import Path from skplay import feats, onehot, bag_of_words, minhash import pandas as pd import polars as pl from sklearn.pipeline import make_pipeline from sklearn.linear_model import LogisticRegression from sklearn.model_selection import GridSearchCV titanic_path = Path(_...
Python
1
: SW_PAD_CTL_PAD_GPIO_AD_B0_15, #[doc = "0x2ec - SW_PAD_CTL_PAD_GPIO_AD_B1_00 SW PAD Control Register"] pub sw_pad_ctl_pad_gpio_ad_b1_00: SW_PAD_CTL_PAD_GPIO_AD_B1_00, #[doc = "0x2f0 - SW_PAD_CTL_PAD_GPIO_AD_B1_01 SW PAD Control Register"] pub sw_pad_ctl_pad_gpio_ad_b1_01: SW_PAD_CTL_PAD_GPIO_AD_B1_01, ...
Rust
0
>(), 1usize, concat!("Alignment of ", stringify!(CGameID__bindgen_ty_1)) ); assert_eq!( unsafe { &(*(::std::ptr::null::<CGameID__bindgen_ty_1>())).m_ulGameID as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(CGameID__bindgen_ty_1), "::", stringify!(m_ulGameID) ) );...
Rust
0
isionW(pchhostname: super::super::Foundation::PWSTR, dwdecision: u32) -> super::super::Foundation::BOOL; #[doc = "*Required features: 'Win32_Networking_WinInet'*"] pub fn InternetSetStatusCallback(hinternet: *const ::core::ffi::c_void, lpfninternetcallback: LPINTERNET_STATUS_CALLBACK) -> LPINTERNET_STATUS_CALLB...
Rust
0
# Exploit Title: Hikvision IP Camera versions 5.2.0 - 5.3.9 (Builds: 140721 - 170109) Backdoor # Date: 15-03-2018 # Vendor Homepage: http://www.hikvision.com/en/ # Exploit Author: Matamorphosis # Category: Web Apps # Description: Exploits a backdoor in Hikvision camera firmware versions 5.2.0 - 5.3.9 (Builds: 140721 - ...
Python
1
raiVars) { let set = |sys: &mut Puzzle, var, val| { if val != 0 { sys.set_value(var, val) } }; let mut sys = Puzzle::new(); let tl = make_sudoku(&mut sys); let tr = make_sudoku(&mut sys); let bl = make_sudoku(&mut sys); let br = make_sudoku(&mut sys); let mid...
Rust
0
pi/libraries/{id}/permissions", summary="Gets the current or available permissions of a particular library.", ) def get_permissions( self, id: LibraryIdPathParam, trans: ProvidesUserContext = DependsOnTrans, scope: Optional[LibraryPermissionScope] = Query( Non...
Python
1
able to immediately pick the event up // ring the doorbell to let it know the event state has changed and needs attention if self.armed() != 0 { ring_vc_doorbell(); } } } impl<T> fmt::Debug for EventAccessor<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { ...
Rust
0
if self.type and self.source_ip: self.config_nets_export_src_addr() if self.type and self.host_ip and self.host_port: self.config_nets_export_host_addr() if self.type == 'vxlan' and self.version == '9': self.config_nets_export_vxlan_ver() if self.type...
Python
1
ten < max_f { pow_ten = (10.0).powf(n); n += 1.0 } let min_string_len = n as usize + 1; // Find out how many pixels there are to actually use // and judge a reasonable precision from this. let mut n = 1; while 10.po...
Rust
0
on) test_session.commit() # Query answered feed (should be ordered by creation date desc) answered_prayers = test_session.exec( select(Prayer) .join(PrayerAttribute, Prayer.id == PrayerAttribute.prayer_id) .where(Prayer.flagged == False) ....
Python
1
, T102, T021D, T021U, T021C, T111D, T111U, T030T, T030C, T201, T120D, T120U, T120C, T210, T300, } impl TriadType { #[inline(always)] fn from_u8(i: u8) -> TriadType { assert!(i < 16); unsafe { mem::transmute(i) } } } pub type NodeId...
Rust
0
while 1 > 0: x = int(input("Enter No. of sec(s): ")) H = x // 3600 h = x / 3600 m = (h - H)*60 m1 = m // 1 M = int(m1) s = (m - m1) * 60 S = int(s) print("Time(HH:MM:SS):", H, ":", M, ":", S) print("-----------------------------")
Python
1
"""微信公众平台常量说明""" class Encrypt: """加密相关常量""" PadLength = 16 # 微信默认的 Pad 补位长度 class URL: """URL中的参数设置""" class Key: """URL 中的参数key""" Echo = "echostr" # 第一次请求的回显消息键 Encrypted = "encrypt_type" # URL 中用来判断是否加密的参数 TimeStamp = "timestamp" # ...
Python
1
text_candidate_subs = {} for k, v in candidate_subs.items(): if k in converters: text_candidate_subs[k] = converters[k].to_url(v) else: text_candidate_subs[k] = str(v) # WSGI provides deco...
Python
1
index: I) -> *mut TcdDoff { self.tcd_doff_reg().ptr(index.into()) } #[doc="Get the *const pointer for the TCD_DOFF register."] #[inline] pub fn tcd_doff_ptr<I: Into<::bobbin_bits::R16>>(&self, index: I) -> *const TcdDoff { self.tcd_doff_reg().ptr(index.into()) } #[doc="Read the ...
Rust
0
] } PreviewMode::PostPreview(_) => { vec![render_preview_overlay( RawData::kind(), jig_id, module_id, state, )] } }, None => { vec![ ...
Rust
0
h_delete_database(self, get): ''' @name 批量删除数据库 ''' check_parm = self.check_db_parm(get) if not check_parm["status"]: return check_parm error_list = [] success_list = [] import database db_obj = database.database() if get.all =...
Python
1
) .map(|it| it.1)) .unwrap(); let mut item = match item_table[dist.sample(&mut rng)].0 { Item::Heal => { let mut object = Object::new(x, y, '#', colors::FUCHSIA, "antientropic fabric", false); object.item = Some(Item::He...
Rust
0
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
Python
1
} for metric_name, metric_value in metrics.items(): writer.add_scalar(f"plasticity/{metric_name}", metric_value, global_step) writer.add_scalar("losses/td_loss", loss, global_step) writer.add_scalar("losses/q_values", old_val.mean().item(), global_step) ...
Python
1
import pytest from dnnv.properties import * from dnnv.properties.parser.dnnp import DNNPParserError, parse_str def test_Compare_single(): spec_str = "x < 0" phi = parse_str(spec_str) with phi.ctx: assert phi.is_equivalent(Symbol("x") < Constant(0)) spec_str = "x <= 0" phi = parse_str(spe...
Python
1
class Solution: def numWaterBottles(self, numBottles:int, numExchange:int) -> int: res = 0 empty = 0 while numBottles > 0: res += numBottles empty += numBottles numBottles = empty // numExchange empty = empty % numExchange return res
Python
1
rty_key: property for property_key, property in merge_dict.items()} def _mapping_group(self, index_result_tables: list, mapping_result: list): # 第三方不合并mapping if self.scenario_id in [Scenario.ES]: return {"es": mapping_result} mapping_group = defaultdict(list) # 排序rt表 最长...
Python
1
n. Its what-you-see-is-what-you-get. So we're just # -- using maya to constrain the joint to the control mc.parentConstraint( control.ctl, joint_to_drive, maintainOffset=False, ) mc.scaleConstraint( control....
Python
1
location: GLint, count: GLsizei, transpose: GLboolean, value: *const GLfloat); #[no_mangle] fn glUseProgram(program: GLuint); #[no_mangle] fn glVertexAttribPointer(index: GLuint, size: GLint, type_0: GLenum, normalized: GLboolean, stride: GLsizei, ...
Rust
0
velocity_x: v_x, velocity_y: v_y, mass: sp.mass }) } self.particals = new_particals; } } fn build_app(gl: GlGraphics) -> App { let mut app = App { gl, particals: Vec::new() }; let mut i = 0; while i < PARTICLE_COUNT { app.particals.push(Partica...
Rust
0
("setminu", (0, 0)), ("cempty", (0, 0)), ("sigma", (0, 0)), ("MinusPl", (0, 0)), ("RightDoubleBrac", (0, 0)), ("larrsi", (0, 0)), ("subdot;", (10941, 0)), ("empty", (0, 0)), ("longleftar", (0, 0)), ("capa", (0, 0)), ("iexcl", (161, 0)), ...
Rust
0
from bs4 import BeautifulSoup import requests def check_link_status(url, ): results = {} site_indicators = { 'rapidgator.net': {'selector': 'div.text-block.file-descr', 'text': 'Downloading:'}, 'katfile.com': {'selector': 'h2', 'text': '.rar'}, 'turbobit.net': {'selector': 'div.file-he...
Python
1
mut u8, write: &'static Cell<u16>, // NOTE the `read` pointer is maintained in host memory } /// Implementation detail /// # Safety /// None of `Channel` methods are re-entrant safe #[doc(hidden)] pub fn stdout() -> Channel { if in_thread_mode() { unsafe { CHANNELS[0] } } else { // TODO...
Rust
0
"""Django management package for articles app."""
Python
1
.") # Save the results ------------------------------------------------------------------------- # define folder name and save path DATA_FOLDER = os.path.join("precomputed_nlp_interactions", ESTIMATOR_NAME) os.makedirs(DATA_FOLDER, exist_ok=True) # see how many files are alread...
Python
1
Fd, Net(net::AddrParseError), Unix(string::ParseError), UnixFd(ParseIntError), } impl fmt::Display for ParseAddressError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &ParseAddressError::MissingUnixPath => write!(f, "missing unix path"), &ParseAdd...
Rust
0
#!/usr/bin/env python3 import time import math from robot.robot import MockRobot2IN013 # ← bibliothèque matérielle from controller.adapter import RealRobotAdapter from controller.StrategyAsync import PolygonStrategy def run_cli(): # 1) Création de l’objet matériel gpg3 = MockRobot2IN013() ...
Python
1
skip_datasets", fallback=[] ) ] id_token = get_id_token() with ProcessingPool(parallelism) as pool: pool.map( partial( write_view_if_not_exists, target_project, Path(output_dir), id_token ), schemas, ) pool.map( ...
Python
1
import random; def guess(para1,para2): random_number = random.randint(para1, para2) guess = 0 while guess != random_number: guess = int(input(f'Guess a number between {para1} and {para2}: ')) print(guess) if guess < random_number: print('Guess again. Too low.') ...
Python
1
() <= Self::bound()).then(move || self) } // Clears the map, removing all elements. pub fn clear(&mut self) { self.0.clear() } /// Return a mutable reference to the value corresponding to the key. /// /// The key may be any borrowed form of the map's key type, but the ordering on the borrowed /// form _must...
Rust
0
, Bi>>>, { type Quotient = PrivateDivQuot<N, D, SetBitOut<Q, UInt<Ui, Bi>, B1>, Diff<R, D>, Sub1<UInt<Ui, Bi>>>; type Remainder = PrivateDivRem<N, D, SetBitOut<Q, UInt<Ui, Bi>, B1>, Diff<R, D>, Sub1<UInt<Ui, Bi>>>; #[inline] fn private_div_if_quotient( self, n: N, ...
Rust
0
) } fn build_dispatch_correct_pc(emit: &mut Emit, vr: &VMRegs, opts: &Opts) { build_dispatch_with_pc_offset(emit, vr, opts, 0) } pub fn main(n: u8) { use self::Instr::*; use self::Op::*; let mut opts = Opts::new(); if env::var("NO_DUP_BR_TAILS").is_ok() { opts.duplicate_branch_op_tails =...
Rust
0
ight); } /// Retrieve this instance as a reference to Any. This is used for downcasting. fn as_any(&self) -> &dyn Any { self } /// Retrieve this instance as a mutable reference to Any. This is used for downcasting. fn as_mut_any(&mut self) -> &mut dyn Any { self } } /// Sh...
Rust
0
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import CustomUser, SpamEmail class CustomUserAdmin(UserAdmin): model = CustomUser list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff', 'is_active') list_filter = ('is_staff', 'is_active') ...
Python
1
tatic ref IMAGE_QUALITIES: Arc<Mutex<HashMap<i32, i32>>> = Default::default(); static ref FRAME_FETCHED_NOTIFIER: (UnboundedSender<(i32, Option<Instant>)>, Arc<TokioMutex<UnboundedReceiver<(i32, Option<Instant>)>>>) = { let (tx, rx) = unbounded_channel(); (tx, Arc::new(TokioMutex::new(rx))) }; }...
Rust
0
E_NICS.try() } /// How many ReceiveBuffers are preallocated for this driver to use. const RX_BUFFER_POOL_SIZE: usize = IXGBE_NUM_RX_QUEUES_ENABLED as usize * IXGBE_MAX_RX_DESC as usize * 2; lazy_static! { /// The pool of pre-allocated receive buffers that are used by the IXGBE NIC /// and temporarily given ...
Rust
0
let blob_len = blob.len(); let start = if start < 0 { start .checked_abs() .map_or(0, |n| blob_len - (n as usize).min(blob_len)) } else if start as usize >= blob_len { return mem::take(blob); } else { start as usize }; ...
Rust
0
StringArray, String, min_string) } DataValueAggregateOperator::Max => { typed_array_min_max_string_to_data_value!(value, StringArray, String, max_string) } DataValueAggregateOperator::Count => DataValue::UInt64(Some(value.len() as u64)), _ => ...
Rust
0
let biny = ((y - self.miny) / self.biny_size) as Integer; if let Some(el) = self.hist2d.get_mut((binx, biny)) { *el += 1; } } } fn add(&self, rhs: &Hist2D) -> Hist2D { Hist2D { hist2d: &self.hist2d + &rhs.hist2d, minx: min(self.min...
Rust
0
nv = T::Real::one() / num_traits::Float::sqrt(r1_hat.square() + beta_new.square()); c_old = c; // store for next iteration s_old = s; // store for next iteration // [ c s ] // [-s c ] c = r1_hat.mul_real(r1_inv); // new cosine s...
Rust
0
n_env = env_bind(Some(env.clone()), p.clone(), args)?; Ok(eval(a.clone(), fn_env)?) } _ => error("attempt to call non-function"), } } pub fn keyword_q(&self) -> bool { match self { Str(s) if s.starts_with("\u{29e}") => true, _ => f...
Rust
0
! { h1 { }}})} p {} ); let (create, change) = dom.diff_lazynodes(left, right); assert_eq!( create.edits, [ CreateElement { root: 1, tag: "div" }, CreateElement { root: 2, tag: "div" ...
Rust
0
""" Métodos Numéricos - Resolução de Equações Solução dos exercícios da Lista 1 """ import numpy as np import matplotlib.pyplot as plt from scipy.optimize import fsolve import math # ============================================================================ # EXERCÍCIO 1: Comparação de funções próximas a zero # ===...
Python
1
from functools import wraps from typing import TYPE_CHECKING, Optional, Union, Type if TYPE_CHECKING: from .types_syntactic import SyntacticType from .types_semantic import SemanticType CastableToSyntactic = Optional[Union[SemanticType, SyntacticType, str, Type]] else: CastableToSyntactic = None # ...
Python
1
3, name='d_geo_concat4') n_concat4 = cropconcat_layer(conv2, n_deconv4, 3, name='n_geo_concat4') d_deconv4_2 = slim.conv2d(d_concat4, root_feature, scope='d_geo_deconv4_2') n_deconv4_2 = slim.conv2d(n_concat4, root_feature, scope='n_geo_deconv4_2') ...
Python
1
c Metadata<'static>) -> Interest { try_lock!(self.inner.read(), else return Interest::sometimes()).register_callsite(metadata) } #[inline] fn enabled(&self, metadata: &Metadata<'_>, ctx: layer::Context<'_, S>) -> bool { try_lock!(self.inner.read(), else return false).enabled(metadata, ctx) ...
Rust
0
import copy from modules import cmd_args if "token-saver-level" in cmd_args.args: token_saver_level = int(cmd_args.args["token-saver-level"]) else: token_saver_level = 3 def save_tokens(messages): global token_saver_level read_file_history = {} write_file_history = {} reversed_messages = co...
Python
1
import numpy as np from allrank.click_models.base import RandomClickModel from tests.click_models import click def test_random_click_model_single(): click_model = RandomClickModel(1) np.random.seed(42) assert click(click_model, [], [1]) == [1] assert click(click_model, [], [1, 2]) == [0, 1] asser...
Python
1
_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> u16 { match *self { SRAMPWDSLPW::NONE => 0, SRAMPWDSLPW::GROUP0 => 1, SRAMPWDSLPW::GROUP1 => 2, SRAMPWDSLPW::GROUP2 => 4, SRAMPWDSLPW::GROUP3 => 8, SRAMPWDSLPW::GROUP4 => 1...
Rust
0
decay=self.decay, momentum=momentum, ) if rand_init_num == 0: # initial (and possibly only) random restart: we only have this set of # adversarial examples for now adv_x[...
Python
1
ict): arg = _copy.copy(arg) else: raise ValueError("""\ The first argument to the plotly.graph_objs.densitymap.colorbar.Tickfont constructor must be a dict or an instance of :class:`plotly.graph_objs.densitymap.colorbar.Tickfont`""") self._skip_invalid = kwargs.pop("skip_invalid...
Python
1
import json def float_to_byte(val, scale = 100): return int(val * scale) & 0xFF def build_match_keys(rule): keys = [] all_features = {"feature_0":None, "feature_1":None, "feature_2":None, "feature_3":None} for feature,op,threshold in rule["conditions"]: all_features[feature] = (op, threshold)...
Python
1
*seat = match seat { SeatFill::Empty => SeatFill::Occupied, SeatFill::Occupied => SeatFill::Empty, _ => panic!("Can't change non-seat!"), }; } } let mut result = 0; for line in input.iter() { result += num_occupied(line); } ...
Rust
0
'ʙ', 'r': 'ʀ', '\\': '\\', '&': '&', 'v': 'ᴠ', '%': '%', '4': '4', '+': '+', 'z': 'ᴢ', '|': '|', 'D': 'ᴅ', '#': '#', 'j': 'ᴊ', 'U': 'ᴜ', 'i': 'ɪ', 'u': 'ᴜ', ',': ',', 'q': 'ǫ', '7': '7', 'e': 'ᴇ', 'd': 'ᴅ', 'y': 'ʏ', 'Y': 'ʏ', ...
Python
1
e); if n >= len { return None; } let start = (len - 1 - n) * self.width; let width = cmp::min(start + self.width, slice.len()); let (rest, out) = unsafe { slice .get_unchecked_mut(.. start + width) .split_at_unchecked_mut_noalias(start) }; self.slice = rest; Some(out) } fn len(&self) ->...
Rust
0
"""Change start/stop state from bool to str Revision ID: b6e332156961 Revises: a6ec4e059470 Create Date: 2019-10-06 13:11:35.264054 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'b6e332156961' down_revision = 'a6ec4e059470' branch_labels = None depends_on = N...
Python
1
} impl Deref for Pbes2HmacAeskwJweDecrypter { type Target = dyn JweDecrypter; fn deref(&self) -> &Self::Target { self } } #[cfg(test)] mod tests { use anyhow::Result; use base64; use serde_json::json; use super::Pbes2HmacAeskwJweAlgorithm; use crate::jwe::enc::aescbc_hmac::A...
Rust
0
Sheet(""" font-size: 18px; background: rgba(255, 255, 255, 0.1); border-radius: 10px; padding: 20px; margin: 10px; border: 2px solid rgba(255, 255, 255, 0.2); """) layout.addWidget(self.result) history_group = QGroupBox("تا...
Python
1
None, }; } } impl<'a> fmt::Display for Value<'a> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.str()) } } fn json_clone_from_ref<'a>(json: &'a Value<'a>) -> Value<'a> { Value { slice: json.json(), owned: String::new(), uescstr...
Rust
0
us = MAX_SUPPORTED_CPUS + 1; let mem = GuestMemory::new(&[(GuestAddress(MPTABLE_START), compute_mp_size(cpus as u8))]) .unwrap(); let result = setup_mptable(&mem, cpus as u8).unwrap_err(); assert_eq!(result, Error::TooManyCpus); } } use std::ops::{Deref, DerefMut}; use serde::{D...
Rust
0
rame[y1 : y2, x1 : x2] def __init__(self, engine, debug=False): self._engine = engine if (engine is not None) and hasattr(engine, 'call_plugins'): self._call_plugins = engine.call_plugins self._call_plugins_later = engine.call_plugins_later else: self._c...
Python
1
truct KERB_PURGE_KDC_PROXY_CACHE_REQUEST { MessageType: KERB_PROTOCOL_MESSAGE_TYPE, Flags: ULONG, LogonId: LUID, }} pub type PKERB_PURGE_KDC_PROXY_CACHE_REQUEST = *mut KERB_PURGE_KDC_PROXY_CACHE_REQUEST; STRUCT! {struct KERB_PURGE_KDC_PROXY_CACHE_RESPONSE { MessageType: KERB_PROTOCOL_MESSAGE_TYPE, C...
Rust
0
#!/usr/bin/python import os import glob from subprocess import call from SimpleCV import * import sys def listFiles(directory): for path, dirs, files in os.walk(directory): for f in files: yield os.path.join(path, f) def magic_examples(self, arg): DIR = os.path.join(LAUNCH_PATH, 'example...
Python
1
records::{NewRecord, RecordGet, RecordHasKey, RecordKey, RecordSet}; mod lists; pub use lists::{ListGet, ListHasKey, ListKey, ListLen, ListSet, NewList}; mod call; pub use call::Call; // TODO: widen/narrow instructions that operate based on a type mod widen; pub use widen::Widen; mod narrow; pub use narrow::Narrow...
Rust
0
import torch import torch.nn as nn import os import torch.nn.functional as F os.environ['KMP_DUPLICATE_LIB_OK']='True' class Classifier(nn.Module): def __init__(self, num_classes=2): super(Classifier, self).__init__() self.conv_cls = nn.Sequential( nn.Conv2d(in_channels=2, out_channels=...
Python
1
k_methods.get(name) return target_attack_method def get_defense_methods(self, name): target_defense_method = self.defense_methods.get(name, default=None, allow_not_exist=True) if target_defense_method is None: self.defense_methods[name] = ComponentDict({}, ...
Python
1
""" # Handle weekdays_for_weekly data separately from the other data because has_changed doesn't work # with CheckboxSelectMultiple widgets and ArrayFields out of the box try: # Have to remove the corresponding field name from self.changed_data self.changed_data.r...
Python
1
rate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [chip_revision](index.html) module"] pub struct CHIP_REVISION_SPEC; impl crate::RegisterSpec for CHIP_REVISION_SPEC { type Ux = u32; } #[do...
Rust
0
ind = err.kind(); assert!( kind == ErrorKind::UnsupportedFileType || kind == ErrorKind::CopyFile, "unexpected ErrorKind {:?}", kind ); // Depending on OS peculiarities, we might detect this at different points, and therefore // return different error kinds, and there may or may n...
Rust
0
shared_release() -> Result<(), Box<dyn Error>> { let mut lib = clipboard(); lib.be_shared(); let root = std::path::PathBuf::from("target/tests/clipboard"); if root.exists() { std::fs::remove_dir_all(&root)? } if !root.exists() { std::fs::create_dir_all(&root)? } let co...
Rust
0
" => "Eqa2nAAhHN0" /// } /// }, /// object!{ /// "kind" => "youtube#searchResult", /// "etag" => "m2yskBQFythfE4irbTIeOgYYfBU/2dIR9BTfr7QphpBuY3hPU-h5u-4", /// "id" => object!{ /// "kind" => "youtube#video", /// "videoId" =>...
Rust
0
# -*- coding: utf-8 -*- # # Copyright 2019 Google LLC. 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 requir...
Python
1
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.manifold import TSNE import pickle FAKE_AUDIO_VOCODER=['melgan', 'parallel_wave_gan', 'waveglow', 'mb_mel_gan', 'fb_mel_gan', 'hifi_gan'] color_map = ['tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple'...
Python
1
alse, True], dtype=np.bool_)) group1 = h5f.create_group('group1') group1.attrs['attr_str'] = 'hello' group1.attrs['attr_int'] = 42 group1.create_dataset('dset_with_nan', data=np.array([1, np.nan, 3], dtype=np.float64)) group1.create_dataset('dset_with_inf', data=np.array([np.inf, 6, -np.inf], dtype...
Python
1