text
string
label_name
string
labels
int64
eld bytes(self) def gett(audio,transcriber,i): global tokenss_list for seg in transcriber(audio): # 可能没有切片 tokenss_list[i][1] += seg tokenss_list[i][2] = True # print(seg) rs() def main(): global l global window try: with AudioRecorder(channels=1, sample_rate=16000) a...
Python
1
lk( 0x00FE, ( '#1500050215V怎么会发生\n', '这么惨的事啊。', TxtCtl.Enter, ), ) CloseMessageWindow() Jump('loc_85D') def _loc_803(): pass label('loc_803') ChrTalk( 0x00FE, ( '#1500050216V我小时候\n', '就认识特蕾莎院...
Python
1
()), Element::Reference(y.clone())] .iter() .cloned(), ); let f2 = PredicateFormula::new( "test1", [Element::Reference(x.clone()), Element::Reference(x.clone())] .iter() .cloned(), ); let f3 = PredicateFormula::new( "test2", ...
Rust
0
VarChar, } } diesel::joinable!(info_blob -> series (series_id)); use port::adapter::model::{mesh_model::MeshModel, stl_filepath_model::StlFilepathModel}; use port::adapter::resource::mesh_resource::convert_base64_to_bytes; use port::adapter::command::perform_on_stl_command::PerformOnStlCommand; use application::o...
Rust
0
al in trading_signals: signals.append({ 'date': signal.get('date', ''), 'type': signal.get('type', ''), 'confidence': signal.get('confidence', 0), 'reason': signal.get('reason', ''), 'price': signal.get('...
Python
1
# self.__make = make #cannot due because make is private to Automobile # self.set_make(make) # can do but too lazy to do # Automobile.__init__(self, make, model, mileage, price) super().__init__(make, model, mileage, price) self.__battery_capacity = battery_capacity # self._...
Python
1
t self) { // Sync data to storage let _result = self.sync(); // Clear out references self.data.clear(); self.path = None; self.fs = None; } } // Unit tests // ------------------------------------------------------------------------------------------------- #[cfg...
Rust
0
ut; use transcribe::model::{ AudioEvent, AudioStream, LanguageCode, MediaEncoding, TranscriptResultStream, }; use transcribe::Blob; const CHUNK_SIZE: usize = 8192; pub async fn transcribe_canary( client: transcribe::Client, expected_transcribe_result: String, ) -> anyhow::Result<()> { let input_stream...
Rust
0
a data bus error has occurred, but the return address in the stack frame is not related to the instruction that caused the error"] #[inline(always)] pub fn impreciserr_1(self) -> &'a mut W { self.variant(IMPRECISERR_A::IMPRECISERR_1) } #[doc = r"Sets the field bit"] #[inline(always)] pub...
Rust
0
schedule[self.CONFIG_RUNS] = { f"{index}": details for index, details in enumerate(merged_runs.values()) } await writer_reader.delete(self.RUN_SCHEDULE_TABLE, (await writer_reader.search()).id == ...
Python
1
.output_size = output_size self.dummy_params = torch.nn.Parameter(torch.rand(1)) def forward(self, images, point_clouds, robot_states, texts): return torch.rand(self.output_size) task_name = "reach_target" evaluator = RLBenchEvaluator( task_name="open_box", imag...
Python
1
g::CertGen(CertGenConf { ca_conf: Config::conf_from_toml(&args[0])?, csr: Config::get_der_file_content(&args[1])?, ca_pk: Config::get_der_file_content(&args[2])?, ca_sk: Config::get_der_file_content(&args[3])?, out_files...
Rust
0
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score import numpy as np def evaluate_model(y_true, y_pred, model_name="Modèle"): """Calcule et affiche les métriques d'évaluation pour un modèle de régression.""" mse = mean_squared_error(y_true, y_pred) rmse = np.sqrt(mse) mae = ...
Python
1
# 此文件版权归pkulab409/dsa2024dev全体技术组同学所有 # The copyright of this file belongs to all technical team members of pkulab409/dsa2024dev # https://github.com/orgs/pkulab409/teams/dsa2024dev # # 此文件归属于项目pkudsa.realm # This file belongs to the project pkudsa.realm # https://github.com/pkulab409/pkudsa.realm # # 特别感谢zhes2Hen和Renk...
Python
1
# # Copyright (c) 2023 Airbyte, Inc., all rights reserved. # from .secrets_manager import SecretsManager __all__ = ("SecretsManager",)
Python
1
*/ => { let escape_ch = cursor.peek()?.ok_or_else(|| { Error::from(io::Error::new( ErrorKind::UnexpectedEof, "unterminated escape sequence in literal", )) })?; ...
Rust
0
/// Update schema with incongruent `maximum` and `minimum`. /// Replaces the schema with `false` schema if `maximum` /// is smaller than `minimum` #[log_processing(cfg(feature = "logging"))] fn update_maximum_minimum( schema: &mut Value, schema_primitive_types: &mut PrimitiveTypesBitMap, ) -> bool { // Chec...
Rust
0
"""A set of services for dialogs.""" from PySide6.QtCore import Qt from PySide6.QtWidgets import (QWidget, QBoxLayout, QHBoxLayout, QLabel, QPushButton, QDialog) class DialogGUIService: """A set of services for dialogs.""" @staticmethod def add_input(dialog: QDialog, ...
Python
1
# -*- coding: utf-8 -*- """ rstblog.cli ~~~~~~~~~~~ The command line interface :copyright: (c) 2010 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ from __future__ import with_statement from __future__ import absolute_import from __future__ import print_function import sys impo...
Python
1
AMZA ABOVE u'\u0627' # 0xC7 -> ARABIC LETTER ALEF u'\u0628' # 0xC8 -> ARABIC LETTER BEH u'\u0629' # 0xC9 -> ARABIC LETTER TEH MARBUTA u'\u062a' # 0xCA -> ARABIC LETTER TEH u'\u062b' # 0xCB -> ARABIC LETTER THEH u'\u062c' # 0xCC -> ARABIC LETTER JEEM u'\u062d' # 0xCD -> A...
Python
1
} #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> EXTMODE1R { match value { false => EXTMODE1R::LEVEL_SENSITIVE, true => EXTMODE1R::EDGE_SENSITIVE, } } #[doc = "Checks if the value of the field is `LEVEL_SENSITIVE`"] #...
Rust
0
cv.next().await { inner.console.write(&[byte]).await.unwrap(); } })); sender } fn start_rx(inner: Arc<Inner>) -> AbortHandle { let ctx = inner.ctx.clone(); let (handle, reg) = futures::future::AbortHandle::new_pair(); ctx.spawn(Box::pin(async ...
Rust
0
bool { self.z.is_zero() } fn is_normalized(&self) -> bool { self.is_zero() || self.z == $basefield::one() } fn batch_normalization<S: std::borrow::BorrowMut<Self>>(v: &mut [S]) { // Montgomery’s Trick and Fast Implementati...
Rust
0
#[test] fn serialize_body_for_api_gateway_v2() { let mut resp = api_gateway_v2_response(); resp.body = Some("foo".into()); assert_eq!( serde_json::to_string(&resp).expect("failed to serialize response"), r#"{"statusCode":200,"headers":{},"multiValueHeaders":{},"body":...
Rust
0
html/rfc7153): IANA Registries for BGP Extended Communities Updates 4360, 5701 - [X] [RFC 8097](https://datatracker.ietf.org/doc/html/rfc8097): BGP Prefix Origin Validation State Extended Community - [X] [RFC 8092](https://datatracker.ietf.org/doc/html/rfc8092): BGP Large Communities ### FlowSpec - [ ] [RFC 8955](htt...
Rust
0
#[description = "Commands that could be considered fun / silly."] #[commands(ascii, printerfacts, urban, randefine, xkcd)] struct Fun; #[group("Info")] #[description = "Informational commands that provide useful information."] #[commands(about, channel, first_message, guild, profile, role, user)] struct Info; #[grou...
Rust
0
columns=pd.MultiIndex.from_tuples( [("multi", "col1"), ("multi", "col2")], names=["level1", None] ), ) df2 = df.copy() for i in range(1, 10): df[i, "colA"] = 10 df = df.append(df2, ignore_index=True) result = df["multi"...
Python
1
f32) -> Self { assert!(left <= right); assert!(top <= bottom); assert!(lerp_coeff > 0.0); Self { left, right, top, bottom, lerp_coeff, } } } pub struct CameraPlugin; impl Plugin for CameraPlugin { fn build(&se...
Rust
0
(self._attr_id) if callable(factor): return factor(self._device_info.state, self.hub.wp_version) return self._device_info.state @property def device_class(self): """Return the class of the sensor.""" return DEVICE_CLASS.get(self._attr_id) @property def n...
Python
1
gify!(SReaderQOSC), "::", stringify!(reliability) ) ); } impl Default for SReaderQOSC { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(i32)] #[doc = " @brief eCAL transport layer types."] #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum e...
Rust
0
match subject.len() { 0 => subject.to_string(), _ => crate::split::words(subject) .into_iter() .map(|c| { if shouty { upper_case(&c) } else { lower_case(&c) } }) ....
Rust
0
degrees = sorted(num_degrees.items(), key=lambda x: x[1], reverse=True) return sorted_num_degrees[0][0] def backtrack(self, assignment): """ Using Backtracking Search, take as input a partial assignment for the crossword and return a complete assignment if possible...
Python
1
from django.contrib.auth.models import User from django.db import models class Concrete(models.Model): pass class Proxy(Concrete): class Meta: proxy = True permissions = (("display_proxys", "May display proxys information"),) class UserProxy(User): class Meta: proxy = True ...
Python
1
, &mut output); output }) .unwrap(); let scope = unsafe { llvm::LLVMRustDIBuilderCreateNameSpace( DIB(cx), parent_scope, namespace_name_string.as_ptr(), ) }; debug_context(cx) .namespace_map .borrow_mut() .insert(d...
Rust
0
#!/usr/bin/env python # # Credits: This code was copied from # https://github.com/ThoughtWorksInc/aws_role_credentials # # Copyright (c) 2015, Peter Gillard-Moss # All rights reserved. # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided th...
Python
1
#!/usr/bin/env python3 ## ## @file flattenArrays.py ## @brief Flattens the arrays code from the given SBML file. ## @author Brett G. Olivier ## ## ## <!-------------------------------------------------------------------------- ## This sample program is distributed under a different license than the rest ## of lib...
Python
1
from workout_api.categories.models import CategoriaModel from workout_api.training_center.models import CentroTreinamentoModel from workout_api.atleta.models import AtletaModel
Python
1
def get_receiver_names(): """Return an unordered set of receiver names (full.module.path.function)""" return { name_from_fn(fn_ref()) for _, fn_ref, *_ in Command.course_published_signal.receivers } def get_receiver_fns(): """Return the list of active receiver functions.""" retur...
Python
1
ate(); let k2 = KeyPair::generate(); let (k1_public, k1_secret) = k1.to_string_pair(); let (k2_public, k2_secret) = k2.to_string_pair(); assert!(KeyPair::try_from((k1_public.clone(), k1_secret.clone().unwrap())).is_ok()); assert!(KeyPair::try_from((k2_public.clone(), k2_secret...
Rust
0
expected = [ { "date": today() , "npatrons": 2 # most recent first , "receipts": 3.00 } , { "date": today() , "npatrons": 3 # Since this is rare, don't worry that we double-count alice. , "re...
Python
1
en(data_loaders) == 1 return data_loaders[0] return data_loaders def build_test_loader(cfg, is_train=False): path_catalog = import_file( "monocd.config.paths_catalog", cfg.PATHS_CATALOG, True ) DatasetCatalog = path_catalog.DatasetCatalog transforms = build_transforms(cfg...
Python
1
chunk[0] as usize], cell_data.positions[chunk[1] as usize], cell_data.positions[chunk[2] as usize], ); let (n1, n2, n3) = ( cell_data.normals[chunk[0] as usize], cell_data.normals[chunk[1] as usize], cell_data.normal...
Rust
0
: ("log2(U9)", "U3"), precedence: !0, n_args: 1, op_type: Function, }, ]; use std::io::Write; write!( f, " /** Convenient type operations. Any types representing values must be able to be expressed as `ident`s. That means they need to be in scope...
Rust
0
APT: u16 = 264; pub const ARPHRD_ROSE: u16 = 270; pub const ARPHRD_X25: u16 = 271; pub const ARPHRD_HWX25: u16 = 272; pub const ARPHRD_PPP: u16 = 512; pub const ARPHRD_CISCO: u16 = 513; pub const ARPHRD_HDLC: u16 = ARPHRD_CISCO; pub const ARPHRD_LAPB: u16 = 516; pub const ARPHRD_DDCMP: u16 = 517; pub const ARPHRD_RAWHD...
Rust
0
import json from typing import Any, Dict, Optional from tau_bench.envs.tool import Tool class UpdateInvestorDetails(Tool): @staticmethod def invoke(data: Dict[str, Any], investor_id: str, name: str, contact_email: str, accreditation_status: str) -> str: investors = data.get("in...
Python
1
#[cfg(test)] mod tests { use super::*; #[test] fn example01() { let mut g = SimpleGrid::create_from("...>>>>>...\n"); step(&mut g); assert_eq!(g.to_string().as_str(), "...>>>>.>..\n"); step(&mut g); assert_eq!(g.to_string().as_str(), "...>>>.>.>.\n"); } #[te...
Rust
0
_base_ = '../mask_rcnn/mask_rcnn_r50_caffe_fpn_mstrain_1x_coco.py' # model settings model = dict( type='PointRend', roi_head=dict( type='PointRendRoIHead', mask_roi_extractor=dict( type='GenericRoIExtractor', aggregation='concat', roi_layer=dict( ...
Python
1
xupéry', 5, 'Un cuento filosófico que sigue las aventuras de un niño extraterrestre mientras viaja por diferentes planetas.'], ['Harry Potter (serie)', 'J.K. Rowling', 5, 'Una serie de libros que sigue las aventuras del joven mago Harry Potter mientras asiste a la escuela de magia Hogwarts.'], ['Crimen y ca...
Python
1
b"&#48;", b"0"); eval(b"&#0048;", b"0"); eval(b"&#000000000000000000000000000000000000000000048;", b"0"); eval(b"&#4433;", b"\xe1\x85\x91"); eval(b"&#1114112;", b"\xef\xbf\xbd"); eval(b"&#999999999999999999999999999999999999999999999;", b"\xef\xbf\xbd"); } #[test] fn test_named_entity_decoding() { ...
Rust
0
s.success() { WalkerRuleResult::IncludeItem } else { WalkerRuleResult::ExcludeItem }) }), }); } } use ::*; /// Sends input params down to children and events back to the parent node. pub struct Passthrough; impl<E, P: Clone...
Rust
0
# configs/dataset_config.py # 数据集划分相关参数,供train/finetune等任务统一调用 # 调整分割比例,确保验证集有足够样本进行评估 # 原来: SPLIT_RATIO = (0.8, 0.1, 0.1) # 训练/验证/测试集比例 # 现在: 增加验证集比例,减少训练集比例 SPLIT_RATIO = (0.7, 0.2, 0.1) # 训练70%,验证20%,测试10% # 这样56张图像会被分割为:训练39张,验证11张,测试6张 SPLIT_SEED = 42 # 随机种子,保证划分可复现
Python
1
""" Copyright 2013 Steven Diamond 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
> { match self.0.get_float(key) { Ok(v) => Ok(Some(v)), Err(config::ConfigError::NotFound(_)) => Ok(None), Err(err) => Err(err).context(SettingsError::GetFloat), } } pub fn get_bool(&self, key: &str) -> Result<Option<bool>> { match self.0.get_bool(key...
Rust
0
data(animal::TYPE).to_string() } pub fn farm() -> String { misc::random_data(animal::FARM).to_string() } pub fn cat() -> String { misc::random_data(animal::CAT).to_string() } pub fn dog() -> String { misc::random_data(animal::DOG).to_string() } #[cfg(test)] mod tests { use crate::animal; use cra...
Rust
0
embedded_ram21; #[doc = "CSE PRAM21LL register."] pub struct EMBEDDEDRAM21LL { register: ::vcell::VolatileCell<u8>, } #[doc = "CSE PRAM21LL register."] pub mod embedded_ram21ll; #[doc = "CSE PRAM21LU register."] pub struct EMBEDDEDRAM21LU { register: ::vcell::VolatileCell<u8>, } #[doc = "CSE PRAM21LU register....
Rust
0
from filepath.file_relative_paths import ImagePathAndProps from tasks.Task import Task import traceback from tasks.constants import TaskName class ClaimQuests(Task): def __init__(self, bot): super().__init__(bot) def do(self, next_task=TaskName.ALLIANCE): super().set_text(title='Claim Quest ...
Python
1
label='Preço Observado', color='blue') axes[0].plot(df_opcao.index, df_opcao['call_price_bs'], label='Black-Scholes', color='orange') axes[0].plot(df_opcao.index, df_opcao['call_price_lstm'], label='LSTM', color='red') axes[0].set_title('Cotação opção vs valores estimados') axes[0].set_ylabel('Preç...
Python
1
ings() -> Result<(), ()> { let settings = Settings { error_message: String::from("There is a problem with the ingress that has been applied to the cluster, and it cannot be mutated to support Istio"), }; assert!(settings.validate().is_ok()); Ok(()) } } mod compiler; mod ...
Rust
0
ils.decode(segms[i]).astype(np.bool) img[mask] = img[mask] * 0.5 + color_mask * 0.5 # draw bounding boxes labels = [ np.full(bbox.shape[0], i, dtype=np.int32) for i, bbox in enumerate(bbox_result) ] labels = np.concatenate(labels) mmcv.imshow_det_bboxes( img, ...
Python
1
rs2: u8 }, Remw { rd: u8, rs1: u8, rs2: u8 }, Remuw { rd: u8, rs1: u8, rs2: u8 }, /* A extension */ /* Base Opcode = AMO */ LrW { rd: u8, rs1: u8, aqrl: Ordering }, LrD { rd: u8, rs1: u8, aqrl: Ordering }, ScW { rd: u8, rs1: u8, rs2: u8, aqrl: Ordering }, ScD { rd: u8, rs1: u8, rs2: u8...
Rust
0
# Copyright 2025 The kauldron Authors. # # 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...
Python
1
arr = [['D', 'A', 'T', 'A', 'W'], ['B', 'B', 'Q', 'K']] num = int(input()) if num % 2 == 1: arr[0]=sorted(arr[0]) else: arr[1]=sorted(arr[1]) for i in range(2): for j in arr[i]: print(j, end = "") print()
Python
1
am_addr.inner = 0b111_10_11101_01010; ppu.increment_vram_addr_y(); // increment should overflow into bit 11 assert_eq!(ppu.current_vram_addr.inner, 0b000_00_00000_01010); // set coarse y = 29, fine y = 6 ppu.current_vram_addr.inner = 0b110_10_11111_01010; ppu.increment_vram_addr_y(); // inc...
Rust
0
DT_FLAGS, DT_PREINIT_ARRAY, DT_PREINIT_ARRAYSZ, DT_SYMTAB_SHNDX, DT_GNU_PRELINKED, DT_GNU_CONFLICTSZ, DT_GNU_LIBLISTSZ, DT_CHECKSUM, DT_PLTPADSZ, DT_MOVEENT, DT_MOVESZ, DT_FEATURE_1, DT_POSFLAG_1, DT_SYMINSZ, DT_SYMINENT, DT_GNU_HASH, DT_TLSDESC_PLT, ...
Rust
0
sed. """ db_user = db.query(models.User).filter(models.User.user_id == user_id).first() if not db_user: raise HTTPException(status_code=404, detail="User not found") return db_user @users_admin_router.delete("/users/{user_id}", response_model=schemas.UserResponse) def delete_user(user_id: int, ...
Python
1
import os import requests import dns.resolver def subdomain_bruteforce(domain, wildcard_ips): # Dynamically get the path to the wordlist in the VulnRecon Suite root project_root = os.path.dirname(os.path.abspath(__file__)) # this points to modules/ project_root = os.path.dirname(project_root) # go one le...
Python
1
= "`read()` method returns [pdac_w1_0_47::R](pdac_w1_0_47::R) reader structure"] impl crate::Readable for PDAC_W1_0_47 {} #[doc = "`write(|w| ..)` method takes [pdac_w1_0_47::W](pdac_w1_0_47::W) writer structure"] impl crate::Writable for PDAC_W1_0_47 {} #[doc = "Peripheral Domain Access Control"] pub mod pdac_w1_0_47...
Rust
0
) as *mut crate::kcapi_handle; let mut ret = crate::kcapi_md_init(&mut handle as *mut _, alg.as_ptr(), 0); assert_eq!(ret, 0); ret = crate::kcapi_md_setkey(handle, FB_KDF_KEY.as_ptr(), FB_KDF_KEY.len() as u32); assert_eq!(ret, 0); let ret = c...
Rust
0
)] pub struct RAM { #[doc = "0x00 - Description cluster\\[n\\]: RAMn power control register"] pub power: self::ram::POWER, #[doc = "0x04 - Description cluster\\[n\\]: RAMn power control set register"] pub powerset: self::ram::POWERSET, #[doc = "0x08 - Description cluster\\[n\\]: RAMn power control c...
Rust
0
(), "level": "INFO", "taskName": None, }, json.loads(fake_out.getvalue()), ) def test_json_logger_extra_args(self): with patch("sys.stdout", new=io.StringIO()) as fake_out: logging.config.dictConfig( ...
Python
1
h image and corresponding annotations. Returns: tuple: A tuple of features from ``rpn_head`` and ``roi_head`` forward. """ assert batch_data_samples != None, 'Copy the code get_flops.py from mmdetection-3.x to mmrotate-1.x' results = () ou...
Python
1
""" 射击型植物基类 """ import random from .base_plant import BasePlant class ShooterPlant(BasePlant): """射击型植物的基类""" def __init__(self, row, col, plant_type, constants, images, level_manager, base_shoot_delay=60): super().__init__(row, col, plant_type, constants, images, level_manager) # 射击参数 ...
Python
1
#!/usr/bin/env python3 import os import re import pandas as pd def parse_timing(file_path): """parse timing from output file""" with open(file_path, 'r') as f: content = f.read() # extract timing using regex match = re.search(r'CPU time: ([\d.]+) seconds|GPU time: ([\d.]+) seconds', co...
Python
1
"\nLikely have zombie(s) with the same cloud name on the network." + "\nLook at the cloud IP's in 'grep Paxos sandbox/*stdout*' for some IP's you didn't expect." + "\n\nYou probably don't have to do anything, as the cloud shutdown in this test should" + "\nhave sen...
Python
1
_index: `torch.Tensor` of shape [2, num_edges] :param h_E: tuple (s, V) of edge embeddings :param seq: if not `None`, int `torch.Tensor` of shape [num_nodes] to be embedded and appended to `h_V` ''' if seq is not None: seq = self.W_s(seq) h_V =...
Python
1
se, } optional_conditions = [ optional_conditions_to_jsonschema(field.name_field, field.optional_conditions) for field in fields if field.optional_conditions ] if optional_conditions: schema["allOf"] = optional_conditions try: ...
Python
1
bug, PartialEq, Eq, Clone, ParenthesizedNode, IntoPy)] pub struct Call<'a> { pub func: Box<Expression<'a>>, pub args: Vec<Arg<'a>>, pub lpar: Vec<LeftParen<'a>>, pub rpar: Vec<RightParen<'a>>, pub whitespace_after_func: ParenthesizableWhitespace<'a>, pub whitespace_before_args: ParenthesizableWh...
Rust
0
as usize }, 32usize, concat!( "Offset of field: ", stringify!(VmbInterfaceInfo_t), "::", stringify!(permittedAccess) ) ); } #[repr(C)] #[derive(Debug, Copy, Clone, PartialEq)] pub struct VmbCameraInfo_t { pub cameraIdString: *const...
Rust
0
arch // explicitly. This results in identical behavior, but a different message. rgtest!(after_match1_explicit, |dir: Dir, mut cmd: TestCommand| { dir.create_bytes("hay", HAY); cmd.args(&["--no-mmap", "-n", "Project Gutenberg EBook", "hay"]); let expected = "\ 1:The Project Gutenberg EBook of A Study In Sc...
Rust
0
e<Rgb565> = Rectangle::new(Coord::new(0, 0), Coord::new(160, 40)) .fill(Some(Rgb565::from((255, 255, 255)))); // disp_lcd.draw(black_backdrop.into_iter()); // disp_lcd.draw(white_backdrop.into_iter()); let messure0: Measurement = Measurement::Ptat { block: Block0 }; let messure1: Measure...
Rust
0
r(), pixel_format.as_raw() as u32, access.as_raw() as i32, width as i32, height as i32, ) }) .map_or_else( || Err(SdlError::UnsupportedFeature), |texture| { Ok(Self { t...
Rust
0
import discord import os import sys from discord.ext import commands from bot.utils.logger import logger class Admin(commands.Cog): def __init__(self, bot): self.bot = bot @commands.hybrid_command(name="restart", description="Redémarre le bot.") @commands.is_owner() async def restart(self, ct...
Python
1
from rectangle import Rectangle r = Rectangle(10, 5) print(r.area) # 50
Python
1
or x, y in cands if (rank[min(x, y)], rank[max(x, y)]) != (rank[min(pos)], rank[max(pos)]) ] else: shift = cluster[inter_size - 1 :] + cluster[: inter_size - 1] cands = zip(cluster + shift, shift + cluster) cands = [pos] + [ (x, y) for x, y in cand...
Python
1
me:ident: $value:expr,)*) => { $( #[test] fn $name() { let (return_type, prices, expected) = $value; let actual = Ret::<FixedNumber>::new(&prices, return_type); assert_ok!(&actual); let actual = actual.unwrap().ret; ...
Rust
0
let height = tree_height(self.mem.get_page(table_root), &self.mem); max_subtree_height = max(max_subtree_height, height); } } Ok(DbStats::new( master_tree_height + max_subtree_height, self.mem.count_free_pages()?, )) } #[allow(dead_cod...
Rust
0
dump_data_mem::dump_as_txt(&data_mem); } println!("Done!"); } fn load_instr(mem: instr_mem::Memory) -> instr_mem::Memory { let mut loader = MemLoader::new(mem); // s0 = *mem loader.load_instr( ADD (S0(), ZERO(), ZERO()) ); loader.load_instr( ADDI(S7(), ZERO(), 256) ); loader.loa...
Rust
0
l_size total_size += len(byte_array) elif os.path.isdir(file_path): subdir_c_code, subdir_handler_code = process_folder(file_path, True) c_code += subdir_c_code handler_code += subdir_handler_code return c_code, handler_code folder_...
Python
1
i, &rule) < 0) { bpf_printk("Error: failed to get rule [index %d]", i); return -1; } if (eval_ipv6_rule(rule, packet)) { action = rule->action; } } } // if action != 1 then it must have matched a rule if (rule && ru...
Rust
0
def compute_loss(self, labels, logits): """CrossEntropyLoss that ignores pad tokens""" loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits= True, reduction=tf.keras.losses.Reduction.NONE) melted_labels = tf.reshape(labels, (-1,)) active_loss = tf.not_equal(melted_labels, self.con...
Python
1
ptr .replace(thread_state.rump_lwp.load(Ordering::SeqCst)); } fn exit(&self) { let yielder: &mut ThreadControlBlock = Environment::thread(); let _prev = self.owner.replace(None); let _prev_ptr = self.lwp_ptr.replace(ptr::null()); let v = self.counter.fetch_sub(1, O...
Rust
0
rCriticRecurrent': # rnn_type = 'lstm' # rnn_hidden_size = 512 # rnn_num_layers = 1 class algorithm: # training params value_loss_coef = 1.0 use_clipped_value_loss = True clip_param = 0.2 entropy_coef = 0.01 num_learning_epochs = 5 num...
Python
1
"""무인도 여행 면적구하기는 dfs, bfs 뭘 써도 똑같음. """ def get_food_amount(sy, sx, height, width, maps, visited): stack = [(sy, sx)] DY = [1, 0, -1, 0] DX = [0, 1, 0, -1] food_amount = int(maps[sy][sx]) visited[sy][sx] = True while stack: y, x = stack.pop() for dy, dx in zip(DY, DX): ...
Python
1
} } x_offset += WIDTH; } let mut b = BytesMut::with_capacity(16384).writer(); // let mut encoder = JpegEncoder::new_with_quality(&mut out, 70); // let r = encoder.encode_image(&img); let encoder = PngEncoder::new_with_quality(&mut b, CompressionType::Default, FilterType::NoFilter); ...
Rust
0
WithoutXyz::<f64>::from(hsv); let hwb: Hwb<_, f64> = Default::default(); WithoutXyz::<f64>::from(hwb); let luma: Luma<Linear<::white_point::E>, f64> = Default::default(); WithoutXyz::<f64>::from(luma); } #[test] fn into_without_xyz() { let color = WithoutXyz::<f64>...
Rust
0
# -*- coding: utf-8 -*- import system_tests class IptcFieldParsingTooStrict(metaclass=system_tests.CaseMeta): url = "http://dev.exiv2.org/issues/501" filename = "$data_path/exiv2-bug501.jpg" commands = ["$exiv2 -u -pi $filename"] encodings = ['windows-1252'] stdout = ["""Iptc.Application2.Re...
Python
1
RY: Lazy<BlockRegistry> = Lazy::new(BlockRegistry::new); struct BlockRegistry { states: Vec<RawBlockState>, id_mapping: AHashMap<RawBlockStateProperties, u16>, valid_properties: AHashMap<BlockKind, ValidProperties>, } impl BlockRegistry { fn new() -> Self { const STATE_DATA: &[u8] = include_by...
Rust
0
ls_like = data["main"]["feels_like"] description = data["weather"][0]["description"] humidity = data["main"]["humidity"] wind_speed = data["wind"]["speed"] return ( f"🌍 Погода в {city_name}:\n" f"🌡 Температура: {temperature}°C\n" f"🤔 Ощущается как: {feels_like}°C\n" f...
Python
1
from server.tests.utils import BaseTestCase class TestZoneCompletions(BaseTestCase): def test_zones(self): self.assert_zones("ui.form_card(box='')") self.assert_zones('ui.form_card(box="")') def test_zones_multilne(self): self.assert_zones("ui.form_card(\nbox=''\n)", False) s...
Python
1
e_circuit(self) -> QuantumCircuit: circuit = QuantumCircuit(self.num_qubits) angles = np.zeros(self.num_qubits) for qubit_index in range(self.num_qubits): dig = bit_value(self.speed, qubit_index) for i in range(self.num_qubits - qubit_index): # (2 * posit...
Python
1