text
string
label_name
string
labels
int64
itude(), (Positive, 0u32)); assert_eq!(5.to_sign_magnitude(), (Positive, 5u32)); assert_eq!(0x7fffffff.to_sign_magnitude(), (Positive, 0x7fffffffu32)); assert_eq!((-0x80000000).to_sign_magnitude(), (Negative, 0x80000000u32)); } #[test] fn test_try_from_sign_magnitude() { ass...
Rust
0
import cv2 import dlib import numpy as np # dlib'in yüz tespiti için kullandığı model detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor( r"C:\Users\mlkoz\OneDrive\Desktop\Python\odev\shape_predictor_68_face_landmarks (1).dat") def detect_redness(face_region): """ Yüz bölgesinde...
Python
1
s, 2, MemoryUsage::Execute)); assert!((state.sp as usize) < cpu::STACK_SIZE); // Stack overflow state.sp = if (state.sp as usize) < cpu::STACK_SIZE { state.sp + 1 } else { state.sp }; // Increment sp state.stack[state.sp as usize] = state.pc; // Put PC on top of the stack state.pc = address; // Set PC...
Rust
0
se_body = response.bytes().await .expect("Bytes"); let inner_response = HttpResponse { status_code, headers, body: response_body.to_vec(), }; //TODO Design problem here: i'm using an abi version specific type here. Needs some engineering tx.clone...
Rust
0
astEditors: <NAME> * @LastEditTime: 2021-08-08 13:45:27 */ struct Solution; impl Solution { pub fn tribonacci(n: i32) -> i32 { match n { 0 => 0, 1..=2 => 1, _ => { let q = vec![vec![1, 1, 1], vec![1, 0, 0], vec![0, 1, 0]]; let res = Sel...
Rust
0
ot(Hybridrear_force[:,0],Hybridrear_force[:,2],color='blue',linestyle='-.',label='Hybrid Adam Fry') axs[3].plot(DDMrear_force[:,0],DDMrear_force[:,2],color='black',linestyle='-.',label='DDM Fry') # axs[3].plot(DDPrear_force[:,0],DDPrear_force[:,2],color='brown',linestyle='-.',label='Hybrid dualdimer Fry') axs[3].set_x...
Python
1
ks commands via CLI.""" def test_install_hooks_cli(self, tmp_path, monkeypatch): """Test install-hooks command via CLI.""" monkeypatch.chdir(tmp_path) runner = CliRunner() result = runner.invoke(cli, ["install-hooks"]) assert result.exit_code == 0 assert Path(".pre...
Python
1
_ratio: n as f64 / m as f64, p, sum_p, sum_better_first, sum_better_last, processing_time_bound, } } /// returns the number of jobs pub fn nb_jobs(&self) -> JobId { self.n } /// returns the number of machines pub fn nb_machines(&s...
Rust
0
# GuiFramework/utilities/config/mixins/__init__.py from .config_handler_mixin import ConfigHandlerMixin from .config_file_handler_mixin import ConfigFileHandlerMixin from .config_dynamic_store_mixin import ConfigDynamicStoreMixin __all__ = [ "ConfigHandlerMixin", "ConfigFileHandlerMixin", "ConfigDynamicS...
Python
1
#read--modify--write-api).\n\nFor information about avaliable fields see [uart_idr](uart_idr) module"] pub type UART_IDR = crate::Reg<u32, _UART_IDR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _UART_IDR; #[doc = "`write(|w| ..)` method takes [uart_idr::W](uart_idr::W) writer structure"] impl crate::Writable for ...
Rust
0
into(), Patch::ChangeText(ChangeText::new( &Text::new("3 items left"), TreePath::start_at(9, vec![0, 1, 0]), &Text::new("2 items left") )) ] ); let mut old_html = String::new(); old.render(&mut old_html).expect("must render"); ...
Rust
0
<filename>src/van/parser/traveler.rs use super::*; #[derive(Debug, Clone)] pub struct Traveler { pub tokens: Vec<Token>, pub top: usize, } #[allow(dead_code)] impl Traveler { pub fn new(tokens: Vec<Token>) -> Traveler { Traveler { tokens, top: 0, } } pub fn...
Rust
0
PROPERTYKEY!{PKEY_Photo_ISOSpeed, 0x14B81DA1, 0x0135, 0x4D31, 0x96, 0xD9, 0x6C, 0xBF, 0xC9, 0x67, 0x1A, 0x99, 34855} DEFINE_PROPERTYKEY!{PKEY_Photo_LensManufacturer, 0xE6DDCAF7, 0x29C5, 0x4F0A, 0x9A, 0x68, 0xD1, 0x94, 0x12, 0xEC, 0x70, 0x90, 100} DEFINE_PROPERTYKEY!{PKEY_Photo_LensModel, 0xE1277516, 0x2B5F,...
Rust
0
_value = False signer_object.attach_to_ssl_context(mock.MagicMock()) assert excinfo.match("failed to configure ECP Offload SSL context") def test_custom_tls_signer_failed_to_attach_provider(): with pytest.raises(exceptions.MutualTLSChannelError) as excinfo: signer_object = _custom_tls_signer.C...
Python
1
wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary(request, target, '/TrafficManager/stopTraffic', traffic__manager__pb2.StopTrafficMsg.SerializeToString, traffic__manager__pb2.TrafficDTO.FromString, opt...
Python
1
print(int(50 / 3)) print(int(125 / 24))
Python
1
\~chinese 提供的输出缓冲区大小 \~english Provided output buffer size ('enFlipType', MV_IMG_FLIP_TYPE), # < \~chinese 翻转类型 \~english Flip type ('nRes', c_uint * 8), # < \~chinese 保留字节 \~english Reserved bytes ] MV_CC_FLIP_IMAGE_PARAM = _MV_CC_FLIP_IMAGE_PARAM_T_ # \~chinese Gamma信息结构体 ...
Python
1
fault_model_local, # n_results=5, # hyperparams=vLLMRAGConfig.HyperparametersAccuracyConfig, # engine="vllm" # ) # end_time = time.time() # print(f"Time taken: {end_time - start_time} seconds") # #print(answer) # print(original_answer) hyperparams = OllamaRAGConfig.Hype...
Python
1
windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3633720702, data2: 58588, data3: 19277, data4: [186, 41, 102, 138, 135, 244, 46, 111] }; pub const WIA_EVENT_DEVICE_READY: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1965288556, data2: 39051, data3: 16798, data4: [154, 10, 66, 90, 195, 27,...
Rust
0
## |---------------------------------------| ## | :by Kolambus <(* ^ ω ^)> | ## | | ## | :The simplest calculator in Python | ## | | ## | :Version 1.0.0 | ## | | ...
Python
1
Err(badarg!().into()) ); Ok(()) }, ) .unwrap(); }); } <reponame>ketotek/sqlx //! Conversions between Rust and **Postgres** types. //! //! # Types //! //! | Rust type | Postgres type(s) ...
Rust
0
import sys sys.path.append("..") import jdepp parser = jdepp.Jdepp() model_path = "../model/knbc/" parser.load_model(model_path) # each input string must end with 'EOS\n' inputs = [] inputs.append("""吾輩 名詞,普通名詞,*,*,吾輩,わがはい,代表表記:我が輩/わがはい カテゴリ:人 は 助詞,副助詞,*,*,は,は,* 猫 名詞,普通名詞,*,*,猫,ねこ,* である 判定詞,*,判定詞,デアル列基本形,だ,である,* 。 ...
Python
1
sult", "PhaseEstimationScale", "PhaseEstimation", "PhaseEstimationResult", "PVQD", "PVQDResult", "SciPyRealEvolver", "SciPyImaginaryEvolver", "TrotterQRTE", "IterativePhaseEstimation", "AlgorithmError", "estimate_observables", "VarQITE", "VarQRTE", "VarQTE", "...
Python
1
ymmetricEncryptedString, pub external_id: Option<Uuid>, } /// A collection resource with additional information. // NOTE: Serialize is only needed for cache #[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct CollectionDetails { #[serde(flatten)] ...
Rust
0
se: print(f"❌ HTTP {response.status_code}: {response.text}") except Exception as e: print(f"❌ Error testing available searches API: {e}") # Test 5: Skills network demo page print("\n5️⃣ Testing /skills-network demo page") try: response = requests.get(f"{base...
Python
1
msg="No idview '%s'" % name) # Reduce add lists for host # to new entries only that are not in res_find. if host is not None: host_add = gen_add_list( host, res_find.get("appliedtohosts")) ...
Python
1
current_parent = entry.parent; } let wip_key = current_parent .iter() .chain(entry.node.key.iter()) .copied() .collect::<Vec<_>>() .into_boxed_slice(); wip_offsets.insert(wip_key, writer....
Rust
0
{struct DIDEVCAPS_DX3 { dwSize: DWORD, dwFlags: DWORD, dwDevType: DWORD, dwAxes: DWORD, dwButtons: DWORD, dwPOVs: DWORD, }} pub type LPDIDEVCAPS_DX3 = *mut DIDEVCAPS_DX3; STRUCT!{struct DIDEVCAPS { dwSize: DWORD, dwFlags: DWORD, dwDevType: DWORD, dwAxes: DWORD, dwButtons: DWO...
Rust
0
ms.video_length, ad_params.batch_size, ad_params.stride, ad_params.overlap, ad_params.closed_loop): if shared.opts.batch_cond_uncond: _context = context + [c + ad_params.video_length for c in context] else: _context = context ...
Python
1
return true; } false } fn attacks_on_square( pins: &mut [Option<BitBoard>; 64], occupancy: BitBoard, other_pieces: &Pieces, coord: BitCoord, colour: Colour, mbb: &MagicBitBoards, ) -> BitBoard { let mut allowed_moves = BitBoard(0xFF_FF_FF_FF_FF_FF_FF_FF); let other_occu...
Rust
0
let r4 = x24 * (C24 + x2 * C26); r1 + r2 + r3 + r4 } // |w| <= π / 4 #[inline] pub(crate) fn sin_cos_remez(self) -> (Self, Self) { let w = self; let t_ = (w.hi / (std::f64::consts::PI / 128.0)).round(); let t = t_ as i32; debug_assert!(-32 <= t && t <= 32...
Rust
0
1_if_no_column_name_given() { let subject = row(indexmap! { "name".into() => string("andres") }); let evaluator = fetch(None); assert_eq!( evaluator(subject, Tag::unknown()), Some(Value::int(1).tagged_unknown()) ); } #[test] fn evaluates_the_tables()...
Rust
0
_rpc_url, args.indexer_rpc_url, args.eth_rpc_url, from, to, args.private_key_path, )?; loop { ckb_relayer.start().await?; std::thread::sleep(std::time::Duration::from_secs(10 * 60)); } } // Copyright 2016 PingCAP, Inc. // // Licensed under the Apache L...
Rust
0
); space(); u64 = ttl as (usize); u64_print(); space(); logtype(type_); space(); name(q); space(); i = 0i32; 'loop1: loop { if !(i as (u32) < len) { _currentBlock = 5; break; } hex(*buf.offset(i as (isize))); if i > 30i32 { ...
Rust
0
age, cv2.COLOR_BGR2RGB) predictor.set_image(image) boxes_xyxy = convert_xywh_to_xyxy(boxes) input_box = torch.tensor(boxes_xyxy, device=predictor.device) transformed_box = predictor.transform.apply_boxes_torch(input_box, image.shape[:2]) input_point, input_lab...
Python
1
import sys sys.path.insert(0, 'ultralytics_yolov8') from ultralytics import YOLO imgsz = 320 if len(sys.argv) > 1: imgsz = int(sys.argv[1]) model = YOLO('yolov8n-pose') model.export( format='tflite', imgsz=imgsz, data="coco128.yaml", int8=True, separate_outputs=True, export_hw_optimized=Tr...
Python
1
from saludtech.procesamiento.seedwork.aplicacion.queries import QueryHandler from saludtech.procesamiento.modulos.procesamiento.infraestructura.fabricas import FabricaRepositorio from saludtech.procesamiento.modulos.procesamiento.dominio.fabricas import FabricaAnonimizacion class AnonimizacionQueryBaseHandler(QueryHan...
Python
1
with primary keys for now" ) })); } let allowed_increments_types = vec!["i32"]; let (check, ty) = is_integer_type(&field.ty); if !check || !allowed_increments_types.contains(&ty) { return Some(TokenStream::from(quote_...
Rust
0
set_keydown_callback(DOCUMENT_NAME.as_ptr() as *const c_char, mem::transmute(&*window.window.events), ffi::EM_FALSE, Some(keyboard_callback))) .map_err(|e| ::CreationError::OsError(format!("emscripten error: {}", e)))?; em_try(ffi::emscripten_set_keyup_callback(DOCUMENT_NAME.as_ptr() as *con...
Rust
0
import numpy as np import matplotlib.pyplot as plt def normal_pdf(x, mu, sigma): pdf = 1/(sigma * np.sqrt(2 * np.pi)) * np.exp( - (x - mu)**2 / (2 * sigma**2)) return pdf fig = plt.figure(figsize=(6,9)) # Random sampling of a normal distribution my_mu, my_sigma = 0, 0.1 # mean and standard deviation bit_gen...
Python
1
cements(display_topics, number=None, days=None, print=False): if number is not None: display_topics = display_topics[-number:] if days is not None: display_topics = filter_days_from_today(display_topics, days, key=lambda t: t.posted_at_date) if print: def print_topic(topic): ...
Python
1
, &self.button_press_event) .field("button_release_event", &self.button_release_event) .field("scroll_event", &self.scroll_event) .field("query_tooltip", &self.query_tooltip) .field("__gtk_reserved1", &self.__gtk_reserved1) .field("__gtk_reserved2", &self.__gtk_reserved2) ...
Rust
0
from fastapi import HTTPException, status class TokenNotFoundHTTPException(HTTPException): """Исключение, когда токен не найден (401).""" def __init__(self): super().__init__( status_code=status.HTTP_401_UNAUTHORIZED, detail="Token not found" ) class TokenExpiredHTTPException(HT...
Python
1
from ner.utils.trie import Trie class Gazetteer: def __init__(self, lower, use_single): self.trie = Trie(use_single) self.ent2type = {} ## word list to type self.ent2id = {"<UNK>":0} ## word list to id self.lower = lower self.space = "" def enumerateMatchList(self, wo...
Python
1
, Clone, Copy, Debug, PartialEq)] pub enum LegPaymentScheduleFixingDateRelativeTo { /// Trade date #[serde(rename = "0")] TradeDate, /// Settlement date #[serde(rename = "1")] SettlementDate, /// Effective date #[serde(rename = "2")] EffectiveDate, /// Calculation period start date #[serde(rename = "3")] Ca...
Rust
0
, ")")?; Ok(()) } else { // I don't care about quotes write!(buf, "{}", sexp.to_string().trim_matches('"')) } } /// A wrapper that uses display implementation as debug pub(crate) struct DisplayAsDebug<T>(pub T); impl<T: Display> Debug for DisplayAsDebug<T> { fn fmt(&self, f: &mut F...
Rust
0
id(doc, "Material") mat = material_obj.Material mat["Name"] = "CalculiX-Steel" mat["YoungsModulus"] = "210000 MPa" mat["PoissonRatio"] = "0.30" material_obj.Material = mat analysis.addObject(material_obj) # constraint fixed con_fixed = ObjectsFem.makeConstraintFixed(doc, "ConstraintFixe...
Python
1
1).transpose(1, 2).contiguous() # 1 c t h w mask_i = mask_i.unsqueeze(0).repeat(num_samples_per_prompt, 1, 1, 1, 1).transpose(1, 2).contiguous() # 1 c t h w masked_pixel_values.append(masked_pixel_values_i) mas...
Python
1
into lines. pub fn get_procfs_file_lines(path: String) -> Option<Vec<String>> { match read_procfs_file(path) { None => None, Some(s) => Some(s.lines().map(String::from).collect()), } } /// Splits a string at commas (',') and returns the list of the elements separated. pub fn commaseparated_to_...
Rust
0
# MIT License # # Copyright (c) 2023 Advanced Micro Devices, Inc. All rights reserved. # # 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 ...
Python
1
0 { None } else if self.0.len() < 4 { None } else { let tag = [self.0[0], self.0[1]]; let len = self.0[2] as usize; let ver = self.0[3]; if len < 4 { return None; } if self.0.len() < len { return None; } let data = &self.0[4..len]; self.0 = &self.0[len..]; log_d...
Rust
0
x = 1 + 2 + 3 print(x)
Python
1
_trait; use futures::future::{self, TryFutureExt}; use futures::stream::{self, StreamExt, TryStreamExt}; use futures::try_join; use log::debug; use safecast::AsType; use tc_btree::Node; use tc_error::*; use tc_transact::fs::{Dir, File}; use tc_transact::{Transaction, TxnId}; use tc_value::{FloatInstance, Number, Numbe...
Rust
0
from aiogram import Router,F from aiogram.types import Message from aiogram.filters import StateFilter from app.bot.filters.role_filter import RoleFilter from app.bot.routers.foreman.object_logic.main_object_router import foreman_router from app.bot.routers.foreman.report import report_router from app.db.models import...
Python
1
x = x.reshape(_b, _d, _h, _w, -1) x = x.permute(0, 4, 1, 2, 3) x=x.reshape(_b, -1, _d, _h, _w, ) x = x[:, :, :d, :h, :w] # 截取原图大小 return x class BiMamba2(_BiMamba2): def __init__(self, cin, cout, d_model, **mamba2_args): super().__init__(cin, cout, d_model, **mamba...
Python
1
item_id=after_update.id, scope="Experiment", # log under Experiment scope so it appears in experiment activity log activity=activity, detail=Detail( # need to use ExperimentSavedMetric here for field exclusions.. changes=changes_between("ExperimentSavedMetric", pr...
Python
1
2: PUER, #[doc = "0x474 - Pull-up Enable Register - Set"] pub puers2: PUERS, #[doc = "0x478 - Pull-up Enable Register - Clear"] pub puerc2: PUERC, #[doc = "0x47c - Pull-up Enable Register - Toggle"] pub puert2: PUERT, #[doc = "0x480 - Pull-down Enable Register"] pub pder2: PDER, #[do...
Rust
0
from django.urls import path from .views import LookupList, LookupDetail urlpatterns = [ path('', LookupList.as_view(), name='lookup-list'), path('<int:pk>/', LookupDetail.as_view(), name='lookup-detail'), ]
Python
1
#!/usr/bin/env python __author__ = "bt3gl" from scapy.all import * import netaddr import random RANGE = "192.168.1.0/24" PORTS = [22, 23, 80, 443, 449] CODES = [1, 2, 3, 9, 10, 13] RANGE_IP = netaddr.IPNetwork(RANGE) def port_scanner(host, ports): for dstPort in ports: srcPort = random.randint(1025,655...
Python
1
filename) Mixin.setMixin('mainframe', 'OnFilePrint', OnFilePrint) def OnFilePrintPreview(win, event): if get_printer(win): win.printer.PrintPreview(win.document.GetText(), win.document.filename) Mixin.setMixin('mainframe', 'OnFilePrintPreview', OnFilePrintPreview) #def OnFilePrinterSetup(win, event): # ...
Python
1
import pandas as pd import pandas._testing as tm def test_relabel_no_duplicated_method(): # this is to test there is no duplicated method used in agg df = pd.DataFrame({"A": [1, 2, 1, 2], "B": [1, 2, 3, 4]}) result = df["A"].agg(foo="sum") expected = df["A"].agg({"foo": "sum"}) tm.assert_series_e...
Python
1
' "\u{305f}\u{309b}", // 'た' + '゛' "\u{305f}\u{ff9e}", // 'た' + '゙' "\u{30bf}\u{3099}", // 'タ' + '゛' "\u{30bf}\u{309b}", // 'タ' + '゛' "\u{30bf}\u{ff9e}", // 'タ' + '゙' ], // "だ", "ダ" [ "\u{3062}", "\u{30c2}", "\u{3061}\u{3099}", // 'ち' + '゛' ...
Rust
0
from sklearn.tree import DecisionTreeClassifire from sklearn.metrics import confusion_matrix #simple dataset : [height, weight] X = [ [150, 50], [160, 60], [170, 65], [180, 80] ] # Labels: 0 = short, 1 = Tail y = [0, 0, 1, 1] #create and train the model model = DecisionTreeClassifire() model.fit(X, y...
Python
1
&mut self.sess { Some(s) => { for event in s.events() { match event { GGRSEvent::WaitRecommendation { skip_frames } => { result.push(("WaitRecommendation", skip_frames.to_variant())) } ...
Rust
0
switchboard /// TODO(ejia): refactor to be more common with main function #[fuchsia_async::run_singlethreaded(test)] async fn test_display() { const STARTING_BRIGHTNESS: f32 = 0.5; const CHANGED_BRIGHTNESS: f32 = 0.8; let (manager_proxy, mut manager_stream) = fidl::endpoints::creat...
Rust
0
import cv2 as cv import numpy as np import os dir=r'C:\Users\Mahendra Reddy\image_clf' face_cas=cv.CascadeClassifier('haarcascade_frontalface_default.xml') p=[] for file in os.listdir(dir): p.append(file) print(p) label=[] feat=[] def fac_tra(): for per in p: path=os.path.join(dir,per) lab=p.in...
Python
1
refix: Self::add_tag(shard_prefix, shard_pfx_bits), } ) } pub fn with_workchain_id(workchain_id: i32) -> Result<Self> { Self::check_workchain_id(workchain_id)?; Ok( Self { workchain_id, prefix: SHARD_FULL, } ) ...
Rust
0
ing options at the start //! //! If your command line looks like this, and does not accept options //! after positional arguments: //! //! ```text //! usage: command [OPTIONS] [ARGS]... //! ``` //! //! then you can use [`Options::next_opt`] directly, just like classical //! `getargs` (before 0.5.0) supported as `next`....
Rust
0
# This is the code for stock market dashboard, it features Bollinger Bands, MACD, RSI indicators plotted using closing prices of S&P 500 companies # To run the project, follow these steps: # 1. install the following libraries: # pandas==1.3.2 # yfinance==0.1.63 # ta==0.7.0 # streamlit # 2. In the terminal type the comm...
Python
1
assert!(environment.collect().unwrap().contains_key("b.a")); env::remove_var("C_B_A"); } #[test] fn test_empty_value_is_ignored() { env::set_var("C_A_B", ""); let environment = Environment::new().ignore_empty(true); assert!(!environment.collect().unwrap().contains_key("c_a_b")); env::remove...
Rust
0
, target): # pragma: no cover if target is None: if os.environ.get('MACOSX_DEPLOYMENT_TARGET'): del os.environ['MACOSX_DEPLOYMENT_TARGET'] else: os.environ['MACOSX_DEPLOYMENT_TARGET'] = target jaraco.path.build( { 'deptargetmo...
Python
1
import os import subprocess _List_Sign_exe = [ "CubeAgent.exe", "CubeAssistant.exe", "CubeCredentialProvider.dll", "CubeHMI.exe", "CubeLicense.exe", "CubeLogStash.exe", "CubeMobileEngine.exe", "CubeRecord.exe", "CubeExtensionInstaller.exe", "CubeJavaBridge_x64.dll", "CubeJavaBridge...
Python
1
(item_id, data["position"]) class ConsumableJson: @staticmethod def serialize(consumable: ConsumableOnGround): return {"consumable_type": consumable.consumable_type.name, "position": consumable.world_entity.get_position()} @staticmethod def deserialize(data) -> ConsumableOnGround: ret...
Python
1
x00, // type 1: (i32) -> () 0x60, 0x00, 0x00, // type 2: () -> () ]; const IMPORT_SECTION: &'static [u8] = &[ 0x02, // id 0x22, // byte length 0x02, // vec length // import func 0: io.get_value() -> (i32) 0x02, 0x69, 0x6f, // mod: `io` 0x0a, 0x72, 0x65, 0x61, 0x64, 0x5f, 0x76, 0x61, 0x6c, 0...
Rust
0
subcommand provided. See --help."), } } use anyhow::{format_err, Error}; use derive_more::{Display, Into}; use serde::{Deserialize, Serialize}; use std::convert::TryFrom; /// Relative Humidity as Percent #[derive(Into, Debug, PartialEq, Copy, Clone, PartialOrd, Serialize, Deserialize, Display)] #[serde(into = "i64",...
Rust
0
of-speech) associated with this token. /// Order is generally not significant. pub tags: Vec<WordData<'t>>, } impl<'t> Word<'t> { /// Creates a new Word with tags. pub fn new_with_tags(text: WordId<'t>, tags: Vec<WordData<'t>>) -> Self { Word { text, tags } } /// Converts to an owned w...
Rust
0
sign_ui(comm.get_data()?).map_err(|_| io::StatusWords::UserCancelled)?; if let Some(o) = out { comm.append(&o) } } Ins::Menu => menu_example(), Ins::ShowPrivateKey => comm.append(&bip32_derive_secp256k1(&BIP32_PATH)), Ins::SingleMessage => comm.app...
Rust
0
_entries.SOURCE_HASSIO}, data=HassioServiceInfo(config=entry_data, name="VLC", slug="vlc", uuid="1234"), ) await hass.async_block_till_done() assert result["type"] == FlowResultType.ABORT @pytest.mark.parametrize( ("error", "connect_side_effect", "login_side_effect"), [ ("invalid_...
Python
1
LLEL PROCESSING PERFORMANCE ANALYSIS") print(f"{'=' * 60}") successful_tests = [r for r in results if r.get("success", False)] if successful_tests: avg_time = sum(r["processing_time"] for r in successful_tests) / len( successful_tests ) visual_tests = [r for r in succes...
Python
1
# Ultroid - UserBot # Copyright (C) 2021-2023 TeamUltroid # # This file is a part of < https://github.com/TeamUltroid/Ultroid/ > # PLease read the GNU Affero General Public License in # <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>. """ ✘ Commands Available - •`{i}addprofanity` If someone sends ba...
Python
1
d": "f1a2b3c4-d5e6-f7a8-b9c0-d1e2f3a4b5c6", "type": "last_reports", "title": "Latest Reports", }, ) with patch("dashboards.widgets.render_to_string") as mock_render: widget.index() # Assertions mock_render.assert_called_once() actual_call_args, _ = mock_ren...
Python
1
.update(&dst_prime); let mut bi = hasher.finalize_reset(); let mut pseudo = Vec::new(); pseudo.extend_from_slice(&bi); for i in 2..(ell + 1) { hasher.reset(); hasher.update(&xor(&bi, &b0)); hasher.update(&[i as u8]); hasher.update(&dst_pri...
Rust
0
from __future__ import print_function from __future__ import division from __future__ import absolute_import import unittest from jnius import autoclass class StringArgumentForByteArrayTest(unittest.TestCase): def test_string_arg_for_byte_array(self): # the ByteBuffer.wrap() accept only byte[]. By...
Python
1
.generics, item.span, report_extra_lifetimes, ); } } fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) { if let TraitItemKind::Fn(ref sig, ref body) = item.kind { let (body, trait_sig) = match *body { ...
Rust
0
# Copyright (c) 1999-2008 Mark D. Hill and David A. Wood # Copyright (c) 2009 The Hewlett-Packard Development Company # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: redistributions of source co...
Python
1
import torch import torch.nn as nn import torch.nn.functional as F def sspsl_loss(psegs, pfeas, labels, regions): ce_loss = nn.CrossEntropyLoss().to(pfeas.device) pfeas = F.normalize(pfeas, dim=1) real_anchors = pfeas[labels < 1].permute(0, 2, 3, 1).contiguous().view(-1, pfeas.size(1)) real_psegs = p...
Python
1
eatures(_item) # features = np.hstack((self.standardize(consecutive_features), self.standardize(interval_features), \ # self.standardize(odd_even_ratio), self.standardize(high_low_ratio), \ # self.st...
Python
1
1: *mut Fl_Widget, arg2: *mut libc::c_void); } extern "C" { pub fn Fl_Widget_deimage(arg1: *const Fl_Widget) -> *mut libc::c_void; } extern "C" { pub fn Fl_Widget_set_callback(arg1: *mut Fl_Widget, arg2: Fl_Callback, arg3: *mut libc::c_void); } extern "C" { pub fn Fl_Widget_set_deleter( arg1: *mut F...
Rust
0
as PrimitiveSigned>::UnsignedOfEqualWidth: Rand, { SpecialRandomNegativeSigned(special_random_unsigned(seed)) } pub struct SpecialRandomSigned<T: PrimitiveSigned>(SpecialRandomUnsigned<T::UnsignedOfEqualWidth>) where <T as PrimitiveSigned>::UnsignedOfEqualWidth: Rand; impl<T: PrimitiveSigned> Iterator for Sp...
Rust
0
"""Velbus switch platform tests.""" from unittest.mock import AsyncMock, patch from syrupy.assertion import SnapshotAssertion from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN from homeassistant.const import ( ATTR_ENTITY_ID, SERVICE_TURN_OFF, SERVICE_TURN_ON, Platform, ) from homea...
Python
1
et([ Point(math.cos(math.pi / 4), math.sin(math.pi / 4)), Point(-math.cos(math.pi / 4), -math.sin(math.pi / 4)) ])) def test_circle_intersect_with_line_tangent(): tangency_point = Point(math.cos(math.pi / 4), math.sin(math.pi / 4)) line = Line(tangency_point + Point(-3, 3), -1)...
Python
1
import torch import torch.nn as nn from model import CNN from PIL import Image import torchvision import torchvision.transforms as transforms device=torch.device("cuda" if torch.cuda.is_available() else "cpu") model = CNN() model.load_state_dict(torch.load('model.pth', map_location=device)) model.to(device) model.eva...
Python
1
, TestStrings, write_strings, read_strings); fn generate_small_bytes() -> Vec<TestBytes<'static>> { let mut s = "hello world from quick-protobuf!!!" .split(' ') .cycle() .map(|s| Cow::Borrowed(s.as_bytes())); (1..800) .map(|_| TestBytes { b1: s.by_ref().next(), ...
Rust
0
lower, upper, k, only_k_bits_lower, only_k_bits_upper, run_len_jumpstart, } } } impl<T> Display for Prefix<T> where T: NumberLike { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { let reps_info = match self.run_len_jumpstart { None => "".to_string(), So...
Rust
0
ule pass. name: str, optional Name for the module pass. Returns ------- decorator The npu_pass decorator. """ def decorator(npu_pass_class): @tvm.ir.transform.module_pass(name=name, opt_level=opt_level) class ModulePassWrapper: """The wrapper for the...
Python
1
import unittest from unittest.mock import MagicMock, patch, call from utils.pdf_generator import ReportGenerator class TestReportGenerator(unittest.TestCase): def setUp(self): self.mock_config = MagicMock() self.mock_config.REPORT_DIR = '/reports' self.mock_config.ORIGINAL_DIR = '/original...
Python
1
""" bilibili番剧排行榜 """ import requests import arrow import looter as lt domain = 'https://bangumi.bilibili.com' def crawl(url): items = requests.get(url).json()['result']['data'] for item in items: data = {} data['番名'] = item['title'] data['链接'] = item['link'] order = item['ord...
Python
1
self.1.position() } fn next(&self) -> (Option<Self::Item>, Self) { if self.0.is_empty() { return (None, self.clone()) } match self.0.next() { (Some(a), s) => (Some(a), ChainedStream::new(vec!(s, self.1.clone()))), (None, _) => ...
Rust
0
saved_count += 1 self.logger.debug(f"保存section成功: {section_id}") else: self.logger.error(f"保存section失败: {section_id}") self.logger.info(f"sections表保存完成,保存条数: {saved_count}") return saved_count e...
Python
1
<u32, _SYNCONF>; #[allow(missing_docs)] #[doc(hidden)] pub struct _SYNCONF; #[doc = "`read()` method returns [synconf::R](synconf::R) reader structure"] impl crate::Readable for SYNCONF {} #[doc = "`write(|w| ..)` method takes [synconf::W](synconf::W) writer structure"] impl crate::Writable for SYNCONF {} #[doc = "Sync...
Rust
0