text
string
label_name
string
labels
int64
= Literal[ "default", "error", "crash", "transaction", "security", "attachment", "session", "internal", "profile", "profile_chunk", "monitor", "span", "log_item", "trace_metric", ] SessionStatus = Li...
Python
1
match get_opposing_key(&key) { Some(key) => { state.down_keys.remove(&key); }, _ => {}, } state.down_keys.insert(key.clone()); } else { // Sway does not send release events when switching between bindings (only down) // We clear the entire state here t...
Rust
0
0-PROTOCOL-ENFORCEMENT.conf", "id": "920273" } }, "request": { "request_line": "GET /?q=\"><script>alert(1)</script> HTTP/1.1", "headers": { "User-Agent": "curl/7.68.0", "Accept": "*/*", "Host": "localhost:9091" } }, "transaction": { "time": ...
Python
1
## # Each connected-to remote device (a device running an openDAQ server) can have a set of enumeration-type connection # statuses stored in its connection status container. These give end-users the information on the state of the # connection, informing them of connection loss, whether we are reconnecting... # # This ...
Python
1
rue) platform_ids = data.get("platform_ids", []) send_frequency = data.get("send_frequency", 24) print( f"📝 收到订阅请求: email={email}, all_platforms={all_platforms}, platform_ids={platform_ids}, send_frequency={send_frequency}" ) if not email: return jsonif...
Python
1
, 40, 115, 116, 114, 105, 110, 103, 41 ]) ); let n = next(&mut source); assert_eq!(n, PdfObject::String(vec![])); let n = next(&mut source); assert_eq!(n, PdfObject::String(vec![0xa1, 0xb2])); let n = next(&mut source); assert_eq!(n, PdfObject::String(...
Rust
0
""" Pyperclip A cross-platform clipboard module for Python. (only handles plain text for now) By Al Sweigart al@inventwithpython.com BSD License Usage: import pyperclip pyperclip.copy('The text to be copied to the clipboard.') spam = pyperclip.paste() if not pyperclip.copy: print("Copy functionality unav...
Python
1
<reponame>RobWalt/rustgym<filename>leetcode/src/d0/_41_first_missing_positive.rs struct Solution; impl Solution { fn first_missing_positive(mut nums: Vec<i32>) -> i32 { let n = nums.len(); for i in 0..n { loop { let j = nums[i] - 1; if j >= 0 && j < n as...
Rust
0
time.sleep(3) cs_console.print(f" [red]重试开始!继续处理目标 '{target_name}'[/red]") raw_quake_data = query_all_pages(target_name, db_conn) if raw_quake_data is None or raw_quake_data == 'skipped': cs_console.print(f" [red]重试后仍失败,跳过目标 '{target_name}'[...
Python
1
import numpy as np import sympy as sp import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # Constants C = 160e-6 # Capacitance in Farads V0 = 450 # Initial voltage in Volts R = 31.2e3 # Resistance in Ohms mass = 2.50 # Mass of resistor in grams specific_heat = 1.67 # Specific heat in kJ/kg°C ...
Python
1
License. use std::{ collections::{HashMap, HashSet}, path::PathBuf, str::{self, FromStr}, }; use anyhow::Result; use cargo_lock::lockfile::Lockfile; use cargo_lock::SourceId; use cargo_platform::Platform; use itertools::Itertools; use crate::{ context::{ BuildableDependency, BuildableTarget, CrateCont...
Rust
0
E_ANGLE: D2D1_SPOTSPECULAR_PROP = 3u32; #[doc = "*Required features: 'Win32_Graphics_Direct2D'*"] pub const D2D1_SPOTSPECULAR_PROP_SPECULAR_EXPONENT: D2D1_SPOTSPECULAR_PROP = 4u32; #[doc = "*Required features: 'Win32_Graphics_Direct2D'*"] pub const D2D1_SPOTSPECULAR_PROP_SPECULAR_CONSTANT: D2D1_SPOTSPECULAR_PROP = 5u32...
Rust
0
# Created for BADS 2018 # See README.md for details # Python 3 import sys from itu.algs4.fundamentals.queue import Queue from itu.algs4.stdlib import stdio # is this really useful?? try: q = Queue() q.enqueue(1) except AttributeError: print("ERROR - Could not import itu.algs4 queue") sys.exit(1) # Ex...
Python
1
B, then the event generated by Runnable B will have Runnable A's ID in the parent_ids field. The order of the parent IDs is from the root parent to the immediate parent. Only supported as of v2 of the astream events API. v1 will return an empty list. """ class StandardStreamEvent(BaseStreamEven...
Python
1
ine similarity model_similarity = torch.mm(output_net, output_net.transpose(0, 1)) target_similarity = torch.mm(target_net, target_net.transpose(0, 1)) # Scale cosine similarity to 0..1 model_similarity = (model_similarity + 1.0) / 2.0 target_similarity = (target_similarity + 1....
Python
1
配置文件""" with open("./config.yaml", "r", encoding="utf-8") as f: settings = yaml.safe_load(f) app = QApplication(sys.argv) window = UIDisplay(settings) window.display_text( """<p>你好!欢迎访问 <a href="https://www.example.com" target="_blank">示例网站</a>,了解更多信息。</p>""", is_non_user_input=...
Python
1
doesn't discriminate well start with alpha=1.0 and work upwards """ alpha=1.0 run_name = "ml-1m" if file_exists("./logs/" + run_name + "/final_weights.h5"): my_tlrnn.load("./logs/" + run_name + "/final_weights.h5") return my_tlrnn my_tlrnn.train_g...
Python
1
import os from dotenv import load_dotenv load_dotenv() def normalize_db_url(raw: str) -> str: if raw.startswith("postgres://"): return raw.replace("postgres://", "postgresql+psycopg://", 1) if raw.startswith("postgresql://") and not raw.startswith("postgresql+psycopg://"): return raw.replace("...
Python
1
# 传感器平台定义 PLATFORMS = ["sensor"] # 传感器基本配置 SENSOR_NAME = "订阅信息" SENSOR_ICON = "mdi:subscription" DOMAIN = "subscription_monitor" # 平台配置字典,仅支持云洞数据平台 PLATFORMS = { "default": { "name": "云洞", "api_url": "https://yundong.xn--xhq8sm16c5ls.com/api/v1/user/getSubscribe", "login_url": "https://yun...
Python
1
self) -> &'static str { "User Datagram Protocol" } fn dissect(&self, data : &[u8]) -> Result { let source = unsigned::<u16, NetworkEndian>(&data[0..2]); let dest = unsigned::<u16, NetworkEndian>(&data[2..4]); let length = unsigned::<u16, NetworkEndian>(&data[4..6]); let checksum = u...
Rust
0
ial guess solver.setInput(VMIN, "lbx") solver.setInput(VMAX, "ubx") solver.setInput(VINIT, "x0") solver.setInput(NP.concatenate(g_min),"lbg") solver.setInput(NP.concatenate(g_max),"ubg") # Solve the problem solver.solve() # Retrieve the solution v_opt = solver.getOutput("x") u0_opt = [v_opt[actionIdx(0,k)] for k in...
Python
1
//! build-script. //! //! ## Example //! //! Let's create a small crate, `snazzy`, that defines a collection of //! snazzy new items in a protobuf file. //! //! ```bash //! $ cargo new snazzy && cd snazzy //! ``` //! //! First, add `prost-build`, `prost` and its public dependencies to `Cargo.toml` //! (see [crates.io]...
Rust
0
#[derive(Clone, Eq, PartialEq)] pub enum EventType { Click, Hover, } fn read_event<'de, A>( access: &mut A, ty: EventType, ) -> Result<(&'de str, Value), <A as MapAccess<'de>>::Error> where A: MapAccess<'de> { let mut action: Option<&str> = None; let mut value: Option<Value> = None; wh...
Rust
0
lna(0,downcast = 'infer',inplace = True) # 特征 feat = pd.DataFrame() feat['USRID'] = pivot.index feat.index = pivot.index # 每种TCH_TYP的特征 tchtyps = list(set(data['TCH_TYP'].tolist())) for i in tchtyps: for j in pivot.columns.tolist(): if i == j[-1]: feat['US...
Python
1
qubits = [qubits] if not isinstance(qubits, (list, tuple)): raise TypeError(f"qubits requires an int or a list/tuple of ints, but get {type(qubits)}") if not all(isinstance(q, int) for q in qubits): raise TypeError("all elements in qubits must be integers") if not all...
Python
1
#this code divides to floating numbers, while getting an interger as the answer num1=input("put in a floating number: ") num2=input("put in a second floating number: ") divide=float(num1)//float(num2) print(divide)
Python
1
img_h_step = img_width img_d_step = 0 img_pix_num_bytes = 4 img_pix_type = Image.PIXEL_SIGNED elif mode == "F": # 32-bit float greyscale img_depth = 1 img_w_step = 1 img_h_step = img_width img_d_step = 0 img_pix_num_bytes = 4 img_pix_type ...
Python
1
ShareVector { let mut shares = Vec::<Share>::with_capacity(n); for j in 1..=n { let x = Scalar::from(j as u64); let share = Share { i: j as u32, yi: self.evaluate(x) }; shares.push(share); } ShareVector(shares) } } impl Evaluate for Polynomial { ...
Rust
0
throttle)); } } } Err(RecvTimeoutError::Timeout) => trace!("recv timeout"), Err(error) => { error!("Request error {}", error); } } } } Ok(()) } impl Onramp for Log...
Rust
0
files(input: TokenStream) -> TokenStream { if !input.is_empty() { Span::call_site().warning("Input will be ignored").emit(); } css_files_impl::css_files() } /// Allows using an outer variable on [`rustyle!`] macro. /// Only constantly evaluable some expression allowed. /// /// [`rustyle!`]: macro....
Rust
0
from sys import argv from rdkit.Chem import MolFromSmiles, MolToSmiles from pikachu.general import read_smiles, structure_to_smiles, smiles_from_file import timeout_decorator @timeout_decorator.timeout(10) def read_and_write(smiles): pikachu_smiles = structure_to_smiles(read_smiles(smiles)) return pikachu_sm...
Python
1
} #[cfg(test)] mod tests { use super::*; use crate::{core_types::Ballot, msg::*, slot::MockScpSlot, test_utils::*}; use maplit::btreeset; use mc_common::logger::test_with_logger; use std::{iter::FromIterator, sync::Arc}; fn get_node( slot_index: SlotIndex, logger: Logger, )...
Rust
0
OOLEAN => {} tag if tag.is_primitive() && !tag.is_universal() => {} _tag => { debug_log!("deserialize_bool: INVALID (found {})", _tag); return Err(Asn1DerError::InvalidData); } } self.h_next_object()?; visitor.visit_bool(Boolean...
Rust
0
-> *mut pdf_obj { let mut id: u32 = 0_u32; let mut gen: u16 = 0_u16; assert!(!pf.is_null()); if !endptr.is_null() { *endptr = start } skip_white(&mut start, end); if start > end.offset(-5) || *(*__ctype_b_loc()).offset(*start as u8 as i32 as isize) as i32 & _ISdi...
Rust
0
ct_all((&mut queries[1..]).iter_mut().map(timeout)).await; assert!(res.is_err()); // Now we complete the query let _ = completion.complete(Ok(())); // And everything should finish let rest = try_join_all((&mut queries[1..]).iter_mut().map(timeout)).await?; for handle in...
Rust
0
weight_count += np.prod(param.size()) return weight_count def _test(): import torch pretrained = False models = [ mnasnet_b1, mnasnet_a1, mnasnet_small, ] for model in models: net = model(pretrained=pretrained) # net.train() net.eval(...
Python
1
ust-clippy/master/index.html> #![allow(clippy::needless_return)] // // Fail build on Clippy warnings #![deny(warnings)] #[macro_use] extern crate lazy_static; use backtrace::Backtrace; use git_version::git_version; use isatty::{stdin_isatty, stdout_isatty}; use line_collector::LineCollector; use std::io::{self, BufRe...
Rust
0
Check if the `epoll_create1` symbol is available on this platform. let ptr = libc::dlsym( libc::RTLD_DEFAULT, "epoll_create1\0".as_ptr() as *const libc::c_char, ); if ptr.is_null() { // If not, use `epoll_create` and manually set `CLO...
Rust
0
def initialize(context): context.symbols = {symbol("TQQQ"):0.50, symbol("TMF"):0.25, symbol("EDZ"):0.25} #TQQQ - 3x performance of the Nasdaq-100 Index® #TMF - 3x performance of the ICE U.S. Treasury 20+ Year Bond Index #EDZ - 3x inverse performance of the MSCI Emerging Markets Index schedule_func...
Python
1
st) >> 8; attacks } pub fn print_knight_attacks() { let mut res = [0u64; 64]; for (square, item) in res.iter_mut().enumerate() { *item = knight_attack(1u64 << square); } println!("{}", arr_to_string(&res, "KNIGHT_ATTACKS")); } pub fn print_ranks() { let mut res = [0u64; 8]; for rank ...
Rust
0
=> &self.inner.high_queue, Priority::Normal => &self.inner.normal_queue, Priority::Low => &self.inner.low_queue, }; queue.queue.push((runnable, self.clone())).unwrap(); unsafe { SubmitThreadpoolWork(queue.work); } } #[cfg(any(feature = "net")...
Rust
0
let c = 150; b.iter(|| { let mut map = IndexMap::with_capacity(c); for x in 0..c { map.insert(x, ()); } map }); } #[bench] fn entry_hashmap_150(b: &mut Bencher) { let c = 150; b.iter(|| { let mut map = HashMap::with_capacity(c); for x in 0..c ...
Rust
0
AppId is `repr(transparent)` of a str unsafe { &mut *(s as *mut str as *mut RefAppId) } } } impl AsRef<str> for RefAppId { fn as_ref(&self) -> &str { &self.0 } } impl AsMut<str> for RefAppId { fn as_mut(&mut self) -> &mut str { &mut self.0 } } impl ToOwned for RefAppId { ...
Rust
0
apper::create_mapper(rom); let mapper = Rc::new(RefCell::new(mapper)); let ppu = Ppu::new(Vram::new(mapper.clone()), Oam::new()); let input = Input::new(); let apu = Apu::new(audio_buffer); let memmap = MemMap::new(ppu, input, mapper, apu); let mut cpu = Cpu::new(memmap); // TODO: Add a fla...
Rust
0
_ss_pad1.hash(state); self.__ss_align.hash(state); self.__ss_pad2.hash(state); } } } } // Non-public helper constant cfg_if! { if #[cfg(all(not(libc_const_size_of), target_pointer_width = "32"))] { const SIZEOF_LONG: usize = 4; } else if #[cfg(all...
Rust
0
. /// If the client wants to cancel the event, `SBProcess::stop` can be /// called and an `eStateExited` process event will be delivered. pub fn new_with_path(path: &str, wait_for: bool, async: bool) -> SBAttachInfo { let p = CString::new(path).unwrap(); SBAttachInfo::wrap(unsafe { ...
Rust
0
================================= # 完整的命题处理管道 # ============================================================================ def process_document_into_propositions(file_path: str, chunk_size: int = 800, chunk_overlap: int = 100, quality_thresho...
Python
1
""" Data module initialization. """
Python
1
partial_signal('bearish', cond, direction=-1) return df # ---------------- Señales combinadas ---------------- def detect_all_patterns(self): df = self.data.copy() pattern_methods = list(self.PATTERN_CANDLE_COUNTS.keys()) for method in pattern_methods: try: ...
Python
1
smithy_json::serialize::JsonObjectWriter, input: &crate::model::GlueDataCatalogConfiguration, ) { if let Some(var_400) = &input.database_arn { object.key("DatabaseARN").string(var_400); } } pub fn serialize_structure_s3_content_base_location( object: &mut smithy_json::serialize::JsonObjectWrit...
Rust
0
-> Option<u16> { match self.port_u16() { Some(port) => Some(port), None => scheme_to_port(self.scheme_str()), } } } // Get port from well-known URL schemes. fn scheme_to_port(scheme: Option<&str>) -> Option<u16> { match scheme { // HTTP Some("http") => S...
Rust
0
)| Into::into(tu)) .map_err(|e| RuntimeError::py_err(format!("{}", e))) } /// glsltcc entry point #[pyfn(m, "main")] pub fn main_py(_py: Python) -> PyResult<()> { use super::cli::*; main(Opts::from_iter(std::env::args().skip(1))) .map_err(|e| RuntimeError::py_err(for...
Rust
0
#!/usr/bin/env python import subprocess from itertools import product _learning = [1e-3, 1e-4, 1e-5] _bk = [10.] _model = [ ('ancient-dream-2393', True, True, False)] _train = ['front back prediction enhance', 'prediction enhance', 'enhance', 'prediction'] i = 0 for prod in product(_learning, _bk, _model, _train)...
Python
1
() self.condition_dim=condition_dim self.linear1=nn.Linear(7,hidden_dim) self.linear2=ModulationLinear(hidden_dim, 1,condition_dim) def forward(self,group_p,new_p,feature): ''' group_p:B,3,N,K new_p:B,N,3 feature:B,C,N group_feature:B,C,N,K ...
Python
1
{ println!("Hi there. This is {} from main thread!", i); thread::sleep(Duration::from_millis(2)); } handle.join().unwrap(); println!("----------------"); let v = vec![1, 2, 3, 4]; // without move, the thread may outlive the borrowed value v. let handle = thread::spawn(move || ...
Rust
0
Runtime>::MustBeEnabled, // ); // assert_eq!( // DexModule::get_target_amounts(&[DNAR, SETUSD], 10000), // Ok(vec![10000, 1659]) // ); // assert_eq!( // DexModule::get_target_amounts(&[DNAR, SETUSD, SERP], 10000), // Ok(vec![10000, 1659, 99397]) // ); // assert_noop!( // DexModule:...
Rust
0
group in groups: print(f" {group_index}. {group['name']} ({group['link']}) - Membri: {group.get('members_count', 'N/A')}") all_groups.append({ "index": group_index, "user": nickname, "group": group }) group_index += 1 ...
Python
1
pub(crate) fn process_internet_protocol_version_4<'lifetime>(&self, now: MonotonicMillisecondTimestamp, packet: impl EthernetIncomingNetworkPacket, layer_3_packet: &'lifetime Layer3Packet, layer_3_length: u16, ethernet_addresses: &'lifetime EthernetAddresses, check_sum_validated_in_hardware: (bool, bool)) { self.i...
Rust
0
std::{ collections::HashSet, fs::File, io::{Read, Write}, path::{Path, PathBuf}, string::ToString, }; use crypto::{ ed25519::*, test_utils::TEST_SEED, x25519::{self, X25519StaticPrivateKey, X25519StaticPublicKey}, }; use logger::LoggerType; use rand::{rngs::StdRng, SeedableRng}; use se...
Rust
0
Loop}; // TODO: remove me fn with_c_str<F, T>(s: &str, f: F) -> T where F: FnOnce(*const libc::c_char) -> T { use std::ffi::CString; let c_str = CString::new(s.as_bytes().to_vec()).unwrap(); f(c_str.as_ptr()) } #[derive(Debug)] enum StateOperation { Remove = 0, // _NET_WM_STATE_REMOVE Add = 1, // ...
Rust
0
ne, self), Condition::Signed => trap_op!(js, self), } } fn emit_set(&mut self, condition: Condition, dst: GPR) { match condition { Condition::Above => dynasm!(self ; seta Rb(dst as u8)), Condition::AboveEqual => dynasm!(self ; setae Rb(dst as u8)), ...
Rust
0
A character (octal 1) is echoed as ^A. Also, the ASCII DELETE character (octal 177) is echoed as ^?. If this flag is not set, the ASCII control characters are echoed as themselves. As with the ECHO flag, this flag affects the echoing of control characters in both canonical and noncanonical modes. // // //Be aware...
Rust
0
import time from selenium.webdriver import Chrome from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By driver_path = "" # TODO: put path to webdriver driver = Chrome(service=Service(driver_path)) driver.maximize_window() driver.implicitly_wait(5) driver.get("https://demo....
Python
1
te points' XYZ values. let src_w_xyz = [src_w.0 / src_w.1, 1.0, (1.0 - src_w.0 - src_w.1) / src_w.1]; let dst_w_xyz = [dst_w.0 / dst_w.1, 1.0, (1.0 - dst_w.0 - dst_w.1) / dst_w.1]; // Compute the white points' ABC values. let src_w_abc = transform_color(src_w_xyz, to_abc); let dst_w_abc = transform...
Rust
0
, {}).get('description', "") or PLUGINS.get(name, {}).get('help', "") print(f" - {name}: {desc}") return if cmd == "term": if not args: error("Komut eksik. Örnek kullanım: term ls -la") return try: result = subprocess.run(args, shell=True) ...
Python
1
\x09\x003E\x11(d\x92p\x0b\x7f\xf0\ @_\xf8 4_\xb0%\xa9\xf8\xd5\xf1\xa8\xc7\xe2\xcf\ \xda;\xc5\x89-\xd4\xd3]\x5c}\xb9|\x1e\xb7\x00\x99\ \xa3\x8ebXM\x7f(v\x17\x17@\x9f\xbc\xf1D\xc5\ \x0c\xb2\xdc~\xa3\xf7\xa2\xb0\xfe%|I\xd0>\x0e\xf8\ \x03X\xf1W\x8a\xb5\x8d?\xc3\xfe\x1c\xf0\xfd\xa4\x97\xda\ \x8e\xa3{0\x86\xde\xce\x08\xc1gwc...
Python
1
/// This is necessary when we want to be able to force a GPU command to run. fn invalidate(&mut self) { self.0 = None; } fn set(&mut self, value: T) { self.0 = Some(value); } /// Check if the cached value is invalid regarding a value. /// /// A non-cached value (i.e. empty) is always invalid wh...
Rust
0
from __future__ import annotations import shap import numpy as np import pandas as pd import torch from .explainer import SHAPExplanation, ensure_data_type_and_reshape from meteors.models import ExplainableModel from typing import Literal AVAILABLE_SHAP_EXPLAINERS = ["exact", "tree", "kernel", "linear"] class Hyp...
Python
1
}, Err(err) => Error::new(Str::new(err.to_string())), }.wrap() } } NativeFn::create(WriteLineFile(path.clone()).wrap()) } fn write(path: &PathBuf) -> Box<dyn Value> { #[derive(Clone, Debug)] struct WriteFile(PathBuf); impl Callable for WriteFile { fn arity(&self) -> usize { 1 } fn call(&mut s...
Rust
0
ier>(deps: &Extern<S, A, Q>, msg: QueryMsg) -> QueryResult { match msg { QueryMsg::MatchDataPoints { data_points } => match_data_point(deps, data_points), QueryMsg::HotSpot { accuracy, zones } => hotspots(deps, accuracy, zones), QueryMsg::TimeRange {} => query_dates(deps), } } pub fn ho...
Rust
0
pe='TensorboardLoggerHook', by_epoch=False) ]) interval = 5000 workflow = [('train', interval)] checkpoint_config = dict( by_epoch=False, interval=interval, save_last=True, max_keep_ckpts=3) # Before 365001th iteration, we do evaluation every 5000 iterations. # After 365000th iteration, we do evaluation every ...
Python
1
.parse::<u32>().unwrap(); let minor = it.next().unwrap().parse::<u32>().unwrap(); if major < 1 || (major == 1 && minor < 2) { println!("cargo:rustc-cfg=pre12"); } } use std::env; use std::ffi::{CString, OsStr, OsString}; use std::fs::File; use std::io::{Error, Result}; use std::iter; use std::marker...
Rust
0
NICE_NOMINATION_MODE_REGULAR, NominationMode::Aggressive => ffi::NICE_NOMINATION_MODE_AGGRESSIVE, NominationMode::__Unknown(value) => value, } } } #[cfg(any(feature = "v0_1_15", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v0_1_15")))] #[doc(hidden)] impl FromGl...
Rust
0
ormat[0].bytes_per_block() as usize; std::thread::spawn(move || { Self::download_thread( start_rx, completed_tx, heightmap_resolution, heightmap_bytes_per_pixel, ) }); Self { streamer: TileStream...
Rust
0
. Use --asm and --bin flags."); } Ok(()) } <gh_stars>0 use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize)] pub struct ServerStatus { #[serde(rename = "description")] pub description: Description, #[serde(rename = "favicon")] #[serde(default)] pub favicon: String, #...
Rust
0
in_image_count + 3; n.min(surface_capabilities.max_image_count).max(n) }; let present_mode = surface .get_present_modes(self)? .iter() .cloned() .find(|&mode| mode == vk::PresentModeKHR::IMMEDIATE) .unwrap_or(vk::PresentModeKHR::FI...
Rust
0
let mut prefix = init.clone(); for s in iter { let mut s = s.chars(); prefix = prefix .chars() .take_while(|c| Some(*c) == s.next()) .collect(); if prefix.is_empty() { break;...
Rust
0
atch [major, minor] { [0x00, 0x38] => Some("Vermeer"), // Ryzen 5XXX [0x00, 0x2E] => Some("Matisse"), // Ryzen 3XXX [0x00, 0x2B] => Some("Pinnacle Ridge"), // Ryzen 2XXX [0x00, 0x19] => Some("Summit Ridge"), // Ryzen 1XXX [0x00, 0x40] => Some(...
Rust
0
arallel(output_layouts=Shard(1)), "ffn_norm": SequenceParallel(), "feed_forward": PrepareModuleInput( input_layouts=(Shard(1),), desired_input_layouts=(Replicate(),), ), "feed_forward.w1": ColwiseParallel(), "feed_forward.w2": RowwiseParallel(output_layout...
Python
1
import json import os import shutil import fire from jinja2 import Template from tqdm import tqdm from src.util.io import read_jsonl, write_jsonl from src.util.openai import openai_batch_completion, OpenAIDecodingArguments def encode_prompt(char, template_path): with open(template_path) as f: template =...
Python
1
pt the SOT if requested if let Some(key) = encryption_key.map(|k| k - 1) { encrypt_mpq_block(&mut buf, key); } writer.seek(SeekFrom::Start(file_start))?; writer.write_all(&buf)?; } // put the writer at the file end, so that we don't overw...
Rust
0
BOOL; #[library(SHCORE)] pub fn GetProcessDpiAwareness( hProcess: HANDLE, value: *mut PROCESS_DPI_AWARENESS, ) -> HRESULT; #[library(SHCORE)] pub fn SetProcessDpiAwareness( value: PROCESS_DPI_AWARENESS ) -> HRESULT; #[library(USER32)] pub fn GetThreadDpiA...
Rust
0
, "açıq ağız və soyuq tərlə gülən üz", "soyuq", "təbəssüm", "tər", "üz", ], }, #[cfg(feature = "be")] crate::Annotation { lang: "be", tts: Some("усміхаецца адкрытым ротам з халодны...
Rust
0
Interface::LAN, SimplePacket { source: IpAndPort::new([1, 2, 3, 4], 53), destination: IpAndPort::new([10, 0, 0, 2], 9779), payload: String::from("10.0.0.1"), }, ), ]; for p in input_packets { match input_sender.send(p.cl...
Rust
0
window.iter_mut().enumerate() { let x_float = T::from(x).unwrap(); *item = a - b * (pi2 * x_float / np_f).cos() + c * (pi4 * x_float / np_f).cos() - d * (pi6 * x_float / np_f).cos(); } window } /// Helper function. Standard Blackman window pub fn blackman<T: Float>(npoints: usize) ...
Rust
0
// buy open logic self.margin_long += margin_value; self.open_price_long = (self.open_price_long * self.volume_long() + price * amount) / (self.volume_long() + amount); self.position_price_long = self.open_price_long; self.vo...
Rust
0
import hashlib import hmac import html import json import typer from fastapi.testclient import TestClient from sweepai.api import app from sweepai.config.server import WEBHOOK_SECRET from sweepai.utils.github_utils import get_github_client, get_installation_id, get_installation def fetch_review_pr_request(issue_url...
Python
1
sample = kde.sample(100, random_state=32).get() nearest = skl_pairwise_distances(sample, X_np, metric=metric) nearest = nearest.min(axis=1) if kernel == "gaussian": from scipy.stats import chi # The euclidean distance of each sample from its cluster # follow...
Python
1
b:1;", true); } #[test] fn deserialize_integer() { assert_deserializes!(i64, b"i:-1;", -1); assert_deserializes!(i64, b"i:0;", 0); assert_deserializes!(i64, b"i:1;", 1); assert_deserializes!(i64, b"i:123;", 123); } #[test] fn deserialize_float() { assert...
Rust
0
unique" spikes to consider (10000) % load predefined principal components (visualization only (Phy): used for features) dd = load('PCspikes2.mat'); % you might want to recompute this from your own data ops.wPCA = dd.Wi(:,1:7); % P...
Python
1
); self.w } } #[doc = "Reader of field `DFLLVAL`"] pub type DFLLVAL_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DFLLVAL`"] pub struct DFLLVAL_W<'a> { w: &'a mut W, } impl<'a> DFLLVAL_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { ...
Rust
0
! أدخل رقم كارت صحيح", } if len(cleaned) != 16 or not cleaned.isdigit(): return { "valid": False, "error": "❌ رقم كارت تيلدا غير صحيح. يجب أن يتكون من 16 رقماً بالضبط", } # Format card number for display (بدون تشفير) formatted...
Python
1
"""Support for executing Docker format containers using Singularity {2,3}.x or Apptainer 1.x.""" import os import os.path import subprocess # nosec from typing import Optional _USERNS: Optional[bool] = None def singularity_supports_userns() -> bool: """Confirm if the version of Singularity install supports the...
Python
1
#!/usr/bin/env python ''' OWASP ZSC https://www.owasp.org/index.php/OWASP_ZSC_Tool_Project https://github.com/zscproject/OWASP-ZSC http://api.z3r0d4y.com/ https://groups.google.com/d/forum/owasp-zsc [ owasp-zsc[at]googlegroups[dot]com ] ''' import binascii import random import string import codecs from core.compatible ...
Python
1
1.conj(); } let mut t3 = t1.clone(); t3.conj(); t2.mul(&t3); t2.mul(&r); r.mul(&t7); t1 = t2.pow(&mut x); if ecp::SIGN_OF_X == SignOfX::NegativeX { t1.conj(); } t3 = t1.clone(); t3.frob(&f, 14); r.mul(&t3); t1 = t1.pow(&mut x); if ecp::SIGN_OF_X == Sig...
Rust
0
def start() : shadows = True; driverType = irr.driverChoiceConsole(); if driverType == irr.EDT_COUNT : return 1; device = irr.createDevice(driverType, irr.dimension2d_u32(640, 480), 16, False, shadows); if device == None : return 1; driver = device.getVideoDriver(); smgr = device.getSceneManager(); mes...
Python
1
e)] struct TraderItemsResponse { #[serde(flatten)] error: ErrorResponse, data: Option<TraderItems>, } #[derive(Debug, Deserialize)] struct TraderItems { items: Vec<Item>, barter_scheme: HashMap<String, Vec<Vec<Price>>>, loyal_level_items: HashMap<String, u8>, } #[derive(Debug, Deserialize)] st...
Rust
0
from flask import session from flask_babel import lazy_gettext as _l from wtforms import PasswordField, SelectField, StringField, TextAreaField from wtforms.fields.html5 import DateField, URLField from CTFd.constants.languages import SELECT_LANGUAGE_LIST from CTFd.forms import BaseForm from CTFd.forms.fields import Su...
Python
1
'#' { left.push(c); continue; } let (is_primary, close_pair) = match iter.next() { Some('[') => (true, ']'), Some('(') => (false, ')'), Some(ch) => { left.push('#'); left.push(ch); continue; ...
Rust
0
# this script adds a target to tcpprobe with 10 seconds # time interval and gets the tcpprobe metrics then shows # them on the console. once you close the script, the # target will be removed from tcpprobe service. # please note, you need to run tcpprobe grpc server # (tcpprobe -grpc) before run this script. # tcpprob...
Python
1