text
string
label_name
string
labels
int64
pmf = pmf[:last_pos] # Set values below toll to zero pmf[pmf < toll] = 0 # Set to zero values to the left of the minimal support m1 = np.min(np.where(pmf1 > 0)) m2 = np.min(np.where(np.atleast_1d(pmf2) > 0)) m = m1 + m2 - 1 if m > 1: pmf[:m - 1] = 0 return pmf / np.sum(pmf) ...
Python
1
}, { "tinh__name": Quảng Bình, "tinh_id": 2, "da_cuu_count": 10 }, ... ] """ ho_dan_da_cuu_by_tinh = ( HoDan.objects.filter(created_time__gt=self.compare_tim...
Python
1
d<'_>; // // Get // assert_eq!(ref_root.get_namespace(Some("xsd")), Some(XSD.to_string())); assert_eq!(ref_root.get_namespace(Some("xslt")), None); assert_eq!(ns_child.get_namespace(Some("xsd")), None); assert_eq!(ns_child.get_namespace(Some("xslt")), Some(XSLT.t...
Rust
0
dark:text-gray-400"><span class="font-medium">{{labels[i]}}</span></dt> <dd class="flex items-center mb-3"> <div class="w-full bg-gray-200 rounded h-2.5 dark:bg-gray-700 mr-2"> <div class="bg-orange-600 h-2.5 rounded dark:bg-orange-500" :style="&apos;wi...
Python
1
let mut index: ProofListIndex<&Fork, Vec<u8>> = ProofListIndex::new(index_name, fork); index.set(idx, value); } _ => { panic!("Attempt to call mutable method with a snapshot"); } } } unsafe extern "C" fn clear(index: *const RawProofListIndex) { let index = &*ind...
Rust
0
opy_from(image, 0, 0).unwrap(); draw_hollow_rect_mut(&mut out, rect, color); out } pub fn draw_hollow_rect_mut<C>(canvas: &mut C, rect: Rect, color: C::Pixel) where C: Canvas, C::Pixel: 'static, { let left = rect.left() as f32; let right = rect.right() as f32; let top = rect.top() as f32; ...
Rust
0
set the source (en_US) """ self.env['res.lang']._activate_lang('fr_FR') env_fr = self.env(context=dict(self.env.context, lang='fr_FR')) record = self.env.ref('test_convert.test_translated_field') # 1. Test xml_import, which is sometimes imported and used directly in addons' code...
Python
1
while let Some(ftest::CaseIteratorRequest::GetNext { responder }) = stream.try_next().await? { const MAX_CASES_PER_PAGE: usize = 50; responder.send(&mut iter.by_ref().take(MAX_CASES_PER_PAGE))?...
Rust
0
uest(#[source] RE), /// /// Errored to parse server response. Parse errors may occur while parsing either successful /// or error responses. /// #[error("Failed to parse server response")] Parse(#[source] serde_json::error::Error, Vec<u8>), /// /// Some other type of error occurred (e.g....
Rust
0
ES> where LaneCount<LANES>: SupportedLaneCount, T: SimdElement, { #[inline] fn as_mut(&mut self) -> &mut [T] { &mut self.0 } } // vector/array conversion impl<T, const LANES: usize> From<[T; LANES]> for Simd<T, LANES> where LaneCount<LANES>: SupportedLaneCount, T: SimdElement, { ...
Rust
0
Unreachable(Box<Expr<'a>>), /// `(lab e1 ... en)` jumps to label `lab` with `e1 ... en` as arguments. /// Here the `VarId` is the target label group, and the `u16` is the index /// in the label group. Jump(VarId, u16, Vec<Expr<'a>>, Option<Box<Expr<'a>>>), /// `(break lab e)` jumps out of the scope containing...
Rust
0
doc)"] pub fn controlledUnitary( qureg: Qureg, controlQubit: ::std::os::raw::c_int, targetQubit: ::std::os::raw::c_int, u: ComplexMatrix2, ); } extern "C" { #[doc = " Apply a general multiple-control single-target unitary, which can include"] #[doc = " a global phase fac...
Rust
0
from_char(cs[6]).unwrap_or(None), t5: NumericTube::from_char(cs[7]).unwrap_or(None), s2: Separator::from_char(cs[8]).unwrap_or(None), t6: NumericTube::from_char(cs[9]).unwrap_or(None), t7: NumericTube::from_char(cs[10]).unwrap_or(None), t8: IN19ATube::from_cha...
Rust
0
f LED pin was moved into the exception handler, just use it if let Some(led) = LED { // Check state variable, keep LED off most of the time and turn it on every 10th tick if *STATE < 10 { // Turn off the LED led.set_low().ok(); // And now increment state variable...
Rust
0
max_temp.is_hidden() assert not gs.min_temp.is_hidden() assert gs.max_temp.label.text() == "The maximum average fluid temperature is 24.82 °C" assert gs.min_temp.label.text() == "The minimum average fluid temperature is -14.93 °C" assert gs.results_ground_temperature.is_hidden() # scenario 6 ma...
Python
1
from flask import Flask def init_app(app: Flask): if app.config.get('API_COMPRESSION_ENABLED'): from flask_compress import Compress app.config['COMPRESS_MIMETYPES'] = [ 'application/json', 'image/svg+xml', 'text/html', ] compress = Compress() ...
Python
1
from enum import Enum class TileType(Enum): """ An enumeration to represent the different types of tiles in the board. """ WALL = (0, 0, 0) PATH = (255, 255, 255) START = (7, 110, 255) END = (254, 33, 33) WALKED = (0, 255, 0) class Tile: """ A class to represent a tile in the...
Python
1
// /// `8086+` /// /// `16/32/64-bit` Mov_rm8_imm8 = 401, /// `XABORT imm8` /// /// `C6 F8 ib` /// /// `RTM` /// /// `16/32/64-bit` Xabort_imm8 = 402, /// `MOV r/m16, imm16` /// /// `o16 C7 /0 iw` /// /// `8086+` /// /// `16/32/64-bit` Mov_rm16_imm16 = 403, /// `MOV r/m32, imm32` /// /// `o32 C7 ...
Rust
0
) => ({ use std::str::FromStr; use std::collections::HashMap; use std::convert::TryInto; use miniscript::descriptor::{Descriptor, DescriptorPublicKey}; let mut keys: HashMap<&'static str, (String, Option<String>, Option<String>)> = HashMap::new(); $( keys =...
Rust
0
}, ..Default::default() } .new_candidate_server_reflexive(None) .await } pub(crate) async fn relay_candidate() -> Result<CandidateBase, Error> { CandidateRelayConfig { base_config: CandidateBaseConfig { network: "udp".to_owned(), address: "0.0.0.0".to_owned(), ...
Rust
0
str = arg.to_string_lossy().to_string(); parse_to_pax(&code, Some(&arg_str), preludes) } else { parse_to_pax(&code, None, preludes) } } } pub fn dump_blocks(blocks: &[Block]) { for (i, block) in blocks.iter().enumerate() { println!(" Block({})", i); fo...
Rust
0
State>::default(); for key in 0..black_box(count) { table.insert(key, key); } b.iter(|| { for key in 1..black_box(count) { assert_eq!(table.get(&key), Some(&key)); } }); }); group.bench_fu...
Rust
0
ibrary_name"] == "Sponsor" assert res["context"] == "context - delete" assert res["expression"] == "expression2" assert res["end_date"] is None assert res["status"] == "Draft" assert res["version"] == "0.1" assert res["change_description"] == "Initial version" assert res["author_username"] =...
Python
1
xc7\x09\xcb\xfa\xb1:mk\xc9\x8cc\xfb\ \xe6\x94\x0f\x7f\xe0\xd5\x5c\xfb\xc6k\xb8\xf7\xfe\x87\xf8\xe1\ \x1d\xf7q\xcbwog\xa5[\x90\xf53Be\xb7\xc3\ \xb8\x08|\x84\x92\xf1P_S\x84jk/J:\xcd\ \xc89V\x16\x85\xe1\xa3k\xafFR9!\x0d\xafx\ \xb4\xbdt\xd1\xbf\xd0*\x8edy\x1d\x22\xd0q\x94\x0b\ \xc1\xa0v\x19J\xe6\xac\x9b\xd4\xbc\xf7mW\xf2\x...
Python
1
cm(ref mut c) => c.encrypt(nonce, plaintext_in_ciphertext_out), CipherVariant::Aes256Gcm(ref mut c) => c.encrypt(nonce, plaintext_in_ciphertext_out), CipherVariant::ChaCha20Poly1305(ref mut c) => c.encrypt(nonce, plaintext_in_ciphertext_out), #[cfg(feature = "v2-extra")] ...
Rust
0
class Fonts: def typewriter(text): style = { 'a': '𝚊', 'b': '𝚋', 'c': '𝚌', 'd': '𝚍', 'e': '𝚎', 'f': '𝚏', 'g': '𝚐', 'h': '𝚑', 'i': '𝚒', 'j': '𝚓', 'k': '𝚔', ...
Python
1
clone())); let mut clients = try_join_all(clients).await?; let time = std::time::Instant::now(); let mut handles = Vec::with_capacity(conns); for client in clients.drain(..) { let request = opt.request.clone(); // number of concurrent stream for single connection let concur = o...
Rust
0
def f(x, y): if x > y: return 0 elif x == y: return 1 else: if x != 30: return f(x + 1, y) + f(x * 2, y) + f(x * 3, y) else: return 0 print(f(10, 60)*f(60, 70)) # --- 40+55
Python
1
// BOB tries to buy Legendary Origin of Shell but not enough funds assert_noop!( PWNftSale::buy_rare_origin_of_shell( Origin::signed(BOB), RarityType::Legendary, RaceType::Cyborg, CareerType::HardwareDruid, ), pallet_balances::Error::<Test>::InsufficientBalance ); // BOB purchases Magic ...
Rust
0
Obj: usize, AEventId: usize); pub fn GroupBox_SetOnEndDock(AObj: usize, AEventId: usize); pub fn GroupBox_SetOnEndDrag(AObj: usize, AEventId: usize); pub fn GroupBox_SetOnEnter(AObj: usize, AEventId: usize); pub fn GroupBox_SetOnExit(AObj: usize, AEventId: usize); pub fn GroupBox_SetOnGetSiteInfo(AObj: usize,...
Rust
0
:read_32be(v)? as i32 as f64), ModbusFormat::I32Le => Ok(ModbusFormat::read_32le(v)? as i32 as f64), ModbusFormat::I32Bs => Ok(ModbusFormat::read_32bs(v)? as i32 as f64), ModbusFormat::I32Ls => Ok(ModbusFormat::read_32ls(v)? as i32 as f64), ModbusFormat::U32Be => Ok(Modbu...
Rust
0
string(&s)), Const::Bool(b) => try!(write!(self.writer, "{}", b)), Const::Nil => try!(write!(self.writer, "nil")), } } } Ok(()) } fn print_var(&mut self, var: &Variable) -> io::Result<()> { match var.value { ...
Rust
0
other super script stuff pass # probaly could use continue else: column_no += 1 superscript_label = tk.Label(main_frame, text="".join(part), font=superscript_font, fg="black", bg="white") superscript_label.grid(row=0, column=c...
Python
1
, 0, -3, -4]); eq(0i8, vec![]); } //#[test] pub fn ints16() { eq(5i16, vec![0, 3, 4]); eq(-5i16, vec![5, 0, -3, -4]); eq(0i16, vec![]); } //#[test] pub fn ints32() { eq(5i32, vec![0, 3, 4]); eq(-5i32, vec![5, 0, -3, -4]); eq(0i32, vec![]); } //#[test] pub fn ints64() { eq(5i64, vec![0...
Rust
0
ol3, col4 = st.columns(4) with col1: clear_accounts = account_summary.get('明确限流', 0) st.metric("明确限流账号", clear_accounts, f"{clear_accounts/total_accounts*100:.1f}%") with col2: suspected_accounts = account_summary.get('疑似限流', 0) st.metric("疑似限流账号", suspected_accounts, f"{suspecte...
Python
1
import cv2 image = cv2.imread('input.png') if image is not None: h , w = image.shape[:2] cv2.circle(image, (w//2, h//2), 200, (255, 0, 255), 1) # image , circle centre , radius , color , thickness cv2.imshow('Image with Circle', image) cv2.waitKey(0) cv2.destroyAllWindows()
Python
1
, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0] ); assert_eq!(onehot.size(), vec![4, 4]) } #[test] fn fallible() { // Try to compare two tensors with incompatible dimensions and check that this returns an // error. let xs = Tensor::of_slice(&[0, 1, 2, 3]); let ys = Tensor::of_slice(&[0, 1, 2, 3, 4]); ...
Rust
0
ok进行下一步,否则发送错误日志到server back_info = parser_log(self.back_log) if back_info['state']: self.message['filename'] = back_info['data'][0] else: self.message['log'] = back_info['data'][0] push_to_queue(self.redis_handle,self.redis_queue,self.message) pr...
Python
1
# coding: UTF-8 import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from sklearn import metrics import time import sys import torch import numpy as np from models import Mynet from tensorboardX import SummaryWriter from utils import My_Dataset,get_time_dif from models import * from Con...
Python
1
import streamlit as st from streamlit_plotly_events import plotly_events from mixedvoices.dashboard.api.client import APIClient from mixedvoices.dashboard.api.endpoints import version_flow_ep from mixedvoices.dashboard.components.sidebar import Sidebar from mixedvoices.dashboard.components.version_selector import rend...
Python
1
logger.warning( "Detected elitism_rate > 0 but 0 elites. " "Try increasing elitism_rate." ) self.individuals = individuals def create_subpopulation_individuals(self): if self.individuals is None: # Select one creator to generate individu...
Python
1
let (client_end, server_end) = Channel::create().unwrap(); let client_end = AsyncChannel::from_channel(client_end).unwrap(); let mut client = UnknownInteractionsClosedProtocolProxy::from_channel(client_end).take_event_stream(); server_end .write( &[ 0x00, 0x...
Rust
0
/odms/metadata/xmls/import", files={"xml_file": ("odm.xml", import_input5, CONTENT_TYPE)}, ) assert_response_status_code(response, 400) res = response.json() assert res["type"] == "BusinessLogicException" assert ( res["message"] == "Provided values for following attributes...
Python
1
# ============================================================================== # Copyright 2024 Intel Corporation # # 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.o...
Python
1
p_sequence) for stop_sequence in self.stop_sequences) return StoppingCriteriaList([StopSequenceCriteria(generate_cfg['stop'], self.tokenizer)]) def _chat_stream( self, messages: List[Message], delta_stream: bool, generate_cfg: dict, ) -> Iterator[List[Message]]: ...
Python
1
::W) writer structure"] impl crate::Writable for UART_MEM_CONF {} #[doc = "UART_MEM_CONF"] pub mod uart_mem_conf; #[doc = "UART_MEM_TX_STATUS\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_me...
Rust
0
import numpy as np import time from tqdm import tqdm import cv2 def shrink(X, tau): return np.sign(X) * np.maximum(np.abs(X) - tau, 0) def ialm(D, image_mask,threshold=1e-7): # 1e-3 """ Performs low-rank and sparse decomposition of the input matrix D using the Inexact Augmented Lagrange Multipl...
Python
1
adir: ImageDataDirectory = read_struct(&mut fd)?; data_dirs.push(datadir); } /* Debug directory is at offset 6, validate we have at least 7 entries */ if data_dirs.len() < 7 { anyhow::bail!("No debug data directory"); } /* Grab the debug table */ let debug_table = data_dirs[6];...
Rust
0
fn xmas() { crate::utils::tests::logging::init(); let record = "v=spf1 ip4:192.168.0.0/24 +ip6:fc00::/7 ?a a/24 a:offsite.example.com/24 ~mx mx/24 mx:mx.example.com/24 -ptr +ptr:mx.example.com exists:%{ir}.%{l1r+-}._spf.%{d} ?include:_spf.example.com redirect=_spf.example.com exp=explain._spf.%{d} ...
Rust
0
[Package("=virtual/ffmpeg-0.10.3:0/53")], ["virtual/ffmpeg-0.10.3"], ), ("virtual/ffmpeg:0/52", [Package("=virtual/ffmpeg-0.10.3:0/53")], []), ( "virtual/ffmpeg:=", [Package("=virtual/ffmpeg-0.10.3:0/53")], ["virtual/f...
Python
1
import sys from PyQt5.QtWidgets import ( QApplication, QCheckBox, QComboBox, QDateEdit, QDateTimeEdit, QDial, QDoubleSpinBox, QFontComboBox, QLabel, QLCDNumber, QLineEdit, QMainWindow, QProgressBar, QPushButton, QRadioButton, QSlider, QSpinBox, QT...
Python
1
- index 3 let param = (4, 2, false).into(); let map_2xi = generate_replica_map_for_topic(&spus, &param, Some(3)); let mut map_2xi_expected = BTreeMap::new(); map_2xi_expected.insert(0, vec![3, 4]); map_2xi_expected.insert(1, vec![4, 0]); map_2xi_expected.insert(2, vec![0...
Rust
0
let key = ContractKey::from((&params, &*data)); WrappedContract { data, params, key } } #[inline] pub fn key(&self) -> &ContractKey { &self.key } #[inline] pub fn code(&self) -> &Arc<ContractCode<'a>> { &self.data } #[inline] pub fn params(&self) -...
Rust
0
0 { 0, 0 } else if nums[i] > 0 { f[i-1] * nums[i], g[i-1] * nums[i] } else if nums[i] < 0 { g[i-1] * nums[i], f[i-1] * nums[i] } */ impl Solution { pub fn max_product(nums: Vec<i32>) -> i32 { let mut max = nums[0]; let mut neg_max = 0; let mut pos_max = 0; for num ...
Rust
0
rcise_from_workout(current_user: Annotated[User, Security(get_current_user)], workout_uuid: UUID, workout_exercise_uuid: UUID, session: Session = Depends(get_db)): workout = session.exec(select(Workout).where(Workout.uuid == workout_uuid).where(Workout.user_id == current_user.id)).first() if not workout: ...
Python
1
f.write_fmt(format_args!("{:?} {:?}", self.key, self.value)) } } #[cfg(test)] mod tests { use crate::unit_test_data::{test_property_in, test_property_out}; #[test] fn test_property_to_string() { assert_eq!(test_property_out().to_string(), test_property_in()) } } extern crate geo; pub fn ge...
Rust
0
import numpy as np def observability_matrix(A, C): """ Compute the observability matrix for a system with matrices A and C. Parameters: - A: System state matrix - C: Output matrix Returns: - Obs: Observability matrix """ n = A.shape[0] Obs = C for _ in range(1, n): ...
Python
1
children, line)?, cats: parse_field(&re_cats, line)?, samoyeds: parse_field(&re_samoyeds, line)?, pomeranians: parse_field(&re_pomeranians, line)?, akitas: parse_field(&re_akitas, line)?, vizslas: parse_field(&re_vizslas, line)?, goldfish: parse_fi...
Rust
0
std::env; /// config! { /// DATABASE_URL < ( /// "postgres://", /// POSTGRES_USERNAME, /// ":", /// POSTGRES_PASSWORD, /// "@", /// POSTGRES_HOST => "localhost:5432", /// "/", /// POSTGRES_DB => "test", /// ), /// } /// /// fn main() { /// env...
Rust
0
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing_extensions import Literal from ..._models import BaseModel __all__ = ["ResponseAudioDoneEvent"] class ResponseAudioDoneEvent(BaseModel): type: Literal["response.audio.done"] """The type of the event. Always `r...
Python
1
import sys from os.path import exists from pathlib import Path from red_gym_env_v2 import RedGymEnv from stream_agent_wrapper import StreamWrapper from stable_baselines3 import PPO from stable_baselines3.common import env_checker from stable_baselines3.common.vec_env import SubprocVecEnv from stable_baselines3.common.u...
Python
1
File::open("verifying_keys/pk_tree_0.bin".to_string())?; let vk_pk_tree = VerifyingKey::deserialize_unchecked(&mut file)?; // Create dummy inputs. let agg_pk_chunks = vec![G2MNT6::rand(rng); 2]; let proof = Proof { a: G1MNT6::rand(rng).into_affine(), b: G2MNT6...
Rust
0
6::new(); hasher.update(&pubkey_jwk_x255); let id_x255 = hasher.finalize(); let id_x255 = base64url::encode_nopad(&id_x255); did["VerificationMethod"][1]["id"] = json!(format!("#{}", id_x255)); let mut hasher = Sha256::new(); hasher.update(&pubkey_base58_ed255); let id_b255 = hasher.finaliz...
Rust
0
et("success"): passed_tests += 1 elif result.get("error"): print(f" Erreur: {result['error']}") print() print(f"🎯 Résultat global: {passed_tests}/{total_tests} tests réussis") print(f"⏱️ Durée totale: {total_duration:.1f} secondes") ...
Python
1
import os import cv2 import numpy as np def single2uint(img): return np.uint8((img.clip(0, 1)*255.).round()) def uint2single(img): return np.float32(img/255.) def child_window(parent): child = parent.copy() for K in range(child.shape[0]): child[K] = (child[K] + 1) / 2 child[0] = np.ce...
Python
1
} } impl<T: ?Sized> MyItertools for T where T: Iterator {} trait MyOrd : PartialOrd + Sized { fn chmax(&mut self, mut rhs: Self) -> bool { if self < &mut rhs { *self = rhs; true } else { false } } fn chmin(&mut self, mut rhs: Self) -> bool { if self > &mut rhs { *self = rhs; true } else { false } } } impl<T: Size...
Rust
0
at" STR_SUBSTR = "str.substr" STR_PREFIXOF = "str.prefixof" STR_SUFFIXOF = "str.suffixof" STR_CONTAINS = "str.contains" STR_INDEXOF = "str.indexof" STR_REPLACE = "str.replace" STR_REPLACE_ALL = "str.replace_all" STR_REPLACE_RE = "str.replace_re" STR_REPLACE_RE_ALL = "str.replace_re_all" RE_COMP = "re.comp" RE_DIFF = "r...
Python
1
DEVSUBTYPE_FLIGHT_SICK => name.push_str(" flight stick"), xinput::XINPUT_DEVSUBTYPE_DANCE_PAD => name.push_str(" dance pad"), xinput::XINPUT_DEVSUBTYPE_GUITAR => name.push_str(" guitar"), xinput::XINPUT_DEVSUBTYPE_DRUM_KIT => name.push_str(" drum"), _ => (), }; ...
Rust
0
at_epoch(relative_epoch) .map_err(|e| ApiError::ServerError(format!("Unable to get all committees: {:?}", e)))? .into_iter() .map(|c| Committee { slot: c.slot, index: c.index, committee: c.committee.to_vec(), }) .collect::<Vec<_>>(); Respo...
Rust
0
Anneal learning rate self.model.updateLearningParams(epoch) # Plot train curves if trainOpt['plotFigs']: plotter.plot() # Terminate if stop: break # Report best train...
Python
1
ligfile = ligfiles[i] qvina_process_multi(ligfile, recfile, qvina_cmd=QVINA_PATH, outfile=None, num_procs=8, score=args.score, ...
Python
1
r, kx_sar, oswGroundRngSize, oswAziSize) for (ind, var_imacs) in enumerate(imacs_names): _ds.loc[0, var_imacs] = imacs[ind] # _________WIND DIR PROJECTION IN RANGE/AZIMUTH _ds.loc[0, 'windir_sar_Ucapt'] = np.cos(np.deg2rad(_ds.loc[0...
Python
1
roccess_add_command(message: Message): await proccess_add(message, message.from_user.id) @router.callback_query(Text(text=['to_add'])) async def proccess_add_button(callback: CallbackQuery): await callback.answer() await proccess_add(callback.message, callback.from_user.id) @router.message(F.text, ~Text...
Python
1
user::public_user::browse_users(&db, query.page.unwrap_or(0), page_limit as u64); let total_count_future = db::user::public_user::total_user_count(db.as_ref()); let (users, total_user_count) = try_join!(browse_future, total_count_future,)?; let pages = (total_user_count / (page_limit as u64) + (t...
Rust
0
mut(&mut self) -> &mut $inner { self.inner.get_mut() } /// Acquires a pinned mutable reference to the underlying reader that this encoder is /// wrapping. /// /// Note that care must be taken to avoid tampering with the state of the reader whi...
Rust
0
hen wakeups have been triggered. #[derive(Default)] struct MockClockInner { tick: Tick, wakeups: Vec<(Tick, oneshot::Sender<()>)>, } impl MockClockInner { fn set_tick(&mut self, tick: Tick) { self.tick = tick; self.wakeup_all(tick); } fn wakeup_all(&mut self, up_to: Tick) { // This finds the position of th...
Rust
0
buf), TcpStreamProj::FastOpen(s) => s.poll_read(cx, buf), } } } impl AsyncWrite for TcpStream { fn poll_write(self: Pin<&mut Self>, cx: &mut task::Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>> { match self.project() { TcpStreamProj::Standard(s) => s.poll_write(cx,...
Rust
0
print("❌ Uso: temp 0.8") continue if user_input.startswith('len '): try: length = int(user_input.split()[1]) print(f"📏 Length: {length}") continu...
Python
1
[], llvm_args: ~[], debuginfo: false, extra_debuginfo: false, lint_opts: ~[], save_temps: false, output_type: link::output_type_exe, addl_lib_search_paths: @mut HashSet::new(), ar: None, linker: None, linker_args: ~[], maybe_sysroot...
Rust
0
caption, tuple): caption, mask = caption else: mask = torch.zeros_like(caption).long() mask[:torch.where(caption == 49407)[0] + 1] = 1 return { 'video': frames, 'text': caption, 'uid': uid, 'mask': ma...
Python
1
# novel_search_command.py import discord from googlesearch import search async def handle_novel_search_command(message, args, command_prefix, send_embed_message): # Function to handle the !novel_search command if len(args) < 1: await send_embed_message(message.channel, "Novel Search", ...
Python
1
64]; let mut salt: [u8; 64] = [0; 64]; let mut md: [u8;136]=[0;136]; for i in 0..hlen { salt[i] = rng.getbyte() } let mask=(0xff as u8)>> (8*emlen-embits); SPhashit(MC_SHA2,sha,&mut h,Some(m)); if emlen<hlen+hlen+2 { return false; } for i in 0..8 { md[i]=0; ...
Rust
0
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.UpdateContactRequest import UpdateContactRequest class AnttechOceanbaseObglobalContactModifyModel(object): def __init__(self): self._update_contact_request = None ...
Python
1
nwrap()); bindings .write_to_file(out_path.join("mjs.rs")) .expect("Couldn't write bindings"); } use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Serialize, Deserialize)] pub enum Op { Get { key: String }, Put { key: String, value: String }, Append { key: String, value: String }, } #...
Rust
0
//aiopen.etri.re.kr:8000/ParaphraseQA" ETRI_API_KEY = settings.ETRI_API_KEY requestJson = { "argument": { "sentence1": ko_answer, "sentence2": input_sentence } } http = PoolManager() para_response = http.request( ...
Python
1
= np.append(human_feature_values, np.zeros(5 - len(human_feature_values))) if len(ai_feature_values) < 5: ai_feature_values = np.append(ai_feature_values, np.zeros(5 - len(ai_feature_values))) # 计算分位数 human_quantiles = np.percentile(human_feature_values, [25, 50, 75]) ai_qua...
Python
1
u8) .collect_vec(); assert_eq!( get_layers(&data, 3, 2), vec![ vec![vec![1, 2, 3], vec![4, 5, 6]], vec![vec![7, 8, 9], vec![0, 1, 2]] ] ) } #[test] fn part_1_valid() { assert_eq!(verify_integrity(), 120...
Rust
0
######################## ### GLOBAL CONSTANTS ### ######################## # Number of alignable graphemes in the CMU Pronouncing Dictionary VOCAB_SIZE = 116002 ARPABET_VOWELS = set(['AA', 'AE', 'AH', 'AO', 'AW', 'AX', 'AXR', 'AY', 'EH', 'ER', 'EY', 'IH', 'IX', 'IY', 'OW', 'OY', 'UH', 'UW', 'UX']) ARPABET_CONSONANTS ...
Python
1
reate_users(&permissions_map); // Act & Assert assert!(api.deploy_draft(not_owner_edit_and_view, "id").await.is_err()); assert!(api.deploy_draft(owner_view, "id").await.is_err()); assert!(api.deploy_draft(owner_edit, "id").await.is_ok()); assert!(api.deploy_draft(owner_edit_and_...
Rust
0
# Update this for the versions # Don't change the forth version number from None VERSION = (3, 7, 0, None)
Python
1
for key in ('targets', 'inside_weights', 'outside_weights'): model.net.SpatialNarrowAs( ['rpn_bbox_' + key + '_wide', 'rpn_bbox_pred'], 'rpn_bbox_' + key ) loss_rpn_cls = model.net.SigmoidCrossEntropyLoss( ['rpn_cls_logits', 'rpn_labels_int32'], 'loss_rpn_cls', ...
Python
1
self.centralWidget().scene.History.Undo() def onEditRedo(self): self.centralWidget().scene.History.Redo() def onEditDelete(self): print('ON FILE NEW CLICKED') def onEditPaste(self): self.centralWidget().ctrl_xcv.paste(self.data) self.centralWidget().scene.History.store...
Python
1
n't fetch certificate der: {}", e))?; chain.push(to_pem("CERTIFICATE", &cert_der)); current_key_id = parent_key_id; } Ok(chain) } // === generate root CA === // fn generate_root_ca(config: &Config, storage: &dyn PickyStorage) -> Result<bool, String> { let name = format!("{} Root CA", co...
Rust
0
Ok(_) => panic!("empty identity is not allowed"), Err(_) => (), }; match key_store.get(&module1_identity, "") { Ok(_) => panic!("empty Key name is not allowed"), Err(_) => (), }; let empty_data = b""; let active_key = key_store.get_active_key().unwrap(); match...
Rust
0
s usize], texture, ); if color != Color::WHITE { draw_command = draw_command.color(color); } draw_buffer.push(draw_command); } pub fn draw_hex_brick_top( map: &HexMap<HexTileData>, draw_buffer: &mut Vec<DrawCommand>, x: f32, y: f32, height: u8, texture: u64, ...
Rust
0
import pytest import torch from unittest import mock from PIL import Image from app.cyclegan_engine import CycleGANEngine from app.architectures.cyclegan_networks import ResnetGenerator # --- Фикстура для конфига --- @pytest.fixture def cyclegan_config(tmp_path): class DummyConfig: DEVICE_PREFERENCE = "...
Python
1
SIGN O..NEWA VOWEL SIGN AU 0x11442..=0x11444, // Mn [3] NEWA SIGN VIRAMA..NEWA SIGN ANUSVARA 0x11445..=0x11445, // Mc NEWA SIGN VISARGA 0x11446..=0x11446, // Mn NEWA SIGN NUKTA 0x11447..=0x1144A, // Lo [4] NEWA SIGN AVAGRAHA..NEWA SIDDHI 0x114...
Rust
0
Mismatch Interrupt //! icm_region1.set_rdm_int(); //! //! // Setup region 2 to monitor memory //! icm_region_desc //! .region2 //! .set_region_address(&message_region2_sha224); //! icm_region_desc.region2.rcfg.reset_region_configuration_to_default(); //! icm_region_desc.region2.rcfg.set_algo(icm_algorithm::SHA...
Rust
0
method to calculate the Exponential Moving Average (EMA). """ return data.ewm(span=window, adjust=False).mean() def calculate_macd(self, data, short_window, long_window): """ Helper method to calculate the Moving Average Convergence Divergence (MACD). """ short_ema ...
Python
1
ting::{Digest, DigestItem, Header} }; use balances; impl_outer_origin! { pub enum Origin for Test {} } // For testing the module, we construct most of a mock runtime. This means // first constructing a configuration type (`Test`) which `impl`s each of the // configuration traits of modules we want to use. #...
Rust
0