text
string
label_name
string
labels
int64
import numpy as np import chainer def sample_continuous(dim, batchsize, distribution='normal', xp=np): if distribution == "normal": return xp.random.randn(batchsize, dim) \ .astype(xp.float32) elif distribution == "uniform": return xp.random.uniform(-1, 1, (batchsize, dim)) \ ...
Python
1
let mut proofs = vec![]; let depth = spec.deposit_contract_tree_depth as usize; let mut tree = MerkleTree::create(&[], depth); for (i, deposit_leaf) in deposit_root_leaves.iter().enumerate() { if tree.push_leaf(*deposit_leaf, depth).is_err() { return Err(String::from("Failed to push leaf...
Rust
0
wrap)] pub fn from_mt_seed_lossy(seed: [u32; 4]) -> Self { qed::const_assert_size_eq!([u32; 4], i128); let seed = unsafe { mem::transmute::<_, i128>(seed) }; // TODO: return a bignum instead of truncating. let seed_bytes = seed.to_ne_bytes(); let mut buf = [0_u8; mem::size_o...
Rust
0
emaining 25% width side_height = side_width * 9 // 16 for i, cctv in enumerate(self.cctv_windows): if i != self.selected_window: cctv.set_video_size(side_width, side_height) def current_window_image(self, index): """Retrieve the current frame from...
Python
1
'జ', '᥅', 'ώ', 'Ğ', '𞊘', '𐖌', '\u{e005b}', '⣯', '𝤼', 'ꀇ', 'ꀄ', '𐡹', 'ੀ', 'く', '𐨦', '\u{8d2}', '𐢜', 'ᐳ', '𐘔', '㈡', '勤', 'ㄕ', '𘠦', '𝁲', '㉢', '⇨', '𑜗', '𔐕', 'ᰇ', 'ⲳ', 'డ', '🦨', '︷', '𝜄', '𝕦', '🐁', '𝈏', 'ꖪ', '𐀦', '𞥖', '𝘋', '𝄍', 'F', '𐡅', '🞡', '🌍', '⇸', '𖫉', 'ὦ', '\u{17b5}', '🁏', ...
Rust
0
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # self.next = None class Solution: # @param root, a tree node # @return nothing def connect(self, root): head = None # Head node...
Python
1
#!/usr/bin/env python3 # This file is protected by Copyright. Please refer to the COPYRIGHT file # distributed with this source distribution. # # This file is part of OpenCPI <http://www.opencpi.org> # # OpenCPI is free software: you can redistribute it and/or modify it under the # terms of the GNU Lesser General Publi...
Python
1
emove_user <queue_id> <username> - удалить участника (создатель) 👆 Или используй кнопки для удобства!""" keyboard = InlineKeyboardMarkup(inline_keyboard=[ [InlineKeyboardButton(text="📋 Главное меню", callback_data="main_menu")], [InlineKeyboardButton(text="📝 Список очередей", callback_data=...
Python
1
n=int(input()) for i in range(1,n+1): for j in range(1,2*n): if j==n-1+i or j==n-i+1 or i==n: print("*",end=" ") else: print(" ",end=" ") print()
Python
1
dentifier.clone(), module_index)); assert_err!(IbcModule::bind_port(identifier.clone(), module_index), Error::<Test>::PortIdBinded); } #[test] fn bind_port_should_work() { new_test_ext().execute_with(|| { bind_port_func(); }); } fn conn_open_init_func() { let identifier = Blake2Hasher::hash("appia-connection...
Rust
0
import streamlit as st import requests from datetime import datetime, timedelta st.title("Simulador Delta Neutro: Short Perp + Long Futuro (Binance)") # --- Configurações iniciais --- PERP_SYMBOL = "BTCUSDT" FUTURE_SYMBOL = "BTCUSD_240628" # Ajuste conforme o contrato trimestral vigente # --- Funções auxiliares ---...
Python
1
= z_num.calculate_shifted_grand_product(&worker)?; assert!(z.size().is_power_of_two()); assert!(z.as_ref()[0] == E::Fr::one()); // println!("Z last = {}", z.as_ref().last().unwrap()); // assert!(z.as_ref().last().expect("must exist") == &E::Fr::one()); let z_commitment = comm...
Rust
0
from django.urls import path, include from rest_framework.routers import DefaultRouter from accounts.views import AccountViewSet from bills.views import BillsViewSet, CategoriesViewSet, PaidBillsListView from cards.views import BrandViewSet, CardViewSet from transactions.views import ( PaymentsViewSet, Transac...
Python
1
# normright = round(rinst[fix] * (10 ** intright), 5) # if (intleft != intright) or (normright != normright): # if abs(intleft-intright) > 1 or (normright != normright): # if round(linst[fix], 6) != round(rinst[fix], 6): # isclose(a, b, *, rel_t...
Python
1
nt(&self) -> MODE8_A { match self.bits { 0 => MODE8_A::DISABLED, 1 => MODE8_A::INPUT, 2 => MODE8_A::INPUTPULL, 3 => MODE8_A::INPUTPULLFILTER, 4 => MODE8_A::PUSHPULL, 5 => MODE8_A::PUSHPULLDRIVE, 6 => MODE8_A::WIREDOR, ...
Rust
0
overwritten by input from the integration via [`RawInput::pixels_per_point`]. /// For instance, when using `eframe` on web, the browsers native zoom level will always be used. pub fn set_pixels_per_point(&mut self, pixels_per_point: f32) { if pixels_per_point != self.pixels_per_point() { se...
Rust
0
#[doc = "Port mapping register, P4.6 and P4.7"] pub mod p4map67; #[doc = "P5MAP01 register accessor: an alias for `Reg<P5MAP01_SPEC>`"] pub type P5MAP01 = crate::Reg<p5map01::P5MAP01_SPEC>; #[doc = "Port mapping register, P5.0 and P5.1"] pub mod p5map01; #[doc = "P5MAP23 register accessor: an alias for `Reg<P5MAP23_SP...
Rust
0
"name": "过去的老照片" }, { "name": "远古的刀" }, { "name": "重工组长于彦舒" }, { "name": "長滒" }, { "name": "陇上优品-陶磊" }, { "name": "降夭除魔齐天大圣" }, { "name": "马周扬律师" ...
Python
1
lib"] #![feature(generic_arg_infer)] struct Foo<const N: usize>; struct Bar<T, const N: usize>(T); fn arr_fn() -> [u8; _] { //~^ ERROR the placeholder `_` is not allowed within types on item signatures for return types [0; 3] } fn ty_fn() -> Bar<i32, _> { //~^ ERROR the placeholder `_` is not allowed wit...
Rust
0
import os import sys PROJECT_ROOT = os.path.abspath(os.path.join( os.path.dirname(__file__), os.pardir) ) sys.path.append(PROJECT_ROOT) from RFEM.initModel import Model from RFEM.enums import * from RFEM.dataTypes import inf from RFEM.TypesForSpecialObjects.surfaceReleaseType import SurfaceReleaseType if Mode...
Python
1
changes to be made self.p_limited_w = self.p_desired_w self.q_limited_qp_var = self.q_desired_var else: # Define watt-var curve qp_curve_p = [-self.der_file.NP_P_MAX_CHARGE, self.exec_delay.qp_curve_p3_load_exec *...
Python
1
{ self.view_filters() } { self.view_affinities_table() } </> } } } impl AffinitiesTable { fn view_filters(&self) -> Html { html! { <div class="devand-affinities-filters pure-form pure-form-stacked pure-g"> { self.view_lang_select() } ...
Rust
0
struct sctp_keyhead { pub lh_first: *mut sctp_shared_key, } #[repr(C)] #[derive(Copy, Clone)] pub struct sctp_shared_key { pub next: C2RustUnnamed_31, pub key: *mut sctp_key_t, pub refcount: uint32_t, pub keyid: uint16_t, pub deactivated: uint8_t, } #[repr(C)] #[derive(Copy, Clone)] pub struc...
Rust
0
l(inv); } } <gh_stars>0 use crate::{policy, Inbound}; use linkerd_app_core::{ identity, io, proxy::http, svc::{self, ExtractParam, InsertParam, Param}, tls, transport::{self, metrics::SensorIo, ClientAddr, OrigDstAddr, Remote, ServerAddr}, transport_header::{self, NewTransportHeaderServer, S...
Rust
0
tring, pub externs: Vec<Node<ExternBlock>>, pub functions: Vec<Node<Function>>, pub operators: Vec<Operator>, pub traits: Vec<Node<Trait>>, pub impls: Vec<Node<Impl>>, pub structs: Vec<Node<Struct>>, pub uses: Vec<Node<Use>>, // TODO: These // pub constants: Vec<Node...
Rust
0
83, 165, 36, 232, 184, 140, 205, 195, 252, 166, 85, 59, 86, 3, 226, 211, 67, 179, 29, 238, 181, 102, 142, 58, 63, 57, 89, 174, 138, ], [ 210, 159, 80, 16, 181, 39, 221, 204, 224, 144, 145, 79, 54, 231, 8, 140, 142, 216, 93, 190, 183, 116, 174, 63, 33, 242, 177, 118, ...
Rust
0
l private::SealedChangeLevelKey for InternalIvk { fn extended_pubkey(&self) -> &ExtendedPubKey { &self.0 } fn from_extended_pubkey(key: ExtendedPubKey) -> Self { InternalIvk(key) } } impl IncomingViewingKey for InternalIvk {} /// Internal ovk used for autoshielding. pub struct Interna...
Rust
0
rive(Debug, StructOpt)] #[structopt(name = "juno", about = "A JavaScript Compiler", setting = AppSettings::DeriveDisplayOrder)] struct Opt { /// Disable pretty printing. #[structopt(long)] no_pretty: bool, /// Select what to emit. #[structopt(flatten)] gen: Gen, /// Input file to parse. ...
Rust
0
""" Module for managing the spawning of asteroids in the game. Contains the AsteroidField class, which periodically spawns Asteroid objects at random edges of the screen with random movement vectors. """ import pygame import random from .asteroid import Asteroid from constants import (ASTEROID_MAX_RADIUS, ...
Python
1
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
Python
1
# SPDX-FileCopyrightText: 2015 Sebastian Wagner # # SPDX-License-Identifier: AGPL-3.0-or-later # -*- coding: utf-8 -*- import unittest import intelmq.lib.test as test from intelmq.bots.parsers.danger_rulez.parser import BruteForceBlockerParserBot RAW = ("IyBJUAkJCSMgTGFzdCBSZXBvcnRlZAkJCUNvdW50CUlECjIwMy4wLjExMy40O...
Python
1
concat!( "Offset of field: ", stringify!(TPMU_SENSITIVE_COMPOSITE), "::", stringify!(ecc) ) ); assert_eq!( unsafe { &(*(::std::ptr::null::<TPMU_SENSITIVE_COMPOSITE>())).bits as *const _ as usize }, 0usize, concat!( "O...
Rust
0
.lower(): print_(f"{sub_title} Skipping Quest") else: completed_task(token, stask) if 'invite' in sub_title.lower(): print_(f"{...
Python
1
'''Write a program that takes an integer and prints out all ways to multiply smaller integers that equal the original number, without repeating sets of factors. In other words, if your output contains 4 * 3, you should not print out 3 * 4 again as that would be a repeating set. Note that this is not asking for prime fa...
Python
1
ht, mode='nearest') xnc = ndimage.filters.convolve(normal_xn, weight, mode='nearest') ypc = ndimage.filters.convolve(normal_yp, weight, mode='nearest') ync = ndimage.filters.convolve(normal_yn, weight, mode='nearest') zpc = ndimage.filters.convolve(normal_zp, weight, mode='nearest') znc = ndimage....
Python
1
eされるので踏襲する if not highres_fix: width, height = init_image.size width = width - width % 32 height = height - height % 32 if width != init_image.size[0] or height != init_image.size[1]: ...
Python
1
import os, sys, shutil, sys def other_suppress_out(): """ Redirect stdout to null device to suppress print statements. Parameters: None Returns: None """ sys.stdout = open(os.devnull, 'w') def other_restore_out(): """ Restore the standard output. Parameters: None Returns: Non...
Python
1
"""Test legacy custom labware in an end-to-end environment. Legacy ProtocolContext objects are prohibitively difficult to instansiate and mock in an isolated unit test environment. """ import pytest import textwrap from decoy import matchers from pathlib import Path from typing import List from opentrons_shared_data ...
Python
1
# Exportar datos de energía de olas por región for region, df in wave_energy_dict.items(): df.to_csv(f'data/processed/wave_energy_{region.replace(" ", "_").lower()}.csv', index=False) sio.savemat(f'data/processed/wave_energy_{region.replace(" ", "_").lower()}.mat', { 'energy': df['energy'].values, ...
Python
1
Ok(full_host) } } /// Name /// /// ```rust /// use oapth::Config; /// let c = Config::with_url("postgres://user_name:password@endpoint/database_name"); /// assert_eq!(c.name().unwrap(), "database_name"); /// ``` #[inline] pub fn name(&self) -> crate::Result<&str> { let opt = || { ...
Rust
0
print('Совместное использование структур данных') # Делала с нейронкой, сложно print('ЗАДАНИЕ 1') list_students = [ ("Аня", "Математика", 90), ("Аня", "Физика", 85), ("Аня", "Русский язык", 80), ("Диана", "Математика", 92), ("Диана", "Физика", 89), ("Диана", "Русский язык", 95), ("Ксюша", "Математика", 70)...
Python
1
std::string::String::new(); io::stdin() .read_to_string(&mut directions) .expect("Could not read stdin!"); for c in directions.chars() { match c { 'L' => direction = direction * Complex::new(0, 1), 'R' => direction = direction * Complex::new(0, -1), '0...
Rust
0
, 0.0), ..Default::default() }, ..Default::default() }) .spawn(Camera2dComponents { transform: Transform::from_scale(Vec3::new(0.25, 0.25, 1.0)), ..Default::default() }); // let texture_handle = asset_server.load("gabe-idle-run...
Rust
0
(msg).encode_wide_nul_term(); MessageBoxW(ptr::null_mut(), err_str.as_ptr(), title.as_ptr(), MB_OK); panic!("Unwrapped empty option"); }, } } } fn msg_box_title() -> &'static Vec<u16> { unsafe { MSG_BOX_TITLE_INIT.call_once(|| { MSG_BOX_TI...
Rust
0
, Error> { for event in events.iter() { /* let stmnt = format!( "INSERT INTO secretary (cal, name, desc, date) VALUES ({}, {}, {}, {})", event.get_cal(), event.get_name(), event.get_desc(), event.get_date() ...
Rust
0
omPath(format!("{}/{}.h", lib_name, entry_name)); bindings::write_to_out_dir(header, out_path); } #[cfg(not(feature = "buildtime_bindgen"))] { use std::fs; fs::copy(format!("{}/bindgen_bundled_version.rs", lib_name), out_path) .expect("Could no...
Rust
0
import psutil import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation # 创建一个新的图形和一个可视化轴 fig, ax = plt.subplots() ax.set_xlim(0, 100) # 设置x轴范围 ax.set_ylim(0, 100) # 设置y轴范围 line, = ax.plot([], []) # 绘制空曲线 def init(): line.set_data([], []) # 初始化曲线数据 return line, def update(frame): ...
Python
1
f_10, proxy_server: f_11, proxy_port: f_12, }; Ok(ret) } pub fn write_to_out_protocol(&self, o_prot: &mut TOutputProtocol) -> thrift::Result<()> { let struct_ident = TStructIdentifier::new("NetworkSettings"); o_prot.write_struct_begin(&struct_ident)?; if let Some(fld_var) = self.is_...
Rust
0
DOMAIN = 'hassbox_notify' PACKAGE_NAME = "custom_components.hassbox_notify" VERSION = "0.0.1" VERSION_STORAGE = 1
Python
1
lignment of field: " , stringify ! ( rd_kafka_group_list ) , "::" , stringify ! ( groups ) )); assert_eq! (unsafe { & ( * ( 0 as * const rd_kafka_group_list ) ) . group_cnt as * const _ as usize } , 8usize , concat ! ( "Alignment of field: " , stringif...
Rust
0
import pytest from datetime import datetime from django.utils import timezone @pytest.mark.django_db class TestWeatherRequestModel: """Test WeatherRequestModel""" NOW = timezone.now() def test_representer_model(self, fixture_weather_request_model): weather_request_model = fixture_weather_request...
Python
1
# Copyright (c) 2016 b<>com # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, so...
Python
1
bls12381::{BLS12381PrivateKey, BLS12381PublicKey, BLS12381Signature}, ed25519::{Ed25519PrivateKey, Ed25519PublicKey, Ed25519Signature}, traits::*, unit_tests::uniform_keypair_strategy, }; use crypto::hash::HashValue; use core::convert::TryFrom; use crypto_derive::SilentDebug; use failure::prelude::*; ...
Rust
0
}; block_x_offset = block_width.wrapping_sub(x_incr); x_incr = opj_uint_min(x_incr, x1.wrapping_sub(x)); src_block = *(*sa).data_blocks.offset( block_y .wrapping_mul((*sa).block_count_hor) .wrapping_add(block_x) as isize, ); if is_read_op != 0 { if src...
Rust
0
me'] = result # ~ if 'text' in data['feeds'][key] and data['feeds'][key]['text'] is not None and \ # ~ 'ai_result' not in data['feeds'][key]: # ~ if len(data['feeds'][key]['text']) > cls.min_text_for_ai: # ~ result = classifier(data['feeds'][key]['text']) ...
Python
1
lt<(TcpStream, TcpStream), Box<dyn std::error::Error>> { let listener = TcpListener::bind("localhost:0").await?; let addr = listener.local_addr()?; let s1 = TcpStream::connect(addr).await?; let (s2, _) = listener.accept().await?; Ok((s1, s2)) } } struct Color { red: u8, ...
Rust
0
#[inline] pub fn gpio_gpe2_pull_ctrl(&mut self) -> _GPIO_GPE2_PULL_CTRLW { _GPIO_GPE2_PULL_CTRLW { w: self } } #[doc = "Bits 2:3"] #[inline] pub fn gpio_gpe1_pull_ctrl(&mut self) -> _GPIO_GPE1_PULL_CTRLW { _GPIO_GPE1_PULL_CTRLW { w: self } } #[doc = "Bits 0:1"] #[inl...
Rust
0
from flask_app.config.mysqlconnection import connectToMySQL from flask import flash DATABASE = 'esquema_tacos_restaurante_complemento' class Taco: def __init__(self, data): self.id = data['id'] self.tortilla = data['tortilla'] self.guiso = data['guiso'] self.salsa = data['salsa'] ...
Python
1
m::CocoaSpecific; use super::Native; use crate::tags::Desktop; #[test] fn it_works() { let _button_a = <Native as Desktop>::Button::new(MockButtonOutlet {}); let _button_b = <Native as HasButton>::Button::new(MockButtonOutlet {}); //let button_c = <Native as CocoaSpecific>::Butt...
Rust
0
alpha = 0.7 # length normalization coefficient for batch_idx in range(batch_size): # iter over seqeuence for t in range(max_len): cand_pool = [] # pool keeps all candidates, max size: beam_size * beam_size # iter over history for beam_idx in range(beam_size): beam = dec_words[batch_idx][beam_...
Python
1
ust accessing this serial port's registers. unsafe { // Before doing anything, disable interrupts for this serial port. serial.interrupt_enable.write(0x00); // Enter DLAB mode so we can set the baud rate divisor serial.line_control.write(0x80); // Set baud rate to 38400, which requires a divisor value...
Rust
0
from django.urls import path from rest_framework.routers import DefaultRouter from article.views import ( ArticleCategoryView, ArticleCommentView, ArticleLikeView, ArticleView, HomePageView, ) router = DefaultRouter() # register modelViewSets for articles router.register("categories", ArticleCate...
Python
1
fn\x9e\xfd?\xfdt\ \xc0\x98 \xe7\xa7\xb7\xff\x00^\xb8*J\xf7w},\ \xf54\xe4\x95\xf6\xfc\x87d\x03\xb7\x80q\x90=\xa9i\ \x9dYNz\x8e\x07\xe0O\xf5\xf5\xfc;\x86\xcb/\x96\ 3\x8c\xf4\xef\x8e\xb9\xf65\xc7+\xb94\x9b\xf3\xd6\xda\ \xf5:\xa1\xcb\xcb}7\xb2\xd3\xfe\x01\x5c\xc8\xcb\xc1s\ \xc6G'\x93\xd7\x04\xf1\xd3\xa7\xe1U\xd9\xd8\xe7\x9...
Python
1
#!/usr/bin/python # # \file 2_build.py # \brief Run all build processes # \date 2009-02-18 09:22GMT # \author Jan Boon (Kaetemi) # Python port of game data build pipeline. # Run all build processes # # NeL - MMORPG Framework <https://wiki.ryzom.dev/> # Copyright (C) 2009-2014 by authors # # This program is free soft...
Python
1
27 => f.write_str("brainpoolP224r1"), 28 => f.write_str("brainpoolP256r1"), 29 => f.write_str("brainpoolP384r1"), 30 => f.write_str("brainpoolP512r1"), 31 => f.write_str("Curve25519"), 32 => f.write_str("Curve448"), n => f.debug_tuple("IkeTransf...
Rust
0
from graph import * from collections import deque class BFSResults: def __init__(self): self.level = dict() self.parent = dict() def bfs(g, s): r = BFSResults() actives = deque() actives.append(s) r.parent[s] = None r.level[s] = 0 while len(actives): v...
Python
1
from colorama import Fore from .field import Field class Email(Field): def __init__(self, value): super().__init__(value) self.validate_email(value) def validate_email(self, email): if "@" not in email: raise ValueError(Fore.CYAN + f"Invalid email address: {email}")
Python
1
pr, Ident, Token, Type, Visibility}; /// Parses the following syntax, which aligns with the input of the real /// `lazy_static` crate. /// /// lazy_static! { /// $VISIBILITY static ref $NAME: $TYPE = $EXPR; /// } /// /// For example: /// /// lazy_static! { /// static ref USERNAME: Regex = R...
Rust
0
from __future__ import annotations import sys if sys.version_info < (3, 8): # noqa: UP036 msg = "pybind11 does not support Python < 3.8. v2.13 was the last release supporting Python 3.7." raise ImportError(msg) from ._version import __version__, version_info from .commands import get_cmake_dir, get_include...
Python
1
ev = qml.device("default.qubit", wires=2) @qml.qnode(dev) def circuit(x): qml.RX(x, wires=0) qml.Hadamard(wires=1) qml.CNOT(wires=[0, 1]) qml.breakpoint() return qml.expval(qml.Z(0)) circuit(1.23) Running the above python scrip...
Python
1
one, Serialize, Deserialize, PartialEq)] pub struct ErrorString { pub name: String, pub string: String, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] pub struct ErrorStringMapping { pub errors: Vec<ErrorString>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] ...
Rust
0
# 다양한 for문의 사용 a = [(1, 2), (3, 4), (5, 6)] for (first, last) in a : print(first + last)
Python
1
import rclpy from rclpy.node import Node from rclpy.action import ActionServer from arduinobot_msgs.action import Fibonacci import time class SimpleActionServer(Node): def __init__(self): super().__init__("simple_action_server") self.get_logger().info("Starting the Server") self.action_ser...
Python
1
import os.path as osp import subprocess as subp HERE = osp.dirname(osp.abspath(__file__)) test_interval = "chr9:4000000-6000000" empty_interval = "chr10:4000000-6000000" test_itv = test_interval.replace(':', '_').replace('-', '_') def test_cli_plot(data_dir, tmp_dir): cmd = [ "python", "-m", "coolbox.cli...
Python
1
time.now().strftime('%Y%m%d_%H%M%S')}.csv", mime="text/csv" ) with col2: # Excel export (simplified) if summary_data: output = io.BytesIO() with pd...
Python
1
mut rng = StdRng::seed_from_u64(42); for _ in 0..20 { let n = rng.gen_range(2..20); let a = generate_concave_sequence(&mut rng, n); let b = generate_concave_sequence(&mut rng, n); let result = concave_maxplus_convolution(&a, &b); let expected = maxplus...
Rust
0
:div_assign, kind: simple, item: $($tts)* } }; (($($rhs:tt)*) $($tts:tt)*) => { newtype_wrap_bin_op_assign! { trait: (::std::ops::DivAssign)::div_assign, kind: rhs($($rhs)*), item: $($tts)* } }; } // ntbop Mul, mul #[macro_export] macro_rules! NewtypeMul { ((*) $($tts:tt)*) => { Ne...
Rust
0
= BasicFeature::Blwf.mask(); for i in ra_indices { glyphs[i].add_mask(mask); glyphs[i + 1].add_mask(mask); } } // Add PREF mask to pre-base-reordering "Ra" sequences in Malayalam/Telugu if shaping_data.script == Script::Malayalam || shaping_data.script == Script::Te...
Rust
0
olders[rdf_type], ) plot_rdf(goo_data, rdf_type, rdf_name, axes[i]) add_figure_text(fig, rdf_name, results, average_data) save_figure(fig, rdf_name, analysis_origin) def add_figure_text(fig, rdf_name, results, average_data): if rdf_name in results and "Diffusion Constant" ...
Python
1
fn is_pangram(sentence: &str) -> bool { let mut chars = sentence .to_lowercase() .chars() .filter(|&c| c >= 'a' && c <= 'z') .collect::<Vec<_>>(); chars.sort(); chars.dedup(); chars.len() == ('z' as usize - 'a' as usize + 1) } <filename>frame/lending/src/mocks/oracle.r...
Rust
0
} debug_assert!(rtn >= sync.cursor && rtn < sync.cursor + bytes); if tmp > sync.sentinel { //debug!("tmp={:?} > sync.sentinel={:?}", tmp, sync.sentinel); unsafe { Address::zero() } } else { //debug!("tmp={:?} <= sync.sentinel={:?}", tmp, sync.sentinel); ...
Rust
0
from collections import namedtuple RESPONSES = namedtuple( 'Responses', [ "STRATEGY_INVALID", "SIGNAL_GENERATION_INPROGRESS", "NO_SUCH_PIPELINE", "JOB_NOT_FOUND", "FINISHED", "IN_QUEUE", "WAITING", "FAILED", ] ) ReturnCodes = RESPONSES( ...
Python
1
.", CStr::from_ptr(ident).display()); } sfnt_read_table_directory(sfont, offset) } else { sfnt_read_table_directory(sfont, (*sfont).offset) }; if error != 0 { sfnt_close(sfont); panic!( "Reading SFND table dir failed for font-file=\"{}\"... Not a TrueType ...
Rust
0
from fastapi import status from core.exception.custom_exception import BusinessException class StoryException(BusinessException): pass class DuplicatePageNumberException(StoryException): def __init__(self): super().__init__( code="STORY001", status_code=status.HTTP_409_CONFL...
Python
1
T License. use anyhow::Result; use process_control::{ChildExt, Output, Timeout}; use std::path::Path; use std::process::Command; use std::time::Duration; use std::{collections::HashMap, process::Stdio}; pub async fn run_cmd<S: ::std::hash::BuildHasher>( program: &Path, argv: Vec<String>, env: &HashMap<Str...
Rust
0
fn from_natural(int: i64) -> Self { Self(int.saturating_mul(DIV)) } /// Return the accuracy of the type. Given that this function returns the value `X`, it means /// that an instance composed of `X` parts (`Fixed64::from_parts(X)`) is equal to `1`. pub fn accuracy() -> i64 { DIV } /// creates self from a r...
Rust
0
# SPDX-FileCopyrightText: 2018-2024 Greenbone AG # # SPDX-License-Identifier: GPL-3.0-or-later # class GmpGetTargetsTestMixin: def test_get_targets(self): self.gmp.get_targets() self.connection.send.has_been_called_with(b"<get_targets/>") def test_get_targets_with_filter_string(self): ...
Python
1
g_spk_idx = np.where(spk_hist_buffer == 1) # Compute the local cost s_sig[sig_spk_idx] = ( self.cost_diagonal[sig_spk_idx] + self.a_in_data[sig_spk_idx] ) return s_sig def _gen_wta_spks(self): # indices of neurons to be integrated: intg_idx = np.where(se...
Python
1
rays, N_samples_ = weights.shape weights = weights + eps # prevent division by zero (don't do inplace op!) pdf = weights / torch.sum(weights, -1, keepdim=True) # (N_rays, N_samples_) cdf = torch.cumsum(pdf, -1) # (N_rays, N_samples), cumulative distribution function cdf = torch.cat([torc...
Python
1
# /// script # dependencies = ["numpy", "matplotlib", "pillow"] # /// import numpy as np import matplotlib.pyplot as plt from PIL import Image def median_filter_vectorized(image, kernel_size=3): """Vectorized median filter using numpy operations""" pad = kernel_size // 2 padded = np.pad(image, pad, mode='...
Python
1
per block (8 bit/px). Variable sized pallet. 8 bit integer RGBA. /// [0, 255] converted to/from float [0, 1] in shader. /// /// Also known as BPTC (unorm). /// /// [`Features::TEXTURE_COMPRESSION_BC`] must be enabled to use this texture format. Bc7RgbaUnorm = 50, /// 4x4 block compressed te...
Rust
0
tBlock { // header, // nonce: 1928712, // short_ids: Vec::from([8219u64; 7]), // prefilled_txns: txs, // }; // let serial = msg.to_bytes().expect("Serializing into vec shouldn't fail"); // assert_eq!(serial.len(), msg.serialized_size()); // ...
Rust
0
ors_parsed = comparators_parsed.join(" "); if comparators_parsed.len() == 0 { let comp = Comparator::empty(); return Ok(Some(vec![comp])); } // TODO: this split should yield an array with one empty string inside // ...
Rust
0
&Patch, restore: bool) -> Result<()> { assert_eq!(patch.original.len(), patch.replacement.len()); let patch_len = patch.original.len(); let call_to_nop = &mut map[patch.offset..patch.offset + patch_len]; ensure!( call_to_nop.len() == patch_len, "EXE is too short - are you sure this is ...
Rust
0
# %% # code by Tae Hwan Jung @graykode import numpy as np import torch import torch.nn as nn import torch.optim as optim def make_batch(): input_batch = [] target_batch = [] for sen in sentences: word = sen.split() # space tokenizer input = [word_dict[n] for n in word[:-1]] # create (1~n...
Python
1
sing Ascii. pub struct AsciiMode; pub struct UTF8Mode; /// This trait will be implemented by readers pub trait ReadMode { fn set_value(&mut self, value: &str); } /// Implement Ascii read mode impl ReadMode for Record<AsciiMode> { /// Sets the record value (which is equivalent to setting all fields). /// ...
Rust
0
)).expect("Could not open/create storage"); // Use the save batch function to save the entire array storage .save_batch(mayors) .expect("Could not save records in batch"); // Query for all republicans. // We can use rust's standard filter function to query by record properties list...
Rust
0
modality = 'km' graph = 'nturgb+d' work_dir = f'./work_dirs/ntu60_xview/km' model = dict( type='RecognizerGCN', backbone=dict( type='ProtoGCN', num_prototype=100, tcn_ms_cfg=[(3, 1), (3, 2), (3, 3), (3, 4), ('max', 3), '1x1'], graph_cfg=dict(layout=graph, mode='random', num_filt...
Python
1
import torch from basicsr.archs.basicvsr_arch import BasicVSR, ConvResidualBlocks, IconVSR def test_basicvsr(): """Test arch: BasicVSR.""" # model init and forward net = BasicVSR(num_feat=12, num_block=2, spynet_path=None).cuda() img = torch.rand((1, 2, 3, 64, 64), dtype=torch.float32).cuda() ou...
Python
1
s.append(profanity_detector.checkLyrics(lyrics)) print('Combining results and sorting...') combined_dict = combineProfanityReports(reports) sorted_items = sorted(combined_dict.items(), key=lambda x: x[1]['total'], reverse=True) # Sort by total found unique_count = len(sorted_items) print(f'Found {unique_count} uni...
Python
1