text
string
label_name
string
labels
int64
): # No filter was specified for this number of components. return True environments_per_component = cls._find_environments_per_component(data_row) if environments_per_component is None: return False match_matrix = numpy.zeros((n_components, n_component...
Python
1
h and without byte classes and premultiplied state ids. fn define_aho_corasick_dfa<B, F>( c: &mut Criterion, group_name: &str, bench_name: &str, corpus: &[u8], kind: MatchKind, count: usize, patterns: Vec<B>, find_count: F, ) where B: AsRef<[u8]>, F: 'static + Clone + Fn(&AhoCora...
Rust
0
# Copyright 2021-2025 The PySCF Developers. 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 required by appl...
Python
1
from multiprocessing import Queue, Value from pathlib import Path import gzip from tqdm import tqdm def count_lines(input_file: Path, max_lines_to_read: int): cnt = 0 with gzip.open(input_file, 'rb') as f: for _ in tqdm(f): cnt += 1 if max_lines_to_read > 0 and cnt >= max_lines_...
Python
1
> """ # 添加详情内容 if details: html += f""" <div class="detail-item"> <span class="detail-icon">📝</span> <span class="detail-label...
Python
1
")); } return rows.join("\n"); } } // pub struct SquareIter { // n: u8, // row_iters: Vec<PermIter>, // current_rows: Vec<Vec<u8>>, // done: bool, // } // // impl SquareIter { // pub fn new(n: u8) -> SquareIter { // let mut iter = SquareIter{ // n, // ...
Rust
0
PrimInt}; use typenum::{U1, U2, U3, U4}; use crate::pac::sercom0::RegisterBlock; use super::*; //============================================================================= // serial::Read //============================================================================= /// Implement [`serial::Read`] for [`Rx`] [`...
Rust
0
# -*- coding: utf-8 -*- """ Unit tests for mathics.builtins.arithmetic.Solve """ from test.helper import check_evaluation, session def test_solve(): for str_expr, str_expected, message in ( # Clean the definitions, because # a previous definition of `a` makes # the test to fail. (...
Python
1
crate::kernel::tty::print_debug_message(3, format_args!(concat!($fmt,"\n")))); ($fmt:expr, $($arg:tt)*) => ($crate::kernel::tty::print_debug_message(3, format_args!(concat!($fmt, "\n"),$($arg)*))); } use crate::entrypoints::{execute, instantiate, query}; use crate::mock_querier::mock_dependencies_with_querier; use ...
Rust
0
from rest_framework import routers from .views import * from django.urls import path from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, ) router=routers.DefaultRouter() router.register('users',UserViewset,basename="users") router.register('profiles',ProfileViewset,basename="pr...
Python
1
uri = b"http://twisted.invalid/\r\npath" self.attemptRequestWithMaliciousURI(uri) self.assertRegex(str(cm.exception), "^Invalid URI") def test_pathWithWithUnprintableASCIIRejected(self): """ Issuing a request with a URI whose path contains unprintable ASCII characters fa...
Python
1
8) & 0b1111 { 4 => $expand!(4), 8 => $expand!(8), 9 => $expand!(9), 10 => $expand!(10), 11 => $expand!(11), _ => panic!("Invalid round value"), } }; } // For sae instructions, the only valid values for sae are 4 and 8. // This macro en...
Rust
0
mbers: //! //! ```rust //! let vector_array = [0, 1, 2]; //! ``` //! //! Let's return to the (admittedly debunked) assumption that you're a mathematician. Mathematician //! you may be aware of the fact that vectors are just single-column matrices. Indeed, you can form //! a matrix by just taking a bunch of vectors (I'v...
Rust
0
from information_retriever.filter.word_in_filter import WordInFilter from state.common_state_manager import CommonStateManager import pandas as pd import pytest metadata = pd.read_json("test/information_retriever/filter/50_restaurants_metadata.json", orient='records', lines=True) test_csv = pd.read_csv("test/informat...
Python
1
} #[test] fn multiplication_cancels_compatible() { assert_eq!( crate::rsass( "$number: 1px * 1rad / 1ms / 1Hz;\ \na {\ \n b: inspect($number * 1s);\ \n}\ \n" ) .unwrap(), "a {\ \n b: 1000px*rad/Hz;\ \n}\ ...
Rust
0
u32 = 0b00000001; /// 0b00000010: Error signalled because the semaphore is non-zero and neither chain bit is set pub const NO_CHAIN: u32 = 0b00000010; /// 0b00000011: Error signalled because an error is reported reading/writing the context buffer pub const CONTEXT_ERRO...
Rust
0
le_songs_twirl' nonlocal zcxkcdc2cnm raise None @('', 0.0, d0mr4ziynp6, wc49xzk3kuh) def upq3n54vxfs(dlb_jyypw79=False, xoalvaax5a1=b'', u5yfvp9rh_v: rypjnzhl6_h=0j, ks5xqi6oo68: z9864h3jgw5=0j, t79t3wehgda=False, vw0757synmd=0.0, tfin_22voj_: aqxs2b5xo33=b'', gvk8jjm1obg: ieb8dc5edwz=0, d7s9y_qx0ix='', byx1ukk...
Python
1
H, OVERALL_TOTAL_CRASHES, OVERALL_UNIQUE_CRASHES, OVERALL_CALLS_FUZZED_NUM ], "EXEC" => vec![ EXEC_AVG_SPEED, EXEC_EXEC_ALL, EXEC_GEN, EXEC_MUTATION, EXEC_MINIMIZE, ...
Rust
0
ct) try: if dtype == Decimal: subtype = (None, int(subtype)) else: subtype = ( s.strip("'\" ") for s in subtype.replace("μs", "us").split(",") ) return dtype(*subtype) # type: ignore[operator] except...
Python
1
ption<i32> } #[derive(Debug, Serialize, Deserialize)] pub struct ClaimRequest { pub prover_did: String, pub issuer_did: String, pub schema_key: SchemaKey, pub blinded_ms: BlindedMasterSecret, pub blinded_ms_correctness_proof: BlindedMasterSecretProofCorrectness, pub nonce: Nonce, } impl JsonEn...
Rust
0
#requires lxml, and beautifulsoup4 #To install lxml #Install lxml on Windows: https://pypi.python.org/pypi/lxml/3.3.3 #To install beautifulsoup4 #In Windows, run cmd as admin" #Run "python get-pip.py" script to install pip #Navigate to "PythonPath/Scripts" #Run "pip install beautifulsoup4" import sys import os from ...
Python
1
import time import socket import sys server_name = 'localhost' server_port = 12000 client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) timer = 1 client_socket.settimeout(timer) mir = 0 hbc = 0 successful_responses = 0 rtts = [] while True: hbc += 1 timestamp = time.time() message ...
Python
1
""" Write a python function to find the sum of the per-digit difference between two integers. assert digit_distance_nums(1,2) == 1 """ def digit_distance_nums(num1, num2): """ This function takes two integers as arguments and returns the sum of the per-digit differences between them. """ num1_str = str(...
Python
1
Trainer() # Extract variants from test files variants = trainer.extract_variants_from_test_files() if not variants: print("❌ No variants found in test files!") return # Prepare training data gly_count, cys_count = trainer.prepare_training_data(variants) if gly...
Python
1
pub static ref INDEXES: Integer = Integer::new(); pub static ref FETCHING: Integer = Integer::new(); pub static ref FETCHED: Counter = Counter::new(); pub static ref FAILURES: Counter = Counter::new(); } type Registry = HashMap<ImageId, IndexRef>; #[derive(Clone)] pub struct Index(Arc<Inner>); struct ...
Rust
0
}<gh_stars>1-10 /* * * * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0.0 * * Generated by: https://openapi-generator.tech */ /// #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Seria...
Rust
0
le}") # Analyze the data analyze_duplicates(df) # Now test with Leaf print("\n=== Testing with Leaf ===") print("1. Import test_duplicate_blocks.csv into Leaf") print("2. Use 'Detect Duplicate Blocks' tool") print("3. Select 'group_id' as the group column") print("4. Ignore 'go...
Python
1
ICS_)] unsafe { return V.vector4_u32[2]; } #[cfg(_XM_ARM_NEON_INTRINSICS_)] { unimplemented!() } #[cfg(_XM_SSE4_INTRINSICS_)] unsafe { let V1: __m128i = _mm_castps_si128(V); return (_mm_extract_epi32(V1, 2)) as u32; } #[cfg(all(not(_XM_SSE4_INTRINSI...
Rust
0
"624")] N624, /// Guyana Dollar #[serde(rename = "328")] N328, /// Hong Kong Dollar #[serde(rename = "344")] N344, /// Hryvnia #[serde(rename = "980")] N980, /// Iceland Krona #[serde(rename = "352")] N352, /// Indian Rupee #[serde(rename = "356")] N356, /// Iranian Rial #[serde(rename = "364")] N36...
Rust
0
"); #[cfg(not(target_os = "macos"))] const FUNCTIONS: &str = include_str!("glsl/glyph.glsl"); const MAIN: &str = "output_color = color_from_msdf(); output_id=vec4(0.0,0.0,0.0,0.0);"; impl System { /// Defines a default material of this system. fn material() -> Material { let mut material = Material::n...
Rust
0
3</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>2</td> <td>3</td> </tr> </tbody> </table> "##, r#"────┬────┬───── Col1│Col2│Col3 ────┼────┼───── 1 │2 │3 ────┴────┴───── "#, 15); } #[test] ...
Rust
0
ter_histogram_vec!( "libra_network_inbound_rpc_handler_latency_seconds", "Inbound RPC request application handler latency in seconds", &["role_type", "network_id", "peer_id", "protocol_id"] ) .unwrap() }); pub fn inbound_rpc_handler_latency( network_context: &NetworkContext, pro...
Rust
0
Vec::new(); encode_error(&err, &test_logs(), &mut buf); let mut cursor = Cursor::new(&buf[..]); let (decoded, logs) = decode_error(&mut cursor); assert_eq!(decoded, err); assert_eq!(logs, test_logs()); } } #[test] fn split_window() { use crate::{PaneSize, SplitWindow,...
Rust
0
d'] = 'Apple' # OBJ_PARENTS['BreadSliced'] = 'Bread' # OBJ_PARENTS['LettuceSliced'] = 'Lettuce' # OBJ_PARENTS['PotatoSliced'] = 'Potato' # OBJ_PARENTS['TomatoSliced'] = 'Tomato' # force a different horizon view for objects of (type, location). If the location is None, force this horizon for all # objects of that type....
Python
1
::new("./tests/func_ptr_cast.bc")); assert_eq!(interp.output, vec!["42", "42"]); } #[test] pub fn func_ptr_direct_cast() { let interp = compile_and_run(Path::new("./tests/func_ptr_direct_cast.bc")); assert_eq!(interp.output, vec!["1"]); } #[test] pub fn sext_8to64() { let interp = compile_and_run(Path...
Rust
0
from pytest import approx, fixture from ase import Atoms from ase.build import bulk from ase.calculators.bond_polarizability import BondPolarizability from ase.calculators.emt import EMT from ase.vibrations.placzek import PlaczekStatic, PlaczekStaticPhonons from ase.vibrations.raman import (StaticRamanCalculator, ...
Python
1
sv_columns = list(res[key0].keys()) csv_columns.insert(0, 'sampler') with open(csv_file, 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=csv_columns) writer.writeheader() for sampler in res.keys(): if sampler == 'model': continue data = res[sampler] ...
Python
1
# Copyright 2018 The dm_control Authors. # # 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 agreed to i...
Python
1
:all)] use libc::{self, FILE}; pub const CRFSUITE_VERSION: &'static [u8; 7usize] = b"0.12.2\0"; pub const CRFSUITE_COPYRIGHT: &'static [u8; 39usize] = b"Copyright (c) 2007-2013 <NAME>\0"; /// Type of a float value. pub type floatval_t = f64; pub const CRFSUITE_SUCCESS: _bindgen_ty_1 = 0; pub const CRFSUITEERR_UNKNOW...
Rust
0
# WARNING: Please don't edit this file. It was generated by Python/WinRT v0.9.210202.1 import typing, winrt import enum _ns_module = winrt._import_ns_module("Windows.Devices.Geolocation.Geofencing") try: import winrt.windows.devices.geolocation except: pass try: import winrt.windows.foundation except: ...
Python
1
.withColumn("load", F.col("sog") / F.col("Speed")) # Detect operational phases (Berth, Anchorage, etc.) ais_sample_ports = op_phase_recog(ais_sample_ports, spark) # Merge Anchorage and Berth segments separately ais_sample_ports = merge_stop_segments(ais_sample_ports, reference_phase="Anchorage", protected_phase="Bert...
Python
1
t txns = txn_transfer(&mut account, gens); let result = block_execute(&chain_state, txns, 0); info!("execute result: {:?}", result); } } #[doc = "Reader of register PE1"] pub type R = crate::R<u32, super::PE1>; #[doc = "Writer for register PE1"] pub type W = crate::W<u32, super::PE1>; #[doc = "Regis...
Rust
0
## } }", format!("{:#<10.2?}", outer) ); assert_eq!("A {\n f1: 1.23######,\n f2: Inner {\n f1: 5#########,\n f2: 10########,\n },\n}", format!("{:#<#10.2?}", outer)); } #[test] #[allow(dead_code)] fn custom_fmt() { #[derive(Debug)] struct Inner { f1: u8, f...
Rust
0
INR23 { pub use super::MDIOS_DINR0::DIN; } /// MDIOS input data register pub mod MDIOS_DINR24 { pub use super::MDIOS_DINR0::DIN; } /// MDIOS input data register pub mod MDIOS_DINR25 { pub use super::MDIOS_DINR0::DIN; } /// MDIOS input data register pub mod MDIOS_DINR26 { pub use super::MDIOS_DINR0::D...
Rust
0
organization_uuid=UUID("12345678-1234-1234-1234-123456789abc"), ) .first() ) assert user_org is not None user_org.role = UserRole.OWNER session.commit() # Get organization and ensure it has billing org = session.get(OrganizationTable, UUID("12345678-1234-1234-1234-1234567...
Python
1
#!/usr/bin/env -S\_/bin/sh\_-xc\_"source\_\$(eval\_echo\_\$ILLOGICAL_IMPULSE_VIRTUAL_ENV)/bin/activate&&exec\_python\_-E\_"\$0"\_"\$@"" # From https://github.com/stwa/wayland-idle-inhibitor # License: WTFPL Version 2 import sys from dataclasses import dataclass from signal import SIGINT, SIGTERM, signal from threadin...
Python
1
str`s as the symbol type. /// /// This is obtained directly from the [TryFrom] instance acting on /// a [X86RelocStrSym]. pub type X86RelocStr<'a> = X86Reloc<Option<&'a str>>; /// Errors that can occur converting an [X86Reloc] to a /// [RelData](crate::reloc::RelData). /// /// At present, this can only happen with a ...
Rust
0
fn can_verify_impl_bounds() { parse_test! { parse { impl<A: Unsigned, B: Unsigned> Trait for Struct<A, B> where _: Verify<{ A + B == 3 }>, { } }, expect { impl<A: Unsigned...
Rust
0
""" INF601 - Advanced Programming in Python Sam Boutros Prof. Zeller FHSU - Fall 2022 11/1/2022 https://samsclass.info/124/proj14/VP100.htm """ greet = "Hello, World!" print(greet) print(f"First 3 characters of the string '{greet}': ", greet[0:3]) print(f"Second 3 characters of the string '{greet}': ", greet[3:6]) p...
Python
1
e.com"}, team=self.team, ) for _i in range(2): _create_event( event="$pageview", distinct_id="person1", properties={"$browser": "Chrome", "$country": "US"}, team=self.team, ) _create_event( ...
Python
1
from pathlib import Path JS = Path(__file__).resolve().parents[1] / 'web' / 'static' / 'js' / 'main.js' def test_rename_triggers_reload(): text = JS.read_text(encoding='utf-8') assert 'btn.dataset.current = j.new_name;' in text assert 'await reloadFileList();' in text
Python
1
ALLING, callback=my_callback, bouncetime=500) # check rec_num from file try: directory_data = os.listdir("/home/pi") if vid_rec_num in directory_data: # read file vid_rec_num, make into int() set rec_num equal to it vrn = open(vid_rec_num_fp, 'r') rec_num = int(vrn.readline()) ...
Python
1
rgs = args_parser() setup_logging(args.dataset, args.iid, args.model, args.FV_method) args.device = torch.device('cuda:{}' if torch.cuda.is_available() else 'cpu') # load dataset and split users if args.dataset == 'mnist': trans_mnist = transforms.Compose([transforms.ToTensor(), transforms.Norm...
Python
1
; const HEIGHT: u32 = 200; const COLOR_RANGE: u8 = 64; const ALPHA_CHANNEL: f32 = 1.0; const LOW_COLOR_COMPONENT: f32 = 0.0; const HIGH_COLOR_COMPONENT: f32 = 1.0; fn main() { // Declare internal buffer for calculations. let mut buffer = vec![vec![0; (WIDTH + 2) as usize]; (HEIGHT / 2) as usize]; // Creat...
Rust
0
th::new(&out_dir).join("java_glue.rs"); //ANCHOR: config let swig_gen = flapigen::Generator::new(LanguageConfig::JavaConfig( JavaConfig::new( Path::new("client") .join("src") .join("main") .join("java") .join("com") ...
Rust
0
expected_output = { "instance":{ "default":{ "vrf":{ "green":{ "address_family":{ "vpnv4 unicast":{ "prefixes":{ "192.1.0.40/32":{ "table_ve...
Python
1
none().0, "notify::row-spacing", transmute(notify_row_spacing_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _) } } } unsafe extern "C" fn notify_baseline_row_trampoline<P>(this: *mut ffi::GtkGrid, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer) where P: IsA<Grid> { let...
Rust
0
<= new_version, DiffErr::IncompatibleVersions { base_version, new_version } ); let new_version = if base_version == new_version { new_version + 1 } else { new_version }; let base_value = base_snapshot .0 .as_object() ...
Rust
0
pub fn hrs28(&self) -> HRS28_R { HRS28_R::new(((self.bits >> 28) & 0x01) != 0) } #[doc = "Bit 29 - Hardware Request Status Channel 29"] #[inline(always)] pub fn hrs29(&self) -> HRS29_R { HRS29_R::new(((self.bits >> 29) & 0x01) != 0) } #[doc = "Bit 30 - Hardware Request Status...
Rust
0
nd truth labels with shape (num_classes) """ inputs = input["features"] bs = inputs.shape[0] # Compute pairwise distance, replace by the official when merged dist = paddle.pow(inputs, 2).sum(axis=1, keepdim=True).expand([bs, bs]) dist = dist + dist.t() dist = pad...
Python
1
.mempool.load_txs", start.elapsed()); Ok((txs.into(), reverted_txs.into())) } /// Adds a new transactions batch to the mempool schema. /// Returns id of the inserted batch pub async fn insert_batch( &mut self, txs: &[SignedZkSyncTx], eth_signatures: Vec<TxEthSignature>, ...
Rust
0
requested: self.msg_queue.put("Operation cancelled.") break command = "WR" + format(addr, '04X') + format(255, '02X') + "\n" ser.write(command.encode()) addr += 1 processed_bytes += 1 ...
Python
1
har_is_cjk_ideograph(c: &char) -> bool { // Block ranges sourced from https://en.wikipedia.org/wiki/CJK_Unified_Ideographs#CJK_Unified_Ideographs_blocks matches!(c, // CJK Unified Ideographs '\u{4E00}'..='\u{62FF}' | '\u{6300}'..='\u{77FF}' | '\u{7800}'..='\u{8CFF}' | '\u...
Rust
0
c) if ((c.0).2) .as_id() .map_or(false, |id| id.1 == special_functions::ECHO) => { false } E_::ObjGet(o) if o.as_ref().3 == ast::PropOrMethod::IsProp => true, E_::ClassGet(c) if c.as_ref().2 == ast::PropOrMethod::IsProp => true, ...
Rust
0
from multiprocessing import Process from runpy import run_module import pytest import draco.server.main as server_main @pytest.mark.parametrize( "raw_args,expected_ns", [ ([], server_main.DracoServerArgs(**server_main.__DEFAULT_ARGS__.__dict__)), ( ["--port", "1234"], ...
Python
1
: {'udf.name': 'Owner'}, 'pests': { 'udf.name': 'Pests', 'udf.choices': [ 'Ash dieback (Chalara fraxiniae)', 'Asian longhorn beetle (Anoplophora glabripennis)', 'Bronze birch borer (Agrilus anxius)', 'Emerald ash borer (Agri...
Python
1
s_time: cpu.cpu_times.sys, idle_time: cpu.cpu_times.idle, irq_time: cpu.cpu_times.irq, } } } /// Store the program arguments. Required for getting / setting the process title or the executable /// path. Libuv may take ownership of the memory that argv points to. This function should...
Rust
0
n: i32, ) -> *mut UChar; } extern "C" { pub fn u_austrcpy_63( dst: *mut ::std::os::raw::c_char, src: *const UChar, ) -> *mut ::std::os::raw::c_char; } extern "C" { pub fn u_austrncpy_63( dst: *mut ::std::os::raw::c_char, src: *const UChar, n: i32, ) -...
Rust
0
std::process::exit(1); } if field == version_field { println!("{}\n\nApp ID and Version fields must be different", usage); std::process::exit(1); } } match fetch_csv_list(csv, field, version_field) { ...
Rust
0
anda.healthy, timeout_sec=60, backoff_sec=1, err_msg="The cluster hasn't stabilized", ) self.logger.debug("Creating a topic with redpanda.remote.write set to true") self.rpk.create_topic("test", config={"redpanda.remote.write": "true"}) self.logger.inf...
Python
1
.div_flow, norm_diff_img0), dim=1) # flownets1 flownets1_flow2 = self.flownets_1(concat1)[0] flownets1_flow = self.upsample2(flownets1_flow2 * self.div_flow) # warp img1 to img0 using flownets1; magnitude of diff between img0 and and warped_img1 resampled_img1 = self.resample2(...
Python
1
sult<()> { let target_path = get_node_bin_path(node_path)?; let _ = download_from_s3_and_install_bin( target_path, "sn-node", "sn_node", SN_NODE_EXECUTABLE, if cfg!(target_os = "linux") { Some("x86_64-unknown-linux-musl") } else { None ...
Rust
0
::Microsecond) => self.cast::<Time64MicrosecondType>(), Time64(TimeUnit::Nanosecond) => self.cast::<Time64NanosecondType>(), Duration(TimeUnit::Nanosecond) => self.cast::<DurationNanosecondType>(), Duration(TimeUnit::Microsecond) => self.cast::<DurationMicrosecondType>(), ...
Rust
0
backend\nWill pass --lower to f2py\nSee https://numpy.org/doc/stable/f2py/buildtools/meson.html\n') f2py_flags.append('--lower') run_main(f" {' '.join(f2py_flags)} -m {modulename} {' '.join(sources)}".split()) else: run_main(f" {' '.join(f2py_flags)} {' '.join(pyf_files)}".sp...
Python
1
import json class Monitor: """Monitor class stores the field pixel positions so that which sections in an image must be read from to read each physiological parameter are known """ def __init__(self, field_pos): pos_centres = {} for key, value in field_pos.items(): pos_centres[k...
Python
1
m(std::process::id()); /// cgroup.add_task(pid)?; /// /// cgroup.remove_task(pid)?; /// # Ok(()) /// # } /// ``` fn remove_task(&mut self, pid: impl Into<Pid>) -> Result<()> { self.root_cgroup().add_task(pid) } gen_getter!( cgroup; "cgroup.procs", "a ...
Rust
0
##################################### #### PART 6: EXERCISE REVIEW ####### ##################################### # Time to review all the basic data types we learned! This should be a # relatively straight-forward and quick assignment. ############### ## Problem 1 ## ############### # Given the string: s = 'django'...
Python
1
ba_mem.ports.len()) .filter(|&i| pi & 1 << i as i32 == 1 << i as i32) .filter_map(|i| { let port = unsafe { &mut *hba_mem.ports.as_mut_ptr().add(i) }; let port_type = port.probe(); crate::serial_println!("disk-{}: {:?}", i, port_type); ...
Rust
0
jvalue { fn clone(&self) -> Self { *self } } pub enum _jfieldID {} pub type jfieldID = *mut _jfieldID; pub enum _jmethodID {} pub type jmethodID = *mut _jmethodID; #[derive(Clone, Copy)] #[repr(C)] pub enum jobjectRefType { JNIInvalidRefType = 0, JNILocalRefType = 1, JNIGlobalRefType = 2,...
Rust
0
s in properties[key]] if "widths" in properties: properties["widths"] = [ np.abs(width * step) * xunits for width in properties["widths"] ] if "plateau_sizes" in properties: properties["plateau_sizes"] = [ np.abs(sizes * step) * xunit...
Python
1
e') parser.add_argument('--verbose', '-v', action='store_true', help='Enable verbose logging') parser.add_argument('--supabase-url', default=DEFAULT_SUPABASE_URL, help='Supabase URL for authentication') parser.add_argument('--supabase-key', default=DEFAULT_SUPA...
Python
1
"""Snowflake Query Engine Pack.""" import os from typing import Any, Dict, List from sqlalchemy import create_engine from llama_index import SQLDatabase, ServiceContext from llama_index.llama_pack.base import BaseLlamaPack from llama_index.indices.struct_store.sql_query import NLSQLTableQueryEngine class SnowflakeQu...
Python
1
style = st.selectbox("🖋 Summary Style", ["Normal", "Simplified", "Bullets"]) name = st.text_input("Summary name", value="summary1") if st.button("💾 Save Summary"): summary = text[:1500] + "..." if len(text) > 1500 else text if style == "Simplified": ...
Python
1
# Copyright 2021 Tencent # SPDX-License-Identifier: BSD-3-Clause import torch import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self): super(Model, self).__init__() def forward(self, x): x, indices = F.adaptive_max_pool1d(x, output_size=7, return_indic...
Python
1
# Copyright 2023 Ant Group Co., Ltd. # # 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 agreed to in wri...
Python
1
# GemRB - Infinity Engine Emulator # Copyright (C) 2003 The GemRB Project # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later versi...
Python
1
import random from pathlib import Path import gradio as gr from PIL import Image from src.project_settings.info import PROJECT_DIR as ROOT_DIR # 图像路径 IMAGES_DIR = ROOT_DIR / "datasets" / "polyvore" / "images" ALL_IMAGES = list(IMAGES_DIR.glob("*.jpg")) + list(IMAGES_DIR.glob("*.png")) if not ALL_IMAGES: raise Runt...
Python
1
the stack), likely leaking data the process binary does not want to // share. Therefore, AllowRo cannot be covariant with respect to 'share. // Contravariance would not have this issue, but would still be confusing // and would be unexpected. // // Additionally, this makes AllowRo !Sync, which is p...
Rust
0
cons_arena.list_to_vec(cons).unwrap(); nia_assert_equal( vec![ Value::Integer(1), Value::Integer(2), Value::Integer(3), Value::Symbol(SymbolId::new(0)), ], result_vector, ...
Rust
0
""" @Description: LLM for inference @Author: Henrychur @Time: 2024/08/26 15:59:20 """ import torch from transformers import AutoModelForCausalLM, AutoTokenizer from typing import List, Literal, Sequence, TypedDict Role = Literal["system", "user", "assistant"] class Message(TypedDict): role: Role content: st...
Python
1
import sys def dijkstra(G, nodes, src, d): dist = [sys.maxsize] * nodes dist[src] = 0 SP_Set = [False] * nodes if src == dist: return 0 if (src not in range(nodes + 1)) or (d not in range(nodes + 1)): return -1 else: for cout in range(nodes): min = sys.maxsi...
Python
1
mmand=self.on_delete_script, state=state) state = tk.NORMAL if buildin else tk.DISABLED if buildin: self.listbox_scripts_menu.add_command(label='Edit', command=self.on_edit_share_script, state=state) self.listbox_scripts_menu.add_separator() self.listbox_...
Python
1
of an account to free balance of another //! account. //! - `check_permission`: Check permission to perform burn, mint or update. //! - `ensure_can_withdraw`: Check if the account is able to make a withdrawal of the given amount //! for the given reason. //! //! ### Usage //! //! The following examples show how to use ...
Rust
0
from .._utilities.dataclass_maker import build_model, param, FormatType @build_model class Email: address: str verified: bool email_password_bypassable: bool = param(key_name="canBypassPasswordForEmailUpdated") @build_model(format_type=FormatType.camel_case) class AccountSettingsMetadata: IsAccounts...
Python
1
#!/usr/bin/env python """ file: __init__.py author: adh created_at: 8/21/25 4:35 PM """ # Copyright (c) 2025 Carnegie Mellon University. # NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE # ENGINEERING INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. # CARNEGIE MELLON UNIVERSITY MAKES NO WARRANTIES O...
Python
1
ited_probability(&self, idx: usize) -> f64 { self.visited[idx] } /// Mover directions when looking from south fn mover_probability(walls: [bool; 4]) -> [f64; 4] { match walls { [true, true, true, true] => [0., 0., 0., 0.], [true, true, true, false] => [0., 0., 0., 1....
Rust
0
0; for instr in prog.iter() { instr.exec(&mut registers, input, &mut input_pos); } registers } fn exec(&self, registers: &mut [i64; 4], input: &[u8], input_pos: &mut usize) { match *self { Self::Inp(op1) => { registers[op1] = input[*i...
Rust
0
else: position_ids = reset_position_ids(attention_mask) # explicitly ignore attention_mask for packing_samples attention_mask = None output = self.model(sequences, attention_mask=attention_mask, position_ids=position_ids) output["logits"] = output["logits"]...
Python
1
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # type: ignore from setuptools import find_namespace_packages, setup with open("README.md", "r") as fh: LONG_DESC = fh.read() setup( name="hydra-example-sweeper", version="1.0.0", author="Omry Yadan", author_...
Python
1
#Escribe un programa que muestre cómo transcurre un juego de tenis y quién lo ha ganado. #El programa recibirá una secuencia formada por "P1" (Player 1) o "P2" (Player 2), según quien #gane cada punto del juego #Las puntuaciones de un juego son "Love" (cero), 15, 30, 40, "Deuce" (empate), ventaja. #Ante la secuencia [P...
Python
1