text
string
label_name
string
labels
int64
dth, self.netHeight), scale=1 / 255, swapRB=True) # Logging network output layers names. logger.info("Network output layers: %s", ",".join(self.netOutLayers)) logger.info( "Created %ux%u network with %u classes.", self.netWidth, self.netHeight, l...
Python
1
yer {player.player_id} (yaw: {player.yaw:.3f} rad, {np.degrees(player.yaw):.1f} deg)") controller.point_at_player(player) rospy.sleep(3) # Clean up controller.clear_constraints() controller.move_to_preset('home') rospy.loginfo("Natural pointing test completed") def demo_custom_pos...
Python
1
g_interval, "failure_count": len(failure_events), } # 測試正常失敗模式 now = datetime.now() normal_failures = [ now - timedelta(minutes=30), now - timedelta(minutes=15), now - timedelta(minutes=5), ] normal...
Python
1
als.font_info[k][MEMORY_WORD_SC] = scaled::new_from_inner($globals.cur_val); // end; true } // assign_font_int: begin n:=cur_chr; scan_font_ident; f:=cur_val; else if $cur_cmd == assign_font_int { /// for temporary short-term use let n: integer; /// identifies a font ...
Rust
0
d last.pt for f in trainer.save_dir.glob("*"): # log all other files in save_dir if f.suffix in {".png", ".jpg", ".csv", ".pt", ".yaml"}: mlflow.log_artifact(str(f)) keep_run_active = os.environ.get("MLFLOW_KEEP_RUN_ACTIVE", "False").lower() == "true" if keep_run_active: LOGGER....
Python
1
# api/slack/events/index.py from fastapi import FastAPI, Request from fastapi.responses import JSONResponse import httpx import os app = FastAPI() SLACK_BOT_TOKEN = os.environ.get("SLACK_BOT_TOKEN") print("SLACK_BOT_TOKEN loaded:", bool(SLACK_BOT_TOKEN)) @app.get("/") async def root(): return {"message": "Hello...
Python
1
CTIONS", "truffle:TRUFFLE_API", ], "maven" : { "tag": ["default", "public"], }, "useModulePath": True, "noMavenJavadoc": True, }, "ESPRESSO_SVM": { "moduleInfo" : { "name" : "org.graal...
Python
1
Documentation', [author], 1) ] # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'PythonDi...
Python
1
''' This code.py file is intended to be used as a seeded code breaker ''' import time import usb_hid import os import board import digitalio import random import re from adafruit_hid.keycode import Keycode from adafruit_hid.keyboard import Keyboard from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS keyboard...
Python
1
t api: *const sys::OrtApi = unsafe { get_api(sys::ORT_API_VERSION) }; Arc::new(Mutex::new(AtomicPtr::new(api as *mut sys::OrtApi))) }; } pub fn ort() -> sys::OrtApi { let mut api_ref = G_ORT_API.lock().expect("failed to acquire OrtApi lock; another thread panicked?"); let api_ref_mut: &mut *mut sys::OrtApi = api_...
Rust
0
ig.error_interval); let formatted_message = format!("<br/>🚨 An error was raised -> <code>crunch</code> on hold for {} min while rescue is on the way 🚁 🚒 🚑 🚓<br/><br/>", config.error_interval); c.send_message(&message, &formatted_message).await.unwrap(); ...
Rust
0
7), Some(-4), None, Some(6), None, Some(-6), Some(-6), None, None, Some(0), Some(6), Some(5), None, Some(9), None, None, Some(-1), Some(-4), None, None, None, Some(-2) ])), 8 ); } // 1...
Rust
0
import sys sys.path.insert(0, "../src") from pymatgen.core.periodic_table import Element from pymatgen.core.structure import Structure from pymatgen.analysis.adsorption import AdsorbateSiteFinder from gnn_eads.functions import get_voronoi_neighbourlist from pymatgen.io.ase import AseAtomsAdaptor def get_act_sites(meta...
Python
1
class Solution: def increasingTriplet(self, nums: List[int]) -> bool: uniq = set(nums) if len(uniq) < 3: return False i = nums[0] j = nums[1] k = nums[2] ipos = 0 jpos = 1 kpos = 2 if i < j < k: return True ...
Python
1
_int = 0x0002; pub const CO_VARARGS : c_int = 0x0004; pub const CO_VARKEYWORDS : c_int = 0x0008; pub const CO_NESTED : c_int = 0x0010; pub const CO_GENERATOR : c_int = 0x0020; /* The CO_NOFREE flag is set if there are no free or cell variables. This information is redundant, but it allows a single flag test to de...
Rust
0
stacks = [['Red', 'Yellow', 'Blue', 'Yellow'], [], [], ['Green', 'Blue', 'Green', 'Red'], [], ['Yellow', 'Red', 'Green', 'Blue']] costs = {0: 4, 1: 5, 2: 3, 3: 3, 4: 3, 5: 5} def is_sorted(): for stack in stacks: if len(stack) > 0 and len(set(stack)) != 1: return False return True def mov...
Python
1
is of kind {:?}", $err, stringify!($kind)), _ => assert!(false, "{:?} is NOT of kind {:?}", $err, stringify!($kind)) }); } use std::str; use {Verifier, Encryptor, KeySize, AesHmacEncryptor, AesGcmEncryptor, DerivedKeyParams, ErrorKind}; #[test] fn is_valid_message_returns_...
Rust
0
t slice: &[i32] = &vector; let slice2: &[i32] = &vector[1..4]; // Use `{:?}` to print something debug-style println!("{:?} | {:?}", vector, slice2); // [1, 2, 3, 4, 5] | [2, 3, 4] // Array, slice, and vector indexing. println!("{}", four_ints[1]); // 2 println!("{}", vector[2]); // 3 print...
Rust
0
# jax2onnx/plugins/jax/lax/cos.py from typing import TYPE_CHECKING import jax import numpy as np from jax2onnx.plugins.plugin_system import PrimitiveLeafPlugin, register_primitive from jax2onnx.plugins._ir_shapes import _stamp_type_and_shape if TYPE_CHECKING: pass @register_primitive( jaxpr_primitive=jax....
Python
1
'''EJERCICIO: - Crea un comentario en el código y coloca la URL del sitio web oficial del lenguaje de programación que has seleccionado. - Representa las diferentes sintaxis que existen de crear comentarios en el lenguaje (en una línea, varias...). - Crea una variable (y una constante si el lenguaje lo soporta). - Crea...
Python
1
ng extension config file: %s" % \ options.configfile e.args = (message,) + e.args[1:] raise opts = { 'input': input_file, 'output': options.filename, 'extensions': options.extensions, 'extension_configs': extension_configs, ...
Python
1
, act_dim)), diffusion_steps=5, ema_rate=0.9999, device=device) # --------------- Training ------------------- actor.train() avg_loss_diffusion, avg_loss_classifier = 0., 0. for t in range(100000): idx = np.random.randint(0, size, (256,)) obs = torch.tensor(dataset['observatio...
Python
1
ine, PolyLine, Pt2D}; use crate::raw::RestrictionType; use crate::{Intersection, Lane, LaneID, Map, RoadID, Turn, TurnID, TurnType}; /// Generate all driving and walking turns at an intersection, accounting for OSM turn restrictions. pub fn make_all_turns(map: &Map, i: &Intersection) -> Vec<Turn> { let mut raw_tu...
Rust
0
 c@sddlTddlZdZdZdddYZdddYZd dd YZd dd YZd ddYZ dddYZ dddYZ dddYZ dS(i(t*Niit ResultErrorcBs8eZdZdZdZdZddZRS(...
Python
1
df = cudf.DataFrame({"a": cp.arange(0, 25)}) n = 25 expected = df.sample(n, replace=replace, random_state=random_state_lib(10)) out = df.sample(n, replace=replace, random_state=random_state_lib(10)) assert_eq(expected, out) def test_sample_invalid_n_frac_combo(axis): n, frac = 2, 0.5 pdf =...
Python
1
from collections import Counter class Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ num_dict = {} ans_dict = {} # Frequency dictionary for the number array. num_dict = Counter(nums) # REDUC...
Python
1
''' Esercizio 9 - Zoo interattivo Tema: Polimorfismo + proprietà Obiettivo: Far interagire oggetti polimorfici in un contesto di zoo virtuale. Traccia: 1. Definisci una classe base AnimaleZoo con: * un metodo info() che restituisce informazioni generali sull’animale (ad esempio il tipo o nome). * un metodo ...
Python
1
x107d1; /// FSB Event Control/Counter Register (R/W) Apply to Intel Xeon processor 7400 series (processor signature 06_1D) only. See Section 17.2.2 pub const MSR_EMON_L3_CTR_CTL6: u32 = 0x107d2; /// IFSB Latency Event Control Register (R/W) See Section 18.17, Performance Monitoring on 64-bit Intel Xeon Processor M...
Rust
0
self.epoch = epoch self.train_epoch() if self.iteration >= self.max_iter: break class Validator(Trainer): def __init__(self, cmd, cuda, model, criterion, val_loader, log_file, print_freq=1): super(Validator, self).__init__(cmd, cuda=cuda, model=model, criterion=...
Python
1
.text("Done") .alignment(ui::VAttach::Middle, ui::HAttach::Center) .attach(&mut *done_button); done_button.add_text(txt); done_button.add_click_func(|_, game| { game.screen_sys.pop_screen(); game.focused = true; ...
Rust
0
# latihan konversi satuan # celcius ke lainnya print("\n=======Celcius=======\n") celcius = float(input('Masukkan derajat Celcius : ')) reamur = (4 / 5) * celcius print('Dalam Reamur : ', reamur) fahrenheit = (9 / 5) * celcius + 32 print('Dalam Fahrenheit : ', fahrenheit) kelvin = celcius + 273 print('Dalam Kelvin...
Python
1
# src/scheduling.py def schedule_interview(candidate_name, preferred_date): """Placeholder function for scheduling interviews with a calendar API.""" print(f"Scheduling interview for {candidate_name} on {preferred_date}") # To be integrated with Google Calendar or another scheduling API.
Python
1
t Point { x: f64, y: f64, } #[derive(Debug, Serialize, Deserialize)] struct MyStruct { a: i64, b: Vec<String>, c: bool, d: Point, } pub fn ser() { let x = MyStruct { a: 42, b: vec!["hello".into(), "world".into()], ...
Rust
0
r (input, expected) in cases { assert_that!(format!("{}", &Qty::from_str(input)?.adjust_scale())) .is_equal_to(expected.to_string()); } Ok(()) } #[test] fn test_display() -> Result<(), Box<dyn std::error::Error>> { let cases = vec![ ("1k", "1....
Rust
0
from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.permissions import * from rest_framework.decorators import api_view, permission_classes @api_view(['GET']) @permission_classes([IsAuthenticated]) def admin_endpoint(request): ...
Python
1
mut self, fd: c_int) -> Self { self.inner.fd = fd; self } } impl Deref for ImportMemoryFdInfoKHRBuilder { type Target = vk::ImportMemoryFdInfoKHR; fn deref(&self) -> &Self::Target { &self.inner } } impl MemoryAllocateInfoNext for ImportMemoryFdInfoKHRBuilder {} impl MemoryAllocat...
Rust
0
83952775, 1724048463, 3932205985, 2088081195, 861756285, 1594614133, 2492863394, 722201448, 1550394506, 571927635, 2659445340, 2801880457, 3132851170, 165526633, 683594542, 3481462370, 2478620971, 2302899208, 3801656181, 1601163220, 3263774847, 1631993133, 1238601788, 1247510535, 1461290983, 4238127104, 212...
Rust
0
""" This module contains definitions of the HTTP protocol. """ FORM_CONTENT_TYPES = [ 'application/x-www-form-urlencoded', 'multipart/form-data' ] METHODS = { "get", "put", "post", "delete", "options", "head", "patch", "trace" }
Python
1
lass.validate(arg, configuration=configuration) @property def map(self) -> typing.Union[MapDict, schemas.Unset]: val = self.get("map", schemas.unset) if isinstance(val, schemas.Unset): return val return typing.cast( MapDict, val ) ...
Python
1
import random user_wins = 0 computer_wins = 0 # Options for the game options = ["rock", "paper", "scissors"] while True: # Get user input user_input = input("Type rock/paper/scissors or Q to quit: ").lower() if user_input == "q": # Exit the game break if user_input not in options: # Check...
Python
1
from teams import views from django.urls import path urlpatterns = [ path('', views.index, name='index'), path('list_players/', views.list_players, name='list_players'), path('create_player/', views.create_player, name='create_player'), ]
Python
1
(cstr_file).expect("C String to Rust String error!"); plan.into_json(File::create(&file).expect(&format!("Create json file: {:?} error", file))) .expect("Write to json error"); std::mem::forget(box_plan); } /// Define the target operator/parameter while setting certain parameters #[allow(dead_code)] #...
Rust
0
, }; use system_configuration::core_foundation::{ array::CFArray, base::{CFType, FromVoid, TCFType}, dictionary::CFDictionary, number::CFNumber, string::{CFString, CFStringRef}, }; use system_configuration::sys::{ dynamic_store_copy_specific::SCDynamicStor...
Rust
0
OCATIONS_BIT: u32 = 0x400; // Vulkan enum ImageAspectFlagBits pub type ImageAspectFlagBits = u32; pub const IMAGE_ASPECT_COLOR_BIT: u32 = 0x1; pub const IMAGE_ASPECT_DEPTH_BIT: u32 = 0x2; pub const IMAGE_ASPECT_STENCIL_BIT: u32 = 0x4; pub const IMAGE_ASPECT_METADATA_BIT: u32 = 0x8; // Vulkan enum SparseImageFormatFla...
Rust
0
domain: *const c_char, log_level: GLogLevelFlags, pattern: *const c_char, ); pub fn g_test_fail(); #[cfg(any(feature = "v2_70", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_70")))] pub fn g_test_fail_printf(format: *const c_char, ...); pub fn g_test_failed...
Rust
0
]; /// Nonprinting characters. const NONPRINT_TABLE: &'static [R] = &[ (0x00000, 0x0001F), (0x0007F, 0x0009F), (0x000AD, 0x000AD), (0x00600, 0x00605), (0x0061C, 0x0061C), (0x006DD, 0x006DD), (0x0070F, 0x0070F), (0x00890, 0x00891), (0x008E2, 0x008E2), (0x0180E, 0x0180E), (0x...
Rust
0
import const """ 运行模式 可以是追加模式append或覆盖模式overwrite append模式:仅可在sqlite启用时使用。每次运行每个id只获取最新的微博,对于以往的即使是编辑过的微博,也不再获取。 overwrite模式:每次运行都会获取全量微博。 注意:overwrite模式下暂不能记录上次获取微博的id,因此从overwrite模式转为append模式时,仍需获取所有数据 """ const.MODE = "overwrite" """ 检查cookie是否有效 默认不需要检查cookie 如果检查cookie,需要参考以下链接设置 config中science_date一定要确保测试号获得的微博...
Python
1
uid_map_file.write_all(uid_map.as_bytes())?; info!("[Host] wrote {} /proc/self/uid_map", uid_map); Ok(()) } fn gid_map(&self, gid: Gid) -> std::io::Result<()> { let mut setgroups_file = File::create("/proc/self/setgroups")?; setgroups_file.write_all(b"deny")?; let mut g...
Rust
0
//! - An interface to view and modify the status of fuses in an application, similar to the [official fuses package]. //! - A fast and configurable alternative implementation of the [electron-evil-feature-patcher] tool created by [<NAME>]. //! All patches it can perform are also exposed in this crate. See its READM...
Rust
0
nect(handler) self.verbose = verbose sock.send(request_body) return self.parse_response(sock.makefile()) finally: if sock: sock.close() def parse_response(self, response): p, u = self.getparser() response_body = '' w...
Python
1
position & attributes pub fn save_cursor_position_attributes() -> impl Display { "\x1B7" } /// Restore cursor position & attributes pub fn restore_cursor_position_attributes() -> impl Display { "\x1B8" } // Cursor Positioning // https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences#cu...
Rust
0
); let rotation = glm::vec3(0.5, 0.0, 1.0); let rotation2 = glm::vec3(0.0, 1.0, 0.0); model_view_matrix = glm::translate(&model_view_matrix, &translation); model_view_matrix = glm::rotate(&model_view_matrix, *square_rotation, &rotation); model_view_matrix = glm::rotate(&model_view_matrix, *square_rotation * 0...
Rust
0
use crate::{loader::error::LoaderError, testing_helpers::MockLoaderRequestBuilder, traits::check_loader}; use serde_yaml::Value; use test_case::test_case; macro_rules! yaml { ($($json:tt)+) => {{ serde_yaml::from_str( serde_json::to_string(&json![$($json)+]).unwrap().as_...
Rust
0
, 1.3, (0, 0, 0), 3, cv2.LINE_AA) character_label.config(text="Predicted Character: " + predicted_character) if predicted_character != 'NO HANDS' and not new_character_detected and start_time is not None: elapsed_time = time.time() - start_time if elapsed_time > 2.0: ...
Python
1
IM, #[doc = "0x13c - Internal. Only to be used through TI provided API."] pub shdw_ana_trim: SHDW_ANA_TRIM, _reserved4: [u8; 36usize], #[doc = "0x164 - Flash number"] pub flash_number: FLASH_NUMBER, _reserved5: [u8; 4usize], #[doc = "0x16c - Flash coordinate"] pub flash_coordinate: FLASH...
Rust
0
[tokio::main(flavor = "current_thread")] async fn main() -> ! { if unsafe { libc::getuid() != 0 } { eprintln!("You must be root to use eBPF!"); std::process::exit(1); } let mut loaded = Loader::load(include_bytes!(concat!( env!("OUT_DIR"), "/target/bpf/programs/biolatpcts/bi...
Rust
0
y = entity.is_valid_stream sha_by_index = entity.index().sha for index in range(entity.index().size()): try: assert pack_verify(sha_by_index(index), use_crc=crc) count += 1 except UnsupportedOperation...
Python
1
_queries = list(set(range(len(dataset))) - set(train_choices)) for estimators, num_samples in experiments: samples = [] for _ in range(num_samples): qid = random.sample(test_queries, 1) label = int(dataset.labels[qid].item()) log_action, log_action_probabilities =...
Python
1
impl SubscribeFilter { pub fn new(path: String, qos: QoS) -> SubscribeFilter { SubscribeFilter { path, qos } } pub fn len(&self) -> usize { // filter len + filter + options 2 + self.path.len() + 1 } fn write(&self, buffer: &mut BytesMut) { ...
Rust
0
<'de>, { let s: String = Deserialize::deserialize(deserializer)?; let mut array = [0 as u8; GRAFFITI_BYTES_LEN]; let start = s .as_str() .get(2..) .ok_or_else(|| D::Error::custom("string length too small"))?; let decoded: Vec<u8> = hex::decode(&start).map_err(D::Error::custom)?;...
Rust
0
(x, y) => { x.to_css(dest)?; if y != x { dest.write_str(" ")?; y.to_css(dest)?; } Ok(()) } } } } // https://www.w3.org/TR/css-backgrounds-3/#background-attachment enum_property!(BackgroundAttachment, Scroll, Fixed, Local ); impl Default for Backgro...
Rust
0
.margin(5) .set_all_label_area_size(50) .build_cartesian_2d(0f32..7f32, 0f32..3f32)?; chart.configure_mesh() .disable_mesh() .x_desc("Petal Length") .y_desc("Petal Width") .x_label_formatter(&|v| format!("{:.1}", v)) .y_label_formatter(&|v| format!("{:.1}"...
Rust
0
ct Todo { id: uuid::Uuid, task: String, priority: PriorityLevel, created_at: DateTime<Utc>, expired_at: Option<DateTime<Utc>>, completed_at: Option<DateTime<Utc>>, } impl Todo { pub fn new(task: String, priority: PriorityLevel, expired_at: Option<DateTime<Utc>>) -> Self { Self { ...
Rust
0
origin: lookfrom, horizontal: u * viewport_w * focus_dist, vertical: v * viewport_h * focus_dist, lower_left_corner: lookfrom - u * viewport_w * focus_dist / 2.0 - v * viewport_h * focus_dist / 2.0 - w * focus_dist, ...
Rust
0
.scope .get(0) .ok_or_else(|| OckamError::InvalidParameter.into()) .and_then(|idx| Index::decode(idx))?; // Peel off this layer of message let inner = msg.body().peel()?; match self.compare_index(index) { IndexState::Low => { w...
Rust
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Voice Typer 应用打包脚本 支持 macOS 和 Windows 平台 """ import os import sys import subprocess import shutil import logging from pathlib import Path import argparse # 初始化 Qt 应用程序 from PySide6.QtWidgets import QApplication app = QApplication([]) # 设置日志 logging.basicConfig(level=...
Python
1
# needs sage.modules [p[], p[1], 3/2*p[1, 1] + 1/2*p[2], 19/6*p[1, 1, 1] + 1/2*p[2, 1] + 1/3*p[3], 193/24*p[1, 1, 1, 1] + 3/4*p[2, 1, 1] + 5/8*p[2, 2] + 1/3*p[3, 1] + 1/4*p[4], 907/40*p[1, 1, 1, 1, 1] + 19/12*p[2, 1, 1, 1] + 5...
Python
1
uins once again are the best hockey team in the NHL.", // ... // error[E0061]: this function takes 1 argument but 0 arguments were supplied // --> src/main.rs:6:5 // | // 6 | returns_summarizable(); // | ^^^^^^^^^^^^^^^^^^^^-- supplied 0 arguments // | | // | expected 1 argument // |...
Rust
0
the digits to create the highest possible number. * */ pub fn descending_order(x: u64) -> u64 { let string: String = x.to_string(); let mut char_vec: Vec<char> = string.chars().collect(); char_vec.sort(); char_vec.reverse(); let vec_to_string: String = char_vec.into_iter().collect(); ...
Rust
0
yer.weight.numel() conv_w = torch.from_numpy(weights[ptr : ptr + num_w]).view_as( conv_layer.weight.data ) conv_layer.weight.data.copy_(conv_w) ptr += num_w print("loading weight {}".format(conv_layer)) def _BuildCSPD...
Python
1
/// A chat invite link #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct TMeUrlTypeChatInvite { #[doc(hidden)] #[serde(rename(serialize = "@extra", deserialize = "@extra"))] extra: Option<String>, #[serde(rename(serialize = "@client_id", deserialize = "@client_id"))] client_id: Op...
Rust
0
of the [examples](https://github.com/boltlabs-inc/dialectic/tree/main/dialectic/examples) are written to be backend-agnostic, so taking a look at them may help if you get stuck. Once you've got a channel, here's what you can do: | [`Session!`](crate::Session@macro) Macro Invocation | Session Type (`S`) | Channel O...
Rust
0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models, api class AccountJournal(models.Model): _inherit = "account.journal" l10n_cl_sequence_ids = fields.Many2many( 'ir.sequence', 'l10n_cl_journal_sequence_rel', 'journal_id', 'sequence_id', string...
Python
1
v_mat) } } use sled::IVec; fn main() { let tree = sled::open("my_db").unwrap(); tree.insert(b"rick", b"123 456 789".to_vec()).unwrap(); assert_eq!(tree.get(b"rick"), Ok(Some(IVec::from(b"123 456 789")))); let result = tree.get(b"rick"); println!("{:?}", result); let k1 = "bill"; le...
Rust
0
""" Bingo card - 5x5 COLUMNS: 0. Values 1-15 1. 16-30 2. MIDDLE 31-45 3. 46-60 4. 61-75 col_start + random.uniform(0,14) -- col_start + SortedSet(0,14) O((n)log(n)) Matrix, every value is randomly generated unique values ------ Time complexity: O(5 * 5 log (5)) = O(1) Space complexity: O(15 + log (5)) = O(1) """ f...
Python
1
@unittest.skip(reason= 'Batching needs to be properly figured out first for this pipeline.') def test_inference_batch_single_identical(self): pass
Python
1
""" Code to convert mat file with structures into json files Created on : 5/18/15 3:27 PM by rama """ import scipy.io as io import os import re import json import string import pdb pathToMat = '/Users/rama/Research/data/pyCider/' matfile = 'pascal_cands.mat' jsonfile = 'pascal_cands' data = io.loadmat(os.path.join(p...
Python
1
2): This variable was originally local, but now is static to prevent stack overflow. static mut MANIFEST: MaybeUninit<Manifest> = MaybeUninit::uninit(); let mut manifest = MANIFEST.get_mut(); let mut params: BootParams = MaybeUninit::uninit().assume_init(); // TODO(HfO2): doesn't need to lock, actually...
Rust
0
config={"callbacks": run_manager.get_child()} ) @property def _chain_type(self) -> str: """Return the chain type.""" return "retrieval_qa" class VectorDBQA(BaseRetrievalQA): """Chain for question-answering against a vector database.""" vectorstore: VectorStore = Field(exclud...
Python
1
Ok(AmlParseType { val: AmlValue::IntegerConstant(0xFFFF_FFFF_FFFF_FFFF), len: 3 + search_pkg.len + first_operand.len + second_operand.len + start_index.len }) } fn parse_def_from_bcd(data: &[u8], ctx: &mut AmlExecutionContext) -> ParseResult { match ctx.state { ...
Rust
0
> <OP_CHECKMULTISIG> fn is_opcheckmultisig(&self) -> bool { if let Ok(res_option) = self.get_opcheckmultisig_n_m() { if res_option.is_some() { return true; } } false } /// Returns a tuple of `(n, m)` (`n-of-m`) of the OP_CHECKMULTISIG script. ...
Rust
0
import requests import json def print_korean_result(response_json): emotion_map = ['기쁨', '슬픔', '분노', '두려움', '혐오', '놀람', '중립'] music_map = { 'tempo_bpm': '템포 (BPM)', 'key': '키', 'mode': '모드', 'dynamics': '다이내믹스', 'chord_progression': '코드 진행', 'complexity': '복잡성' ...
Python
1
erKind::NONE, &mut rr, &mut lw); tokio::pin!(l2r); tokio::pin!(r2l); let _ = future::select(l2r, r2l).await; }); } }); tokio::task::yield_now().await; let context = Context::new_shared(ServerType::Local); let mut connect_opts = Con...
Rust
0
import spacy import re from spacy.matcher import PhraseMatcher import pymorphy3 #Хрень которая переводит в ед число им падежа с большой буквы (вспоминаем уроки русского языка 4 класс) def to_nominative_singular(word): word = word.split(" ") morph = pymorphy3.MorphAnalyzer() # Умный чел который умеет определ...
Python
1
import sys sys.setrecursionlimit(10**6) def solution(n, m, x, y, r, c, k): # 사전순 이동 순서 (d -> l -> r -> u) directions = {'d': (1, 0), 'l': (0, -1), 'r': (0, 1), 'u': (-1, 0)} order = ['d', 'l', 'r', 'u'] # 사전순 정렬 answer = [] # 맨해튼 거리 계산 min_dist = abs(x - r) + abs(y - c) # 도달할 수 없는...
Python
1
lf) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(...
Rust
0
E_WATCHDOG_TIMEOUT: i32 = -2145386391i32; #[repr(C)] #[doc = "*Required features: `\"Win32_Networking_BackgroundIntelligentTransferService\"`*"] pub struct BG_FILE_INFO { pub RemoteName: ::windows_sys::core::PWSTR, pub LocalName: ::windows_sys::core::PWSTR, } impl ::core::marker::Copy for BG_FILE_INFO {} impl :...
Rust
0
quence. if start_position != current_position: leading_text = string[current_position:start_position] parts.append(percent_encoded(leading_text, safe=safe)) # Add the '%xx' escape sequence. parts.append(matched_text) current_position = end_position # Add any...
Python
1
]+1)/2.0) # action = action.at[:,:3].set((action[:,:3]+1)/2.0) # action = action.at[:,3].set((action[:,3]+1)*3.0) action = action.at[:,1].set(0.0) # Set do_shoot = 1.0 AFTER the scaling action = action.at[:,0].set(1.0) # Set shoot_last_enemy to 0.0 for first agent ...
Python
1
all_tools, index_cls=VectorStoreIndex, ) tool_retriever = obj_index.as_retriever(similarity_top_k=2,verbose=True) tools_needed = tool_retriever.retrieve("What is the Adaptive retrieval in the c-RAG?") print('Tools needed to answer the question:') for tool in tools_needed: print(tool.metadata.name) ...
Python
1
## ## This file is part of the libsigrokdecode project. ## ## Copyright (C) 2019 Stephan Thiele <stephan.thiele@mailbox.org> ## ## 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 ...
Python
1
write!(f, "{}", self.as_str()) } } impl fmt::Display for JS_KEY_STR { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.as_str()) } } #[derive(Debug, Default)] pub struct Video { id: String, info: VideoInfo, config: VideoConfig, initialized: bool, sourc...
Rust
0
gain. return self._vcs_version vcs_version = self.call_vcs_version() self._vcs_version = vcs_version return vcs_version def get_remote_call_options(self) -> CommandArgs: """Return options to be used on calls to Subversion that contact the server. These options ...
Python
1
#!/usr/bin/env python """ """ from functools import partial from bacpypes.debugging import bacpypes_debugging, ModuleLogger from bacpypes.consolelogging import ArgumentParser from bacpypes.core import run_once from bacpypes.service.detect import DetectionAlgorithm, monitor_filter from bacpypes.object import Analog...
Python
1
or( f"Operation failed: {decoded_message}" ) return print(decoded_message) return exit_code except Exception as e: ws.sock.close() self._error = WebSocketOperationError(f"Error processing message: {str(e)}") ...
Python
1
# Copyright 2023 osiworx # 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, software #...
Python
1
n::Reannounce, ); work.push(future); } let work = futures::future::join_all(work).await; for i in work.into_iter() { let _ = i?; } info!("maintain done"); Ok(()) }; loop { ...
Rust
0
a, mut b| async move { a.write_all(b"test").await.unwrap(); let mut tmp = [0; 4]; b.read_exact(&mut tmp).await.unwrap(); assert_eq!(&tmp[..], b"test"); }) .await } #[tokio::test] async fn test_transfer_after_close() { symmetric(|handle, mut a, mut b| async move { Asy...
Rust
0
c_ie_1(&self) -> bool { **self == TEXC_IE_A::TEXC_IE_1 } } impl core::ops::Deref for TEXC_IE_R { type Target = crate::FieldReader<bool, TEXC_IE_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `TEXC_IE` writer - Trigger Exception Interrupt Enable"] ...
Rust
0
ef(start_offset + 1, INVALID) == '?' { self.with_offset(start_offset); Some(self.make_markup_suffix()) } else { None }; (hashbang, suffix) } pub fn scan_header(&mut self) -> (Option<TF::Token>, Option<(TF::Token, Option<TF::Token>)>) { ...
Rust
0