text
string
label_name
string
labels
int64
# Created: March, 2018 # Author(s): Calvin Feng import numpy as np from layer.affine import Affine from layer.relu import ReLU from layer.dropout import Dropout class AffineReLUDropout(object): def __init__(self, dropout_param=None): """ Args: dropout_param: A dictionary with the foll...
Python
1
"https://youtube-v2.p.rapidapi.com/channel/details", headers=headers, params={"channel_id": test_channel}, timeout=30 ) if response.status_code == 429: if attempt == max_retries - 1: return jsonify(...
Python
1
if composer_json.get('require', {}).get('php') and options_json.get("PHP_VERSION"): print('WARNING: A version of PHP has been specified in both `composer.json` and `./bp-config/options.json`.') print('WARNING: The version defined in `composer.json` will be used.') if ctx.get('O...
Python
1
AGE_SYM_ABSOLUTE => SymbolSection::Absolute, pe::IMAGE_SYM_DEBUG => { if symbol.storage_class == pe::IMAGE_SYM_CLASS_FILE { SymbolSection::None } else { SymbolSection::Unknown } } index if index > 0 => SymbolSection::Section(Sec...
Rust
0
ds: ::WORD, } BITFIELD!(SCRIPT_VISATTR bit_fields: ::WORD [ uJustification set_uJustification[0..4], fClusterStart set_fClusterStart[4..5], fDiacritic set_fDiacritic[5..6], fZeroWidth set_fZeroWidth[6..7], fReserved set_fReserved[7..8], fShapeReserved set_fShapeReserved[8..16], ]); #[repr(C)] #...
Rust
0
{ unsafe { (*Self::ptr()).mth.write(|w| w.mth().bits(level as u8)) } } #[inline] fn get_threshold_level() -> Level { unsafe { core::mem::transmute((*Self::ptr()).mth.read().mth().bits() & 0xF) } } #[inline] fn set_level_priority_bits(lp: LevelPriorityBits) { unsafe { (*...
Rust
0
should not be used: bundled feature has not been enabled"); } #[cfg(feature = "buildtime_bindgen")] { use super::{bindings, HeaderLocation}; let header = HeaderLocation::FromPath(format!("{}/duckdb.h", lib_name)); bindings::write_to_out_dir(header, out_path)...
Rust
0
-> RUImage, pub scaled_to_width: extern "C" fn(self_c: *const RUBase, w: i32, mode: u32) -> RUImage, pub scaled_to_height: extern "C" fn(self_c: *const RUBase, h: i32, mode: u32) -> RUImage, pub mirrored: extern "C" fn(self_c: *const RUBase, horizontally: bool, vertically: bool) -> RUImage, pub...
Rust
0
{BigEndian, BitWrite, BitWriter}; use std::collections::VecDeque; use std::io::Write; use std::mem::MaybeUninit; use std::sync::Arc; use std::{fmt, io, mem}; use crate::rayon::iter::*; use rust_hawktracer::*; #[allow(dead_code)] #[derive(Debug, Clone, PartialEq)] pub enum CDEFSearchMethod { PickFromQ, FastSearch...
Rust
0
::def_id::DefId; use rustc_span::symbol::sym; use super::InferCtxtPrivExt; crate trait InferCtxtExt<'tcx> { /*private*/ fn impl_similar_to( &self, trait_ref: ty::PolyTraitRef<'tcx>, obligation: &PredicateObligation<'tcx>, ) -> Option<DefId>; /*private*/ fn describe_enclosu...
Rust
0
ient1.get_protocol_mappers.return_value = [mapper1] client2 = Mock() realm2 = Mock() realm2.get_unmanaged_attribute_policy.return_value = "ADMIN_EDIT" client2.get_realm.return_value = realm2 mapper2 = Mock() mapper2.get_protocol_mapper.return_value = "oidc-usermodel-attr...
Python
1
# -*- coding: latin-1 -*- # # West European languages character translation table for HD44780U controller # Do not use for HD44780 controllers # # $Id: European.py,v 1.3 2023/01/24 12:25:08 bob Exp $ # # Author : Bob Rathbone # Site : http://www.bobrathbone.com # # License: GNU V3, See https://www.gnu.org/copyleft/gp...
Python
1
_msg.chain.append(item) send_result = await self.context.send_message(original_msg_origin, final_msg) logger.info(f"消息发送结果: {send_result}") async def _update_conversation_history(self, original_msg_origin: str, curr_cid: str, new_contexts: list): """更新对话历史""" try: ...
Python
1
import json import pygame import sys # Importing custom modules import animator import background import logic import sprites import synchronizer from constants import * # ---------------------------------------------- # Sequence Loading # ---------------------------------------------- # Function to load configurat...
Python
1
import numpy as np import random from PIL import Image import matplotlib.pyplot as plt import myTransforms def main(img, time=0, SAVE=False): preprocess = myTransforms.Compose([ myTransforms.RandomChoice([myTransforms.RandomHorizontalFlip(p=1), myTransforms.RandomVertic...
Python
1
<security::Pallet<T>>::ensure_parachain_status_not_shutdown() } } #[cfg_attr(test, mockable)] pub(crate) mod treasury { use crate::types::Wrapped; use currency::ParachainCurrency; use frame_support::dispatch::DispatchResult; pub fn mint<T: crate::Config>(requester: &T::AccountId, amount: W...
Rust
0
by_cmc_rank, Message, MessageType}; pub fn fetch_symbols_retry(exchange: &str, market_type: MarketType) -> Vec<String> { let retry_count = std::env::var("REST_RETRY_COUNT") .unwrap_or_else(|_| "5".to_string()) .parse::<i64>() .unwrap(); let cooldown_time = get_cooldown_time_per_request(...
Rust
0
OCK_SSID: &str = "network_ssid"; pub fn mock_psk_supplicant() -> (MockSupplicant, MockSupplicantController) { let config = auth::Config::ComputedPsk( psk::compute(MOCK_PASS.as_bytes(), MOCK_SSID.as_bytes()) .expect("Failed to create mock psk"), ); mock_supplicant(config) } pub fn mock_...
Rust
0
from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('black-friday', views.black_friday, name='black_friday'), path('package/<int:id>/', views.package_detail, name='package_detail'), ]
Python
1
"""Tests for the NRK TV API.""" from pathlib import Path from nrkdownload.nrk_tv import TVProgram, TVSeries, TVSeriesType def test_tv_series() -> None: # noqa: D103 series = TVSeries.from_series_id("kongen-av-gulset") assert series.title == "Kongen av Gulset" assert len(series.season_info) == 2 def t...
Python
1
.unwrap(); let (res, task_rt) = Service::new(self.config.clone(), task_rt); let service = match res { Ok(s) => s, Err(_e_) => { panic!("new service failure") } }; println!("run server!!"); core_rt.block_on(server(0,...
Rust
0
"projectId": project_1.id} ] def test_metrics_details_with_date_range(self): metrics = ( ("c:custom/clicks_1@none", 0), ("c:custom/clicks_2@none", 1), ("c:custom/clicks_3@none", 7), ) for mri, days in metrics: self.store_metric( ...
Python
1
ing in"); self.driver.click_element(".signInButton button")?; Ok(()) } fn balance(&self) -> WebDriverResult<String> { println!("getting amount"); self.driver.get_text(".amount") } } //! //! An in-memory layer stores recently received page versions in memory. The page version...
Rust
0
# -*- coding: utf-8 -*- # # This file is part of EventGhost. # Copyright © 2005-2020 EventGhost Project <http://www.eventghost.net/> # # EventGhost 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 versio...
Python
1
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/7/25 10:30 # @Author : CoderCharm # @File : test_aioredis.py # @Software: PyCharm # @Github : github/CoderCharm # @Email : wg_python@163.com # @Desc : """ 测试aioredis 本来是想直接使用redsi的, 但是查阅资料都是使用aioredis 看了很多在FastAPI中使用redis的demo 所以参照着写,把redsi挂载...
Python
1
import time import math class MessageHandler: def __init__(self): # Initialize the sequence number self.sequence_number = 0 @staticmethod def show_speed(content, elapsed, operation_type,interval): """ 显示数据传输速度,并打印操作时间。 :param content: 传输的数据内容 :param elapsed:...
Python
1
#Este projeto vai te introduzir ao mundo do web scraping com Python. Voce vai criar um programa Python que acessa uma pagina da internet, extrai informações expecificas e as exibe. Para começar, vamos focar em uma pagina simples e publica para aprender os fundamentos. #Qque voce vai aprender: Requisicoes HTTP, parsing...
Python
1
ausality == MD::CausalityType::Output { out_ids.push(variable.id); } } let fixture = DtasmFixture { inst, map_name_id, out_ids }; fixture } #[rstest] fn it_adds_two_reals(mut fix: DtasmFixture) { let mut input_vals = DtasmVarValues::new(); let re...
Rust
0
data = element.data.read(); let data = vs::ty::Data { screen_size, position: [ element_data.dimensions.0 as f32, element_data.dimensions.1 as f32, ], size: [ element_data.dimensions.2 as f32, element_...
Rust
0
from src.abc.infra.imessage_repo import IMessageRepo from src.abc.infra.inode_client import INodeClient from src.abc.infra.ipeer_repo import IPeerRepo from src.abc.use_case.find_node_use_case import FindNodeUseCase from src.abc.use_case.send_message_use_case import SendMessageUseCase from src.settings import NodeSettin...
Python
1
ization. In future, interlocking_dir will /// respond all data in Chunk format which is different to the format in storage. At that time, /// this structure is no longer useful and should be removed. #[derive(Clone, Debug)] pub enum QuiesceBatchColumn { Primitive_Causet(BufferVec), Decoded(VectorValue), } impl...
Rust
0
from abc import ABC, abstractmethod class Expression(ABC): @abstractmethod def ejecutar(self, ast, context, gen, lvlbreak, lvlcont, lvlreturno): pass
Python
1
).unwrap(); } }); } } impl UiState for Default { fn draw(&self, assets: &Assets, ctx: &Context) { let hex = &assets.hex; let map = &assets.map; let mut hex_iter = map.hex_iter(hex, ctx); n18brush::draw_map(hex, ctx, &mut hex_iter); // Draw the activ...
Rust
0
tag_str.replace("".to_string()); } _ => { if let Some(tag) = tag_str.as_mut() { tag.push(c); } else { return Err(VaporettoError::invalid_argument( "lab...
Rust
0
import os, sys from tqdm.auto import tqdm sys.path.append('./ScanNet/SensReader/python') from SensorData import SensorData def main(output_dir, input_dir: str = "./datasets/ScanNet/scans"): scenes = os.listdir(input_dir) for scene in tqdm(scenes): scene_base_dir = os.path.join(input_dir, scene) ...
Python
1
os:", cuadrados) # Muestra [1, 4, 9, 16, 25] # Ordenar estudiantes por nota y longitud de nombre ordenar_personalizado() # Muestra estudiantes ordenados por sus notas y longitud de nombre # Ejemplo de función decorada print("\nLlamadas a la función sumar:") sumar(2, 3) # Llamada 1 a la función ...
Python
1
())) }, "PRIORITY" => { Ok(Priority(parse_expr::<LitInt>(*static_item.expr)?.value() as i32)) }, _ => return Err(Error::new(static_item.ident.span(), "Unexpected name")), } } } fn export_string(name: &str, value: &str) -> TokenStream { let...
Rust
0
are ready"] #[doc = " for your audio callback function to be called. Since the audio driver"] #[doc = " may modify the requested size of the audio buffer, you should allocate"] #[doc = " any local mixing buffers after you open the audio device."] pub fn SDL_OpenAudio(desired: *mut SDL_AudioSpec, obtained: ...
Rust
0
commender<T, U> { user_map: Map<T>, item_map: Map<U>, rated: HashMap<usize, HashSet<usize>>, global_mean: f32, user_factors: Array2<f32>, item_factors: Array2<f32>, // use lazy initialization to save memory // https://doc.rust-lang.org/std/cell/#implementation-details-of-logically-immut...
Rust
0
#!/usr/bin/env python # coding: utf-8 # In[ ]: from jokers.joker_a import JokerA from jokers.joker_b import JokerB from jokers.joker_c import JokerC if __name__ == '__main__': jokeA = JokerA() print(jokeA.get_random_joke()) jokeB = JokerB() print(jokeB.get_random_joke()) API = '' jokeC = J...
Python
1
from src.modules.group_info import GroupInfo from src.params import GroupSetting from src.utils.log import logger from . import _jx3_event as Event from .jx3_websocket import ws_client async def ws_init(): """初始化连接ws服务器""" logger.info("<g>正在链接jx3api的ws服务器...</g>") flag = await ws_client.init() if fla...
Python
1
d_image_paths[start:end], caption_list) ): caption = caption.replace(" <|image|>", "") # print(f"Processing {generated_image_path}: {caption}...") ic(idx, reference_image, generated_image_path, caption) gen_image = Image.open(generated_image_path) si...
Python
1
c = " @since Added in version 3.0."] #[doc = ""] #[doc = " @ingroup window"] pub fn glfwGetWindowMonitor(window: *mut GLFWwindow) -> *mut GLFWmonitor; } extern "C" { #[doc = " @brief Sets the mode, monitor, video mode and placement of a window."] #[doc = ""] #[doc = " This function sets the m...
Rust
0
import os from qfluentwidgets import ConfigItem, QConfig, RangeConfigItem, RangeValidator, BoolValidator, OptionsConfigItem, \ OptionsValidator from core.gobal_components import i18n CURRENT_DIR = os.path.dirname(os.path.abspath(__file__)) CONFIG_FILE_NAME = "config.json" CONFIG_FILE = os.path.join(CURRENT_DIR, ...
Python
1
, "🧛🏿‍♀", "🧛🏿‍♀️", "🧛🏿‍♂", "🧛🏿‍♂️", "🧜", "🧜‍♀", "🧜‍♀️", "🧜‍♂", "🧜‍♂️", "🧜🏻", "🧜🏻‍♀", "🧜🏻‍♀️", "🧜🏻‍♂", "🧜🏻‍♂️", "🧜🏼", "🧜🏼‍♀", "🧜🏼‍♀️", "🧜🏼‍♂", "🧜🏼‍♂️", "🧜🏽", "🧜🏽‍♀", "🧜🏽‍♀️", "🧜🏽‍♂", "🧜🏽‍♂️", "🧜🏾", "🧜🏾‍♀", "🧜🏾‍♀️", "🧜🏾‍♂", "🧜🏾‍♂️", "🧜🏿", "🧜🏿‍♀", "🧜🏿‍♀️", "🧜🏿‍♂...
Python
1
mut window = WindowBuilder::new(&display) .title("Custom font") .theme(BinaryColorTheme::OledBlue) .build(); window.show_static(&display); } use ncollide3d::shape::{ConvexHull, Cuboid, ShapeHandle}; use nphysics3d::joint::{FreeJoint, RevoluteJoint}; use nphysics3d::object::{BodyPartHandle,B...
Rust
0
node_device.id, "bus": node_device.bus, "bus_name": node_device.get_bus_display(), "hardware_type": node_device.hardware_type, "hardware_type_name": node_device.get_hardware_type_display(), "system_id": node_device.node_config.node.system_...
Python
1
ator; use itsybitsy_m4::{ clock::GenericClockController, dotstar_bitbang, gpio::v2::PA22, gpio::{Input, Output, Pa27, Pb2, Pb3, Pin, PullUp, PushPull}, prelude::*, timer::{SpinTimer, TimerCounter, TimerCounter2}, uart, }; use panic_halt as _; use smart_leds::{SmartLedsWrite, RGB8}; use usbd_...
Rust
0
); move_and_assert_list_state!(app, Movement::Prev, POS_WRAP_MATCH_MULTI_0_4); move_and_assert_list_state!(app, Movement::Prev, POS_WRAP_MATCH_MULTI_0_3); move_and_assert_list_state!(app, Movement::Prev, POS_WRAP_MATCH_MULTI_0_2); move_and_assert_list_state!(app, Movement::Prev, POS_WRAP...
Rust
0
/// TXT-DATA One or more <character-string>s. /// /// TXT RRs are used to hold descriptive text. The semantics of the text /// depends on the domain where it is found. /// ``` TXT(TXT), /// A DNSSEC- or SIG(0)- specific record. See `DNSSECRData` for details. /// /// These ty...
Rust
0
int('HKS errors, exit') sys.exit() # normalize the gaussian curvature gaussian_curvature = torch.exp(-(torch.from_numpy(np.load(os.path.join(gaussian_curvature_path, d, ...
Python
1
[0x80000000], 0xFFFFAAAA mov dword [0x80000004], 0x11223344 cmpxchg8b [0x80000000] hlt"); assert_eq!(vm.reg32(Reg32::EAX), 0xFFFFAAAA); assert_eq!(vm.reg32(Reg32::EDX), 0x11223344); assert_eq!(vm.flags, X86Flags{..Default::default()}); } #[test] fn test_cmpxchg8b_2()...
Rust
0
let p = Tuple::point(1.0, 0.0, 1.0); let a = Matrix4x4::rotation_x(std::f64::consts::PI / 2.0); let b = Matrix4x4::scaling(5.0, 5.0, 5.0); let c = Matrix4x4::translation(10.0, 5.0, 7.0); let t = c * b * a; assert_eq!(t * p, Tuple::point(15.0, 0.0, 7.0)); } #[test] fn chain_transformation_using...
Rust
0
(相对总数): {(total_with_magnet / max(total_videos, 1) * 100):.2f}%\n\n" ) f.write("【图片下载情况】\n") f.write(f"已下载图片数: {total_image_downloaded} 个\n") f.write( f"图片下载率: {(total_image_downloaded / max(total_videos, 1) * 100):.2f}%\n\n" ...
Python
1
ab_url = colab_url self.running = True self.daemon = True # TTS 시스템 초기화 self.tts_system = TTSSystem() # 음성 인식 초기화 self.recognizer = sr.Recognizer() self.mic = sr.Microphone() print(" 음성 인식 스레드 초기화 완료") def run(self): ...
Python
1
vacuum flow = OptionsFlowHandler(config_entry) flow.hass = hass flow.selected_vacuum = "test_device_id" # Test the edit step result = await flow.async_step_edit() assert result["type"] == data_entry_flow.FlowResultType.FORM assert result["step_id"] == "edit" assert CONF_AUTODISCOVERY ...
Python
1
from flask import ( Blueprint, redirect, render_template, request, session, ) from settings import Settings from utils.log import Log from utils.paginate import paginate_query adminPanelPostsBlueprint = Blueprint("adminPanelPosts", __name__) @adminPanelPostsBlueprint.route("/admin/posts", methods...
Python
1
from plotGaussian import plotGaussian import matplotlib.pyplot as plt def plotModes(means, covMats, X): plt.subplot() plt.scatter(X[:, 0], X[:, 1]) M = means.shape[1] for i in range(M): plotGaussian(means[:, i], covMats[:, :, i])
Python
1
, 0, 0, 0, 0, 0, 0, 0, 0], ); rfm.aes(&[]).ok().unwrap(); assert_eq!( rfm.spi.rx_buffer[0..=3], [ Registers::PacketConfig2.read(), 0, Registers::PacketConfig2.write(), 0b0000000_0 ] ); rfm.spi.rx_buffer.clear(); let mut ke...
Rust
0
x_2k_t1 = self.forward_loop( x_t0=x_2k_t0, t0=timesteps[-t0 - 1].item(), t1=timesteps[-t1 - 1].item(), generator=generator, ) # Perform backward process from time T_1 to 0 x_1k_t1 = torch.cat([x_1_t1, x_2k_t1]) b, l, d = prompt_emb...
Python
1
from typing import IO, Optional from pydantic import ConfigDict from core.model_runtime.entities.model_entities import ModelType from core.model_runtime.model_providers.__base.ai_model import AIModel from core.plugin.manager.model import PluginModelManager class Speech2TextModel(AIModel): """ Model class fo...
Python
1
crate vga_buffer; // for println_raw!() extern crate x86_64; extern crate mod_mgmt; extern crate memory; extern crate spin; extern crate tss; extern crate gdt; use spin::Mutex; use x86_64::structures::{ idt::{LockedIdt, ExceptionStackFrame, PageFaultErrorCode}, tss::TaskStateSegment, }; use gdt::{Gdt, create...
Rust
0
""" Problem: Search Element in a Matrix Description: ------------ Given a 2D matrix and a target value, find the position (row, column) of the target element. If the element is not found, return -1. This approach performs a brute-force search by checking every element in the matrix. Approach: --------- - Iterate ove...
Python
1
\x1B[37;1m \r \x1B[33;1m /\/ \ + | _/ ` \/ \ + \x1B[1;34m wwwww wwwwwwwww \x1B[0m QUICK START:\r \x1B[33;1m // ` \ | / __ \ `\ _ \x1B[1;34m ww wwwwww w wwwwwww \x1B[0m • WAPM commands: wapm\r \x1B[33;1m // . \ /^...
Rust
0
ub fn is_identity(&self) -> bool { self.m.m[0][0] == 1.0 as Float && self.m.m[0][1] == 0.0 as Float && self.m.m[0][2] == 0.0 as Float && self.m.m[0][3] == 0.0 as Float && self.m.m[1][0] == 0.0 as Float && self.m.m[1][1] == 1.0 as Float && s...
Rust
0
pub struct InnerClass { pub inner_class_info_index: ConstantPoolIndex, pub outer_class_info_index: ConstantPoolIndex, pub inner_name_index: ConstantPoolIndex, pub access_flags: AccessFlags } #[derive(Debug)] pub struct LineNumberTable { pub start_pc: u16, pub line_number: u16 } #[derive(Debug...
Rust
0
.buf.as_ptr(), it.len(), it.cap); } } let mut vec = Vec::new(); // must delegate to spec_extend() since extend() itself delegates // to spec_from for empty Vecs vec.spec_extend(iterator); vec } } impl<'a, T: 'a, I> SpecFromIter<&'a T, I> for Vec<T> where...
Rust
0
"""update Revision ID: 492998d32864 Revises: 2bd9fa7ff371 Create Date: 2025-08-29 02:31:55.028124 """ from typing import Sequence, Union import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision: str = "492998d32864" down_revision: Union[str, Sequence[str], None] = "2bd9fa7ff...
Python
1
); // LivingSpirit #[wasm_bindgen] extern "C" { /// The ID of a [`LivingSpirit`]. #[wasm_bindgen(extends = SpiritID, extends = LivingDestructibleID, typescript_type = "SpiritID")] #[derive(Clone, Debug, PartialEq, Eq)] pub type LivingSpiritID; /// A spirit that has positive HP. /// /// [Ya...
Rust
0
ecified depth. GetLocal(u32), /// Pop a value and put it in at the specified depth. SetLocal(u32), /// Copy a value to the specified depth. TeeLocal(u32), /// Similar to the Wasm ones, but instead of a label depth /// they specify direct PC. Br(Target), BrIfEqz(Target), BrIfNe...
Rust
0
= <(u32, u32)>::try_from(point) { if x < self.size.width && y < self.size.height { let start_index = (x + y * self.size.width) as usize * 3; return self.data.get_mut(start_index..start_index + 3); } } None } /// Converts the framebuffer i...
Rust
0
hallenges = [] if "Time constraints" in requirements.constraints: challenges.append("Tight timeline may require scope prioritization") if len(requirements.integrations) > 3: challenges.append("Multiple integrations may increase complexity") if r...
Python
1
)] //! pub struct MyArgs { //! #[clap(flatten)] //! evm_opts: EvmArgs, //! #[clap(flatten)] //! opts: BuildArgs, //! } //! //! // add `Figment` and `Config` converters //! foundry_config::impl_figment_convert!(MyArgs, opts, evm_opts); //! let args = MyArgs::parse_from(["build"]); //! //! let figment: Fi...
Rust
0
n_value, } } pub fn new(mir: MirCodeBlock, span: Span, return_value: Option<TypedMemory>) -> Self { OutputData { mir, span, return_value, } } } <gh_stars>0 // Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-I...
Rust
0
from datetime import datetime from sqlalchemy import Column, Integer, Boolean, DateTime, CheckConstraint from app.core.config import INVESTED_AMOUNT, FULLY_INVESTED from app.core.db import Base class DonationCharityBase(Base): __abstract__ = True full_amount = Column(Integer, nullable=False) invested_am...
Python
1
# -*- coding: utf-8 -*- import torch from torch import nn from load_data import START_TAG, STOP_TAG, label2idx from transformers import BertPreTrainedModel, BertModel device = "cuda" if torch.cuda.is_available() else 'cpu' def log_sum_exp(smat): ''' for example: 输入: tensor([[[0.5840, 0.6834, 0.8859, 0...
Python
1
ction log(message) { console.log(message); } // Handle file selection document.getElementById('audioFile').addEventListener('change', function(e) { log('File selected: ' + (e.target.files[0] ? e.target.files[0].name...
Python
1
#오늘의 공부 순서: 오늘 진도 문제 다풀기, 교재 복습, 노션 정리 마무리 ! ##a=input("문자를 입력하세요") ##for i in range(len(a)): ## print(a[:i+1]) ##import turtle ##t=turtle.Turtle() ##t.shape("turtle") ##a=int(turtle.textinput("","다각형을 입력하세요")) ##for i in range(a): ## t.fd(100) ## t.lt(360/a) #순서쌍 만들기 ##for i in range(4): ## for j in r...
Python
1
# Código para resolver un Sudoku con backtracking y recursividad # Esta función muestra el Sudoku de una manera más simple y limpia def print_sudoku(sudoku): # Itera sobre cada fila del Sudoku for i in range(9): # Imprime una línea de separación cada 3 filas if i == 3 or i == 6: pr...
Python
1
n columns(&self) -> Vec<&str> { self.df.get_column_names() } #[napi(setter, js_name = "columns")] pub fn set_columns(&mut self, names: Vec<&str>) -> napi::Result<()> { self.df .set_column_names(&names) .map_err(JsPolarsErr::from)?; Ok(()) } #[napi] ...
Rust
0
pub const WEBAUTHN_ASSERTION_VERSION_1: u32 = 1u32; #[doc = "*Required features: `\"Win32_Networking_WindowsWebServices\"`*"] pub const WEBAUTHN_ASSERTION_VERSION_2: u32 = 2u32; #[doc = "*Required features: `\"Win32_Networking_WindowsWebServices\"`*"] pub const WEBAUTHN_ATTESTATION_CONVEYANCE_PREFERENCE_ANY: u32 = 0u32...
Rust
0
mut this: Raw<'a, R>) -> R::Target where R: ResidentUnwrap<Raw<'a, R>> { unsafe { let data = this.data.as_ptr(); let size = R::resident_size(data, &mut this.meta); let resident = R::resident_unwrap(&this); ptr::drop_in_place(&mut this.meta); mem::forge...
Rust
0
# 17 - Verificação de Palíndromo: # Escreva um programa que solicite uma palavra ao usuário e # use um laço while para verificar se a palavra é um palíndromo # (lê-se da mesma forma de trás para frente). palavra = '' word = input('Digite a palavra: ') while palavra != word if print(word)
Python
1
"""Test solving the DKE/MDKE.""" import cola import desc import jax.numpy as jnp import monkes import numpy as np import yancc from yancc.collisions import MonoenergeticPitchAngleScattering from yancc.trajectories import DKESTrajectories def _solve_mdke(field, pitchgrid, species, E_psi, v): CL = MonoenergeticPi...
Python
1
(1.0, 2.0), $newvec2(3.0, 4.0)); assert_eq!(a, b); let c = $newmat2($newvec2(1.0, 2.0), $newvec2(3.0, 4.0)); assert_eq!(a, c); let d = b.to_cols_array(); let f = $mat2::from_cols_array(&d); assert_eq!(b, f); }); glam_test!(test_mat...
Rust
0
t.execute(self,_actor) def setUp(self,_actor): self.sprite_rate = self.base_sprite_rate if self.last_frame > 0: _actor.changeSprite(self.sprite_name) if self.sprite_rate < 0: _actor.changeSpriteImage(len(_actor.sprite.image_library[_actor.sprite.flip][_ac...
Python
1
r distributed // except according to those terms. use rustc_hash::FxHashMap; use std::borrow::Cow; use std::collections::{BTreeMap, BTreeSet}; mod datafrog_opt; mod location_insensitive; mod naive; use facts::{AllFacts, Atom}; #[derive(Debug, Clone, Copy)] pub enum Algorithm { Naive, DatafrogOpt, Locatio...
Rust
0
from django.urls import path, include from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r'countProveedores',views.countProveedoresviewSet,basename='countProveedores') router.register(r'countProductos',views.countProductoviewSet,basename='countProductos') router.reg...
Python
1
"// TODO text/html message should be converted into text/plain".to_string(), ); } } } } return Ok("// TODO Message not found".to_string()); } /** * @todo */ fn get_purpose(email: &Email) -> Result<String, Error> { if email.subject.to_ascii_lowe...
Rust
0
from typing import Optional from mangoui import * from src.models.user_model import UserModel from src.network import HTTP class UserPage(QWidget): def __init__(self, parent): super().__init__() self.parent = parent self.layout = MangoVBoxLayout() self.user_info: Optional[UserMo...
Python
1
es, vectors[j]) if k in discrete_axes } if i_discrete_location != j_discrete_location: continue graph[i][j] = vdiff_hypot2(vectors[i], vectors[j]) tree = minimum_spanning_tree(graph, overwrite=True) rows, cols = tree.nonzero() ...
Python
1
2021, 10, 1), "foo", data::Amount { commodity: "JPY".to_string(), value: dec!(10), }, ); txn.effective_date(NaiveDate::from_ymd(2021, 10, 1)); assert_eq!(txn.effective_date, None); } #[test] fn test_effective_date_...
Rust
0
RD0>; #[allow(missing_docs)] #[doc(hidden)] pub struct _Q5_WORD0; #[doc = "`read()` method returns [q5_word0::R](q5_word0::R) reader structure"] impl crate::Readable for Q5_WORD0 {} #[doc = "`write(|w| ..)` method takes [q5_word0::W](q5_word0::W) writer structure"] impl crate::Writable for Q5_WORD0 {} #[doc = "UHCI_Q5_...
Rust
0
let player_obstacle_count = simulator::calculate_obstacle_count_from_chain_count(chain_count); if player_obstacle_count > self.player.obstacle_block_count() { let player_spawned_obstacle_count = player_obstacle_count - self.player.obstacle_bloc...
Rust
0
1 ) } for round in 2..50 { let _ = game.round().play(); if let Some(raw_map) = load_combat_round(round) { assert_eq!( trim(&raw_map), trim(&game.map().status().to_string()), "combat...
Rust
0
添加巡检代码内容") screen_width = self.global_info.main_window.window_obj.winfo_screenwidth() screen_height = self.global_info.main_window.window_obj.winfo_screenheight() width = 420 height = 300 win_pos = f"{width}x{height}+{screen_width // 2 - width // 2}+{screen_height // 2 - height /...
Python
1
is_struct_or_enum(&tx.ty_env) { // FIXME: DebugWithContext を使う tx.logger .error(result, format!("struct or enum type required")); } } _ => unimplemented!(), }, KPrim::GetField => match (node.args.as_m...
Rust
0
'*"] pub union MIXERCONTROLW_1 { pub cSteps: u32, pub cbCustomData: u32, pub dwReserved: [u32; 6], } impl ::core::marker::Copy for MIXERCONTROLW_1 {} impl ::core::clone::Clone for MIXERCONTROLW_1 { fn clone(&self) -> Self { *self } } #[doc = "*Required features: 'Win32_Media_Audio'*"] pub co...
Rust
0
Named(ident) => ident.clone(), Member::Unnamed(index) => Ident::new(&index.index.to_string(), index.span), } } } /* impl Questionable for ExprMethodCall { fn unwrap_tries(self) -> Result<Unwrapped> { let cloned_call = quote! {#self}; ymlog!("_+" => "Processing Method Call: {}", cloned_call); ...
Rust
0
from web3core.models.types import ContractFields wavax: ContractFields = { "name": "wavax", "desc": "Wrapped AVAX", "type": "erc20", "address": "0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7", "chain": "avax", } usdc: ContractFields = { "name": "usdc", "desc": "USDC Circle token", "type":...
Python
1