text
string
label_name
string
labels
int64
string(), &"1.0.0".to_string(), ]); Ok(()) } #[test] fn replace_maven_version() -> Result<()> { let mut hook = Hook::from_str("mvn versions:set -DnewVersion={{version}}")?; hook.insert_versions(None, &HookVersion::new("1.0.0")) .unwrap(); ass...
Rust
0
/rss-rust-command extern crate rss; extern crate url; extern crate curl; extern crate chrono; extern crate glob; extern crate termion; #[macro_use] pub mod streamrss; pub mod terminal; use streamrss::*; use std::io; fn main() { print!("{clear}{goto}", clear = termion::clear::All , goto = termion::cursor::Goto(1,1...
Rust
0
n21,n22)) #print("q2[%s] = %s" % (self.eid, q2)) #print("Lambda = \n"+str(Lambda)) #print("Lsize = ", Lambda.shape) #print("qsize = ", q.shape) u_axial = array(Lambda) @ q_axial du_axial = -u_axial[0] + u_axial[1] u_torsion = array(La...
Python
1
les. let parent_symbol_table_la = Arc::new(RwLock::new(SymbolTable::new_with_parent(None))); let child_symbol_table_la = Arc::new(RwLock::new(SymbolTable::new_with_parent(Some(parent_symbol_table_la.clone())))); parent_symbol_table_la.write().unwrap().define_symbol("stuff", Value::from(200u32)).expect("tes...
Rust
0
e) => { ctx.error_spanned_by(attr, e.to_compile_error()); Err(()) } } } } pub fn lit_str_to_expr_path(ctx: &mut Context, lit: &Lit) -> Result<ExprPath, ()> { match lit { Lit::Str(lit_str) => { let token_stream = syn::parse_str(&lit_str.val...
Rust
0
ND, formatted_message, severity) self.result_area.tag_configure(severity, foreground=color) self.result_area.see(tk.END) def check_swagger(self): config = self._get_config() paths = [ "/swagger-ui/index.html", "/prod-api/v2/api-docs", "/prod-api/v3...
Python
1
, color='tab:green', label="Steering Rate (u1)") axs[8].set_ylabel("Steering Rate") axs[8].legend() axs[-1].set_xlabel("Time [s]") plt.suptitle(f"True vs Predicted States + Controls (Trajectory {traj_idx} in Batch {bid})") plt.tight_layout() plt.s...
Python
1
i_config.tts_engine=self.csv_tts_engine_var.get() anki_config.cleanup_csv=False anki_config.cleanup_jpg=False anki_config.extract_audio_segment=False # 创建线程执行查询,避免界面卡顿 threading.Thread(target=self._generate_anki_from_csv_thread, args=(anki_config,), daemon=True).start()...
Python
1
def concat_first(feat: torch.Tensor, dim: int=2, scale: float=1.0 ) ->torch.Tensor: feat_style = expand_first(feat, scale=scale) return torch.cat((feat, feat_style), dim=dim)
Python
1
CH_S390X, ArtifactNames.CH_LOONGARCH64, ] ) clickhouse_debians = Artifact.Config( name="*", type=Artifact.Type.S3, path=f"{TEMP_DIR}/*.deb", ).parametrize( names=[ ArtifactNames.DEB_AMD_RELEASE, ArtifactNames.DEB_AMD_DEBUG, ...
Python
1
*mut ::std::os::raw::c_uchar, ); } extern "C" { pub fn ofdmframe_validate_sctype( _p: *mut ::std::os::raw::c_uchar, _M: ::std::os::raw::c_uint, _M_null: *mut ::std::os::raw::c_uint, _M_pilot: *mut ::std::os::raw::c_uint, _M_data: *mut ::std::os::raw::c_uint, ); } ext...
Rust
0
:" // "cid" ]; fn part_one() -> usize { let mut valid = 0; let input = read_to_string("./data/input.txt").unwrap(); // empty line 'outer: for passport in input.split("\n\n") { for field in &FIELDS { if !passport.contains(field) { continue 'outer } } valid += 1; } valid } fn valid_field( key:...
Rust
0
from dragonfly import MappingRule, Function, Repeat, ShortIntegerRef from castervoice.lib import utilities from castervoice.lib import virtual_desktops from castervoice.lib.actions import Key from castervoice.lib.ctrl.mgr.rule_details import RuleDetails from castervoice.lib.merge.state.short import R class WindowMan...
Python
1
er_pipeline_descriptor = wgpu::RenderPipelineDescriptor { label: Some("Render Pipeline"), layout: Some(&render_pipeline_layout), vertex: wgpu::VertexState { module: &shader, entry_point: "vs_main", buffers: &[Vertex::layout()], }, fragment: None, primitive: wgpu::PrimitiveState { topol...
Rust
0
plex(2, 0.005), mean_square_slope=0.02, temperature=265), make_soil("geometrical_optics", complex(5, 0.005), mean_square_slope=0.2, temperature=265), make_soil("iem_fung92", complex(5, 0.005), roughness_rms=0.0001, corr_length=0.005, temperature=265), make_soil("iem_fung92_brogioni10", complex(5...
Python
1
) .await .unwrap(); let insert = Insert::single_into("mysql_blobs_roundtrip_test").value("bytes", blob.as_slice()); connection.query(insert.into()).await.unwrap(); let roundtripped = Select::from_table("mysql_blobs_roundtrip_test").column("bytes"); let roundt...
Rust
0
r = DBSQLTransactionManager(warehouse_id=WAREHOUSE_ID) serverless_transaction_manager.execute_dbsql_transaction(sql_string=str(mst_scd_transaction_sql), tables_to_manage=['main.iot_dashboard.temp_batch_to_insert', 'main.iot_dashboard.silver_sensors_scd_2']) except Exception as e: delta_logger.fail_run() raise(...
Python
1
2kgLSA2NDpdDQogICAgICAgIHRtcCA9IFswLCAwLCAwLCAwLCAwLCAwLCAwLCAwLCAwLCAwLCAwLCAwLCAwLCAwLCAwLCAwXQ0KICAgICAgICBpID0gMA0KICAgICAgICB3aGlsZSBpIDwgbGVuKHRleHQpOg0KICAgICAgICAgICAgdG1wW2kgPj4gMl0gfD0gb3JkKHRleHRbaV0pIDw8ICgoaSAlIDQpIDw8IDMpDQogICAgICAgICAgICBpICs9IDENCiAgICAgICAgdG1wW2kgPj4gMl0gfD0gMHg4MCA8PCAoKGkgJSA0KSA8P...
Python
1
.https_or_http().enable_http1().enable_http2().build()), auth); /// // As the method needs a request, you would usually fill it with the desired information /// // into the respective structure. Some of the parts shown here might not be applicable ! /// // Values shown here are possibly random and not representative ! ...
Rust
0
VPN underlay L3 multicast group.""" offset = vrf_id - 1 + evpn_underlay_l3_multicast_group_ipv4_pool_offset return get_ip_from_pool(underlay_l3_multicast_group_ipv4_pool, 32, offset, 0) def evpn_underlay_l2_multicast_group( self, underlay_l2_multicast_group_ipv4_pool: str, v...
Python
1
seq_num", CMsgRemoteClientBroadcastDiscovery::has_seq_num, CMsgRemoteClientBroadcastDiscovery::get_seq_num, )); ::protobuf::reflect::MessageDescriptor::new::<CMsgRemoteClientBroadcastDiscovery>( "CMsgRemoteClientBroadcastDiscove...
Rust
0
`] method on iterators. Types which /// implement the trait can be generated by the [`sum`] method. Like /// [`FromIterator`] this trait should rarely be called directly and instead /// interacted with through [`Iterator::sum`]. /// /// [`sum`]: ../../std/iter/trait.Sum.html#tymethod.sum /// [`FromIterator`]: ../../std...
Rust
0
] #[doc = " \\ingroup group_user_kernels"] pub type vx_meta_format = *mut _vx_meta_format; #[doc = "< \\brief An invalid type value. When passed an error must be returned."] pub const vx_type_e_VX_TYPE_INVALID: vx_type_e = 0; #[doc = "< \\brief A <tt>\\ref vx_char</tt>."] pub const vx_type_e_VX_TYPE_CHAR: vx_type_e = 1...
Rust
0
t coord `x + 1` map to coord `x`. Repeat, /// Samples at coord `x + 1` map to coord `1 - x`. Mirror, /// Samples at coord `x + 1` map to coord `1`. Clamp, /// Same as Mirror, but only for one repetition, MirrorClamp } impl ToGlEnum for SamplerWrapFunction { #[inline] fn to_glenum...
Rust
0
::ext::base::SingleRegisterAccess<()> for Emulator { fn read_register( &mut self, _tid: (), reg_id: gdbstub_arch::mips::reg::id::MipsRegId<Address>, dst: &mut [u8], ) -> TargetResult<(), Self> { let w = match reg_id { MipsRegId::Gpr(i) => self.cpu.reg[i as usi...
Rust
0
) }) } /// Get [`Voicer`](struct.Voicer.html) pub fn voice_handler(&self) -> Arc<Mutex<Voicer>> { Arc::clone(&self.voicer) } /// Get [`OutVoicer`](struct.OutVoicer.html). pub fn out_voice_handler(&self) -> Arc<Mutex<OutVoicer>> { Arc::clone(&self.out_voicer) } } #[no_mangl...
Rust
0
#[test] fn thirteen_times_100() { let factory = Arc::new(FBuilder::mk().len(1300).build()); for _ in 0..13 { run(&factory, 100, 100); } } #[test] fn seven_times_10000() { let factory = Arc::new(FBuilder::mk().len(10000).build()); for _ in 0..7 { run(&factory, 10000, 100); } } ...
Rust
0
# coding: utf-8 # author: lu yf # create date: 2019-12-25 11:23 import math import os import pickle import numpy as np import multiprocessing as mp # def dcg_at_k(scores): # # assert scores # return scores[0] + sum(sc / math.log(ind+1, 2) for sc, ind in zip(scores[1:], range(2, len(scores) + 1))) # ind+1!!!...
Python
1
"Error while decoding response from ZeroMQ: {}", err )), } } <reponame>yufan022/datafuse<filename>common/meta/flight/src/flight_action.rs<gh_stars>1-10 // Copyright 2020 <NAME>. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except ...
Rust
0
def binary(array,target): left,right=0,len(array)-1 while left<=right: mid=(left+right)//2 if array[mid]==target: return mid elif array[mid]<target: left=mid+1 else: right=mid-1 return -1 arr=[32,70,81,93,107] # sorted array target=float(...
Python
1
finish() run = None logging.info('Task done, results saved in %s', cfg.run_dir) @register_train('inference-only') def inference_only(loggers, loaders, model, optimizer=None, scheduler=None): """ Customized pipeline to run inference only. Args: loggers: List of loggers loaders...
Python
1
v1_14", feature = "dox"))] pub fn set_vlan_protocol(&self, vlan_id: u32, protocol: SriovVFVlanProtocol) { unsafe { nm_sys::nm_sriov_vf_set_vlan_protocol( self.to_glib_none().0, vlan_id, protocol.to_glib(), ); } } /// Se...
Rust
0
.unwrap(); project_kanban .members .iter() .find(|x| x.name == "shaunxu2") .unwrap(); Ok(()) } #[test] fn t02_agile_projects_list_scrum() -> helper::TestResult { let output = helper::TestHelper::get_exe_command() .arg("agile") .arg("projects") ...
Rust
0
let fold = CaseFold::Ascii; /// assert_eq!(fold.casecmp("Crate: focaccia", "Crate: FOCACCIA"), Ordering::Equal); /// assert_eq!(fold.casecmp("Fabled", "failed"), Ordering::Less); /// /// assert!(fold.case_eq("Crate: focaccia", "Crate: FOCACCIA")); /// assert!(!fold.case_eq("Fabled", "failed")); /// ``` /// /// Turkic ...
Rust
0
lFlags::Unused), cell: UnsafeCell::new(a) } } pub fn into_inner(self) -> A { self.cell.into_inner() } } impl<A: ?Sized> GcCell<A> { pub fn borrow(&self) -> GcCellRef<A> { if self.flags.get().is_writing() { panic!("GcCell<T> already mutably borrowed"); ...
Rust
0
writeln!(type_description, "{}", property_description)?; } } spec.definitions.insert(definition_path, definition); return Ok(()); } } } } Err("never applied WatchEvent override".into()) } <gh_stars>10-100 use std::sync::Arc; use spdlog::{prelude::*, sink::Sink}; fn main() { // Bui...
Rust
0
e_rounds() { let validator_signer = ValidatorSigner::from_int(0); let safety_rules = SafetyRules::new( InMemoryStorage::default_storage(), Arc::new(validator_signer.clone()), ); // build a tree of the following form: // ___________ // / \ // ...
Rust
0
from tkinter import * def addDateFunc(): def addDate(item): with open("Data\\datum.txt", "a") as file: file.write(str(item) + "\n") def continuelol(): result_dateadd = date_add.get() addDate(result_dateadd) date_add.delete(0, 'end') dateAdd = Toplevel() dat...
Python
1
roj_seq_len = lambda args: torch.einsum('bnd,nk->bkd', *args) k_input = x if itp_x is None else itp_x v_input = x keys = self.to_k(k_input) values = self.to_v(v_input) if not self.share_kv else keys kv_projs = (self.proj_k, self.proj_v if not self.share_kv else self.proj_k) ...
Python
1
# Copyright (c) 2023-2024, NVIDIA CORPORATION. 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 ...
Python
1
import trio import tractor async def main(): async with tractor.open_root_actor( debug_mode=True, loglevel='cancel', ) as _root: # manually trigger self-cancellation and wait # for it to fully trigger. _root.cancel_soon() await _root._cancel_complete.wait() ...
Python
1
isect); black_box(&mut v); }) }) .throughput(Throughput::Elements(1)), ); } criterion_group!(benches, hit_scalar, hit_vector); criterion_main!(benches); // Copyright 2016 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not ...
Rust
0
import os import glob import numpy as np import pickle import json from tqdm import tqdm def process_nucla_to_json(root="N_UCLA", save_dir="N-UCLA_processed"): os.makedirs(save_dir, exist_ok=True) label_map = {} # e.g., {'a01': 1, 'a02': 2, ...} label_counter = 1 datasets = { "train": {"view...
Python
1
plementNB#sklearn-naive_bayes-complementnb", "import_from": "sklearn.naive_bayes", "type": "object", "tags": {"pre": [], "op": ["estimator", "classifier"], "post": []}, "properties": { "hyperparams": _hyperparams_schema, "input_fit": _input_fit_schema, "input_predict": _input_pre...
Python
1
eader<bool, CH1SEL_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `CH1SEL` writer - Channel 1 Select"] pub struct CH1SEL_W<'a> { w: &'a mut W, } impl<'a> CH1SEL_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(sel...
Rust
0
super().do_show() def do_close(self): """Override close signal to stop audio capture and shut down thread pool.""" print("DictationOverlay: Stopping audio capture and shutting down thread pool...") try: self.audio_capturer.stop() except Exception as e: ...
Python
1
c = "Reader of field `SCANGAIN`"] pub type SCANGAIN_R = crate::R<u8, u8>; #[doc = "Write proxy for field `SCANGAIN`"] pub struct SCANGAIN_W<'a> { w: &'a mut W, } impl<'a> SCANGAIN_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { ...
Rust
0
urn # Read the current angle current_angle = read_rotary_angle() # Only print if the angle has changed significantly if abs(current_angle - rotary_prev_angle) >= rotary_threshold or rotary_prev_angle == -1: print(f"Angle: {current_angle} degrees") rotary_prev_angle = current_an...
Python
1
mask(&self) -> u32 { self.deviceNodeMask } #[inline] pub fn is_device_luid_valid(&self) -> bool { self.deviceLUIDValid != 0 } } #[cfg(feature = "VK_KHR_external_memory_capabilities")] unsafe impl Struct for VkPhysicalDeviceIDPropertiesKHR {} #[cfg(feature = "VK_KHR_external_memory_capabilities")] unsafe...
Rust
0
# Part of Odoo. See LICENSE file for full copyright and licensing details. # The currencies supported by Razorpay, in ISO 4217 format. Last updated on May 26, 2021. # See https://razorpay.com/docs/payments/payments/international-payments/#supported-currencies. # Last seen online: 16 November 2022. SUPPORTED_CURRENCIES...
Python
1
let now = Local::now(); hrs24 = parse_unit(&format!("{}", now.format("%H"))); hrs = parse_unit(&format!("{}", now.format("%H"))) % 12; mins = parse_unit(&format!("{}", now.format("%M"))); } else { let p = LPattern::new("%hh:%mm"); let caps = p.apply_to(&timestr); ...
Rust
0
""" This test is skipped until specutils is restored to working status """ # try: # import specutils # import specutils.io.tests # SPECUTILS_OK = True # except ImportError: # SPECUTILS_OK = False # # import pytest # import os # # from ... import Spectrum, Spectra # # @pytest.mark.skipif("not SPECUT...
Python
1
reader = linefeed::Interface::new("application")?; let completer = CommandCompleter::new(commands(), db); let histpath = dirs::home_dir() .ok_or("failed to access home".to_string())? .join(HISTORY_FILE_PATH); if histpath.exists() { reader.load_history(histpath)?; } reade...
Rust
0
Err(err) => { panic!("oh damn, it probably doesn't exist - {}", err); }, Ok(fp) => fp, }; let manifest_digest = file_path .file_name() .unwrap() .to_str() .unwrap() .to_owned(); let file_size = std::fs::metadata(&file_path) ...
Rust
0
y of this distribution and at https://raw.githubusercontent.com/lemonrock/security-keys-rust/master/COPYRIGHT. No part of security-keys-rust, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. // Copyright © 2021 The developers of secu...
Rust
0
The number of iterations to run the algorithm embedding_density : int The density of the generated embeddings (number of bits per embedding) output_dimension : int | None, default=None The dimension of the output embeddings. neighbor_influence : float | None, defa...
Python
1
let default_namespace = Collection::new(client.clone(), None, spawn_pool.clone()); Zdb { client, spawn_pool, default_namespace, } } /// Get a reference to a `Collection`. pub fn collection(&self, name: &str) -> Collection { Collection::new( ...
Rust
0
on Module Resolution](https://www.typescriptlang.org/docs/handbook/module-resolution.html). #[derive(Deserialize, Debug, PartialEq, Copy, Clone)] pub enum ModuleResolutionMode { #[serde(rename = "node")] Node, #[serde(rename = "classic")] Classic, } /// Controls how JSX constructs are emitted in JavaSc...
Rust
0
import boto3 from typing import Optional def get_model_ids(client: Optional = None): if not client: client = boto3.client("bedrock") models = client.list_foundation_models() model_ids = [model["modelId"] for model in models["modelSummaries"]] return model_ids
Python
1
ckets. #[serde(rename = "userProject")] pub user_project: Option<String>, } impl std::fmt::Display for BucketAccessControlsPatchParams { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { if let Some(ref v) = self.provisional_user_project { write!( f, ...
Rust
0
rx.recv(); match recv { Ok(RawEvent { path, op: Ok(fsop::CLOSE_WRITE), .. }) => { if let Some(path) = path { log::info!("Filesystem write event: {:?}", path); tx_parent.send(path).unwrap(); } else { log::err...
Rust
0
let not_eq = Expression::equals(cs.namespace(|| "not_eq"), &a, &b).unwrap(); let not_eq2 = Expression::equals(cs.namespace(|| "eq a bit_true"), &bit, &a).unwrap(); let eq = Expression::equals(cs.namespace(|| "eq"), &a, &c).unwrap(); let eq2 = Expression::equals(cs.namespace(|| "eq a d"...
Rust
0
xcentroid'].value[0], y_pos=dao_src['ycentroid'].value[0], n_slits=12, err=data_err) morph_dict = phot_tools.ProfileTools.measure_morph_photometry(rad_profile_dict=profile_di...
Python
1
coding_style, sanitize_tracebacks=args.sanitize_tracebacks, valid_syntax=args.valid_syntax, global_decls=args.global_decls, target=args.target, print_stack_structs=args.print_stack_structs, unk_inference=args.unk_inference, stack_spill_detection=args.stack_spill_d...
Python
1
cpu.execute_instruction((load_instruction, OpInput::UseImmediate(1))); compare(&mut cpu, -1i8 as u8); assert!(!cpu.registers.status.contains(Status::PS_ZERO)); assert!(!cpu.registers.status.contains(Status::PS_CARRY)); assert!(!cpu.registers.status.contains(Status::PS_NEGATIVE));...
Rust
0
TARGET_EXE_PATH, &["-e", "a(b)c", "-f", "$0", "--color", "always"], env, b"abcabca" as &[u8], ); assert_eq!(oup.stderr, ""); assert_eq!(oup.stdout, "<S>abc<E><S>abc<E>a\n"); assert_eq!(oup.status.success(), true); } // #[test] ...
Rust
0
def get_dataset_order(dataset_id): task_list = [ "yelp", "amazon", "dbpedia", "yahoo", "agnews", "MNLI", "QQP", "RTE", "SST-2", "WiC", "CB", "COPA", "BoolQA", "MultiRC", "IMDB" ] if datase...
Python
1
self.square, value: self.value, }) } Constraint::SquareNumber { .. } => None, }, ) } } impl From<Possibility> for latin_square::Possibility { fn from(src: Possibility) -> Self { latin_square::Possibility { ...
Rust
0
X`"] pub struct PLLA_MMAX_W<'a> { w: &'a mut W, } impl<'a> PLLA_MMAX_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !0x07ff) | ((value as u32) & 0x07ff); self.w } } impl R { #[doc...
Rust
0
: //! //! ```rust, no_run //! # #![feature(async_await, futures_api)] //! #[macro_use] //! extern crate serde_derive; //! use tide::body; //! //! #[derive(Serialize, Deserialize, Clone, Debug)] //! struct Message { //! author: Option<String>, //! contents: String, //! } //! //! async fn echo_json(msg: body::Jso...
Rust
0
en nodes are stored the inverse function from get_travel_costs_1to1 has to be called here origin_position, destination_position = od_pos origin_node = origin_position[0] origin_overhead = (0.0, 0.0, 0.0) if origin_position[1] is not None: origin_node = ori...
Python
1
it gets dropped assert (delta.to_pytimedelta() * 2) / off == 2 result = np.array([2 * td64, td64]) / off expected = np.array([2.0, 1.0]) tm.assert_numpy_array_equal(result, expected) @pytest.mark.parametrize("cls1", tick_classes) @pytest.mark.parametrize("cls2", tick_classes) def test_tick_zero(c...
Python
1
combobox.get_active_id().unwrap().parse::<usize>().unwrap()) .expect("Couldn't generate passwords"); store.clear(); for password in passwords { let score = scorer::score(&analyzer::analyze(&password)); store.insert_with_values(None, &[0, 1], &[&password, &format!("{}/100", score as i32)....
Rust
0
e(&self) -> Node<'a> { self.into() } fn kind(&self) -> NodeKind { NodeKind::AssignPat } } impl<'a> CastableNode<'a> for AssignPat<'a> { fn to(node: &Node<'a>) -> Option<&'a Self> { if let Node::AssignPat(node) = node { Some(node) } else { None } } fn kind() -> NodeKind { ...
Rust
0
h = self.path / "logs" / key full_path.parent.mkdir(parents=True, exist_ok=True) # Touch if it doesnt exist if not full_path.exists(): full_path.touch() with open(full_path, "a", encoding="utf-8") as file: file.write(f"\n{datetime.now().isoformat()}\n") ...
Python
1
---- ; ; FileBrowser ; 'directory' 'каталог' 'Default Directory' 'Каталог запуска' 'Home Directory' 'Корневой каталог ' 'rename' 'переименовывать' 'Move To' 'Перемещать' 'new' 'создавать' 'properties...
Rust
0
Drop::drop(&mut self.guard); ManuallyDrop::drop(&mut self.object); } } } impl InitSdfCache { pub fn new() -> InitSdfCache { InitSdfCache { cache: Mutex::new(None), } } pub fn lock_owned(self: Arc<Self>) -> OwnedMutexGuard<Self, Option<SdfCache>> { ...
Rust
0
import os import asyncio from typing import Optional # Force in-memory DB backend by default for easy local testing os.environ.setdefault("DB_MODE", "memory") # Ensure .env variables are loaded if present from dotenv import load_dotenv load_dotenv() from backend.agent import handle_chat def print_banner(): pri...
Python
1
# Given the ncurses source directory as its only argument, this script # extracts buildable files from ncurses "modules" and prints some # lines for the BUILD.ncurses file. import os import sys def convert_modules(base_dir): mod_file = os.path.join(srcdir, base_dir, "modules") for l in open(mod_file): ...
Python
1
_eq!(join_with_conjunction("and", &strs[..1]), "X"); assert_eq!(join_with_conjunction("and", &strs[..2]), "X and Y"); // Oxford comma! assert_eq!(join_with_conjunction("and", &strs[..3]), "X, Y, and Z"); } #[test] fn test_div_ceil() { assert_eq!(div_ceil(0, 5), 0); assert_eq!(div_ceil(1, 5), 1); ...
Rust
0
e!("Unexpected type of factor: {}", factor)), } } //! Routines for bitwise input/output. use std::io::Read; use std::io::Write; use std::io; pub struct BitReader<R> { inner: R, buf: u8, mask: u8, extra_bits: usize, } impl<R: Read> BitReader<R> { /// Create a new `BitReader` from a `Read` inst...
Rust
0
", "csv", "--kind", "line_comment"].iter()) .assert() .stdout( r"Group,Files,Tokens,Kind(line_comment) Rust,5,156,9 Go,1,52,0 Ruby,2,43,0 Unsupported,1,0,0 ", ) .success(); } #[test] fn test_count_node_kind_patterns() { tcount() .current_dir("tests/fixtures/") ...
Rust
0
) self.assertNoMoreResources() def test_pre_upgrade_restart(self): config_file = self.get_src_folder()+"/test/python/stacks/2.0.6/configs/default.json" with open(config_file, "r") as f: json_content = json.load(f) version = '2.2.1.0-3242' json_content['commandParams']['version'] = version...
Python
1
::RGB, gl::SHORT) => gl::RGB16, (gl::RGB, gl::UNSIGNED_BYTE) => gl::RGB, (gl::RGB, gl::UNSIGNED_SHORT) => gl::RGB16, (gl::RGB, gl::FLOAT) => gl::RGB32F, (gl::RGBA, gl::BYTE) => gl::RGBA, (gl::RGBA, gl::SHORT) => gl::RGBA16, (gl::RGBA, gl::UNSIGNED_...
Rust
0
oordinator = hass.data[DOMAIN][config_entry.entry_id][KEY_COORDINATOR] for description in BUTTON_TYPES: if description.key not in buttons: continue entities.append( XiaomiGenericCoordinatedButton( device, config_entry, f"{desc...
Python
1
if t not in trks_connected: trks_connected.append(t) wxLogDebug('t added: '+(str(tseg)),debug) wxLogDebug('trks_connected '+str(len(trks_connected)),debug) return trks_connected # def isEq (p1,p2): epsilon = FromMM(0.003) # tolerance 3 nm delta = math.hypot(p...
Python
1
), host: String::from(host), } } } use std::str::FromStr; use std::string::ToString; impl FromStr for Hostmask { type Err = Error; fn from_str(s: &str) -> Result<Hostmask, Error> { // nick!user@host.domain if s.contains("@") { let (mut nick, mut user, mut ho...
Rust
0
import asyncio import re from collections.abc import Sequence from pywebio.output import * from pywebio.session import get_info requirejs_config_tpl = """ <script type="text/javascript"> require.config({ paths: { "bokeh": "https://cdn.bokeh.org/bokeh/release/bokeh-__version__.min", "bokeh-widgets"...
Python
1
(&self) -> TableSummary { TableSummary { name: self.table_name.to_string(), columns: self.table.stats(), } } /// Return the approximate memory size of the chunk, in bytes including the /// dictionary, tables, and their rows. /// /// Note: This does not includ...
Rust
0
#coding=utf8 import jieba def stop_words(): stop_words_file = open('stop_words_ch.txt', u'r') stopwords_list = [] for line in stop_words_file.readlines(): stopwords_list.append(line.decode('gbk')[:-1]) return stopwords_list def jieba_fenci(raw, stopwords_list): # 使用结巴分词把文件进行切分 word_lis...
Python
1
code")] UnknownErrorCode, #[error("InvalidResponse")] InvalidResponse, } impl From<u8> for CommandError { fn from(value: u8) -> Self { use CommandError::*; match value { 0x05 => ReceivedMessageInvalid, 0x06 => FailedToActOnMessage, 0x07 => InvalidCrc...
Rust
0
#!/usr/bin/env python3 """ Test different Ollama model configurations """ import subprocess import json import tempfile import os def test_model_configurations(): print("🤖 TESTING CONFIGURABLE OLLAMA MODELS") print("="*50) # Different model configurations to test model_configs = [ { ...
Python
1
temp_df["振幅"], errors="coerce") temp_df["最高"] = pd.to_numeric(temp_df["最高"], errors="coerce") temp_df["最低"] = pd.to_numeric(temp_df["最低"], errors="coerce") temp_df["今开"] = pd.to_numeric(temp_df["今开"], errors="coerce") temp_df["量比"] = pd.to_numeric(temp_df["量比"], errors="coerce") temp_df["换手率"] = pd....
Python
1
node, warning) # fix section nodes for node in document.traverse(nodes.section): # remove spurious IDs (first may be from duplicate name) if len(node['ids']) > 1: node['ids'].pop() # fix section levels section_l...
Python
1
7\xd0\xbc\xd0\xb5\xd1\x80 \xd0\xb3\xd1\x80\xd1\x83\xd0\xb4\xd0\xb8","likes":{"count":1,"user_likes":0,"can_like":1},"reply_to_uid":167496147,"reply_to_cid":195296},{"cid":195298,"uid":76332491,"from_id":76332491,"date":1386602852,"text":"\xd0\x90 \xd1\x87\xd0\xb5\xd0\xb3\xd0\xbe \xd1\x81\xd1\x82\xd0\xb5\xd1\x81\xd0\xbd...
Python
1
65 * 287.05) ) if h >= 11000: # up to 20000 m p = 22632 * np.exp(-(9.81 * (h - 11000) / (287.05 * 216.65))) if mach < 0.3: temp = vtas ** 2 * p / (vias ** 2 * aero.rho0 * aero.R) rho = p / (aero.R * temp) vtas2 = v...
Python
1
&typ)), Box::new(day5::Day5::new(&typ)), Box::new(day6::Day6::new(&typ)), Box::new(day7::Day7::new(&typ)), Box::new(day8::Day8::new(&typ)), Box::new(day9::Day9::new(&typ)), Box::new(day10::Day10::new(&typ)), Box::new(day11::Day11::new(&typ)), Box::new(day1...
Rust
0
er, attack: trigger, rm: 0.0 }), (Electro, Physical) => Neutralize(Self { enemy_aura, trigger, attack: trigger, rm: 0.0 }), (Cryo, Pyro) => Melt(Self { enemy_aura, trigger, attack: trigger, rm: 2.0 }), (Cryo, Hydro) => Freeze(Self { enemy_aura, trigger, attack: trigger,...
Rust
0
or non-fungible-token module. #[pallet::error] pub enum Error<T> { /// No available class ID NoAvailableClassId, /// No available token ID NoAvailableTokenId, /// Token(ClassId, TokenId) not found TokenNotFound, /// Class not found ClassNotFound, /// The operator is not the owner of the t...
Rust
0
icted TM score is computed. Returns: ptm_score: The predicted TM alignment or the predicted iTM score. """ # residue_weights has to be in [0, 1], but can be floating-point, i.e. the # exp. resolved head's probability. if residue_weights is None: residue_weights = np.ones(logits.shape[0]) bin_cent...
Python
1