text
string
label_name
string
labels
int64
)) centers_.append(center) scales_.append(scale) parts_.append(part) Ss_.append(S24) openposes_.append(openpose) # store the data struct if not os.path.isdir(out_path): os.makedirs(out_path) out_file...
Python
1
tions( ptr: *const CorpusStorage, corpus_name: *const libc::c_char, component_type: AnnotationComponentType, component_name: *const libc::c_char, component_layer: *const libc::c_char, list_values: bool, only_most_frequent_values: bool, ) -> *mut Matrix<CString> { let cs: &CorpusStorage =...
Rust
0
"_zend_expected_type_Z_EXPECTED_LONG", "_zend_expected_type_Z_EXPECTED_OBJECT", "_zend_expected_type_Z_EXPECTED_RESOURCE", "_zend_expected_type_Z_EXPECTED_STRING", "_zend_new_array", "_zval_struct__bindgen_ty_1", "_zval_struct__bindgen_ty_2", "ext_php_rs_executor_globals", "ext_php_rs_ph...
Rust
0
dexVec<BasicCoverageBlock, Vec<BasicCoverageBlock>>, pub predecessors: IndexVec<BasicCoverageBlock, Vec<BasicCoverageBlock>>, dominators: Option<Dominators<BasicCoverageBlock>>, } impl CoverageGraph { pub fn from_mir(mir_body: &mir::Body<'tcx>) -> Self { let (bcbs, bb_to_bcb) = Self::compute_basic_...
Rust
0
from_slice(&src[src_index..src_index + count as usize]); src_index += count as usize; dest_index += count as usize; } } dest } use std::fmt::{Show,Formatter}; use std::fmt; use std::hash::Hasher; use std::hash::sip::SipHasher; use std::io::MemWriter; use std::str; use serialize::...
Rust
0
ttr) }; let value = &attr.value; let cast = &attr.class.cast; let slice = unsafe { ByteSlice::from_raw_parts(*data, len as usize) }; let res; let verr; let result = if let Some(cast) = cast.as_ref() { res = cast.cast(attr, &slice); res.as_ref() } else if let Some(val) = valu...
Rust
0
oss, batch_size=testing_count, shuffle=False, num_workers=0) ######################################################## TRAINING ##################################### # print('--------training processing-------') count, best_hr = 0, 0 model = Classifier(embed_dim=factor_num, out_dim=1) ...
Python
1
0: with open(snapshot_pkl, 'wb') as f: pickle.dump(snapshot_data, f) # Evaluate metrics. training_set_kwargs_tmp = training_set_kwargs.copy() training_set_kwargs_tmp['load_obj'] = False if (snapshot_data is not None) and (len(metrics) > 0) and (cur_ti...
Python
1
_tensorboard_invalid_configuration_handling(self) -> None: """Test tensorboard invalid configuration handling.""" invalid_configs = [ {"port": 80}, # Privileged port {"port": 70000}, # Port out of range {"host": ""}, # Empty host {}, # Missing required...
Python
1
s::raw::c_char; } extern "C" { pub fn Tcl_ChannelVersion(chanTypePtr: *const Tcl_ChannelType) -> Tcl_ChannelTypeVersion; } extern "C" { pub fn Tcl_ChannelBlockModeProc(chanTypePtr: *const Tcl_ChannelType) -> Tcl_DriverBlockModeProc; } extern "C" { pub fn Tcl_ChannelCloseProc(chanTypePtr: *const Tcl_...
Rust
0
# Forward Pass x = [1.0, -2.0, 3.0] # input values w = [-3.0, -1.0, 2.0] # weights b = 1.0 # bias # Multiplying inputs by weights xw0 = x[0] * w[0] # 1.0 * -3.0 xw1 = x[1] * w[1] # -2.0 * -1.0 xw2 = x[2] * w[2] # 3.0 * 2.0 print("Inputs * weights: ", xw0, xw1, xw2) # -3.0, 2.0, 6.0 # Adding weighted inputs and a bi...
Python
1
new(span.clone(), ExpX::Binary(BinaryOp::Eq, x_var, exp.clone())); Spanned::new(span.clone(), StmX::Assume(eq)) } fn get_function(ctx: &Ctx, expr: &Expr, name: &Path) -> Result<Function, VirErr> { match ctx.func_map.get(name) { None => err_string(&expr.span, format!("could not find function {:?}", &nam...
Rust
0
import torchvision.datasets as dsets if __name__ == "__main__": dsets.MNIST(root='./data', download=True) dsets.KMNIST(root='./data', download=True)
Python
1
import sqlite3 def conectar(): try: conexion = sqlite3.connect('contactos.db') print('Se ha conectado a la base de datos') return conexion except sqlite3.Error as err: print('Ha ocurrido un error', err) def crear_tabla(conexion): cursor = conexion.cursor() sentencia_s...
Python
1
ssful_launches: i32, pub failed_launches: i32, pub pending_launches: i32, pub consecutive_successful_landings: i32, pub successful_landings: i32, pub failed_landings: i32, pub attempted_landings: i32, pub info_url: Option<String>, pub wiki_url: String, pub logo_url: String, pub i...
Rust
0
d during leakchecks because the third or fourth iteration of the # test hangs on CPython 2/posix for some reason, likely due to # the use of _close_on_teardown keeping something alive longer than intended. # cf test__makefile_ref with self.assertRaises(ssl.SSLError): super(Te...
Python
1
nto::into) } } /// snap `value` to previous `step` multiple from `start` pub fn snap_prev(start: f64, step: f64, value: f64) -> f64 { start + ((value - start) / step).floor() * step } /// snap `value` to next `step` multiple from `start` pub fn snap_next(start: f64, step: f64, value: f64) -> f64 { start +...
Rust
0
, Clone, Debug, PartialEq, JsonSchema)] pub struct InitMsg {} #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum SwapDataEndpointMsg { ReceiveSwapData { asset_in: Asset, asset_out: Asset, account: HumanAddr, }, } #[derive...
Rust
0
import pygame, random, sys from read_colors import read_color_parameters from microbe import microbe from food import SimulatedEvolution # Setup pygame.init() # Declarations size = 800 width = 800 height = 800 cellsize = 3 microbe_size=6 food_spawn_per_tick = 1000 fps = 100 # Color read = read_color_parameters() read...
Python
1
1. 验证概率配置和数值范围配置是否有效 2. 生成[0.0,1.0)区间的均匀分布随机数 3. 根据随机数选取对应的数值区间 4. 按区间策略在选定区间内生成具体数值 5. 对结果进行舍入处理 异常: ValueError: 概率未配置或数值范围配置为空时抛出 返回: float: 经过区间策略计算和舍入处理后的最终数值 """ # 前置校验:确保概率配置和数值范围已正确初始化 if not self.get_probabilitie...
Python
1
iommu_va_data_reg: crate::Reg<iommu_va_data_reg::IOMMU_VA_DATA_REG_SPEC>, #[doc = "0x198 - IOMMU Virtual Address Configuration Register"] pub iommu_va_config_reg: crate::Reg<iommu_va_config_reg::IOMMU_VA_CONFIG_REG_SPEC>, _reserved57: [u8; 0x64], #[doc = "0x200 - IOMMU PMU Enable Register"] pub iom...
Rust
0
import gymnasium as gym import numpy as np import matplotlib.pyplot as plt from gym_quad.envs.mujoco import UAVQuadBase from gym_quad.controller import HTNMPC # Define the length of the cube's side side_length = 2 # Calculate the half side to center the cube at the origin half_side = side_length / 2 # Define the ve...
Python
1
import sqlite3 def connect_to_db(): conn = sqlite3.connect("chatbot.db") cursor = conn.cursor() return conn, cursor conn, cursor = connect_to_db() print("Database Connected!")
Python
1
} superblocks.push(BtrfsSuperblock::for_bytes( &data[btrfs_device.superblock_offset() ..btrfs_device.superblock_offset() + mem::size_of::<BtrfsSuperblockData>()], )); devices.insert(btrfs_device.device_id(), btrfs_device); } ...
Rust
0
for line in response.split('\n'): if line.strip().startswith('{'): in_json = True if in_json: json_lines.append(line) if in_json and line.strip().endswith('}'): break ...
Python
1
else: trends = {'cpu_trend': 0, 'memory_trend': 0, 'error_rate_trend': 0} # 生成建議 recommendations = self._generate_health_recommendations(current_metrics, trends) return { 'timestamp': current_metrics.timestamp.isoformat(), 'current_s...
Python
1
if k == key { *self = KeyTracker::NoKey; } } key_press_iter(0, key) } pub fn update(&mut self, dt: f32) -> KeyPressIterator { if let KeyTracker::OneKey(key, ref mut d) = *self { *d -= dt; let count = (1.0 - *d / KEY_REPEAT_SPA...
Rust
0
import numpy as np import cv2 as cv video_path = "videos/jog.mp4" cap = cv.VideoCapture(video_path) # take first frame of the video ret, frame = cap.read() # setup initial location of window x, y, w, h = 625, 375, 75, 125 # simply hardcoded the values track_window = (x, y, w, h) # Step 1: Extract ROI roi = frame[...
Python
1
# Copyright (c) 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 appli...
Python
1
# Convert to numpy arrays for analysis time_array = np.array(time_history["time"]) temperature_array = np.array(time_history["temperature"]) # Prepare final results dictionary results = { "time": time_array, "tempera...
Python
1
ss over SOCKS5 /// /// # Note /// /// Current SOCKS5 support is provided via blocking IO. #[cfg(feature = "socks")] fn socks5(addr: SocketAddr) -> ::Result<Self> { Ok(ProxyScheme::Socks5 { addr, auth: None, remote_dns: false, }) } /// ...
Rust
0
lf.cos_2k_alpha[2] + cos_theta_o * self.sin_2k_alpha[2]; cos_theta_op = cos_theta_o * self.cos_2k_alpha[2] - sin_theta_o * self.sin_2k_alpha[2]; } else { sin_theta_op = sin_theta_o; cos_theta_op = cos_theta_o; } // sample $M_p$ to compute $\thetai$ u[1...
Rust
0
} }), (Unparsed(StatementToken::FieldPointerAccess), |l, r| { if let (StatementElement::Var(lhs), StatementElement::Var(rhs)) = (&l, &r) { //Because of the l -> r pattern, these are guaranteed to be Cow::Borrowed, so cloning isn't too dumb Ok(StatementElement::FieldPointerAccess( lhs.clone...
Rust
0
headers: (0,0);(0,1);(0,2) import pandas as pd df = pd.DataFrame({ 'Basic Indicators': ['Average Household Size', 'Percentage of female-headed households', 'Percentage of households with a modern roof', 'Percentage of households with modern floor', 'Percentage of households with modern walls', 'Percentage of hous...
Python
1
hyper_linked_para_title, self.db) # Sometimes article titles are updated over times but the hyperlinked titles are not. e.g., Winds <--> Wind # in our current database, we do not handle these "redirect" cases and thus we cannot recover. # If we cannot retrieve th...
Python
1
", self.status, self.body) } } impl Error for HttpResponseError { fn source(&self) -> Option<&(dyn Error + 'static)> { Some(self) } } <reponame>tov/chi-rust-02202019 //! Testing my buggy quicksort. fn partition<T: Ord>(slice: &mut [T]) -> usize { let pivot = slice.len() - 1; let mut i = 0;...
Rust
0
ary expressions, and more. //! //! See the [ECMAScript spec](https://www.ecma-international.org/ecma-262/5.1/#sec-11). use super::decl::{arrow_body, class_decl, formal_parameters, function_decl, method}; use super::pat::pattern; use super::util::*; use crate::{ ast::{BinExpr, BinOp, Expr, GroupingExpr, UnaryExpr},...
Rust
0
import inspect from hgq import layers from hgq.config import QuantizerConfigScope from ..initializers import QInitializer as QInitializer # TODO: use qkeras initializers when called from here from ..quantizers import get_quantizer kw_map = { 'kq_conf': ('kernel_quantizer', 'kq'), 'bq_conf': ('bias_quantizer...
Python
1
from __future__ import annotations import pluggy project_name = "sdgx.data_connector" """ The entry-point name of this extension. Should be used in ``pyproject.toml`` as ``[project.entry-points."{project_name}"]`` """ hookimpl = pluggy.HookimplMarker(project_name) """ Hookimpl marker for this extension, extension mo...
Python
1
# Python Program to implement merge sort using # multi-threading import threading MAX=20 # number of threads THREAD_MAX = 4 A = [0] * MAX part = 0 # merge function for merging two parts def Merge(low, mid, high): L = A[low:mid+1] R = A[mid+1:high+1] # n1 is size of left part and n2 is size # of ri...
Python
1
API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [trig2_chain_1_0](trig2_chain_1_0) module"] pub type TRIG2_CHAIN_1_0 = crate::Reg<u32, _TRIG2_CHAIN_1_0>; #[allow(missing_docs)] #[doc(hidden)] pub struct _TRIG2_CHAIN_1_0; #[doc = "`read()` method returns [trig2_chai...
Rust
0
def saudacao(): print("Olá Mundo!")
Python
1
class GovernanceContract: def __init__(self): self.proposals = {} self.votes = {} self.proposal_count = 0 def create_proposal(self, description): self.proposal_count += 1 proposal_id = self.proposal_count self.proposals[proposal_id] = { "description":...
Python
1
#[derive(Clone, PartialEq, ::prost::Message)] pub struct PartOfSpeech { /// The part of speech tag. #[prost(enumeration = "part_of_speech::Tag", tag = "1")] pub tag: i32, /// The grammatical aspect. #[prost(enumeration = "part_of_speech::Aspect", tag = "2")] pub aspect: i32, /// The grammati...
Rust
0
ug_struct.field("extent_root_gen", &self.extent_root_gen); debug_struct.field( "fs_root", &NakedString::from(format!("0x{:x}", self.fs_root)), ); debug_struct.field("fs_root_gen", &self.fs_root_gen); debug_struct.field( "dev_root", &Nake...
Rust
0
# Contenido para: inspector.py import pkgutil import importlib import inspect import pysui # El paquete que queremos inspeccionar def inspect_package(package): """ Recorre un paquete de Python e imprime sus módulos y su contenido público. """ print(f"--- Inspeccionando el paquete: {package.__name__} -...
Python
1
{ rng: ThreadRng, sprite_sheet: Image, orcs: Vec<Orc>, spawn_timer: i32, } impl GameState { fn new(ctx: &mut Context) -> Self { let mut rng = rand::thread_rng(); let sprite_sheet = Image::from_file(ctx, "examples/res/0x72_dungeon_ii.png") .expect("Could not load sprite ...
Rust
0
}; #[cfg(target_os = "cuda")] use necsim_core::impl_report; #[allow(clippy::module_name_repetitions)] #[derive(rust_cuda::common::RustToCuda, rust_cuda::host::LendToCuda)] pub struct EventBuffer<ReportSpeciation: Boolean, ReportDispersal: Boolean> { #[r2cEmbed] speciation_buffer: CudaExchangeBuffer<Option<Spe...
Rust
0
from enum import StrEnum from typing import Optional from pydantic import BaseModel, ConfigDict from fitness_app.users.schemas import UserCreateSchema class UserGoal(StrEnum): BE_ACTIVE = "BE_ACTIVE" BE_STRONG = "BE_STRONG" LOSE_WEIGHT = "LOSE_WEIGHT" class FitnessLevel(StrEnum): NOVICE = "NOVICE"...
Python
1
Marker { pos, bomb: DropBomb::new("Marker must be either completed or abandoned") } } /// Finishes the syntax tree node and assigns `kind` to it, /// and mark the create a `CompletedMarker` for possible future /// operation like `.precede()` to deal with forward_parent. pub(crate) fn complete...
Rust
0
[cfg(target_arch = "spirv")] use spirv_std::num_traits::Float; #[derive(Copy, Clone)] #[allow(unused_attributes)] #[spirv(block)] pub struct ShaderConstants { pub width: u32, pub height: u32, pub time: f32, } pub fn saturate(x: f32) -> f32 { x.max(0.0).min(1.0) } pub fn pow(v: Vec3, power: f32) -> Ve...
Rust
0
"""BlackRoad utilities."""
Python
1
z * z).sqrt()).atan2(x) * 180.0) / PI; // let mut pgyro = xx * 0.00005; // let mut pgyroy = yy * 0.00005; // let CFILTIER_COEF = 0.95; // let mut angle: f32 = -4.7; // let angle = ((CFILTIER_COEF) * ((angle) + pgyro) + (1.0 - CFILTIER_COEF) * (pitch)); // iprintln!(&mut...
Rust
0
#!/usr/bin/env python3 # ####################################################################################### # # Copyright (c) KylinSoft Co., Ltd. 2024. All rights reserved. # SecureGuardian is licensed under the Mulan PSL v2. # You can use this software according to the terms and conditions of the Mulan PSL v2. #...
Python
1
n params. pub fn gamma( &self, shape: &[usize], shape_param: f64, scale: f64, ) -> ndarray::Array<T, ndarray::IxDyn> { let dist = rand_distr::Gamma::new(shape_param, scale).unwrap(); self.gen_random_array(shape, dist) } ...
Rust
0
turn_command = torch.tensor([-1.0, 0.0, 1.0]) obs, robot_obs = l_env.observe(turn_command) obs = obs.reshape(1, -1) begin_policy = time.perf_counter() action = l_policy(obs) assert ...
Python
1
{ assert_eq!( Entity::Face { vertices: vec!( FaceVertex::new2(0, Some(1), Some(2)), FaceVertex::new2(3, Some(4), Some(5)), FaceVertex::new2(6, Some(7), Some(8)), FaceVertex::new2(9, Some(10), Some(11)), FaceVertex::n...
Rust
0
"acc", "a0", "a1"]; pub const ADD_REG_REG: u8 = 0x01; pub const ADD_REG_VAL: u8 = 0x02; pub const SUB_REG_REG: u8 = 0x03; pub const SUB_REG_VAL: u8 = 0x04; pub const INC_REG: u8 = 0x05; pub const DEC_REG: u8 = 0x06; pub const ADD_REG_AREG: u8 = 0x07; pub const SUB_REG_AREG: u8 = 0x08; ...
Rust
0
s.Forbidden` if the signatures don't match """ # Retrieve the received signature from the data received_signature = notification_data.get('sign') if not received_signature: _logger.warning("received notification with missing signature") raise Forbidden() ...
Python
1
['Nd'].Z: 14, Element['Pm'].Z: 15, Element['Sm'].Z: 16, Element['Dy'].Z: 20, Element['Ho'].Z: 21, Element['Lu'].Z: 11, Element['Hf'].Z: 12, Element['Ta'].Z: 13, Element['W'].Z: 12, Element['Re'].Z: 15, Element['Os'].Z: 14, Element['Ir'].Z: 15, Element['Pt'].Z: 16, Element['...
Python
1
import win32com.client import os import speech_recognition as sr import webbrowser import datetime speaker = win32com.client.Dispatch("SAPI.SpVoice") def say(text): speaker.Speak(f"{text}") def takecommand(): r = sr.Recognizer() with sr.Microphone() as source: r.pause_threshold = 1 audio ...
Python
1
ify \ user-modify-playback-state playlist-modify-public \ playlist-modify-private ugc-image-upload", ) .build() .unwrap(); let mut spotify = SpotifyBuilder::default() .credentials(creds) .oauth(oauth) .bui...
Rust
0
enter_poses( extrinsics, method="vertical" ) point_cloud = transform_rigid(homogenize_points(point_cloud), transform)[ ..., :3 ] # Scale the rotated point_cloud to unit cube positions = point_cloud # 99.6% of points are within 3std in all directi...
Python
1
'''Sandbox execution command implementations.''' import typer import subprocess from pathlib import Path from typing import List, Optional from .. import utils from ..core import sandbox_manager app = typer.Typer( name="sandbox", help="Run AI agents in a controlled, policy-enforced environment." ) @app.comm...
Python
1
p similar to the `Balance` one. Shares get(fn shares): Vec<(T::AccountId, u64)>; } add_extra_genesis { /// The shareholders to initialize the SettCurrencys with. /// Shares are basically SettPay Slots. The Shares are the entities that receive newly minted settcurrencies/stablecoins. config(sharehol...
Rust
0
y"), "header".into() => MatchingRuleCategory::empty("header"), "query".into() => MatchingRuleCategory::empty("query") } }.is_empty()).to(be_true()); } #[test] fn rules_are_not_empty_when_there_is_a_nonempty_category() { expect!(MatchingRules { rules: hashmap!{ "body".i...
Rust
0
, sabbath, sadism, salvage, salvageoff, sanctify, scatter, scramble, scramblespam, serendipity, shardgolem, shtriga, shuffle3, silence, sing, singularity, sinkhole, siphon, siphonactive, siphonstrength, skeleton, skull, skyblitz, slow, snipe, solar, sosa, soulcatch, spores, sskin, staff, ...
Rust
0
entrypoint=os.path.join(os.path.dirname(__file__), "driver.py"), args=[ "--job_id", str(job_id), "--data_root", self.data_root, "--runtime_ctx_path", runtime_ctx.runtime_ctx_path, ...
Python
1
act_bm_stone_earth_01.nif", 0x2521_1578, 0x5E22_CCBE), (r"meshes\f\act_bm_stone_water_01.nif", 0x2521_1578, 0xCC73_4762), (r"meshes\f\active_bm_forcefield.nif", 0x2529_013D, 0x7E66_1E6F), (r"meshes\f\active_glacier_wind.nif", 0x2529_013D, 0xC98D_D917), (r"meshes\x\bm_ex_ice_exit03_ice.nif", 0x261D_0...
Rust
0
.cross_zone_load_balancing), repr(self.access_log), repr(self.connection_draining), repr(self.connecting_settings)) def startElement(self, name, attrs, connection): if name == 'CrossZoneLoadBalancing': return self.cross_zone_load_balancing if name == ...
Python
1
written on R2000+ assert_contains( &drawing, vec!["1001", "IXMILIA", "1040", "1.1"].join("\r\n"), ); } } } #[test] fn normalize_mline_styles() { let mut file = Drawing::new(); file.clear(); ...
Rust
0
from PIL import Image import numpy as np from path_finder import PathFinder class RGB_diff: def __init__(self): self.path_finder = PathFinder() self.TCX_BC_dir = self.path_finder.tcx_BC_directory_path self.codes = [ "11-0601", "11-4302", "13-4305...
Python
1
import datetime from typing import Optional import beanie import pydantic import pymongo from beanie import PydanticObjectId class SearchRecord(beanie.Document): created_date: datetime.datetime = pydantic.Field(default_factory=datetime.datetime.now) episode_date: Optional[datetime.datetime] = None episod...
Python
1
task = self.preparing.take().expect("Must `begin()` a task creation before ending it!"); let mut tasks = self.tasks.entry(task.product.clone()).or_insert_with(|| Vec::new()); assert!( !tasks.contains(&task), "{:?} was double-registered for {:?}", task, task.product, ); task.clau...
Rust
0
f.vtfs)}I", *self.vtfs) write_struct(file, f"{len(self.vmts)}H", *self.vmts) materials_list = [self.materials[o] for o in sorted(self.materials)] # maintain order file.write(b"\0".join(m.encode("ascii") for m in materials_list) + b"\0") file.write(b"".join([c.as_bytes() ...
Python
1
init().unwrap()); chip.v[5] = 14; chip.run_op_code(0x8506); assert_eq!(chip.v[0xF], 0); assert_eq!(chip.v[5], 7); } #[test] fn test_8xy7() { let mut chip = Chip8::new(&sdl2::init().unwrap()); chip.v[1] = 0x1; chip.v[2] = 0x2; chip.run_op_cod...
Rust
0
# -*- coding: utf-8 -*- import pygcb def CreateDBObject(): dbObj=pygcb.tcStoresDBObject() dbObj.mzClass='S-400 Triumf Store' dbObj.natoClass='S-400 Triumf Store' dbObj.mnModelType=0 dbObj.mnType=0 dbObj.cost=0.000000 dbObj.weight_kg=0.000000 dbObj.volume_m3=0.000000 dbObj.initialYear...
Python
1
ypes::BOOL; use crate::gui::dlg_main::DlgMain; use crate::gui::events::WindowEventsAll; use crate::gui::privs::{create_ui_font, delete_ui_font}; use crate::gui::raw_main::{RawMain, WindowMainOpts}; use crate::gui::runtime_error::RunResult; use crate::kernel::decl::{ErrResult, HPROCESS, IsWindowsVistaOrGreater}; ...
Rust
0
x.push(rect.top_left.x); min_y.push(rect.top_left.y); max_x.push(rect.bottom_right.x); max_y.push(rect.bottom_right.y); } f32::print_interleaved(writer, &min_x)?; f32::print_interleaved(writer, &min_y)?; f32::print_interleaved(writer, &max_x)?; ...
Rust
0
07_test_2"); assert_eq!(part_1(input), 24); } } use std::collections::HashMap; use llvm_sys::core::*; use llvm_sys::prelude::*; use llvm_sys::target::*; use llvm_sys::target_machine::*; use llvm_sys::{LLVMAttributeReturnIndex, LLVMLinkage}; use arret_runtime::abitype::{AbiType, BoxedAbiType, RetAbiType}; ...
Rust
0
# Programmer: limodou # E-mail: limodou@gmail.com # # Copyleft 2006 limodou # # Distributed under the terms of the GPL (GNU Public License) # # UliPad 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 Foun...
Python
1
import os import pandas as pd import matplotlib import matplotlib.pyplot as plt import seaborn as sns from snownlp import SnowNLP matplotlib.use('Agg') matplotlib.rc('font', family='Microsoft JhengHei') def generate_mood_trend_plot(user_id, user_entries): output_dir = "static/moodtrend" os.makedirs(output_dir...
Python
1
`` pub mod ts_microseconds_option { use core::fmt; use serde::{de, ser}; use super::ts_microseconds::MicroSecondsTimestampVisitor; use crate::NaiveDateTime; /// Serialize a datetime into an integer number of microseconds since the epoch or none /// /// Intended for use with `serde`s `seria...
Rust
0
interface_stack: InterfaceStack::Ap, } } #[cfg(esp_idf_ppp_support)] pub fn ppp_default_client() -> Self { Self { key: "PPP_CL_DEF".into(), description: "ppp".into(), route_priority: 30, ip_configuration: InterfaceIpConfiguration:...
Rust
0
ize, usize)> { let (x, y) = crossterm::terminal::size()?; Ok((x.into(), y.into())) } ///XXX fn draw(&self, draw: &dyn Draw) -> CatchAll<()> { self.term.draw(draw) } fn present(&self) -> CatchAll<()> { self.term.present() } } ///XXX use tuikit::prelude::Draw; // T...
Rust
0
left_node_string.splitlines(), right_node_string.splitlines() ) ] ) length = max([len(line) for line in string.splitlines()]) string = "\n".join( [line + " " * (length - len(line)) for line in string.splitlines()] ) return string def parse(strin...
Python
1
Permissions::MANAGE_GUILD, guild_only: true, ..default }; Arc::new(options) } async fn run(&self, message: Message, args: Args, ctx: Context) -> Result<(), Box<dyn Error + Send + Sync>> { if let Some(guild_id) = message.guild_id { let switches = get_...
Rust
0
AreaErrorKind<E> { fn fmt(&self, fmt: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { return match self { DrawingAreaErrorKind::BackendError(e) => write!(fmt, "backend error: {}", e), DrawingAreaErrorKind::SharingError => { write!(fmt, "Mulitple backend ope...
Rust
0
, newline: Optional[str] = None, ): """ Return file descriptor with asynchronous write operations. """ global IOPathManager if not IOPathManager: logging.info("ioPath is initializing PathManager.") try: from iopath.common.file_i...
Python
1
ss PostBody(BaseModel): topic: str data: str @app.post("/api/v0/ipfs/pubsub/pub") @app.post("/api/v0/p2p/pubsub/pub") async def publish_data(body: PostBody): """ Publish a new POST message on the Aleph Network. """ private_key = get_fallback_private_key() account: ETHAccount = ETHAccount(p...
Python
1
# network_optimizer.py import pandas as pd import matplotlib.pyplot as plt from sklearn.linear_model import LogisticRegression # 1. Load your latency data df = pd.read_csv('network_latency.csv') print("Loaded data:") print(df) # 2. Label the best route (the row with smallest AvgRTT) df['BestRoute'] = 0 df.loc[df['Av...
Python
1
from __future__ import annotations from pathlib import Path from trame.assets.local import LocalFileManager from trame_slicer.core import VolumeRendering def resources_path() -> Path: return Path(__file__).parent def get_terminologies_path() -> Path: return resources_path() / "terminologies" def get_vo...
Python
1
QuerySegment::Key(String::from("foo"))], ), "QueryKeyOnly", ), ]; let mut router = Router::new(); for (spec, svc_name) in request_specs { let svc = NamedEchoUriService(String::from(svc_name)); router = router.route(spec, svc.cl...
Rust
0
f update_metric(self, episode, action, *args: Any, **kwargs: Any): self._step_count += 1 house_map, map_agent_x, map_agent_y = self.update_map( self._sim.get_agent_state().position ) current_obj_positions = self.update_object_positions(episode) self._metric = { ...
Python
1
min_heap.push(Reverse(neighbor)); } } } if travel_count == graph.len() { travel_path } else { String::new() } }//! //! Unpack postgresql binaries //! use std::path::PathBuf; use archiver_rs::{Archive, Compressed}; use futures::TryFutureExt; use crate::pg_errors::{PgEmbedError, PgEm...
Rust
0
r_id=at_user_id_str, at_user_nickname=at_user_data.get( "nickname" ), at_user_home_page_url=at_user_data.get( ...
Python
1
// The output of our download command is a boxed slice of pixel values. We'll use debug // formatting to turn it into a string and log it to the console with `web_sys`. web_sys::console::log_1(&format!("Pixel data: {:?}", pixels).into()); })); } use std::rc::Rc; use rust_graph_lib::{ a...
Rust
0
new(&sim.r, &sim.m, bb); // println!("\n\nQuadtree: {:?}", quadtree); // For each point for i in 0..sim.n { sim.a[i] = Vector3D::zero(); // println!("r[i] = ({}, {})", sim.rx[i], sim.ry[i]); let quadtree_iter = MassQuadtreeIterator::new(sim.r[i].x, sim.r[i].y, theta, &q...
Rust
0
dim=cat_dim) else: merged_sd[key] = sd_list[0][key] else: merged_sd[key] = torch.cat([sd[key] for sd in sd_list], dim=cat_dim) else: assert len(sd_list) == 1 num_part ...
Python
1
_greater, a1, smile)); }<gh_stars>100-1000 /* Copyright 2013 Jesse 'Jeaye' Wilkerson See licensing in LICENSE file, or at: http://www.opensource.org/licenses/BSD-3-Clause File: shared/obj/primitive/vertex.rs Author: Jesse 'Jeaye' Wilkerson Description: A collection base vertex types. ...
Rust
0