text
string
label_name
string
labels
int64
import argparse from pathlib import Path import tomli as tomllib def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--typeshed", type=Path, required=True) args = parser.parse_args() typeshed_p_to_d = {} for stub in (args.typeshed / "stubs").iterdir(): if not stub...
Python
1
"""empty message Revision ID: ffa75d04e6ef Revises: c3470e2d3224 Create Date: 2021-08-02 11:30:05.509051 """ import sqlalchemy_utils from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'ffa75d04e6ef' down_revision = 'c3470e2d3224' branch_labels = None depends_on = None...
Python
1
etary::kinds::scalar_data_envelope::ScalarDataEnvelope; use anyhow::Result; use cid::Cid; use sk_cbor::Value; use std::convert::TryFrom; #[derive(thiserror::Error, Debug)] pub enum Error { #[error("failed to read HoliumCBOR data")] FailedToReadHoliumCborData, #[error("failed to write HoliumCBOR data")] ...
Rust
0
, 10, 5, 1] plot_embeddings(classes,im_index,npz_path,ax, cm, ['a','Leukemia'],representative_indices,0.8) def annotate_bld(ax): classes={ 6: 'NEU', 2: 'EBO', 7: 'PLA', 1: 'EOS', 5: 'MONO', 3: 'GRA', 4: 'LYMPH', 0: ...
Python
1
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from lxml import html from json import dumps from requests import get from os import chmod from stat import S_IREAD, S_IRGRP, S_IROTH from json import load with open('as-renamed.json','r', encoding='utf-8') as f: as_renamed = load(f) url_as = 'https://bgp.potaroo.ne...
Python
1
try: with open(final_output_path, 'w') as f_out: json.dump(all_molecules, f_out, indent=4) print(f"Successfully merged {len(intermediate_files)} files into {final_output_path}.") except Exception as e: print(f"Failed to save merged JSON file {final_output_path}: {e}") def check...
Python
1
os); // Can only go left or right if turn.is_none() { continue; } let turn = turn.unwrap(); let mut steps = 0; let vec: Vector2D = turn.absolute.into(); let mut pos = new_robot.position + vec; while let Some...
Rust
0
.rs use crate::world::Location; use bracket_lib::prelude::*; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash, Default)] pub struct Position { pub x: usize, pub y: usize, } impl Position { pub const fn new(x: usize, y: usize) -> Self { Self { ...
Rust
0
", failure_tests=True ) self.assertTrue(success) def testEnableWarnDiags(self): import pprint def filtered_vars(var_dict): dunders = [nm for nm in var_dict if nm.startswith("__")] return { k: v for k, v in var_dict.items() ...
Python
1
] pub type W = crate::W<u32, super::CRSR_IMG>; #[doc = "Register CRSR_IMG[%s] `reset()`'s with value 0"] impl crate::ResetValue for super::CRSR_IMG { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `CRSR_IMG`"] pub type CRSR_IMG_R = crate::R<u32...
Rust
0
import time from unittest.mock import Mock, patch import numpy as np import pytest from providers.unitree_camera_vlm_provider import ( UnitreeCameraVideoStream, UnitreeCameraVLMProvider, ) @pytest.fixture def mock_video_client(): with patch("providers.unitree_camera_vlm_provider.VideoClient") as mock: ...
Python
1
et(labels))) nb_instances = len(labels) data = np.zeros(shape=(nb_instances, 1)) for i in range(0, nb_instances): current_label = labels[i] idx = unique_labels.index(current_label) data[i] = idx return DataFrame(data=data, index=index, columns=columns...
Python
1
Changes the process group. pub fn set_process_group(&mut self, pg: Weak<SpinLock<ProcessGroup>>) { self.process_group = pg; } /// The current process group. pub fn process_group(&self) -> Arc<SpinLock<ProcessGroup>> { self.process_group.upgrade().unwrap() } /// The current pro...
Rust
0
ot_empty(&self) { let string = self.value.clone().into(); if string.is_empty() { panic!("Expected {} to not be empty, but it is.", self.name) } } fn has_length(&self, expected_length: usize) { let string = self.value.clone().into(); let len = string.len(); ...
Rust
0
!(data1, data); assert_eq!(data2, data); assert_eq!(data4, data); assert_eq!(data8, data); } #[test] fn declare_byte_can_get_set() { let mut db = Instruction::with_declare_byte_16(0x77, 0xA9, 0xCE, 0x9D, 0x55, 0x05, 0x42, 0x6C, 0x86, 0x32, 0xFE, 0x4F, 0x34, 0x27, 0xAA, 0x08); db.set_declare_byte_value(0, 0xE2); ...
Rust
0
the UART error interrupt is\n asserted"] ENABLE, } impl From<DMAONERR_A> for bool { #[inline(always)] fn from(variant: DMAONERR_A) -> Self { match variant { DMAONERR_A::DISABLE => false, DMAONERR_A::ENABLE => true, } } } #[doc = "Reader of...
Rust
0
c_method("java/util/Locale$FilteringMode\0", "valueOf\0", "(Ljava/lang/String;)Ljava/util/Locale$FilteringMode;\0"); __jni_env.call_static_object_method_a(__jni_class, __jni_method, __jni_args.as_ptr()) } } // // Not emitting: Non-public method // /// [FilteringMode]...
Rust
0
Fields::Named(ref fields) => generate_write_body_for_struct(fields), Fields::Unnamed(_) => unimplemented!(), Fields::Unit => quote!(Ok(())), }, Data::Enum(ref data) => generate_write_body_for_enum(data), Data::Union(_) => unimplemented!(), }; // Complete ...
Rust
0
m[team] = by_team.get(team, 0) + 1 observations = [] for team, count in by_team.items(): observations.append((count, {"team": team})) return observations except Exception: return [(0, {"team": "error"})] def observe_team_capacity(options): """Callba...
Python
1
ng.""" temperature: float """A higher temperature increases randomness in the outputs.""" top_p: float """An alternative to temperature for nucleus sampling; 1.0 includes all tokens.""" class CreateEvalCompletionsRunDataSourceParam(TypedDict, total=False): source: Required[Source] """Determi...
Python
1
&IInspectable, localName: &HStringArg) -> Result<Option<XmlAttribute>> { unsafe { let mut out = null_mut(); let hr = (self.get_vtbl().GetAttributeNodeNS)(self.get_abi() as *const _ as *mut _, namespaceUri.get_abi() as *const _ as *mut _, localName.get(), &mut out); if hr == S_OK { Ok(XmlAttrib...
Rust
0
ate = 0.0001 # 0.0005 # 0.001 n_layers = 1 #2 n_neurons = 256 #512 batch_size = 64 n_epochs = 1000 early_stop_patience = 150 #100 #50 lr_scheduler_patience = 10 model_type = 'MobileNetV1' n_splits = 10 #Para rodar teste de leave-one-out cross validation descomente abaixo #run_lo...
Python
1
onIds or whose error value is an `Error<Value>` describing the error that occurred. pub async fn get_transactions(self, transaction_ids: Vec<&str>) -> Result<Transactions> { valid_vec_len(&transaction_ids, ERR_EMPTY_TRANSACTION_IDS)?; valid_vec_hash(&transaction_ids)?; let ids = Transactio...
Rust
0
from!(i8, NonMaxI32); impl_smaller_from!(i8, NonMaxI64); impl_smaller_from!(i8, NonMaxI128); impl_smaller_from!(i8, NonMaxIsize); impl_smaller_from!(i16, NonMaxI32); impl_smaller_from!(i16, NonMaxI64); impl_smaller_from!(i16, NonMaxI128); impl_smaller_from!(i16, NonMaxIsize); impl_smaller_from!(i32, NonMaxI64); impl_sm...
Rust
0
crypto::verify_chunking( &crypto::ChunkingInstance { g1_gen: miracl::ECP::generator(), public_keys: public_keys.clone(), ciphertext_chunks: ciphertext.cc.clone(), randomizers_r: ciphertext.rr.clone(), ...
Rust
0
LOAD_OPENGL_DLL = ''' version(Windows) { private import std.c.windows.windows; } else { private import core.sys.posix.dlfcn; } version(Windows) { private __gshared HMODULE libGL; } else { private __gshared void* libGL; } extern(System) private @nogc alias gladGetProcAddressPtrType = void* function(con...
Python
1
ue) associated with the given position on the unit sphere, /// in `[0, 12*nside^2[` /// # Panics /// If `lat` **not in** `[-90, 90]`, this method panics. #[wasm_bindgen(js_name = multiLonlatToNested)] pub fn wasm_hash_multi(depth: u8, coords: &[f64]) -> Box<[f64]> { let mut vec: Vec<f64> = Vec::with_capacity(coor...
Rust
0
'series_list.pkl'), 'wb') as pkl_fh: pickle.dump(series_list, pkl_fh) util.print_err('Dumping JSON file...') with open(os.path.join(output_dir, 'series_list.json'), 'w') as json_file: json.dump([dict(series) for series in series_list], json_file, indent=4, sort_keys=True, defau...
Python
1
出告警</span>" ), "4": ( lambda x: "<span>{}分钟内连续{}次失败登录触发,每{}秒后再次检测</span>".format( x["task_data"].get("cycle"), x["task_data"].get("count"), x["task_data"].get("interval"), ) ), "5": ( lambda x: "<span>服务停止时发送一次通知,{}秒后再次检测</span>".format...
Python
1
""" Author: YidaChen Time is: 2023/9/6 this Code: 图像配准评价指标计算方法 [MI, MS-SSIM, NCC] """ import os.path import math import numpy as np import torch from PIL import Image import torch.nn.functional as F from pytorch_msssim import ms_ssim # 避免错误提示 np.seterr(divide='ignore', invalid='ignore') class ImageMetrics: def...
Python
1
from typing import TYPE_CHECKING, Any from langchain._api import create_importer if TYPE_CHECKING: from langchain_community.tools import StdInInquireTool # Create a way to dynamically look up deprecated imports. # Used to consolidate logic for raising deprecation warnings and # handling optional imports. DEPRECA...
Python
1
# Copyright (c) OpenMMLab. All rights reserved. from .base_panoptic_fusion_head import \ BasePanopticFusionHead # noqa: F401,F403 from .heuristic_fusion_head import HeuristicFusionHead # noqa: F401,F403 from .maskformer_fusion_head import MaskFormerFusionHead # noqa: F401,F403
Python
1
# SPDX-License-Identifier: Apache-2.0 # © Crown Copyright 2025. This work has been developed by the National Digital Twin Programme # and is legally attributed to the Department for Business and Trade (UK) as the governing entity. """002_create_epc_assessment_table Revision ID: e4517d52c442 Revises: 0cba3d41c22e Crea...
Python
1
_instruction_if_vx_equals_vy_negative() { // 0x5XY0: Skips the next instruction if VX equals VY. let program: Vec<u8> = vec![0x54, 0x60]; let mut chip8 = create_and_load(&program).unwrap(); chip8.v[4] = 0x17; chip8.v[6] = 0x23; let orig_pc = chip8.pc; chip8.ex...
Rust
0
# ------------------------------------------------------------------------------ # Copyright 2022 Upstream Data Inc - # - # Licensed under the Apache License, Version 2.0 (the "License"); ...
Python
1
import os #path = "C:\\Users\\cakow\\Desktop\\test.txt" path = "~/Desktop/py-code-bro" expanded_path = os.path.expanduser(path) print(expanded_path) if os.path.exists(expanded_path): print("yes") if os.path.isfile(expanded_path): print("that is a file") elif os.path.isdir(expanded_path): p...
Python
1
::std::mem::transmute(th_off) }; th_off as u64 }); __bindgen_bitfield_unit } } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct tcphdr__bindgen_ty_1__bindgen_ty_2 { pub source: u16, pub dest: u16, pub seq: u32, pub ack_seq: u32, pub _bitfield_1: __BindgenBitfieldU...
Rust
0
{:?}'", stringify!($function), status); } } } } use std::mem::replace; const IDX_PART1: usize = 2020; const IDX_PART2: usize = 30_000_000; const SEED_LEN: usize = 6; #[inline] pub fn solve() -> (usize, usize) { let mut prev = 0; let mut last_seen = vec![0; IDX_PART2]; include_str!("input.txt") ...
Rust
0
#!/usr/bin/env python # -*- encoding: utf-8 -*- import pprint import pytest import torch import torch.nn as nn import colossalai.legacy.nn as col_nn from colossalai.legacy.context.parallel_mode import ParallelMode from colossalai.legacy.core import global_context as gpc from colossalai.legacy.initialize import launc...
Python
1
.store_command(control_word); } } } // Each instance of this represents one of the PIT counters. They are used to // implement one-shot and repeating timer alarms. An 8254 has three counters. struct PitCounter { // EventFd to write when asserting an interrupt. interrupt_evt: Option<EventFd>, /...
Rust
0
orig_time[i].into(), orig_signal[i].into(), orig_time[i + 1].into(), orig_signal[i + 1].into(), )); break; } } if item.into() > orig_time[orig_time.len() - 1].into() { ...
Rust
0
::proposal::Action; use ic_nns_governance::pb::v1::{ manage_neuron::{Command, NeuronIdOrSubaccount}, manage_neuron_response::Command as CommandResponse, proposal, AddOrRemoveNodeProvider, ExecuteNnsFunction, GovernanceError, ListNodeProvidersResponse, ManageNeuron, ManageNeuronResponse, NnsFunction, Nod...
Rust
0
rn indices_columns_chosen def decode(self, syndrome : np.array): # Usamos el primer BP para encontrar el error. start = timer() recovered_error = self._bpd.decode(syndrome) end = timer() #print(f"[Python] First stage bp: {end-start}") # Si converge de...
Python
1
g slice without checking that the string contains /// valid UTF-16. /// /// See the safe version, [`from_slice_mut`][Self::from_slice_mut], for more information. /// /// # Safety /// /// This function is unsafe because it does not check that the slice passed to it is valid /// UTF-16. If...
Rust
0
""" Module: app.urls Description: This module defines URL patterns for the Archimatch application using Django's path() function. It includes routing configurations for various API endpoints using Django Rest Framework's DefaultRouter. """ from django.urls import include from django.urls import path from rest_fram...
Python
1
alled domain = InferencerFactory._get_labels_domain(model) match domain: case Domain.CLASSIFICATION: inferencer = ClassificationInferencer(model, device=device, max_async_requests=max_async_requests) case Domain.DETECTION: inferencer = DetectionInf...
Python
1
from collections.abc import Mapping from typing import Any, TypeVar from attrs import define as _attrs_define from attrs import field as _attrs_field T = TypeVar("T", bound="RemoveAllArgs") @_attrs_define class RemoveAllArgs: """PersonFindArgs.""" additional_properties: dict[str, Any] = _attrs_field(init=F...
Python
1
): if isinstance(child_module, HunyuanVideoSingleTransformerBlock): child_module.forward = create_checkpointed_forward( child_module, torch.device(config.train_device), ["hidden_states"], conductor, layer_index, ) layer_index +=...
Python
1
# MIT License # Copyright (c) 2024 The HuggingFace Team # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, ...
Python
1
from itertools import product import pytest import pandas as pd import instructor from litellm import completion from pydantic import BaseModel class Address(BaseModel): number: int street_name: str city: str country: str entries = pd.DataFrame( { "input": [ "Please send th...
Python
1
lur_median") self.print_current_algorithm_ofImage(2) if SI.syncFlag_blur_ofImage: self.forbid_blur_ofImage(False) # 恢复中值滤波下禁止第二个滤波核设置参数 elif rbName == "rbtn_blur_median_ofImage": if "blur_median" not in SI.imageAugmentAlgorithm_ofImage: SI.imageAugmentAlgor...
Python
1
# defer next_chr data_length times return ''.join(itertools.imap( defer, itertools.repeat(next_ch, data_length))) if __name__ == "__main__": import sys import os if len(sys.argv) != 3: print "use: python steganohide.py text.txt bild.bmp" sys.exit() else: ...
Python
1
# import tkinter # from tkinter import mainloop # # window = tkinter.Tk() # window.title("My Window") # window.minsize(width=500,height=500) # # my_lable = tkinter.Label(text="Hey There how are you?",font=("Arial",24,"bold")) # my_lable.pack() # # # # # # # # window.mainloop() # # import tkinter as tk # # # Function to...
Python
1
ionParams { transaction_id: None, return_error: None, description: None, } } } <reponame>cvng/prisma-engines use super::{super::helpers::*, AttributeValidator}; use crate::ast::Span; use crate::diagnostics::DatamodelError; use crate::{ast, dml, Datamodel, WithDatabaseNa...
Rust
0
local_location="TMP2", remote_location="sales/B.avro", folder_id="root" ), mock.call().upload_file( local_location="TMP3", remote_location="sales/C.avro", folder_id="root" ), ] ) @mock.patch(MODULE + ".GCSHoo...
Python
1
Op::Load { dst: select_u16(instr, 11, 9), offset: select_i16(instr, 8, 0), }), 0b0011 => Some(Op::Store { src: select_u16(instr, 11, 9), offset: select_i16(instr, 8, 0), }), 0b0100 => match select_bool(instr, 11) { false => Some...
Rust
0
if os.path.exists(file_path): logging.info( f"Uploading output file {file_path} to gs://{target_gcs_bucket}/{target_gcs_path}" ) storage_client = storage.Client() bucket = storage_client.bucket(target_gcs_bucket) blob = bucket.blob(target_gcs_path) blob.uploa...
Python
1
for neg, pos in neg_opt.items(): if pos == opt: opt = neg val = None break else: raise AssertionError("Shouldn't be able to get here") ...
Python
1
Theta1 = debugInitializeWeights(hidden_layer_size, input_layer_size) Theta2 = debugInitializeWeights(num_labels, hidden_layer_size) # Reusing debugInitializeWeights to generate X X = debugInitializeWeights(m, input_layer_size - 1) y = np.arange(1, 1+m) % num_labels # print(y) # Unroll param...
Python
1
ute: bool, pub self_deaf: bool, pub mute: bool, pub deaf: bool, } impl VoiceState { pub fn decode(value: Value) -> Result<VoiceState> { let mut value = try!(into_map(value)); warn_json!(value, VoiceState { user_id: try!(remove(&mut value, "user_id").and_then(UserId::decode))...
Rust
0
:new(((self.bits >> 13) & 0x01) != 0) } #[doc = "Bit 14 - DMA Channel 14"] #[inline(always)] pub fn dmach14(&self) -> DMACH14_R { DMACH14_R::new(((self.bits >> 14) & 0x01) != 0) } #[doc = "Bit 15 - DMA Channel 15"] #[inline(always)] pub fn dmach15(&self) -> DMACH15_R { DM...
Rust
0
ut_size: u32, pub activation: Activation, pub memory: Vec<f32>, pub hidden: Vec<f32>, pub states: LSTMState, pub g_gate: Arc<RwLock<Dense>>, pub i_gate: Arc<RwLock<Dense>>, pub f_gate: Arc<RwLock<Dense>>, pub o_gate: Arc<RwLock<Dense>>, pub v_gate: Arc<RwLock<Dense>> } impl LSTM {...
Rust
0
let expr2_0 = constructor_x64_load(ctx, expr0_0, &pattern1_0, &expr1_0)?; let expr3_0 = RegMemImm::Reg { reg: expr2_0 }; let expr4_0 = constructor_ushr_i8x16_mask(ctx, &expr3_0)?; return Some(expr4_0); } _ => {} } return None; } // Generated as int...
Rust
0
rsion { Version::HTTP_11 => Ok(stream.into()), Version::HTTP_2 => { #[cfg(feature = "http2")] { let connection = crate::h2::proto::handshake(stream).await?; Ok(connection.into()) } #[cfg(not...
Rust
0
######################################################################## # File name: __init__.py # This file is part of: aioxmpp # # LICENSE # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundat...
Python
1
cU64::new(1); ID.fetch_add(1, Ordering::Relaxed) } /// Create a new stream #[macro_export] macro_rules! stream { {$($block:tt)*} => { $crate::AsyncStream::new(|mut __y| async move{ macro_rules! yield_ { ($v:expr) => { __y.yield_item($v).await ...
Rust
0
pub trait Trait: frame_system::Trait { type Event: From<Event<Self>> + Into<<Self as frame_system::Trait>::Event>; } decl_storage! { trait SpotExchangeStore for Module<T: Trait> as SpotExchangeModule { Asset get(fn something): Option<u32>; Pair get(fn something): Option<u32>; OrderBook get(fn something): ...
Rust
0
;" => "\u{0231D}", "urcorner;" => "\u{0231D}", "urcrop;" => "\u{0230E}", "Uring;" => "\u{0016E}", "uring;" => "\u{0016F}", "urtri;" => "\u{025F9}", "Uscr;" => "\u{1D4B0}", "uscr;" => "\u{1D4CA}", "utdot;" => "\u{022F0}", "Utilde;" => "\u{00168}", ...
Rust
0
--- setup.py.orig 2019-05-10 21:59:01 UTC +++ setup.py @@ -295,19 +295,9 @@ package_data_exclude = { } data_files = [ - ('docs', ['docs/*.*']), - ('', ['readme/README.html']), - ('config', ['theonionbox/config/*.*']), - ('service', []), - ('service/FreeBSD', ['FreeBSD/theonionbox.sh']), - ('servic...
Python
1
,a3,1x,a10,2x,a. Note the postal code is an ascii string and left justified (a10). """ from geopy.geocoders import Nominatim, ArcGIS, GoogleV3 from pygmi.misc import ProgressBarText piter = ProgressBarText().iter ifile = r"D:\Workdata\seismology\macro\Copy of Intensity_Database_30Septembe...
Python
1
(message, length, &mut cur_token, token); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_field_name_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result...
Rust
0
let mut data = Vec::new(); data.resize(len as _, 0u8); let s = unsafe { sys::amd_comgr_action_info_get_options(h, &mut len, data.as_mut_ptr() as *mut _) }; Error::check(s)?; // we only allow setting the name using a `String`, // so we don...
Rust
0
import logging from adapter_covid19.corporate_bankruptcy import CorporateBankruptcyModel from adapter_covid19.data_structures import ( SimulateState, Utilisations, ) from adapter_covid19.datasources import Reader from adapter_covid19.gdp import BaseGdpModel from adapter_covid19.personal_insolvency import Perso...
Python
1
DWORD, sv103_anndelta: DWORD, sv103_licenses: DWORD, sv103_userpath: LMSTR, sv103_capabilities: DWORD, }} pub type PSERVER_INFO_103 = *mut SERVER_INFO_103; pub type LPSERVER_INFO_103 = *mut SERVER_INFO_103; STRUCT! {struct SERVER_INFO_402 { sv402_ulist_mtime: DWORD, sv402_glist_mtime: DWORD, ...
Rust
0
_class(panel_type) def draw_add_menu(self, context): layout = self.layout for cat in cat_list: if cat.poll(context): layout.menu("NODE_MT_category_%s" % cat.identifier) # stores: (categories list, menu draw function, submenu types, panel types) _node_categories...
Python
1
queue_len = 200; let mut fasta_reads: bool = false; let filename_str = qfile.to_str().unwrap(); if filename_str.contains(".fasta.") || filename_str.contains(".fa.") || filename_str.ends_with(".fa") || filename_str.ends_with(".fasta") ...
Rust
0
der<R: io::BufRead> { ticker: usize, line: String, reader: R, } impl<R: io::BufRead> LineReader<R> { /// Constructs a new line reader. pub fn new(r: R) -> LineReader<R> { LineReader { ticker: 0, line: String::with_capacity(256), reader: r, } } /// Returns the line number of the contained line. pu...
Rust
0
T, E>` 的处理只在从 Rust 函数向 T10 运行时返回一个值的时候进行。 pub trait IntoValue<T> { fn into_value(t: T) -> Result<Value, TError>; } /// 在这一层的 specialization 中特殊处理 `&Option<T>` 和 `&mut Option<T>` /// /// `&Option<T>` 或者 `&mut Option<T>` 会被进一步视为 `Option<&T>` 和 `Option<&mut T>`。 /// 这种特殊处理只会在从 Rust 函数向 T10 运行时返回一个值的时候进行。 pub trait I...
Rust
0
elf.mpf, &self.mpf, &other.mpf); self } } } impl<'a, 'b> Sub<&'a Mpf> for &'b Mpf { type Output = Mpf; fn sub(self, other: &Mpf) -> Mpf { unsafe { let mut res = Mpf::new(cmp::max(self.get_prec(), other.get_prec())); __gmpf_sub(&mut res.mpf, &self.mpf, &ot...
Rust
0
Rule::int, s), (Rule::quantifier, q), (Rule::EOI, _)] => { let n: usize = s.parse()?; let q = quantifier_from(q)?; Ok(TimeClue::Relative(n, q)) } [(Rule::time_clue, _), (Rule::relative_future, _), (Rule::int, s), (Rule::quantifier, q), (Rule::EOI, _)] => ...
Rust
0
mut self, buffer: BufferId, offset: u32, index_type: IndexSize); fn draw( &mut self, vertex_count: u32, first_vertex: u32, instance_count: u32, instance_offset: u32, ); fn draw_indexed( &mut self, index_count: u32, first_index: u32, ve...
Rust
0
: Mutex::new(msg_receiver), msg_sender: Mutex::new(msg_sender), call_sender: Mutex::new(tx), call_receiver: Mutex::new(rx), call_processor_thread_handle: Mutex::new(None), call_stop_event: Mutex::new(None), thread_handle: Mutex::new(None), ...
Rust
0
BABELCOLOR.iter() { let xyz = spd.to_xyz(); let xyz_ref: XYZf32 = colorchecker::XYZ_D65[name].into(); println!(" xyz: {}", xyz); println!("ref xyz: {}", xyz_ref); assert!(xyz.approx_eq( xyz_ref, F32Margin { ...
Rust
0
Lock => "Memory lock", WS2811Error::Mmap => "mmap error", WS2811Error::MapRegisters => "Map registers error", WS2811Error::GpioInit => "GPIO initialization error", WS2811Error::PwmSetup => "PWM setup error", WS2811Error::MailboxDevice => "Mailbox device error"...
Rust
0
0.035; /// Inertia information at a point in time. #[derive(Clone, Debug, PartialEq, PartialOrd)] pub struct Instant { /// The gyroscope inertia inforamation. pub gyroscope: Vector3, /// The accelerometer inertia inforamation. pub accelerometer: Vector3, } /// An inertia sensor. #[derive(Debug)] pub ...
Rust
0
region index. pub glyph: u32, /// Min and max coordinates in texture space. pub tex_bounds: [f32; 4], } mod tests { #[test] fn test_size() { assert_eq!(std::mem::size_of::<super::Prim>(), 88); } } // WARNING: This file was autogenerated by jni-bindgen. Any changes to this file may ...
Rust
0
successfully (un)bound fn set_depth_stencil_surface(&self, depth_stencil_surface: Option<&Surface>) -> Result<(), MethodError> { let ds = depth_stencil_surface.map_or(null_mut(), |ds| ds.as_raw()); let hr = unsafe { self.as_winapi().SetDepthStencilSurface(ds) }; MethodError::check("IDirect3...
Rust
0
from scapy.all import ARP, Ether, srp def discover_devices(target_ip): arp = ARP(pdst=target_ip) ether = Ether(dst="ff:ff:ff:ff:ff:ff") packet = ether/arp result = srp(packet, timeout=2, verbose=0)[0] devices = [] for sent, received in result: devices.append({'ip': received.psrc, 'mac...
Python
1
categories = { "flowers": ["Rose", "Lily", "Tulip", "Orchid", "Sunflower", "Daisy", "Jasmine", "Marigold", "Lotus"], "colors": ["Red", "Blue", "Green", "Yellow", "Pink", "Purple", "Orange", "Black", "White", "Cyan"], "fruits": ["Apple", "Banana", "Mango", "Grapes", "Orange", "Pineapple", "Strawber...
Python
1
self.test_cfg.iou_thr) nms_bboxes.append(class_bboxes[nms_ids]) nms_scores.append(class_scores[nms_ids]) nms_labels.append( bboxes.new_full( class_scores[nms_ids].shape, i, dtype=torch.long)) if len(nms_bboxes): ...
Python
1
` defaults to [`Stdout`](https://doc.rust-lang.org/std/io/struct.Stdout.html). */ #[macro_export] macro_rules! prn { ($($arg:tt)*) => ( { use std::io::Write; writeln!($crate::PrWriter, $($arg)*).ok(); } ); } /** Prints to the active [`Runtime`](struct.Runtime.html)'s current [`epr_writer`](f...
Rust
0
sing_docs)] pub unsafe fn new_u32(a: u32) -> Self { $what::U32(a) } #[allow(missing_docs)] pub unsafe fn new_u64(a: u64) -> Self { $what::U64(a) } #[allow(missing_docs)] pub unsafe fn new_u32u32(a: u32,...
Rust
0
let _policy = String::from(r#"{"OR": [{"ATT": "aa1::B"}, {"ATT": "aa2::A"}]}"#); // cp-abe ciphertext let _ct: BdabeCiphertext = encrypt(&_pk, &vec![_att1_pk, _att2_pk], &_policy, &_plaintext).unwrap(); // and now decrypt again with mathcing sk let _match = decrypt(&_pk,...
Rust
0
pub fn generate() -> u128 { 0x1234567890_abcdef_1234567890_abcdef } pub fn validate(_: u128) -> bool { true } } #[derive(Identifier, Eq, PartialEq, FromStr, Debug)] #[identifier(with = "mod_id")] struct Id(u128); fn main() { let id = Id::generate(); let expected_id: Id = "12345678...
Rust
0
()) .unwrap() } #[cfg(test)] mod tests { use std::{io::Write, iter, sync::Arc}; use assert_matches::assert_matches; use flate2::{write::GzEncoder, Compression}; use hyper::header::HeaderValue; use crate::dml_handlers::mock::{MockDmlHandler, MockDmlHandlerCall}; use super::*; co...
Rust
0
e), } impl FragmentArgument { fn into_value_string(self) -> TemplatingResult<String> { match self { FragmentArgument::Value(s) => Ok(s), FragmentArgument::Directive(_) => Err(TemplatingError::argument_error( "unknown", format!("Expected Value argument...
Rust
0
ScalarValue::Number(BigDecimal::from(123))) ); assert_eq!( ScalarValue::Number( BigDecimal::from_str( "12345678901234567890123456789012345678901234567890123456789012345678901234567890" ) .unwrap()...
Rust
0
########################################################## # pytorch-kaldi v.0.1 # Mirco Ravanelli, Titouan Parcollet # Mila, University of Montreal # October 2018 ########################################################## import sys import configparser import os from utils import create_curves # Checking arguments i...
Python
1
( Arg::with_name("URL") .help("List of URLs to get video link") .multiple(true) // This flag should allow multiple .required(true), // By default this argument MUST be present ) .get_matches() } fn run() { let matches = arg_parse(); l...
Rust
0
assert_eq!(buf, &[42, 43, // leaf values // inner 0, // flags 42,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, // digest 1,0,0,0,0,0,0,0, // tip ptr, left leaf 0, // flags 43,0,0,0,0,0,0,0, 0,0,0,0,0,0,0...
Rust
0