text
string
label_name
string
labels
int64
uit = (card_val & 0xE0) >> 5 # 花色 rank = card_val & 0x1F # 点数 # 设置花色颜色 if suit in [1, 2]: # 红桃和方块为红色 painter.setPen(QColor(255, 0, 0)) else: # 梅花和黑桃为黑色 painter.setPen(QColor(0, 0, 0)) # 绘制花色符号 suit_symbol = "" ...
Python
1
err { () => (log!(::log::Level::Error)); ($fmt:expr) => (log!(::log::Level::Error, $fmt)); ($fmt:expr, $($arg:tt)*) => (log!(::log::Level::Error, $fmt, $($arg)*)); } #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)] pub enum Level { Info, Warning, Error, Panic } impl Display for Level { ...
Rust
0
expect["DownloadableArchives"] assert count == len(expect["DownloadableArchives"]) count = 0 for item in entry.auto_dependon: count += 1 assert item in expect["AutoDependOn"] assert count == ...
Python
1
sformer_ckpt_path, args.num_layers, args.num_attention_heads, args.use_rotary_positional_embeddings, args.i2v, dtype, ) if args.vae_ckpt_path is not None: vae = convert_vae(args.vae_ckpt_path, args.scaling_factor, dtype) text_encoder_i...
Python
1
{Bencher, TestName, TestResult, TestDesc, TestDescAndFn, TestOpts, TrFailed, TrIgnored, TrOk, Metric, MetricMap, StaticTestFn, StaticTestName, DynTestName, DynTestFn, run_test, test_main, test_main_static, filter_tests, parse_opts, StaticBenchFn, ShouldFa...
Rust
0
ting)), )) } } <gh_stars>0 use serde::{Deserialize, Serialize}; pub type PlayerId = u32; pub type PlaylistId = i32; // 0..2, but default is -1 pub type PlaylistPosition = i32; // positive but default is -1 // "Playlist.Item" #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(untagged)] pub enum Playl...
Rust
0
" {:08x}: {:12} {}, {}, {}", text_addr, "sc.d", rd, rs1, rs2 ); } // Supervisor Memory-Management Instructions Inst::SFENCEWINVAL => { println!(" {:08x}: {:12}", text_addr, "sfence.w.inval"); } Inst::SFENCEINVALIR => ...
Rust
0
help text. Then the program will exit. _ => "launcher", }; fuchsia_syslog::init_with_tags(&[log_tag]).context("initializing logging").unwrap(); let args = v2_argh_wrapper::load_command_line::<LauncherArgs>()?; match args.program { ChildArgs::Detect(args) => detect::main(args).await, ...
Rust
0
scale[2] md_dict['SAMP_OFF'] = fmt % rpc.image_offset[0] md_dict['LINE_OFF'] = fmt % rpc.image_offset[1] md_dict['SAMP_SCALE'] = fmt % rpc.image_scale[0] md_dict['LINE_SCALE'] = fmt % rpc.image_scale[1] md_dict['SAMP_NUM_COEFF'] = ' '.join(fmt % c for c in rpc.coeff[0, :]) md_dict['SAMP_DEN_COEF...
Python
1
, "(module ${}", name).unwrap(); for ty in ty.imports() { self.import(&ty); } for ty in ty.exports() { self.export(&ty); } self.dst.push_str(")\n"); } ExternType::Instance(ty) ...
Rust
0
, min: T, max: T); // -- metadata declarations fn declare(&mut self, zone: &mut T, key: &str, value: &str); } pub struct PrintMeta {} impl Meta for PrintMeta { fn declare(&mut self, key: &str, value: &str) -> () { println!("declare: {} {}", key, value); } } pub struct PrintUI<T> { ...
Rust
0
ed: bool, time_quant: Duration, } impl TaskManager { pub fn new(time_quant: Duration) -> Self { Self { tasks: Vec::new(), current_task: 0, started: false, time_quant, } } pub fn add_task(&mut self, mut task: TaskContext) -> Result<u64, Ta...
Rust
0
from syntheseus import SingleProductReaction from .base import IndependentStochasticProcess, StochasticProcess class FeasibilityModel(StochasticProcess[SingleProductReaction]): """Base class for feasibility models.""" pass class IndependentFeasibilityModel(IndependentStochasticProcess[SingleProductReactio...
Python
1
return Err(RadosError::new("Rados ioctx not created. Please initialize first".to_string())); // } // // unsafe { // } // } // /// Sychronously notify watchers of an object /// This blocks until all watchers of the object have received and reacted to the notify, or a timeout is reached. pub fn rados_object_notify(ctx:...
Rust
0
// SYN: Synchronize sequence numbers // FIN: No more data from sender // window: u16: number of bytes the sender can accept // checksum: u16 // urg ptr: u16 #[derive(Copy, Clone, Default, Debug)] #[repr(C)] pub struct TcpHeader { src_port: u16, dst_port: u16, seq_num: u32, ack_num: u32, data_off_r...
Rust
0
st_invalid_token(self, group, channel_layer): """Test that connection fails with an invalid token.""" invalid_token = "invalid.token.value" group_instance, _, _ = await group communicator = WebsocketCommunicator( application, f"/ws/groups/{group_instance.pk}/?tok...
Python
1
WasmType::VisaNFT => storage::get::<VisaNFTWASMBytes>().0.clone().unwrap_or(ByteBuf::new()), WasmType::PABToken => storage::get::<PABWalletWASMBytes>().0.clone().unwrap_or(ByteBuf::new()), }; let install_args = encode_args(()).expect("Failed to encode arguments."); install_canister(&caniste...
Rust
0
n & MAN_MASK) | ((exp_u64 << 52) & EXP_MASK) | ((sign_u64 << 63) & SIGN_MASK) } impl<T: Float> Zero for NotNan<T> { fn zero() -> Self { NotNan(T::zero()) } fn is_zero(&self) -> bool { self.0.is_zero() } } impl<T: Float> One for NotNan<T> { fn one() -> Self { NotNan(T::one()) } } impl<T: Float> Bounded f...
Rust
0
the documents/options used to construct it. fn fixtures(opts: Option<InsertManyOptions>) -> TestFixtures { lazy_static! { static ref DOCUMENTS: Vec<Document> = vec![ Document::new(), doc! {"_id": 1234, "a": 1}, doc! {"a": 123, "b": "hello world" }, ]; } ...
Rust
0
''')) sys.exit( 1) def trace_runpage( use_display_list, doc, number): page = mupdf.FzPage( doc, number-1) mediabox = page.fz_bound_page() print( f'<page number="{number}" mediabox="{mediabox.x0} {mediabox.y0} {mediabox.x1} {mediabox.y1}">') output = mupdf.FzOutput( mupdf.FzOutput.Fixed_STDO...
Python
1
lights.""" mock_wled.segment.side_effect = WLEDError with pytest.raises(HomeAssistantError, match="Invalid response from WLED API"): await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.wled_rgb_light"}, blocking=True, ...
Python
1
import time import math from inventor import Inventor2040W, NUM_SERVOS, LED_SERVO_1 """ An example of applying a wave pattern to a group of servos and the LEDs. Press "User" to exit the program. """ SPEED = 5 # The speed that the LEDs will cycle at BRIGHTNESS = 0.4 # The brightness of the LEDs UPDAT...
Python
1
x86::Register::Esp => "esp", } } fn cond_name(cond: x86::Condition) -> &'static str { match cond { x86::Condition::Above => "a", x86::Condition::AboveEqual => "ae", x86::Condition::Below => "b", x86::Condition::BelowEqual => "be", x86::Condition::Equal => "e", ...
Rust
0
ee2 { type KeySize = U16; } impl KeyInit for TdesEee2 { #[inline] fn new(key: &Key<Self>) -> Self { let k1 = u64::from_be_bytes(key[0..8].try_into().unwrap()); let k2 = u64::from_be_bytes(key[8..16].try_into().unwrap()); let d1 = Des { keys: gen_keys(k1) }; let d2 = Des { ke...
Rust
0
R>, vtype: &str, desc: &str, ) -> Result<glib::Variant> { let header = entry.header(); let size = validate_metadata_header(header, desc)?; let mut buf: Vec<u8> = Vec::with_capacity(size); let n = std::io::copy(&mut entry, &mut buf)?; assert_eq!(n as usize, size); let v = glib::Bytes::fr...
Rust
0
() ) }) } } } pub(crate) fn remote(c: &Client<BindleTokenManager>, id: &Id) -> Self { Self { inner: BindleReaderInner::Remote(c.clone(), id.clone()), } } #[allow(dead_code)] pub(crate) async fn standalone(base_path...
Rust
0
from PyObjCTools.TestSupport import TestCase, min_os_level import CloudKit import objc class TestCKDatabase(TestCase): def test_enum_types(self): self.assertIsEnumType(CloudKit.CKDatabaseScope) @min_os_level("10.10") def testClasses(self): self.assertHasAttr(CloudKit, "CKDatabase") ...
Python
1
# 01_parallel_sum.py from mpi4py import MPI import argparse import sys # 得到MPI信息 comm = MPI.COMM_WORLD size = comm.size rank = comm.rank # 1. 任务分配 # ---------- # 0号进程拿到总数,并将信息[分发]给其他进程 total_number = 0 if rank == 0: parser = argparse.ArgumentParser() parser.add_argument("--total", type = int, ...
Python
1
0d, 0x0087000d, 0x008d000d, 0x0094000d, 0x009a000d, 0x00a1000d, 0x00a7001a, 0x00b4001a, 0x00c1001a, 0x00ce001a, 0x00da001a, 0x00e7001a, 0x00f4001a, 0x0101001a, 0x010e0033, 0x01280033, 0x01410033, 0x015b0033, 0x01750033, 0x018f0033, 0x01a80033, 0x01c20033, 0x01dc0067, 0x020f0067, 0x02430067, 0x02...
Rust
0
"""StreamFlow wrappers This file contains all the scripts and wrapper code related to StreamFlow and its execution """ import argparse import asyncio import logging import os from logging import Logger, getLogger from streamflow.config.config import WorkflowConfig from streamflow.config.validator import SfValidator ...
Python
1
from .sql import SQL
Python
1
overflowing-pow-unsigned.rs<gh_stars>1000+ // run-fail // error-pattern:thread 'main' panicked at 'attempt to multiply with overflow' // ignore-emscripten no processes // compile-flags: -C debug-assertions fn main() { let _x = 2u32.pow(1024); } <filename>frame/lending/src/lib.rs //! Lending pallet #![cfg_attr( no...
Rust
0
// let a = { #[cfg(feature = "has_abc")] { "abc" } #[cfg(not(feature = "has_abc"))] { "not abc" } }; let a_iif = cfg_iif!(#[cfg(feature = "has_abc")] { "abc" } else { "not abc" }); ...
Rust
0
self.data["last_job"] = self.last_job self.data["last_advert"] = self.last_advert self.data["last_wormhole"] = self.last_wormhole self.data["donor_status"] = self.donor_status self.data["early_supporter"] = self.early_supporter return self.data def create_user(user_id: str)...
Python
1
-LABEL: @fsqrt_32x2 #[no_mangle] pub unsafe fn fsqrt_32x2(a: f32x2) -> f32x2 { // CHECK: call <2 x float> @llvm.sqrt.v2f32 simd_fsqrt(a) } // CHECK-LABEL: @fsqrt_32x4 #[no_mangle] pub unsafe fn fsqrt_32x4(a: f32x4) -> f32x4 { // CHECK: call <4 x float> @llvm.sqrt.v4f32 simd_fsqrt(a) } // CHECK-LABEL: ...
Rust
0
assert_eq!(get_block_comment("(;;)"), "(;;)"); assert_eq!(get_block_comment("(; ;)"), "(; ;)"); assert_eq!(get_block_comment("(; (;;) ;)"), "(; (;;) ;)"); } fn get_token(input: &str) -> Token<'_> { Lexer::new(input) .parse() .expect("no first token") ...
Rust
0
10(self): clr = AdaBoostRegressor(n_estimators=5) model, X_test = fit_regression_model(clr) model_def = to_onnx(model, X_test.astype(numpy.float32), target_opset=10) X_test = X_test.astype(numpy.float32) oinf = OnnxInference(model_def) res0 = ...
Python
1
let new_hash = <H256>::from(digest::digest(&digest::SHA256, &[0x00 as u8])); let mut new_hash_vec = Vec::<H256>::new(); new_hash_vec.push(new_hash); let mut rand_addr_H160 = <H160>::from(digest::digest(&digest::SHA256,"442cabd17e40d95ac0932d977c0759397b9db4d93c4d62c368b95419db574db0".as_bytes())); l...
Rust
0
if self.msno_or_superseded_applied(patch_string, os, depth + 1): at_least_one_superseding_patch_applied = 1 if self.verbose: print "[+] %s supersedes %s (and has been applied)" % (m.group(1), msno) ...
Python
1
from collections import defaultdict dict1 = {'gfg': [1, 2, 3], 'is': [1, 4], 'best': [4, 2]} res = defaultdict(list) for key, val in dict1.items(): for ele in val: res[ele].append(key) print('The values associated dictionary:', dict(res)) ''' # Python3 code to demonstrate working of # Values Associated Keys # Usi...
Python
1
from django.template import Context, Engine from django.template.base import TextNode, VariableNode from django.test import SimpleTestCase class NodelistTest(SimpleTestCase): @classmethod def setUpClass(cls): cls.engine = Engine() super().setUpClass() def test_for(self): template ...
Python
1
200.59], # 80 [ 81, "Tl", "Thallium", 204.3833], # 81 [ 82, "Pb", "Lead", 207.2], # 82 [ 83, "Bi", "Bismuth", 208.98040], # 83 [ 84, "Po", "Polonium", None], # 84 [ 85, "At", "Astatine", None], # 85 [ 86, "Rn", "Radon", None], # 86 [ 87, "Fr", "Francium", None], # 87 [ 88, "Ra", "Radium"...
Python
1
: Mem); // fp div fn emit_divsd_f64_f64(&mut self, dest: Reg, src: Reg); fn emit_divsd_f64_mem64(&mut self, dest: Reg, src: Mem); fn emit_divss_f32_f32(&mut self, dest: Reg, src: Reg); fn emit_divss_f32_mem32(&mut self, dest: Reg, src: Mem); // fp mul fn emit_mulsd_f64_f64(&mut self, dest...
Rust
0
scope_1176.instant(var_1177, smithy_types::instant::Format::DateTime); } #[allow(unused_mut)] let mut scope_1178 = writer.prefix("PartitionEndDate"); if let Some(var_1179) = &input.partition_end_date { scope_1178.instant(var_1179, smithy_types::instant::Format::DateTime); } } #[allow(unused...
Rust
0
import re from html import unescape from typing import Iterable from scrapy import Spider from scrapy.http import FormRequest, Response from locations.categories import Categories, apply_category from locations.hours import CLOSED_AT, DAYS_AT, OpeningHours from locations.items import Feature from locations.user_agent...
Python
1
from typing import Optional, Union import httpx class HTTPHandler: def __init__(self, concurrent_limit=1000): # Create a client with a connection pool self.client = httpx.AsyncClient( limits=httpx.Limits( max_connections=concurrent_limit, max_keepalive_...
Python
1
# coding=utf-8 # Copyright 2023 The Deeplab2 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 ...
Python
1
from __future__ import annotations from dify_oapi.core.enum import HttpMethod from dify_oapi.core.model.base_request import BaseRequest from .stop_chat_request_body import StopChatRequestBody class StopChatRequest(BaseRequest): def __init__(self) -> None: super().__init__() self.task_id: str | N...
Python
1
ce('z', 'v') get_input_field_width = dict(t[1] for t in tokenize_pattern(skeleton) if t[0] == "field").get best_skeleton = None best_distance = None for option in options: get_opt_field_width = dict(t[1] for t in tokenize_pattern(option) if t[0] == "field").get distance = 0 for ...
Python
1
rivative=True) kn[1][2] = spherical_kn(2, x, derivative=True) kn0 = -kn[0][1] kn1 = -kn[0][0]-2.0/0.2*kn[0][1] kn2 = -kn[0][1]-3.0/0.2*kn[0][2] assert_array_almost_equal(kn[0],[6.4302962978445670140, 38.581777787067402086, ...
Python
1
# Exercise 01 names = {"Ali", "Ayan"} names.add("Maxamad") print(names) # Ku dar "Maxamad" set-ka # Output: {'Ali', 'Ayan', 'Maxamad'} # Exercise 02 colors = {"red", "green", "blue"} colors.remove("green") print(colors) # Ka saar "green" adoo isticmaalaya remove() # Output: {'red', 'blue'} # Exercise 03 days = {"Mon...
Python
1
ion_level being in a range (0,10] : Dependency { identifier: "compression_level", Constraint { condition : GT, value: 0 }, Constraint { condition : LT_EQ, value: 10 } } visibility: If any of the dependencies match their constraints, this level of visibili...
Python
1
print_result(&content, 2020, 2, "two"); print_result(&content, 2020, 3, "three"); Ok(()) } fn get_contents(input: String) -> Vec<usize> { input .lines() .map(str::parse::<usize>) .enumerate() .map(|(count, value)| { if let Ok(value) = value { So...
Rust
0
= true; } // Parse #[elephantry(column = "")] syn::NestedMeta::Meta(syn::Meta::NameValue(m)) if m.path == crate::symbol::COLUMN => { let column = get_lit_str(crate::symbol::COLUMN, &m.lit)?; param...
Rust
0
_level: u16, pub bit_offset_qindex: u16, pub bit_offset_first_partition_size: u16, pub bit_offset_segmentation: u16, pub bit_size_segmentation: u16, pub log2_tile_rows: u8, pub log2_tile_columns: u8, pub skip_frame_flag: u8, pub number_skip_frames: u8, pub skip_frames_size: u32, } #[...
Rust
0
(); assert_eq!(ts3.values, vec![4, 4, 4, 4]); // Check subtracting TS with different timeline is not OK let tl2 = Timeline::new(dr, Period::Year); let v4 = vec![1]; let ts4 = TimeSeries::new(&tl2, v4).unwrap(); let ts5 = &ts4 - &ts1; assert!(ts5.is_err()); ...
Rust
0
odeled after [equippable interaction](https://github.com/rmrk-team/rmrk-spec/blob/master/standards/rmrk2.0.0/interactions/equippable.md) /// /// Parameters: /// - issuer: The caller of the function, must be issuer of the base /// - base_id: The Base containing the Slot Part to be updated /// - part_id: The Slot Pa...
Rust
0
GOOMBA_HEIGHT}, {"type": "goomba", "x": 1100, "y": SCREEN_HEIGHT - GROUND_HEIGHT - GOOMBA_HEIGHT}, {"type": "goomba", "x": 1500, "y": SCREEN_HEIGHT - GROUND_HEIGHT - GOOMBA_HEIGHT}, {"type": "goomba", "x": 1900, "y": SCREEN_HEIGHT - GROUND_HEIGHT - GOOMBA_HEIGHT}, {"type...
Python
1
/! This crate exposes functionality to be called from build scripts to simplify building crates //! which depend on PyO3. //! //! It used internally by the PyO3 crate's build script to apply the same configuration. mod errors; mod impl_; #[cfg(feature = "resolve-config")] use std::io::Cursor; use std::{env, process::...
Rust
0
" • SDP2 : instance optimizing economic outcomes") print(" • Pareto : SDP_Pareto(SDP_Parent, [SDP1, SDP2]) computes Pareto front.") class ClimateMatterMost(MatterMostPareto): # Value is added for transitioning into states which are not comitted to # severe future climate change. de...
Python
1
st.append(crv.getParent()) return crv_list @errorHandler def generateProfile(self): n_polyType = pm.nurbsToPolygonsPref(q=1,polyType = 1) n_format = pm.nurbsToPolygonsPref(q=1,format = 1) n_uType = pm.nurbsToPolygonsPref(q=1,uType = 1) n_uNumber = pm.nurbsToP...
Python
1
ter<'_>) -> Result<(), std::fmt::Error> { self.as_str().fmt(f) } } impl<B> AsRef<str> for ValidStr<B> where B: zerocopy::ByteSlice, { fn as_ref(&self) -> &str { self.as_str() } } #[cfg(test)] mod tests { use super::*; use assert_matches::assert_matches; #[test] fn tes...
Rust
0
"""MELCloud client library.""" from datetime import timedelta from typing import Dict, List, Optional from aiohttp import ClientSession from .ata_device import AtaDevice from .atw_device import AtwDevice from .client import Client as _Client from .client import login as _login from .const import DEVICE_TYPE_ATA, DEV...
Python
1
= cfg.get("tune_mm_mlp_adapter", False) freeze_mm_mlp_adapter = cfg.get("freeze_mm_mlp_adapter", False) apply_fsdp = cfg.get("apply_fsdp", None) max_txt_len = cfg.get("max_txt_len", 128) max_output_txt_len = cfg.get("max_output_txt_len", 256) low_resource = cfg.get("low_resource...
Python
1
import torch def sample_top_p(probs, p): probs_sort, probs_idx = torch.sort(probs, dim=-1, descending=True) probs_sum = torch.cumsum(probs_sort, dim=-1) mask = probs_sum - probs_sort > p probs_sort[mask] = 0.0 probs_sort.div_(probs_sort.sum(dim=-1, keepdim=True)) next_token = torch.multinomial...
Python
1
//github.com/ethereum/eth2.0-specs/blob/65b615a4d4cf75a50b29d25c53f1bc5422770ae5/specs/core/0_fork-choice.md> //! //! `assert`s from Python are represented by statements that either delay the processing of the //! offending object or return `Err`. All other operations that can raise exceptions in Python //! (like index...
Rust
0
, *b.count_mut(Piece::White)); } #[test] fn test_do_flip() { let mut b = SAMPLE_BOARD.clone(); b.do_flip(Piece::White, Coord(0, 3), Coord(1, 1), 2); assert_eq!(24, b.white); assert_eq!(23, b.black); assert_eq!( Matrix([ [N, N, W, W, N, B, ...
Rust
0
.usbregstatus .read() .vbusdetect() .is_vbus_present() {} // wait until USB 3.3V supply is stable while !board .POWER .events_usbpwrrdy .read() .events_usbpwrrdy() .bit_is_clear() {} ...
Rust
0
}; } impl_fuzzable_for_prims! { u8, u16, u32, u64, i8, i16, i32, i64, usize, isize, u128, i128, bool, } macro_rules! impl_bounded_fuzzable_for_prims { ($($t:ty,)*) => { $( impl BoundedFuzzable for $t { fn fuzz_bound(range: Range<Self>) -> Self { ...
Rust
0
memory[0xFFFD] = 0x02; processor.memory[0x0002] = 0x00; // 0x02 + 0x04 processor.memory[0x0003] = 0x80; processor.memory[0x8004] = 0x42; let expected_cycles = 5; let used_cycles = processor.execute_cycles(expected_cycles); assert_eq!(processor.registers.a, 0x45 | 0x42); assert_eq!(used_cyc...
Rust
0
import pomegranate from collections import Counter from model import model def generate_sample(): # Mapping of random variable name to sample generated sample = {} # Mapping of distribution to sample generated parents = {} # Loop over all states, assuming topological order for state in mod...
Python
1
_ref().map(Sourced::with_project) } } #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct BinaryPlatformSpec { pub node: Version, pub npm: Option<Version>, pub yarn: Option<Version>, } impl PlatformSpec for BinaryPlatformSpec { fn node(&self) -> Sourced<&Version> { Sourced::with_bi...
Rust
0
from fastapi import FastAPI, File, Form, UploadFile from fastapi.middleware.cors import CORSMiddleware import os import requests from dotenv import load_dotenv import shutil import json import uuid load_dotenv() PINATA_API_KEY = os.getenv("PINATA_API_KEY") PINATA_SECRET_API_KEY = os.getenv("PINATA_SECRET_API_KEY") ap...
Python
1
] = df['Country'].map(sports_inv_values) df['Previous_medals'] = df['Country'].map(prev_medals) # Анализ добавленных данных print(f"\nДобавлено {len(df.columns) - 6} новых столбцов:") for col in ['GDP', 'HDI', 'Continent', 'Sports_investment', 'Previous_medals']: print(f"- {col}: {df[col].dtype...
Python
1
# Code generated by Lark OpenAPI. from typing import Any, Optional, Union, Dict, List, Set, IO, Callable, Type from lark_oapi.core.construct import init from .compensation_cost import CompensationCost class CompensationCostItem(object): _types = { "number_of_individuals_for_payment": int, "compen...
Python
1
, &mut lines, Edit { pos: 17, kind: EditKind::Insert("123\r\n45\r\n6789"), }, ); assert_eq!( text.as_str(), "abcd\r\nefg\r\nhijklm123\r\n45\r\n6789\r\nno\r\n" ); assert_eq!( doc_lines(lines), vec![ doc_line(0), doc_line(6), ...
Rust
0
}else{ Ok(info.addr) } }else{ Err(format!("Label:[{}] referenced at line:{} col:{} not found.",expression.value,expression.line(),expression.col())) } }, ExpressionType::Value=>{ ...
Rust
0
2usize, concat!("Alignment of ", stringify!(TPMS_CREATION_INFO)) ); assert_eq!( unsafe { &(*(::std::ptr::null::<TPMS_CREATION_INFO>())).objectName as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(TPMS_CREATION_INFO), ...
Rust
0
"""The module contains the OctiDomainModel class, which represents an OpenCTI Domain Name.""" from typing import Any from connector.src.stix.v21.models.scos.domain_name_model import DomainNameModel class OctiDomainModel: """Model for creating OpenCTI Domain Name objects.""" @staticmethod def create( ...
Python
1
None, ))) } }; let input = s.trim().to_string(); return Ok(Value::Str(input)); } Fun::KeyChar => return Ok(Value::None), Fun::EmptySlot => { for n in 0..isize::MAX { i...
Rust
0
from glidergun._grid import Grid, grid def tick(grid: Grid): g = grid.focal_sum() - grid return (grid == 1) & (g == 2) | (g == 3) def test_glidergun30(): gosper = tick(grid(".data/glidergun30.asc")) md5s = set() while gosper.md5 not in md5s: md5s.add(gosper.md5) gosper = tick(gos...
Python
1
Sub<Self::Sub, DemirootComp::Msg>, ) -> Html<DemirootComp> { Self::with_children(props, sub, vec![]) } } pub trait Update: Component { fn update(&mut self, _: &Self::Props, _: Self::Msg) -> Cmd<Self> { Cmd::None } fn on_assemble(&mut self, _: &Self::Props) -> Cmd<Self> { Cm...
Rust
0
import torch import torch.nn as nn import torch.nn.functional as F class Anti_Alias_Filter(nn.Module): """ adaptive low pass filter (anti-alias) used before downsampling (pooling or stride>1 conv) idea from Delving-Deeper-Into-Anti-Aliasing-in-ConvNets (BMVC2020 best paper) https://arxiv.org/pdf/2008.0960...
Python
1
n crate wasm_bindgen_test; extern crate wasm_game_of_life; use wasm_bindgen_test::*; use wasm_game_of_life::Universe; extern crate web_sys; wasm_bindgen_test_configure!(run_in_browser); // A macro to provide `println!(..)`-style syntax for `console.log` logging. macro_rules! log { ( $( $t:tt )* ) => { web...
Rust
0
use super::*; #[no_mangle] pub unsafe extern "C" fn Java_com_example_vampire_opengl_Rust_init( env: JNIEnv, _: JClass, ) -> jlong { // Our Java companion code might pass-in "world" as a string, hence the name. // let world = rust_greeting(env.get_string(java_pattern)....
Rust
0
from typing import Dict from transformers import BertTokenizer, BertForSequenceClassification import torch class SentimentModule: """ 中文情感分析模組,預設用 IDEA-CCNL/Erlangshen-Roberta-330M-Sentiment """ def __init__(self, model_name: str = 'IDEA-CCNL/Erlangshen-Roberta-330M-Sentiment'): self.tokenizer ...
Python
1
bplots(3, gridspec_kw={'hspace':0.05}) fig.suptitle(f'Correct label: {i}, {label}', fontsize=20) for j in range(3): col = 'b' if j == i else 'r' idx_max = np.where(combs_max[:, i, j] > -0.1)[0] p = seaborn.histplot(data=combs_max[idx_max, i, j],bins=15,kde=False, binr...
Python
1
.res_output_syscall(res) .iter() .map(|sid| target.syscall_of(*sid).name().to_string()) .collect::<Vec<_>>(); let in_syscalls = target .res_input_syscall(res) .iter() .map(|sid| target.syscall_of(*sid).name...
Rust
0
// submission codes start here impl Solution { pub fn search(nums: Vec<i32>, target: i32) -> bool { false } } // submission codes end #[cfg(test)] mod tests { use super::*; #[test] fn test_81() {} } use std::borrow::Cow; use std::convert::TryInto; use crate::facet::value_encoding::{i64...
Rust
0
o_u16; /// /// assert_eq!(i16_to_u16(0_i16), 0_u16); /// assert_eq!(i16_to_u16(32767_i16), 32767_u16); /// ``` pub fn i16_to_u16(a: i16) -> u16 { match i16_to_u16_res(a) { Ok(i) => i, Err(err) => panic!("{}",err) } } /// Parse [`i32`](https://doc.rust-lang.org/std/primitive.i32.html) to //...
Rust
0
0.1 scale = 0 while step > tolerance: while i_max_pu < self.der_file.NP_CURRENT_PU: scale = scale + step i_pos_pu = (self.i_pos_d_ref_pu * scale + 1j * self.i_pos_q_ref_pu) \ * np.exp(1...
Python
1
# python ''' 1、类型分类 数字(int、float、complex复数)、 bool、字符串、 复杂数据类型(列表、元组、字典、集合) 2、查看变量类型:type(a) 3、强制转换: Python 提供了将变量或值从一种类型转换成另一种类型的内置函数 int(x [,base ]) 将 x 转换为一个整数 long(x [,base ]) 将 x 转换为一个长整数 float(x ) 将 x 转换到一个浮点数 complex(real [,imag ]) 创建一个复数 str(x ) 将对象 x 转换为字符串 repr(x ) 将对象 x 转换为表达式字符串 eval(str ) 用来计算在字符串中的有效 ...
Python
1
UID as libc::mode_t; /// `S_ISGID` const ISGID = libc::S_ISGID as libc::mode_t; /// `S_ISVTX` const ISVTX = libc::S_ISVTX as libc::mode_t; } } /// WASI doesn't have Unix-style mode flags. #[cfg(target_os = "wasi")] pub struct Mode {} #[cfg(target_os = "wasi")] impl Mode { ///...
Rust
0
def test_smoke(): assert True
Python
1
screen.blit(knight_image, (x * SQUARE_SIZE, y * SQUARE_SIZE)) #draw number of possible moves onto board if chessBoard[x][y] > 0: num = chessBoard[x][y] num_text = str(num) render_num = font.render(num_text, True, (0,0,0)) #prints t...
Python
1
IFIER: Regex = Regex::new(r"\babstract\b").unwrap(); static ref EXPORT_MODIFIER: Regex = Regex::new(r"\bexport\b").unwrap(); } #[derive(Debug, Deserialize, Serialize)] pub enum CodeLensSource { #[serde(rename = "implementations")] Implementations, #[serde(rename = "references")] References, } #[derive(Debug...
Rust
0
of line(R RRRy(R((sw/private/var/folders/vy/31wknkcs30l6xb2fzgwnrkh80000gn/T/pip-build-VQoj4y/setuptools/pkg_resources/_vendor/pyparsing.pyR& scCs;t||dkr|gfSt|||j|dS(Ni(R7RRy(RRERR...
Python
1
.name == "nt": cadquery_path = slash_drive(pathlib.WindowsPath(cadquery_path).as_posix()) print( f"Created the {patch_file_name} file and copied it to cadquery source directory" ) print("To apply the patch, from a bash shell:") print(f" cd {cadquery_path}") print(f" patch --...
Python
1
sult); } fn main() { let input_file = File::open("input.txt").expect("Failed to open input.txt"); let input = BufReader::new(input_file) .lines() .map(|line| { line.expect("Invalid line") .chars() .map(Square::try_from) .collect::<Resu...
Rust
0
"""LEETCODE""" #QUESTION LINK:-https://leetcode.com/problems/single-element-in-a-sorted-array/ #SOLUTION:- class Solution(object): def singleNonDuplicate(self, nums): """ :type nums: List[int] :rtype: int """ l,r=0,len(nums)-1 if r==0: return nums[-1] ...
Python
1