text
string
label_name
string
labels
int64
nce: 2.50"] #[doc = " @G_UNICODE_SCRIPT_TANGUT: Tangut. Since: 2.50"] #[doc = " @G_UNICODE_SCRIPT_MASARAM_GONDI: Masaram Gondi. Since: 2.54"] #[doc = " @G_UNICODE_SCRIPT_NUSHU: Nushu. Since: 2.54"] #[doc = " @G_UNICODE_SCRIPT_SOYOMBO: Soyombo. Since: 2.54"] #[doc = " @G_...
Rust
0
working_cycles.push(cycle); } } (hunt_cycles, working_cycles) } } #[cfg(test)] mod tests { use crate::{method::FullClass, Block, MethodLib}; #[test] fn classification() { let mut num_misclassifications = 0usize; for (name, pn, class) in MethodLib::cc_lib().u...
Rust
0
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse from alipay.aop.api.domain.AssetResult import AssetResult class AntMerchantExpandAssetinfoSyncResponse(AlipayResponse): def __init__(self): super(AntMerchantExpandAssetinfoSyncResp...
Python
1
class Player: MAX_STAMINA = 100 MIN_STAMINA = 0 players_list = [] def __init__(self, name: str, age: int, stamina: int = MAX_STAMINA) -> None: self.name = name self.age = age self.stamina = stamina @property def name(self): return self.__name @name.setter ...
Python
1
import os from typing import Annotated from uuid import uuid4 from fastapi import Header, Depends, UploadFile, File, HTTPException, Path, APIRouter, Request from loguru import logger import sys from app.models_pydentic import ( TweetRequest, MediaResponse, TweetResponse, LikeResponse, FollowerRespo...
Python
1
, buf) } fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> { let stream = &mut Pin::into_inner(self).wrapped_stream; Pin::new(stream).poll_flush(cx) } fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<...
Rust
0
"""Test function for intensity data augmentation.""" import chex import jax from absl.testing import parameterized from chex._src import fake from imgx.data.augmentation.intensity import batch_random_adjust_gamma, batch_rescale_intensity from imgx.datasets.constant import IMAGE # Set `FLAGS.chex_n_cpu_devices` CPU ...
Python
1
import wfdb import pywt import seaborn import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix from sklearn.model_selection import train_test_split from scipy.fft import fft, ifft def plot_heat_map(y_test, y_pred): con_mat = confusion_matrix(y_test, y_pred) # normalize ...
Python
1
""" Replaces Latin and Arabic numbers with Farsi ones. Several Persian users needs this feature because of using legacy or unchangable environments. """ import sys import fontforge def setFarsiDigits(infile, outfile): font = fontforge.open(infile) font.encoding = "Unicode" # copy Farsi digits (0 1 2 3...
Python
1
cending=True) filtered_hs = list() filtered_mask = list() filtered_query = list() filtered_rp = list() filtered_labels = list() selected_ids = list() for b_i in range(B): num_candidates = corner_nums[b_i] * 3 ids = sorted_ids[b_i, :max_cand...
Python
1
[tokio::main] /// async fn run() -> Result<(), Box<dyn std::error::Error>> { /// let client = esplora_api::async_impl::ApiClient::new("https://blockstream.info/testnet/api/", None).unwrap(); /// let response = client.get_block_txid_at_index("000000000000003aaa3b99e31ed1cac4744b423f9e52ada4971461c81d...
Rust
0
_imm64_mem( RelationalCondition::NotEqual, vtable as *const _ as i64, Mem::Base(value, offset_of!(Obj, vtable) as i32), ) } pub fn branch_if_string(&mut self, value: Reg) -> Jump { self.branch_if_type(value, &crate::builtins::STRING_VTBL) } pub fn bra...
Rust
0
K_KHR_STORAGE_BUFFER_STORAGE_CLASS_SPEC_VERSION: u32 = 1; #[cfg(feature = "VK_KHR_storage_buffer_storage_class")] pub const VK_KHR_STORAGE_BUFFER_STORAGE_CLASS_EXTENSION_NAME: &str = "VK_KHR_storage_buffer_storage_class\0"; // feature: VK_AMD_gpu_shader_int16 // VK_AMD_gpu_shader_int16 //////////////////////////// #[...
Rust
0
4, 1, 2, 3], [4, 1, 3, 2], [4, 2, 1, 3], [4, 2, 3, 1], [4, 3, 1, 2], [4, 3, 2, 1]] all_types = [[all_types[iat][0] - 1, all_types[iat][1] - 1, all_types[iat][2] - 1, all_types[iat][3] - 1] for iat in range(24)] tpe = all_types[mt] p1 = Point((xs[0], ys[tpe[0]])) p2 = Point((xs[1], ys[t...
Python
1
), ( new_append_message_with_entries(2, 2, 2, 3, vec![new_entry(2, 3), new_entry(2, 4)]), 4, 3, false, ), ( new_append_message_with_entries(2, 2, 2, 4, vec![new_entry(2, 3)]), 3, 3, false, ...
Rust
0
Expression>)]) -> Node<Expression> { let mut vm = Vec::from(v); build_binop_left_assoc_tree_aux(first, &mut vm) } fn build_binop_left_assoc_tree_aux(first: Node<Expression>, v: &mut Vec<(Node<BinaryOp>, Node<Expression>)>) ...
Rust
0
_image_tokens): image_tokens = torch.cat((self.start_img.expand(_bsz, -1, -1), image_tokens, self.end_img.expand(_bsz, -1, -1)), dim=1) l_image_tokens[i] = image_tokens image_tokens = torch.ca...
Python
1
); } } <reponame>peterhj/liboperator use prelude::*; use opt::{NesterovParamState, ClassOptStats}; use rw::{ReadBuffer, WriteBuffer, AccumulateBuffer}; use densearray::{Reshape, ReshapeMut}; use rand::{Rng}; use std::cmp::{min}; use std::marker::{PhantomData}; #[derive(Clone, Copy, Debug)] pub struct AdamConfig ...
Rust
0
d_accessor::<_, ::protobuf::types::ProtobufTypeMessage<StorageReceivedDeletedBlocksProto>>( "blocks", BlockReceivedAndDeletedRequestProto::get_blocks_for_reflect, BlockReceivedAndDeletedRequestProto::mut_blocks_for_reflect, )); ...
Rust
0
#!/usr/bin/python3 for i in range(9): for j in range(i + 1, 10): if i * 10 + j < 89: print("{:d}{:d}".format(i, j), end=", ") print("{:d}".format(89))
Python
1
et( carrier, self.TRACE_ID_KEY, # Encode as string, most services should be able to support 128 bit trace id's. # Those that cannot will need to upgrade str(span_context.trace_id), ) setter.set(carrier, self.SPAN_ID_KEY, format_span_id(span_con...
Python
1
r.read_u8()?; // Reserved value (not used) entry.reserved = r.read_u8()?; // This may be either the number of color planes (0 or 1), or the horizontal coordinate // of the hotspot for CUR files. entry.num_color_planes = r.read_u16::<LittleEndian>()?; if entry.num_color_planes > 256 { r...
Rust
0
Url{ scheme: "pkg".to_string(), namespace: String::new(), package_type: package_type, name: name, version: version } } // format: 'scheme:type/namespace/name@version?qualifiers#subpath' pub fn build_purl(&self) -> String { let mut s = format!("{}:{}/", self.scheme, self.package_type); if !...
Rust
0
ce': query = query.order_by(Product.price) elif sort == 'stock': query = query.order_by(Product.stock) elif sort == 'category': query = query.order_by(Category.name) # Paginate products = query.paginate(page=page, per_page=20) return jsonify({ 'items': [...
Python
1
).await { Ok(chat) => chat, Err(e) => { eprintln!("❗ IPFS: {:#?}", e); return; } }; let chat_handle = tokio::spawn(async move { chat.st...
Rust
0
raw_receipt, Receipt); if receipt.success { let mut c_results = Vec::with_capacity(*results_len as usize); for value in receipt.results.iter() { let c_value = wasmer_value_t::from(value.clone()); c_results.push(c_value); ...
Rust
0
pub fn call(&self, cpu: &mut CPU) { let cpu: *mut CPU = cpu as _; let ptr = self.get_ptr(); let f: fn(*mut CPU, *mut [u8; 0x800]) -> () = unsafe { mem::transmute(ptr) }; let ram = unsafe { &mut (*cpu).ram }; trampoline_to_nes(f, cpu, ram); } pub fn get_ptr(&self)...
Rust
0
decimal_parts.sort(reverse=True, key=lambda x: x[0]) # 按小数部分降序排列 # 分配剩余的宽度 for _, idx in decimal_parts[:new_remaining]: int_allocations[idx] += 1 # 将分配结果加上最小值 final_allocations = [int_allocations[i] + min_allocation for i in range(n)] return final_allocatio...
Python
1
rage subfigure width/height. If not given, the values will be inferred from rcParams if using constrained layout (see `~.ConstrainedLayoutEngine`), or zero if not using a layout engine. width_ratios : array-like of length *ncols*, optional Defines the relative widths of the columns. Each column gets a ...
Python
1
terfly12 => 12, Recipe::Butterfly13 => 13, Recipe::Butterfly15 => 15, Recipe::Butterfly16 => 16, Recipe::Butterfly17 => 17, Recipe::Butterfly19 => 19, Recipe::Butterfly23 => 23, Recipe::Butterfly29 => 29, Recipe::Butterfly31...
Rust
0
= self.session.query(Message).filter(Message.id == data["id"]).first() if not msg: return {"err": "params.not_found", "msg": _(u"查无此ID")} msg.unread = False msg.update_time = datetime.datetime.now() msg.save() return {"err": "ok"} class UserInfo(BaseHandler): ...
Python
1
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and relate...
Python
1
import os, json, bioCommons ''' Write PCR primer design parameters to a file, and design primers Output files: masked.template.mutationTemplate.minus2.txt.right.parameters.txt masked.template.mutationTemplate.minus2.txt.right.primer3.txt masked.template.mutationTemplate.minus2.txt.left.parameters.txt masked.templa...
Python
1
from collections import Counter n = int(input()) a = Counter(map(int, input().split())) print(max(a.values()))
Python
1
# # Copyright (c) 2023 Airbyte, Inc., all rights reserved. # url_base = "http://api.weatherstack.com/"
Python
1
import os import pandas as pd import zipfile from tqdm import tqdm dir = r'Z:\Discrete emotions' # unzip files in dir for file in os.listdir(dir): if '.zip' in file: with zipfile.ZipFile(os.path.join(dir, file), 'r') as zip_ref: zip_ref.extractall(dir) types = ['journalists', 'ngos', 'politicia...
Python
1
d(32, 8, 3, stride=1, padding=1, bias = True), nn.BatchNorm3d(8), nn.ReLU(), nn.Conv3d(8, 3, 3, stride=1, padding=1,bias = True), ) elif paras['structure'] == 'deepflash': ##########################2D Net################################################# encoder = nn...
Python
1
list_spes.append(spe) self.dict_taxon[spe] = [seq.replace( " ", "")] # seq要替换其他符号 has_interleave_seq = True if len(list_spes) != taxnum: for i in list_spes[0:-taxnum]:...
Python
1
random.shuffle(perm_idx) actual_lowess = lowess(y, x, xvals=x[perm_idx], missing="none") assert_almost_equal(target[perm_idx, 1], actual_lowess, decimal=13) target_it0 = lowess(y, x, return_sorted=False, it=0) actual_lowess2 = lowess(y, x, xvals=x[perm_idx], it=0) assert_almost_...
Python
1
import numpy as np import pytest import cv2 from model_1.augmentacija import clip, flip_polygon, transform def test_clip(): assert clip(1.5) == 1.0 assert clip(-0.2) == 0.0 assert clip(0.75) == 0.75 def test_flip_polygon(): polygon = [0.1, 0.5, 0.3, 0.5, 0.3, 0.7, 0.1, 0.7] flipped = flip_polygon...
Python
1
']) st.write(f"Now Playing: {selected_video['title']}") # Embed the video with 1920x1080 resolution using HTML video_url = f"https://www.youtube.com/embed/{selected_video['id']}" st.markdown( f'<iframe width="1920" height="1080" src="{video_url}" frameborder="0" allowfullscreen></iframe>', unsafe_allow_htm...
Python
1
self.complications_of_failure_label, 10, 1) # self.grid.addWidget(self.complications_of_failure_combo, 11, 1) self.grid.addWidget(self.complications_during_disassembly_label, 48, 1) self.grid.addWidget(self.complications_during_disassembly_combo, 49, 1) self.scheme_bop_...
Python
1
} #[doc = "Enables Bank2 of the SRAM"] #[inline(always)] pub fn bnk2_en_1(self) -> &'a mut W { self.variant(BNK2_EN_A::BNK2_EN_1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bi...
Rust
0
#!/usr/bin/env python3 import argparse import os from strands import Agent from strands.tools.mcp import MCPClient from strands_tools import file_read, file_write from mcp import StdioServerParameters, stdio_client from dotenv import load_dotenv load_dotenv() def get_environment_variables(): """Get environment v...
Python
1
} } impl From<FromUtf8Error> for Error { #[inline] fn from(err: FromUtf8Error) -> Self { Error::StringError(err) } } impl MagicCrypt { /// Create a new MagicCrypt instance. You may want to use `new_magic_crypt!` macro. pub fn new<S: AsRef<str>, V: AsRef<str>>(key: S, bit: SecureBit, iv: Op...
Rust
0
# ruff: noqa from .v5.api import *
Python
1
prefix_len: #prefix } } } } /// Helper struct to parse Cidr addresses from string. struct Ipv4AddrWithPrefix { address: std::net::Ipv4Addr, prefix: u8, } #[derive(thiserror::Error, Debug)] enum Ipv4AddrWithPrefixParseError { #[error("failed to parse as CIDR address...
Rust
0
Pubkey>, dst: &mut [u8; 4 + PUBKEY_BYTES]) { #[allow(clippy::ptr_offset_with_cast)] let (tag, body) = mut_array_refs![dst, 4, PUBKEY_BYTES]; match src { COption::Some(key) => { *tag = [1, 0, 0, 0]; body.copy_from_slice(key.as_ref()); } COption::None => { ...
Rust
0
"""Models for accounts app. We'll use Django's built-in User model for auth and create a Profile to store extra user data (like avatar).""" from django.db import models # Django ORM models from django.contrib.auth.models import User # built-in User model from django.db.models.signals import post_save # signal t...
Python
1
# Copyright (C) 2015 Optiv, Inc. (brad.spengler@optiv.com) # This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org # See the file 'docs/LICENSE' for copying permission. from lib.cuckoo.common.abstracts import Signature class AntiAnalysisDetectReg(Signature): name = "antianalysis_detectreg" descri...
Python
1
server").to_here() model = Model() # "0" will be wake up twice as a slave reducer, and once # as the master reducer. for i in range(2): model.zero_grad() loss = model(t.ones([1, 1])) loss.backward() server.p...
Python
1
0, 200)), (15, 9,(200, 200, 200)), (16, 9,(100, 100, 100)), # Undecimo nivel (3, 8,(100, 100, 100)), (4, 8,(200, 200, 200)), (8, 8,(200, 200, 200)), (9, 8,(200, 200, 200)), (10, 8,(200, 200, 200)), (11, 8,(200, 200, 200)), (15, 8,(200, 200, 200)), (16, 8,(100, 100, 100)), # Duodecimo nivel (3, 7,(100, 100, 100)...
Python
1
ender<Vec<Op>>), AddOperation(Op), MarkInput(TokenId, String), MarkOutput(TokenId, String), NextLabel(SyncSender<LabelId>), } impl<'a> ProgramBuilder { pub fn new() -> ProgramBuilder { let (tx, rx) = mpsc::sync_channel(0); ProgramBuilder { id: thread_rng().gen(), ...
Rust
0
0xC0000247, LoginWorkstationRestriction = 0xC0000248, ImageMpUpMismatch = 0xC0000249, InsufficientLogonInfo = 0xC0000250, BadDllEntryPoint = 0xC0000251, BadServiceEntryPoint = 0xC0000252, LpcReplyLost = 0xC0000253, IpAddressConflict1 = 0xC0000254, IpAddressConflict2 = 0xC0000255, Re...
Rust
0
import gradio as gr from ktem.app import BasePage from ktem.db.models import User, engine from ktem.embeddings.ui import EmbeddingManagement from ktem.index.ui import IndexManagement from ktem.llms.ui import LLMManagement from sqlmodel import Session, select from .user import UserManagement class ResourcesTab(BasePa...
Python
1
s using standard Pipecat pattern await processor.push_frame( TTSSpeakFrame( "Hello, this is Jamie calling about your appointment. Please call me back at 555-0123 when you get this." ) ) # NOTE: A common pattern is to end pipeline after the voicemail is le...
Python
1
# https://leetcode.com/problems/frequency-of-the-most-frequent-element/ class Solution: def maxFrequency(self, nums, k): nums.sort() prefixSum = [] s = 0 for i in nums: prefixSum.append(s) s += i res = 1 l = 0 for r in range(len(nums)...
Python
1
a:String, b:i32 } fn main() { let c = Struct{a : "giuseppe".to_string(), b : 67}; println!("{:?}", c); } // #![deny(missing_docs, dead_code)] //! # Nexus //! //! A high performance networking library #![cfg_attr(all(test, feature = "json_codec"), feature(custom_derive, plugin))] #![cfg_attr(all(test, fe...
Rust
0
test_loader_wt = DataLoader(dataset=test_dataset_wt, batch_size=batch_size, shuffle=False) return { "train_loader": train_loader, "test_loader": test_loader, "test_loader_wt": test_loader_wt, "downstream_loader_ag": downstream_loader_ag if args.task_name == "imdb" else None, ...
Python
1
CategoriesInfo>, } /// Deserialized category info. #[derive(Deserialize, Clone, Debug)] #[non_exhaustive] pub struct CategoriesInfo { pub category: String, pub kills: u32, pub deaths: u32, pub kd: f32, pub headshots: u32, pub headshot_percentage: f32, pub times_chosen: u32, pub bullets_...
Rust
0
__ == "__main__": env = FlappyBirdEnv() done = False state = env.reset() while True: action = 0 # Default to no flap # Handle events for event in pygame.event.get(): if event.type == pygame.QUIT: env.close() sys.exit() ...
Python
1
ld be controlled by a scope. unsafe { v8__Context__Exit(self) }; } } <gh_stars>10-100 use std::fs; use std::path::Path; use pretty_assertions::assert_eq; use corewars_sim::Core; #[test] fn validate_redcode() { // Workaround for the fact that `test_resources` paths are based on workspace Cargo.toml // h...
Rust
0
ator.fresh(); let tmp3 = self.label_allocator.fresh(); self.new_body.insert(entry, Instruction::BinaryOp(x64BinaryOp::mov, reg2, Register::Rax, tmp2)); self.new_body.insert(tmp2, Instruction::BinaryOp(x64BinaryOp::div, reg1, Register::Rax, tmp3)); self.new...
Rust
0
5AC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {405827CB-84E1-46F3-82C9-D889892645AC}.Debug|Any CPU.Build.0 = Debug|Any CPU {405827CB-84E1-46F3-82C9-D889892645AC}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {405827CB-84E1-46F3-82C9-D889892645AC}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {405827CB-84E1-46F...
Rust
0
k_grid_data.json" }, "outage": { "weather_file": "mock_weather_storm.json", "grid_file": "mock_grid_outage.json" } } if scenario in scenario_configs: config = scenario_configs[scenario] orchestrator.threat_agent.update_mock_config({ ...
Python
1
""" 题目: 有M个数组,每个数组中若干个不同字符。从每个数组中任意取一个字符,拼接成一个字符串,求所有字符串 示例: input: [['1', '2'], ['a', 'b', 'c'], ['A', "B", "C"]] output: ['1aA', '1aB', '1aC', '1bA', '1bB', '1bC', '1cA', '1cB', '1cC', '2aA', '2aB', '2aC', '2bA', '2bB', '2bC', '2cA', '2cB', '2cC'] 思路: 要解决本题,采用递归的思路即可。 每一步递归就是将两个数组进行做笛卡...
Python
1
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. from datetime import datetime from importlib.metadata import PackageNotFoundError, version from typing import O...
Python
1
, pub foo_union_type: namespace_b::UnionInNestedNS, pub foo_union: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>, pub foo_struct: Option<&'a namespace_b::StructInNestedNS>, } impl<'a> Default for TableInFirstNSArgs<'a> { #[inline] fn default() -> Self { TableInFirstNSArgs { ...
Rust
0
import execute_resilient_operation from rhoshift.utils.stability_coordinator import StabilityLevel from rhoshift.utils.utils import run_command # All imports should succeed assert all( [ main, parse_args, install_operator, ...
Python
1
s_hat_df.join(df[out_columns + (labels_all if labels_present else [])]) out_path = data_path / config.get("predict_file_name") print(f"Storing predictions with {len(out_df)} records and {len(out_df.columns)} columns in output file {out_path}...") if out_path.suffix == ".parquet": out_df.to_parquet...
Python
1
_x1) = C // P(k = m) = C * (hIntegral(m + 1/2) - hIntegral(m - 1/2)) for m >= 2 // // where C = 1 / (h_integral_num_elements - h_integral_x1) if k64 - x <= self.s || u >= ZipfDistribution::h_integral(k64 + 0.5, self.exponent) - ZipfDi...
Rust
0
fn index_mut_pair<T>(slice: &mut [T], i: usize, j: usize) -> (&mut T, &mut T) { if i < j { let (left, right) = slice.split_at_mut(j); (&mut left[i], &mut right[0]) } else if j < i { let (left, right) = slice.split_at_mut(i); (&mut right[0], &mut left[j]) } else { pani...
Rust
0
ot stored in the cell map they will be ignored. pub fn get_cell_entities(&self, coords: &[C::Coordinates]) -> Vec<Entity> { coords .iter() .filter_map(|c| self.cells.get(c)) .copied() .collect() } /// Adds a `Cell` entity to the map at `coordinates`. ...
Rust
0
mb_native_cuda_back_and_forth(b: &mut Bencher) { sync_back_and_forth(b, cuda_backend(), native_backend(), 128 * 1_048_576); } #[bench] fn bench_sync_128mb_native_to_cuda(b: &mut Bencher) { unidirectional_sync(b, native_backend(), cuda_backend(), 128 * 1_048_576); } #[bench] fn ...
Rust
0
c( K::initialize_pthread_key(), pointer as *const libc::c_void ); TlsValue( value ) }); *pointer = SlotKind::Initialized( ManuallyDrop::new( value.0 ) ); match *pointer { SlotKind::Initialized( ref value ) => &value, _ => unreachable!() } } pub trait Key { type Value; ...
Rust
0
wszLogicalPath: LPCWSTR, wszComponentName: LPCWSTR, status: VSS_FILE_RESTORE_STATUS, ) -> HRESULT, fn AddNewTarget( writerId: VSS_ID, ct: VSS_COMPONENT_TYPE, wszLogicalPath: LPCWSTR, wszComponentName: LPCWSTR, wszPath: LPCWSTR, wszFileName: L...
Rust
0
test_html! { |t4| 42 } test_html! { |t5| 1.234 } test_html! { |t6| true } test_html! { |t10| <span>{ "" }</span> } test_html! { |t11| <span>{ 'a' }</span> } test_html! { |t12| <span>{ "hello" }</span> } test_html! { |t13| <span>{ 42 }</span> } test_html! { |t14| <span>{ 1.234 }</span> } test_html! { |t15| <span>{ tru...
Rust
0
2.") sys.exit(2) squares = perfect_squares_up_to(2 * N) edges = build_edges(N, squares) degrees = {v: len(edges[v]) for v in edges} # --- Quick structural witnesses (proofs of impossibility) witness = None deg_lt2 = [v for v, d in degrees.items() if d < 2] if deg_lt2: witne...
Python
1
# Testing accuracy of the naive Bayes classification with dataset "Titanic" from src.CSVReader import CSVReader from src.naiveBayesClassifier import NaiveBayesClassifier import csv train_file_path = 'Titanic_train.csv' test_file_path = 'Titanic_test.csv' result_file_path = 'Titanic_result.csv' # Import train dataset...
Python
1
import requests import sys import re if __name__ == "__main__": assert(len(sys.argv) == 4) handle = sys.argv[1] token = sys.argv[2] readmePath = sys.argv[3] headers = { "Accept": "application/vnd.github.v3+json", "Authorization": f"token {token}" } followers = [] for ...
Python
1
Ok(PyArray1::from_iter( py, self.inner.decode_iid_symbols(amt, &model).map(|symbol| { (symbol.expect("We use constant `PRECISION`.") as i32) .wrapping_add(min_supported_symbol) }), )) } #[text_signature = "(amt, model)"] pub fn...
Rust
0
<RistrettoPoint> = (0..n).map(|i| // RistrettoPoint::vartime_multiscalar_mul(&[u_square.clone()], &[H_vec[i]]) // ).collect(); let Y_hat_vec: Vec<EdwardsPoint> = (0..n).map(|i| H_vec_temp[i] + P_vec_temp[i]).collect(); // let Y_hat_vec: Vec<RistrettoPoint> = (0..n).map(|i| ...
Rust
0
ias(f"spending_consistency_{window_name}"), # Behavioral diversity score (combination of location and merchant diversity) ( pl.col(f"unique_merchants_{window_name}") + pl.col(f"unique_categories_{window_name}") ).alias(f"behavioral_diversity_{window_na...
Python
1
&mut D) -> common::Result<Resp> { let old = dict.get_or_insert_with(self.key, || Value { data: DataType::Set(Box::new(Set::new())), expires_at: 0, visit_log: Value::new_visit_log(), }); if let DataType::Set(ref mut set) = old.data { let old_len = ...
Rust
0
ite_Shadowing_samples_nlos - clutter_loss P_received_fspl_ShF_SSF = (satellite_EIRP_total + G_max_Rx + 20*np.log10(np.abs(Satellite_Channel_fading_samples))) - fspl_solo - atmospheric_loss -Satellite_Shadowing_samples P_recieved_at_edge_point = P_received_fspl_ShF_SSF + 10 * 2 * ...
Python
1
Y ranges of [0:127]... // Column set: [2:129] spi_w8( &spi, 0x2A ); dat_cmd( &spi, &gpioa, true ); spi_w16( &spi, 0x0200 ); spi_w16( &spi, 0x8100 ); dat_cmd( &spi, &gpioa, false ); // Row set: [1:128] spi_w8( &spi, 0x2B ); dat_cmd( &spi, &gpioa, true ); spi_w16( &spi, 0x0100 ); ...
Rust
0
ip=(0, 1), bw_adjust=0.5, kernel='epanechnikov') # 添加更詳細的標題和軸標籤 plt.title('情感分數核密度估計圖\n(顯示情感分數的分布趨勢)', fontproperties=fm.FontProperties(fname=FONTS, size=14)) plt.xlabel('情感分數\n(0表示最負面,1表示最正面)', fontproperties=fm.FontProperties(fname=FONTS, size=12)) plt.ylabel('密度\n(情感分數在該處聚集的...
Python
1
self.current_block_versions .insert(ZERO_HASH, (Block::default(), String::default())); // Start a thread to accept new worker connections let mut workers_th = self.workers.clone(); let id_th = self.id.clone(); let mut stats_th = self.stratum_stats.clone(); let _listener_th = thread::spawn(move || { a...
Rust
0
cy) }; } } // Level 3 #[inline] pub fn cublas_sgemm(handle: *mut StructCublasContext, transa: CublasOperation, transb: CublasOperation, m: i32, n: i32, k: i32, alpha: *const f32, a: *const f32, lda: i32, b: *const f32, ldb: i32, beta: *const f32, c: *mut f32, ldc: i32) { #[cfg(not(feature = "disable_checks")...
Rust
0
TCD Signed Minor Loop Offset (Minor Loop Mapping and Offset Enabled)"] pub mod tcd5_nbytes_mloffyes; #[doc = "TCD Last Source Address Adjustment\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic:...
Rust
0
_CH2_CSR_PH_ADV_MSB: u32 = 7; pub const PWM_CH2_CSR_PH_ADV_LSB: u32 = 7; pub const PWM_CH2_CSR_PH_ADV_ACCESS: &'static [u8; 3usize] = b"SC\0"; pub const PWM_CH2_CSR_PH_RET_RESET: u32 = 0; pub const PWM_CH2_CSR_PH_RET_BITS: u32 = 64; pub const PWM_CH2_CSR_PH_RET_MSB: u32 = 6; pub const PWM_CH2_CSR_PH_RET_LSB: u32 = 6; p...
Rust
0
BackupFileName: LPCWSTR, dwReplaceFlags: DWORD, lpExclude: LPVOID, lpReserved: LPVOID, ); pub fn ReplacePartitionUnit( TargetPartition: PWSTR, SparePartition: PWSTR, Flags: ULONG, ) -> BOOL; pub fn RequestDeviceWakeup(hDevice: HANDLE) -> BOOL; pub fn RequestWakeupLatency(latency: LAT...
Rust
0
array_compatible: value & 0x00000020 > 0, block_texel_view_compatible: value & 0x00000080 > 0, extended_usage: value & 0x00000100 > 0, protected: value & 0x00000800 > 0, disjoint: value & 0x00000200 > 0, corner_sampled_nv: value & 0x00002000 > 0, s...
Rust
0
import pytest from llm_guard.input_scanners.ban_code import BanCode @pytest.mark.parametrize( "prompt,expected_valid,expected_score", [ ("Just a simple prompt", True, -1.0), # Simple prompt ( """Fix the following JS code: function sayHello() { return "Hello, World!"; } conso...
Python
1
tion.translate Form.setWindowTitle(_translate("Form", "Form")) self.groupBox.setTitle(_translate("Form", "原始数据")) item = self.tableWidget.verticalHeaderItem(0) item.setText(_translate("Form", "1")) item = self.tableWidget.verticalHeaderItem(1) item.setText(_translate("For...
Python
1
2] != "OK": msg = status.split(";") if len(msg) == 1: raise RuntimeError("Status message is malformed {}".format(status)) # pylint: disable=protected-access raise _impl._make_specific_exception(None, None, ";".join(msg[1:]), int(msg[0])) # pylint: enabl...
Python
1
import sys import time import RPi.GPIO as GPIO import signal from xbox360controller import Xbox360Controller baseStepPin = 20 baseStepDir = 12 baseStepEn = 19 step2pin = 23 step2dir = 22 step2en = 13 timeBetweenSteps = 0.0005 isFast = False fastMult = 5 baseIsRotating = False baseIsMoving = False xVal = 0.0 yVal = ...
Python
1
let should_create_new_subtree = tree_root.is_none(); let tree_root = tree_root.unwrap_or( // If `tree_root` is still None, then there is no known // subtree that contains `slot`. Thus, create a new // subtree rooted at the earliest known ancesto...
Rust
0
#!/usr/bin/env python3 def main(): f = open("../input/day_04_input") key_fields = {"byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"} eye_colours = {"amb", "blu", "brn", "gry", "grn", "hzl", "oth"} rules = { "byr": lambda x: int(x) >= 1920 and int(x) <= 2002, "iyr": lambda x: int(x) >= 2...
Python
1
h).count('%25') <= 0: _path = quote(_path) cache_key = key_prefix % _path else: cache_key = key_prefix return cache_key decorated_function.uncached = f decorated_function.cache_timeout = timeout ...
Python
1