text
string
label_name
string
labels
int64
# Generated by Ollama Llama 3 # Task: inside_op_array_usage_rich # Attempt: 7 # Success: False # Overall Score: 0.518 Here is an example of a Verilog/SystemVerilog to Python transformation module that generates test cases for using arrays in the inside operator: ```python import pyverilog import re from argparse impor...
Python
1
let subscriber = Registry::default() .with(JsonStorageLayer) .with(formatting_layer); tracing::subscriber::with_default(subscriber, action); // Return the formatted output as a string to make assertions against let mut buffer = BUFFER.lock().unwrap(); let output = buffer.to_vec(); ...
Rust
0
AVColorTransferCharacteristic_AVCOL_TRC_IEC61966_2_1: AVColorTransferCharacteristic = 13; #[doc = "< ITU-R BT2020 for 10-bit system"] pub const AVColorTransferCharacteristic_AVCOL_TRC_BT2020_10: AVColorTransferCharacteristic = 14; #[doc = "< ITU-R BT2020 for 12-bit system"] pub const AVColorTransferCharacteristic_AVCO...
Rust
0
##This script takes a JSON file of a paper (wish I knew the name of the format) #and makes it into a txt file, puting a newline each paragraph. #It also creates a 'rebuild_reference.txt' file, necessary at the end of the BioBERT pipeline I created. #This file contains information not given by the BioBERT output but nec...
Python
1
import os from typing import List def collect_test_dirs(test_root: str, test_levels: List[int]) -> List[str]: """Returns a list of test directories. Args: test_root (str): Should be `{LAGRIT_ROOT}/test/` test_levels (List): A list containing one or more of [1, 2, 3] Returns: List...
Python
1
Device, descriptorSet: VkDescriptorSet, descriptorUpdateTemplate: VkDescriptorUpdateTemplate, pData: *const ::std::os::raw::c_void, ); } pub type VkPhysicalDeviceImagelessFramebufferFeaturesKHR = VkPhysicalDeviceImagelessFramebufferFeatures; pub type VkFramebufferAttachmentsCreateInfoKHR...
Rust
0
r Antônio Couto Pereira': game.stadium = 'Couto Pereira' game.save() elif game.stadium == 'Estádio Governador Magalhães Pinto': game.stadium = 'Mineirão' game.save() elif game.stadium == 'Estádio José Pinheiro Borda': game.stadium = 'Beira-Rio' game.save() elif game.stadium == 'Estadio Jornalist...
Python
1
t(self, *sizes: int, repeat: bool = False) -> InlineKeyboardBuilder[ButtonType]: sizes = sizes or (self.max_width,) sizes_iter = cycle(sizes) if repeat else chain(sizes, cycle([sizes[-1]])) markup = [] row = [] for button in self.buttons: if len(row) >= next(sizes_it...
Python
1
import unittest from api import get_alerts, get_alert_detail, get_facilities, get_facility_detail, get_lines, get_line_detail class TestMBTAApi(unittest.TestCase): def test_get_alerts(self): response = get_alerts() self.assertIn("links", response) # Testing if an expected structure exists ...
Python
1
_u64(&mut x3485, &mut x3486, 0x0, x3473, 0xb9feffffffffaaab); let mut x3487: u64 = 0; let mut x3488: fiat_bls381_u1 = 0; fiat_bls381_subborrowx_u64(&mut x3487, &mut x3488, x3486, x3475, 0x1eabfffeb153ffff); let mut x3489: u64 = 0; let mut x3490: fiat_bls381_u1 = 0; fiat_bls381_subborrowx_u64(&mut x3489, &mu...
Rust
0
print("start preprocessing") N_rows = 0 for i, stop_node_pos in enumerate(stop_node_positions): if i%100 == 0: print(" ... {}/{} done! max length {}".format(i, length, max_length)) print(".... -> number rows {}".format(N_rows)) res = routing_engine.return_travel_costs_...
Python
1
mail, password) return jsonify({'success': True, 'message': f'账号 {email} 添加成功'}) except Exception as e: return jsonify({'success': False, 'message': str(e)}) @app.route('/api/config/accounts/remove', methods=['POST']) @require_auth def api_config_accounts_remove(): """删除账号""" try: d...
Python
1
""" * Copyright 2008 Google Inc. * * 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 writing, s...
Python
1
shape: raise ValueError(...) # 安全检查 for t in range(n_samples): recon_spatial[t, boolean_mask] = recon_valid_flat[t] orig_spatial_masked[t, boolean_mask] = orig_valid_flat[t] diff_spatial = np.where(boolean_mask, recon_spatial - orig_spatial_masked, np.nan) ...
Python
1
import argparse from certifi import contents, where parser = argparse.ArgumentParser() parser.add_argument("-c", "--contents", action="store_true") args = parser.parse_args() if args.contents: print(contents()) else: print(where())
Python
1
// Sometimes we may want to bring items into scope with the same name: // use std::fmt; // use std::io; // fn function1() -> fmt::Result {} // fn function2() -> io::Result<()> {} // But if we had used instead: // use std::fmt::Result; // use std::io::Result; // Then we'd have a problem if we were only using `Result`...
Rust
0
) = self.calc_gas_density_and_pressure(elevation)?; let sl = self.sl_max; let sg = 1.0 - sl; let nf = self.nf_0; let rho_s_real = self.rho_s_real_0; nf * sl * rho_l_real + nf * sg * rho_g_real + (1.0 - nf) * rho_s_real }; let delta_z = self.z_m...
Rust
0
{ let math = create( context.gc_context, Some(avm.prototypes().object), Some(avm.prototypes().function), ); assert_eq!( atan2(avm, context, math, &[10.0.into()]).unwrap(), std::f64::consts::FRAC_PI_2.in...
Rust
0
: t1, }), to, })) } _ => { let rhs = Self::parse_binary_rhs(p, &lhs, eager_brace, op, &mut lookahead_tok)?; Self::Binary(Box::new(ast::ExprBinary { attribu...
Rust
0
inputs.clone(), config.name.clone(), config.output.clone(), ); build_flow(&mut window, &mut io_generator, index, config.resolution); if flow_count > 1 { let node = desktop.get_stereo_desktop_node(&window); window.add_node(Box::new(node), index); ...
Rust
0
# Copyright 2019 Uber Technologies, Inc. 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 applica...
Python
1
let Err(e) = _set_device_idx(devs, 0) { panic!(e); } } let err_return = _stream_init(); // give enough time for device to initialize and call callback let sleep_time = time::Duration::from_millis(50); thread::sleep(sleep_time); match err_return { Ok(_) => { ...
Rust
0
er().fold(0, |acc, key| { acc + board .get(key) .map(|s| s.pieces.filtered_indicies(|p| p.colour != colour).len()) .unwrap_or(0) }) } const HUD_LINE: f32 = 0.675; const WARNING_TIMEOUT: u32 = 2500; fn place_card( p: &Platform, state: &mut...
Rust
0
class WordDictionary: class Node: def __init__(self): self.is_word = False self.next = [None for _ in range(26)] def __init__(self): """ Initialize your data structure here. """ self.root = WordDictionary.Node() def addWord(self, word: str) -...
Python
1
ames")] pub keep_fn_names: bool, #[serde(default, alias = "keep_private_props")] pub keep_private_props: bool, #[serde(default, alias = "ie8")] pub ie8: bool, #[serde(default, alias = "safari10")] pub safari10: bool, #[serde(default, alias = "reserved")] pub reserved: Vec<JsWord>...
Rust
0
ocked' : True, 'hidden' : True, }], 'defaults' : { 'read' : False } } self.driver = ElfinderVolumeLocalFileSystem() self.driver.mount(options) self.root = self.driver.decode(self.driver.default_path()) def test...
Python
1
index]; if self.components_index >= array.n as usize { self.arrays_index += 1; self.components_index = 0; if self.arrays_index >= self.arrays.len() { return None; } ...
Rust
0
. //! This file provides a no-std Hasher object that is wired to take seeds from mcrand //! RdRandRng. This hasher is used in `mc_common::HashMap` in and out of the enclave. use core::hash::BuildHasher; use mc_crypto_rand::McRng; use rand_core::RngCore; use siphasher::sip::SipHasher13; #[derive(Clone)] pub struct Ha...
Rust
0
unwrap()); } let bullet_proof = secp.bullet_proof_agg(values.clone(), blinds.clone(), nonce, None, None); println!( "Values:\t\t{:#?}\nBlinds:\t{:#?}\nCommits:\t{:#?}\n\nBullet Proof:\t{:?}", values, blinds, commits, bullet_proof, ); let proof_range = se...
Rust
0
Invalid = 0, /// Method call. This message type may prompt a reply. MethodCall = 1, /// Method reply with returned data. MethodReturn = 2, /// Error reply. If the first argument exists /// and is a string, it is an error message. Error = 3, /// Signal emission. Signal = 4, } /// Maj...
Rust
0
d = D2D1_FIGURE_END_CLOSED, } #[derive(Clone, Copy, PartialEq, Eq, Debug)] #[repr(u32)] pub enum FillMode { Alternate = D2D1_FILL_MODE_ALTERNATE, Winding = D2D1_FILL_MODE_WINDING, } #[derive(Clone, Copy, PartialEq, Eq, Debug)] #[repr(u32)] pub enum Filter { MinMagMipPoint = D2D1_FILTER_MIN_MAG_MIP_POINT, ...
Rust
0
from aiogram import Dispatcher from routers.manage import router as r_manage from routers.teacher_edit import router as r_teacher_edit def create_dispatcher(): dp = Dispatcher() dp.include_router(r_manage) dp.include_router(r_teacher_edit) return dp
Python
1
take().expect("already checked"); if inner.request.parts.transport.reliable() { self.state = State::Terminated; } else { self.state = State::Completed; // TODO can this be handled via tsx-registration instead of spawning a new...
Rust
0
routes![index, submit]) .attach(Template::fairing()) .mount("/", StaticFiles::from(crate_relative!("/static"))) } // Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the A...
Rust
0
fer std and stderr def leave_Call(self, original_node: cst.Call, updated_node: cst.Call) -> cst.Call: # Match the call to asyncio.create_subprocess_exec if m.matches( original_node.func, m.Attribute( value=m.Name("asyncio"), attr=m.Name("create_subprocess_exec") ) ...
Python
1
993322; "###.to_string(); let program = parse(input)?; assert_eq!(3, program.exprs.len()); for expr in program.exprs { if let Ast::Return(ret) = expr { assert_eq!("return", ret.token.literal); } else { panic!("expr {:?} was not ...
Rust
0
ail) } } impl Drop for Reactor { fn drop(&mut self) {} } <gh_stars>10-100 use sorbus::*; #[test] fn works_properly() { let kind0 = Kind(0); let kind1 = Kind(1); let kind2 = Kind(2); let mut builder = green::TreeBuilder::new(); #[rustfmt::skip] let inner = builder .start_node(k...
Rust
0
ethod.name.as_bytes()), params = FmtFuncParams(&method.func, strings), vis = FmtVisibility(method.visibility), )?; print_coeffects(w, &method.coeffects)?; print_func_body(w, &method.func, verbose, strings)?; writeln!(w, "}}")?; writeln!(w) } fn incdec_flag(op: IncDecOp) -> &'static ...
Rust
0
# coding: utf-8 """ Dataddo Headless BETA API Dataddo Headless BETA API The version of the OpenAPI document: 1.0.0-beta.1 Generated by OpenAPI Generator (https://openapi-generator.tech) Do not edit the class manually. """ # noqa: E501 import unittest from openapi_client.models.aws_aurora_use...
Python
1
"""Per-prefix data, mapping each prefix to a dict of locale:name. Auto-generated file, do not edit by hand. """ from ..util import u # Copyright (C) 2011-2024 The Libphonenumber Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Licens...
Python
1
if(schedule = "DirtyCpu")] pub fn resize( #[allow(unused_variables)] env: Env, resource: ResourceArc<Image>, width: u32, height: u32, filter: FilterEnum, ) -> MirageImage { resource.0.resize(width, height, filter.into()).into() } #[rustler::nif(schedule = "DirtyCpu")] pub fn resize_to_fill( ...
Rust
0
Rng::seed_from_u64(seed), None => StdRng::from_entropy(), }; let mut contracts: Vec<(Address, ShardId, ContractArg)> = Vec::with_capacity(opts.contract.len()); let deploy_txs: Vec<(SignedTxRequest, ShardId)> = opts .contract .iter() .enumerate() .map(|(id, &c...
Rust
0
rloaded operator. self.write_operator_name(op)?; } } } Name::NonTemplate(ref name) => { self.w.write_all(name)?; } Name::Template(ref name, ref params) => { self.write_one_name(nam...
Rust
0
# Copyright 2025 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
Python
1
1/4712/bar")); assert!(double_asterisk.is_match("foo/4711/4712/bar?foo=true&bar=false")); assert!(!double_asterisk.is_match("foo/alice/bar/bob")); } #[test] fn can_match_var_routes () { let route_store = &mut Router::<()>::new(); route_store.add_route(Method::GET, "/foo/:userid", middleware! { "hello ...
Rust
0
import pyaudio import wave import pandas as pd # Using laptop microphone to get audio # and check speech recognition audio_path = 'audio/' filename = 'arduino_audio_COM4.wav' CHUNK = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 2 RATE = 44100 time_rec = 1 filepath = audio_path + filename wf = wave.open(filepath, 'wb') ...
Python
1
equence_number(), next: tcp_hdr.sequence_number() + 1, window: tcp_hdr.window_size(), up: false, }, tcp: etherparse::TcpHeader::new(tcp_hdr.destination_port(), tcp_hdr.source_port(), iss, wnd), ip: etherparse::Ipv4Header::new( ...
Rust
0
ORD_NOT_ALLOWED = 1132, /// Can't find any matching row in the user table ER_PASSWORD_NO_MATCH = 1133, /// Rows matched: %ld Changed: %ld Warnings: %ld ER_UPDATE_INF = 1134, /// Can't create a new thread (Errno %d); if you are not out of available memory, you can consult the manual for a possible OS...
Rust
0
"id", "exec count", "time" ); METHODS.with(|m| { let mut v: Vec<_> = m .borrow() .counter .iter() .enumerate() .map(|(id, counter)| (id, counter.clone())) .collect(); v.so...
Rust
0
on::diff`. #[derive(Debug)] pub(crate) struct TopologyDescriptionDiff<'a> { pub(crate) removed_addresses: HashSet<&'a ServerAddress>, pub(crate) added_addresses: HashSet<&'a ServerAddress>, pub(crate) changed_servers: HashMap<&'a ServerAddress, (&'a ServerDescription, &'a ServerDescription)>, } fn ...
Rust
0
uation let help_lit = match attr_it.next().unwrap() { Literal(literal) => literal, _ => panic!("expected literal for command help") }; let section = format!(".shell_cmds.{}", cmd_name); let cmd_name_str = format!("{}", cmd_name); let help_str = help_lit.to_string().trim_matches('"'...
Rust
0
#[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x3f) | ((value as u32) & 0x3f); self.w } } impl R { #[doc = "Bits 18:23 - HPMRAMP3_LTH"] #[inline(always)] pub fn hpmramp3_lth(&self) -> HPMRAMP3_LTH_R { HPMRAMP3_LTH_R::new(...
Rust
0
s[:, leftover[1]], s=50 * normed_z, c="green", label="drone trajectory" ) # scatter trajectory normed_knot_z = (knots[:, fixed_axis] - min_z) / (max_z - min_z) plt.scatter( knots[:, leftover[0]], knots[:, leftover[1]], s=50 * normed_knot_z, c="red"...
Python
1
.read() .avm2_object .map(|o| o.into()) .unwrap_or(Avm2Value::Undefined) } fn as_bitmap(self) -> Option<Bitmap<'gc>> { Some(self) } } /// Static data shared between all instances of a bitmap. #[derive(Clone, Collect)] #[collect(no_drop)] struct BitmapStatic { ...
Rust
0
login_error = { "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "properties": { "loginErrors": { "type": "string" } }, "required": [ "loginErrors" ] } login = { "$schema": "http://json-schema.org/draft-04/schema#", "type": "obj...
Python
1
=> ret.push(N::isize(v as isize)), N::i16(v) => ret.push(N::isize(v as isize)), N::i32(v) => ret.push(N::isize(v as isize)), N::i64(v) => ret.push(N::isize(v as isize)), _ => {} } } ret } #[test] fn test_ordering() { let numbers: Vec<_> = NUMBERS.it...
Rust
0
id: u64, /// The state of the transfer. pub state: String, /// True if the domain auto-renew was requested. pub auto_renew: bool, /// True if the domain WHOIS privacy was requested. pub whois_privacy: bool, /// The reason if transfer failed. pub status_description: Option<String>, //...
Rust
0
import time # Import time module for adding delays in the game loop from turtle import Screen # Import Screen class to set up the game screen from player import Player # Import custom Player class to handle player functionality from car_manager import CarManager # Import custom CarManager class to manage car objec...
Python
1
# Python program to find the factorial of a number provided by the user. def factorial(n): if n < 0: # factorial of number less than 0 is not possible return "Oops!Factorial Not Possible" elif n == 0: # 0! = 1; when n=0 it returns 1 to the function which is calling it previously. return 1 else: re...
Python
1
from __future__ import annotations from narwhals.selectors import ( all, boolean, by_dtype, categorical, datetime, matches, numeric, string, ) __all__ = [ "all", "boolean", "by_dtype", "categorical", "datetime", "matches", "numeric", "string", ]
Python
1
sponse = example['response'] pred_ans = parse_multi_choice_response(response) # print(pred_ans) example_anno = qa_data.loc[vid_idx] video_uid, qid = example_anno["video_uid"], example_anno['qid'] for i in range(len(submission_reference[video_uid]['benchmark_dataset'])): ...
Python
1
jects; pub use self::cached_objects::CachedObjects; pub use self::file_objects::FileObjects; pub use self::git_objects::GitObjects; use crate::checksum::Checksum; use crate::git; use crate::update::Update; use core::errors::{Result, ResultExt as _}; use core::Source; use std::io::Read; use std::path::{Path, PathBuf}; ...
Rust
0
# Python bytecode 2.7 (decompiled from Python 2.7) # Embedded file name: scripts/client/gui/impl/lobby/crew/crew_sounds.py from shared_utils import CONST_CONTAINER from sound_gui_manager import CommonSoundSpaceSettings class SOUNDS(CONST_CONTAINER): COMMON_SOUND_SPACE = 'crew' STATE_PLACE = 'STATE_hangar_place...
Python
1
# Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals from frappe import _ def get_data(): return { 'fieldname': 'course', 'non_standard_fieldnames': { }, 'transactions': [ { 'label': _('Cou...
Python
1
ntId) -> Self::Balance; /// The owner of the given token ID. Returns `None` if the token does not /// exist. fn owner(token: (Self::ClassId, Self::TokenId)) -> Option<AccountId>; /// Transfer the given token ID from one account to another. fn transfer( from: &AccountId, to: &AccountId, token: (Self::ClassI...
Rust
0
# --- Data type examples --- # Integer my_int = 42 print(f"Integer: {my_int} (type: {type(my_int)})") # Float my_float = 3.14159 print(f"Float: {my_float} (type: {type(my_float)})") # String my_string = "Python is Fun!" print(f"String: '{my_string}' (type: {type(my_string)})") # --- String manipulation examples ---...
Python
1
start or end. /// - `"basis-closed"`: a closed B-spline, as in a loop. /// - `"cardinal"`: a Cardinal spline, with control point duplication on the ends. /// - `"cardinal-open"`: an open Cardinal spline; may not intersect the start or end, but /// will intersect other control points. /// - `"cardinal-closed"`: a close...
Rust
0
!task.is_stopped { let mut ptrace_regs: native_user_regs_struct = Default::default(); if task.ptrace_if_alive( PTRACE_GETREGS, RemotePtr::null(), PtraceData::WriteInto(u8_raw_slice_mut(&mut ptrace_regs)), ) { task.registers.set_from_ptrace(&ptrace...
Rust
0
imal}f}" dir_name = f"{gridname}_{value_str}" dst = os.path.join(base_dir, dir_name) shutil.copytree('./mesabasic', dst, dirs_exist_ok=True) grids.append(dst) for i, path in enumerate(grids): filename = os.path.join(path, inlist_name) value = get_value(start, ste...
Python
1
r col in range(grid_cols): x = col * single_image_width y = row * single_image_height grid_positions.append((x, y)) # Run the main display loop, now with the `is_mqtt_configured` status main_display_loop(config, screen, font, grid_positions, target_image_size, is_mqtt_config...
Python
1
try_from(other.0).map_err(|_| ()) } } impl TryFrom<c_slonglong> for i128 { type Error = (); fn try_from(other: c_slonglong) -> Result<Self, ()> { Self::try_from(other.0).map_err(|_| ()) } } impl TryFrom<u32> for c_uint { type Error = (); fn try_from(other: u32) -> Result<Self, ()> { ...
Rust
0
put Serde derives behind a cfg_attr would // need to use some silly feature name that depends on both serde and // serde_derive. // // [features] // serde-impls = ["serde", "serde_derive"] // // [dependencies] // serde = { version = "1.0", optional = true } // serde_derive = { version = "1.0", opti...
Rust
0
generic_asset::Module::<Test>::free_balance(&2, &bob),(14*UNIT)/100); // Full+half queue limit orders for Alice ( Token1 ) and Bob ( Token 2) assert_ok!(DEXModule::submit_order(Origin::signed(alice),BidLimit,trading_pair,10750*UNIT,(14*UNIT)/100)); let orderbook: Orderbook<Test> = <Orderbooks<...
Rust
0
de::from_hex( "c120ff2ae1363593a0b92e0d281ec341a0cc989b4ee836dc3405c9f4215242a6", ) .unwrap(), time: 1634590600, bits: 0x170e0408, nonce: 0xb48e8b0a, }; assert!(is_timestamp_valid(&store, &header)); // Monday, October 1...
Rust
0
|| { // ERROR let _y = x; })(); } #[macro_use] extern crate lazy_static; pub mod constants; pub mod error; pub mod file_handler; pub mod query; pub mod request; pub mod responder; pub mod server; pub mod time; use crate::constants::*; use crate::server::Octane; #[tokio::main] async fn main() { let mu...
Rust
0
#!/usr/bin/env python # -*- coding:utf-8 -*- # # @name: Wascan - Web Application Scanner # @repo: https://github.com/m4ll0k/Wascan # @author: Momo Outaadi (M4ll0k) # @license: See the file 'LICENSE.txt from re import search, I def fingerprint(headers, content): _ = False for header in headers.items()...
Python
1
ric { /// L-1 or Manhattan distance. See [\[Wikipedia\]](https://en.wikipedia.org/wiki/Taxicab_geometry). Manhattan, /// L-2 or Euclidean distance. See [\[Wikipedia\]](https://en.wikipedia.org/wiki/Euclidean_distance) Euclidean, /// L-inf or Chebyshev distance. See [\[Wikipedia\]](https://en.wikiped...
Rust
0
"apple", "banana", "orange" ] } ], "home_address": { "version": "bfc6ed1d49aa9677265232c470fdbc3e", "employee_id": 7757869432666662, "street_1": "73243 Wuckert Prairie", "street_2": "Suite 189", "city": "San Francisco", "state": "CA", "zip": "94107", "...
Rust
0
()).cmp(&Unicode(y.as_ref())), } } } impl<S: FromStr + AsRef<str>> FromStr for UniCase<S> { type Err = <S as FromStr>::Err; fn from_str(s: &str) -> Result<UniCase<S>, Self::Err> { s.parse().map(UniCase::new) } } #[cfg(test)] mod tests { use super::UniCase; use std::hash::{Has...
Rust
0
=> Err(anyhow!(e)), }; let result = match result { Ok(_) => { // Event has been durably persisted. NvDsMsgApiErrorType::NVDS_MSGAPI_OK }, Err(e) => { error!("nvds_msgapi_send: write_event error: {:?}", e); NvDsMsgApiErrorType::NVDS_MSGAPI_ERR ...
Rust
0
))] self.assertAllClose(decimal_examples, rel_tol=1e-8) self.assertAllNotClose(decimal_examples, rel_tol=1e-9) def test_fractions(self): # test with Fraction values from fractions import Fraction # could use some more examples here! fraction_examples = [(Fraction(1,...
Python
1
} a } /// Reverse NTT fn rev_ntt<const N: usize>(p_hat: &Poly3329<N>) -> Poly3329<N> { let mut a = Poly3329::init(); // Zero polynomial's NTT is zero if p_hat.is_zero() { return Poly3329::zero(); } // Unwraps safely since the case None has been tested above let d = p_hat.degree...
Rust
0
ode:X}, errmsg={tmq_err2str(code)}", errno=code ) tmq_assignments = TmqTopicAssignments(assignment, num_of_assignment.value) for tmq_assignment in tmq_assignments: assignments.append( (tmq_assignment.vg_id, tmq_assignment.current_offset, tmq_assignment.begin, tmq_assignment.end) ...
Python
1
t env = self.env; let self_ref = Box::leak(Box::from(self)); check_status!(unsafe { sys::napi_create_threadsafe_function( env, ptr::null_mut(), ptr::null_mut(), async_resource_name, 0, 1, ptr::null_mut(), None, self_ref as *mut Future...
Rust
0
; 4] = ret.as_mut(); f.store(ret_mut.as_mut(), 0 as usize); } ret } } } #[cfg(feature = "simd")] impl Into<Simdf32x4> for Quaternion<f32> { #[inline] fn into(self) -> Simdf32x4 { let self_ref: &[f32; 4] = self.as_ref(); Simdf32x4::load(self_re...
Rust
0
true, track_difficulty .unwrap_or(XmlTrackDifficulty::Expert)), XmlTrackType::Vocals => { XmlFile::parse_vocal_track_from_midi(mid) }, } } } fn parse_guitar_track_from_midi...
Rust
0
} }) } /// Returns the largest element of the set that is smaller or equal to `x`. /// /// # Example /// ```rust /// # use aatree::AATreeSet; /// let mut set = AATreeSet::new(); /// assert!(set.largest_leq_than(&43).is_none()); /// set.insert(42); /// set.insert(44); /// set.insert(40); /// assert_eq...
Rust
0
oad_threshold: bt.logging.success( f"Trained model had a best_avg_loss of {best_avg_loss} which is below the threshold of {config.avg_loss_upload_threshold}. Uploading to hugging face. " ) # First, reload the best model from the training run. ...
Python
1
: Option<String>, pub redirect: Option<String>, pub cache: Option<CacheSpec>, pub hash: String, pub pure: bool, pub pure_mode: String, pub trace: Option<serde_json::Value>, // change it to Option<Trace> pub dev: bool, pub domain: String, #[serde(skip)] pub rendered: String, ...
Rust
0
<a href="https://exposeprofi.de" target="_blank">https://exposeprofi.de</a> </p> </div> <div class="reviews"> <p> Kundenbewertungen: <a href="{review_link1}" target="_blank">Bewertung 1</a> | <a href="{review_link2}" target="...
Python
1
Sugg::hir(cx, x, "x").to_string()); let end = Sugg::hir(cx, y, "y"); db.span_suggestion(expr.span, "use", format!("{}..={}", start, end)); }, ); ...
Rust
0
m: &Matrix<f64>, z: usize) -> Vec<f64> { let shape = m.shape(); let sub_shape = shape[1..].to_vec(); matrix::cartesian_product_of_shape(sub_shape).map( |mut position| { position.insert(0, z); m.get(position.as_slice()).clone() } ).collect() }<filenam...
Rust
0
kage { /// Create a new package /// /// Returns Err if package is not in the apt cache. pub fn new<T: AsRef<str>>(s: T) -> Result<Self, AptError> { match apt_cache("search", s.as_ref(), &search) { Some(p) => { if p.contains(&s.as_ref().to_string()) { ...
Rust
0
import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import load_iris def kmeans(X, K, max_iters=100): centroids = X[:K] for _ in range(max_iters): distances = np.linalg.norm(X[:, np.newaxis] - centroids, axis=2) labels = np.argmin(distances, axis=1) new_centroids =...
Python
1
from .. import Provider as DateTimeProvider class Provider(DateTimeProvider): DAY_NAMES = { "0": "neděle", "1": "pondělí", "2": "úterý", "3": "středa", "4": "čtvrtek", "5": "pátek", "6": "sobota", } MONTH_NAMES = { "01": "leden", "02...
Python
1
import matplotlib import pandas as pd import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties df = pd.read_csv('Commits over time.csv') total_commits = df['Commits'].sum() print(f"总提交次数为: {total_commits}") df['年份'] = pd.to_datetime(df['Week of']).dt.year yearly_commits = df.groupby('年份')['C...
Python
1
from multiprocessing import Process from bilibili import Bilibili from config import config from mirrativ import Mirrativ from openrec import Openrec from tools import check_ddir_is_exist, get_logger from twitcasting import Twitcasting from youtube import Youtube, start_temp_daemon logger = get_logger() class Even...
Python
1
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig import sys device = "cuda" # the device to load the model onto model_path = sys.argv[1] model_path = "./" + model_path quantization_config = BitsAndBytesConfig( load_in_8bit=False, load_in_4bit=True ) model = AutoModelForCausalLM.f...
Python
1
bb6}\u{0bcd}\u{0bb0}\u{0bc0}"; // #SRI -ஶ்ரீ pub const KSHA: &str = "\u{0b95}\u{0bcd}\u{0bb7}"; // #KSHA - க்ஷ pub const KSH: &str = "\u{0b95}\u{0bcd}\u{0bb7}\u{0bcd}"; // #KSH - க்ஷ் pub const INDIAN_RUPEE: &str = "₹"; pub const TAMIL_SYMBOLS: [&'static str; 11] = [ DAY, MONTH, YEAR, DEBIT, CREDIT,...
Rust
0
if vel_x == 0 { break; } } } // get all possible velocities let mut solutions = 0; for vel_x in result.into_iter() { let max_vel = (rect.bottom + 1).abs(); for vel_y in rect.bottom..=max_vel { if hits_target(vel_x, vel_y, &rect...
Rust
0