text
string
label_name
string
labels
int64
"""Add block schema indexes Revision ID: d335ad57d5ba Revises: 61c76ee09e02 Create Date: 2022-06-17 20:44:09.726661 """ from alembic import op # revision identifiers, used by Alembic. revision = "d335ad57d5ba" down_revision = "61c76ee09e02" branch_labels = None depends_on = None def upgrade(): # ### commands a...
Python
1
lass]). latex_documents = [ (master_doc, 'rfc5424sysloghandler.tex', 'rfc5424 syslog handler Documentation', 'Joris Beckers', 'manual'), ] # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors,...
Python
1
import random class MathQuiz: def __init__(self): self.operators = ['+', '*'] self.min_number = 1 self.max_number = 10 def create_question(self): operator = random.choice(self.operators) num1 = random.randint(self.min_number, self.max_number) num2 = random.randi...
Python
1
from .post import register_post_handlers def register_handlers(dp): register_post_handlers(dp)
Python
1
X export. It can be " "useful when exporting a model supported in transformers but not in optimum, otherwise it is not " "recommended." ), ) args = parser.parse_args() if args.export_with_transformers or not is_optimum_available(): export_with_transformers(args) ...
Python
1
read config file: {}", e); return Ok(None); } } let res = if path.extension().map_or(false, |e| e == "json") { serde_json::from_str(&string) .with_context(|| format!("Failed to load json config file from {}", path.display()))? } else { toml::from_str(&string...
Rust
0
cities = [] # empty list cities = list() # also empty list cities = ['Portland', 'Pittsburgh', 'Peoria'] print(f"cities: {cities}\n") cities.append('Miami') cities.append('Montgomery') print("after cities.append('Miami')") print("after cities.append('Montgomery')") print(f"cities: {cities}\n") cities.insert(0, 'Bost...
Python
1
print("Hai, Git World!")
Python
1
persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, /...
Rust
0
} #[test] fn test_i16() { validate_variant!(i16, 1337i16, VT_I2); } #[test] fn test_f32() { validate_variant!(f32, 1337.9f32, VT_R4); } #[test] fn test_f64() { validate_variant!(f64, 1337.9f64, VT_R8); } #[test] fn test_bool_t() { valid...
Rust
0
self), self) for fname in fnames: old_value = next(iter(old_value), old_value)[fname] # determine the new value new_value = field.convert_to_record( field.convert_to_cache(vals[field.name], self), self) # drop if t...
Python
1
>> 25) & 0x03) as u8) } #[doc = "Bits 27:28 - I2S APB2 clock source selection"] #[inline(always)] pub fn i2s2src(&self) -> I2S2SRC_R { I2S2SRC_R::new(((self.bits >> 27) & 0x03) as u8) } } impl W { #[doc = "Bits 0:4 - PLLI2S division factor for SAIs clock"] #[inline(always)] pub ...
Rust
0
" }); let recv = wire2.wait(Some(Duration::from_millis(100))).unwrap(); assert!(recv.get_i32(CODE).unwrap() == 0); // send let _ = wire1.send(msg!{ CHAN: "aaa", "hello": "world" }); // recv let recv = wire2.wait(Some(Duration::from_millis(100))).unwrap(); assert!...
Rust
0
import os import json from PIL import Image import numpy as np import tensorflow as tf import streamlit as st import time working_dir = os.path.dirname(os.path.abspath(__file__)) model_path = f"trained_model/plant_disease_prediction_model.h5" # Load the pre-trained model model = tf.keras.models.load_model(model_path)...
Python
1
tle=f'{dataset}: Predicted ' f'Marginals') fig.savefig(reports_path + figure_name, bbox_inches='tight', dpi=300) # Plot loss figure_name = save_file_name + '_loss.png' num_iters_per_epoch = int((num_train) / BATCH_SIZE) train_epochs = np.arange(1, ...
Python
1
import os import tkinter as tk from tkinter import filedialog, messagebox from installer import create_installer_batch, auto_install_exes, run_with_admin_privileges from backup_and_logging import copy_exe_files_with_backup, view_logs def select_folder(title="Select Folder"): """ نمایش پنجره انتخاب پوشه """ fol...
Python
1
is is ignored and the group keys are used instead. (default: content) Yields: dict: the number of counted items Examples: >>> stream = ({'x': x} for x in range(5)) >>> next(pipe(stream)) == {'count': 5} True >>> stream = [{'word': 'two'}, {'word': 'one'}, {'...
Python
1
_UPDATE, } pub type POINTER_COLOR_UPDATE = _POINTER_COLOR_UPDATE; #[repr(C)]#[derive(Copy, Clone)] pub struct _POINTER_COLOR_UPDATE { pub cacheIndex: UINT32, pub xPos: UINT32, pub yPos: UINT32, pub width: UINT32, pub height: UINT32, pub lengthAndMask: UINT32, pub lengthXorMask: UINT32, ...
Rust
0
//! Braintree's main site. Remember to also change `Environment::Sandbox` to //! `Environment::Production` when you make the switch. //! //! # Stability Note //! //! This crate is very much in a pre-alpha state, and as such the design of its //! API is subject to change. You have been forewarned! extern crate elementt...
Rust
0
print("Niepoprawny format!") continue if minuta > 59 or minuta < 1: print("Niepoprawna minuta!") continue try: sekunda = int(input("Podaj sekundę:")) except: print("Niepoprawny format!") continue if sekunda >...
Python
1
// use super::*; // #[test] // fn empty() { // let mut interner = DefaultStringInterner::new(); // interner.extend(Vec::<&str>::new()); // assert_eq!(interner, DefaultStringInterner::new(),); // } // #[test] // fn simple() { // assert_eq!( // { // ...
Rust
0
#!/usr/bin/env python3 """Script para debug do problema de duplicatas.""" import re from pathlib import Path def _esta_em_subpasta(caminho: str) -> bool: """Verifica se arquivo está em subpasta com padrão XX_pasta_Y.""" padrao_subpasta = r'\\(\d+)_pasta_(\d+)\\' return re.search(padrao_subpasta, caminho) ...
Python
1
C_ILInstr, arg: INT32); pub fn set_arg_16(instr: C_ILInstr, arg: INT16); pub fn set_arg_8(instr: C_ILInstr, arg: INT8); pub fn set_arg_instr(instr: C_ILInstr, arg: C_ILInstr); pub fn get_arg_8(instr: C_ILInstr) -> INT8; pub fn get_arg_32(instr: C_ILInstr) -> INT32; pub fn get_next(instr: C...
Rust
0
ps[np.isnan(overlaps)] = 0 score = np.array(score) score[np.isnan(score)] = 0 precision = np.zeros(len(thresholds)) recall = np.zeros(len(thresholds)) for i, th in enumerate(thresholds): if th == - np.inf: idx = score > 0 else: idx = score >= th if np....
Python
1
2, 3 => CAPTURE_MODE_A::CAPTURE_MODE_3, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `CAPTURE_MODE_0`"] #[inline(always)] pub fn is_capture_mode_0(&self) -> bool { *self == CAPTURE_MODE_A::CAPTURE_MODE_0 } #[doc = "Checks if the va...
Rust
0
5510`. pub const MAX_COMPRESSED_SIZE: usize = MAX_BLOCK_SIZE - WRAPPER_SIZE; /// A bgzip block, that can contain compressed, uncompressed data, or both. /// /// You can extend uncompressed data using [extend_contents](#method.extend_contents), and /// and then compress the block using [compress](#method.compress). #[d...
Rust
0
_FAULTY: SectorTermination = 3; pub const CRON_QUEUE_HAMT_BITWIDTH: u32 = 6; pub const CRON_QUEUE_AMT_BITWIDTH: u32 = 6; pub const PROOF_VALIDATION_BATCH_AMT_BITWIDTH: u32 = 4; #[derive(Serialize_tuple, Deserialize_tuple, Clone)] pub struct CreateMinerParams { pub owner: Address, pub worker: Address, pub ...
Rust
0
import tkinter as tk from tkinter import ttk, messagebox import time import threading import pyautogui from PIL import Image, ImageOps import pytesseract import mss import platform import re import os import json import sys # --- Глобальные переменные --- current_runner = None stop_event = threading.Event() is_running...
Python
1
e(status_sid).unwrap(); log::trace!("|status: Message: {:?}", msg); match FromPrimitive::from_usize(msg.body.id()) { Some(StatusOpcode::BattStats) => msg_scalar_unpack!(msg, lo, hi, _, _, { stats = [lo, hi].into(); battstats_tv.clear_str(); // ...
Rust
0
#!/usr/bin/python3 """This module defines a JSON-to-object function""" import json def from_json_string(my_str): """Returns the Python object representation of a JSON string""" return json.loads(my_str)
Python
1
from securityheaders.checkers import InfoCollector, FindingType, Finding, FindingSeverity from securityheaders.models import ModelFactory class InfoDirectiveCollector(InfoCollector): def check(self, headers, opt_options=dict()): headernames = ModelFactory().getheadernames() findings = [] f...
Python
1
# Copyright (c) OpenMMLab. All rights reserved. from typing import Union import mmcv import numpy as np import torch from torch import Tensor def imrenormalize(img: Union[Tensor, np.ndarray], img_norm_cfg: dict, new_img_norm_cfg: dict) -> Union[Tensor, np.ndarray]: """Re-normalize the image. ...
Python
1
import numpy as np import pytest from sklearn.utils.estimator_checks import check_estimator from chemotools.derivative import NorrisWilliams # Test compliance with scikit-learn def test_compliance_norris_williams_der_1(): # Arrange transformer = NorrisWilliams() # Act & Assert check_estimator(transfo...
Python
1
buffer pub partial_pos_out: usize, // How much output to the user in total (<= rb) // For ReadHuffmanCode pub symbol: u32, pub repeat: u32, pub space: u32, pub table: [HuffmanCode; 32], // List of of symbol chains. pub symbol_lists_index: usize, // AllocU16::AllocatedMemory, // Storage from symbol_l...
Rust
0
3.angle_from_equator().is_zero()); } #[test] fn good_latitude_max() { let l: Latitude<AccurateDegree> = 90.try_into().unwrap(); assert_eq!(Latitude::from(North), l); } #[test] #[should_panic(expected = "ObtuseAngle")] fn bad_latitude_max() { let _l = Latitude::<Accu...
Rust
0
import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('reduce_benchmark.csv') for bsize in sorted(df['BlockSize'].unique()): df_b = df[df['BlockSize'] == bsize] plt.plot(df_b['InputSize'], df_b['KernelTime(ms)'], marker='o', label=f'BlockSize={bsize}') plt.xscale('log', base=2) plt.yscale('log...
Python
1
interrupt_request6 = (*self.internal.get()).interrupt_request6.read(); let interrupt_request7 = (*self.internal.get()).interrupt_request7.read(); [ interrupt_request0, interrupt_request1, interrupt_request2, interrupt_request3, ...
Rust
0
_max_width / remaining_children as f64; let label_bc = BoxConstraints::new( Size::new(MIN_TAB_SIZE.min(max_width), bc.min().height), Size::new(max_width, bc.max().height), ); let child_size = label.layout(ctx, &label_bc, label_data, env); ...
Rust
0
_LENGTH, global_batch_size=128 * SEQUENCE_LENGTH, include_default_evals=True, freeze_embeddings=False, model_config_builder=build_model_config, dataset_config_builder=build_dataset_config, trainer_config_builder=build_trainer_config, tr...
Python
1
(e, |e| { P(Expr { id: DUMMY_NODE_ID, kind: ExprKind::Paren(e), span: DUMMY_SP, attrs: ThinVec::new(), tokens: None }) }); } } fn main() { rustc_span::with_default_session_globals(|| run()); } fn ru...
Rust
0
vent)).await } /// Sends final message. /// Consumes transmitter because further messages are not allowed. pub async fn finish(&mut self, finish: F) -> Result<(), SendError> { self.priv_send(Item::Finish(finish)).await } } impl<E, F> StreamingTx<E, F> {} /// Streaming receiver pub struct S...
Rust
0
a Native backend. #![allow(unused_imports)] #![allow(unused_variables)] #![allow(unreachable_code)] use co::Error; use co::plugin::Error as PluginError; use co::plugin::numeric_helpers::Float; use co::plugin::numeric_helpers::Bounded; use co::prelude::*; use plugin::*; use std::cmp::PartialOrd; use std::fmt::Debug; u...
Rust
0
array = [10, 70, 20, 30, 50, 11, 30] array2 = [-1, 1] array3 = [10, 15, 4, 5, 11, 14, 31, 25, 31, 23, 25, 31, 50] def maxSumIncreasingSubsequence(array): # Write your code here. sequences = [None for x in array] sums = [num for num in array] maxSumIdx = 0 for idx in range(len(array)): curr...
Python
1
onst INTERNET_REQFLAG_VIA_PROXY: u32 = 4u32; #[doc = "*Required features: 'Win32_Networking_WinInet'*"] pub const INTERNET_RFC1123_BUFSIZE: u32 = 30u32; #[doc = "*Required features: 'Win32_Networking_WinInet'*"] pub const INTERNET_RFC1123_FORMAT: u32 = 0u32; #[doc = "*Required features: 'Win32_Networking_WinInet'*"] pu...
Rust
0
pm_srgb(OUTPUT_FILE, width, height, camera.tonemap, sum_rad.iter().map(|&sr| sr / spp as f32)); } pub fn render_preview_file(scene: Scene, camera: Camera) { let camera = camera; let (width, height) = camera.resolution(); let mut sum_rad = vec![Vec3::zero(); width * height]; let mut spp = 0; let mut rngs: Vec<ra...
Rust
0
: `\"Win32_System_Iis\"`*"] pub const MD_SSL_KEY_PASSWORD: u32 = <PASSWORD>; #[doc = "*Required features: `\"Win32_System_Iis\"`*"] pub const MD_SSL_KEY_REQUEST: u32 = 5503u32; #[doc = "*Required features: `\"Win32_System_Iis\"`*"] pub const MD_SSL_PRIVATE_KEY: u32 = 5501u32; #[doc = "*Required features: `\"Win32_Syste...
Rust
0
crate::parser::Parser; mod html; mod lexer; mod parser; mod token; fn parse_file(filename: &String) -> io::Result<()> { let input_filename = Path::new(filename); let mut file = File::open(&input_filename).expect("[ERROR] Failed to read file"); let mut input = String::new(); file.read_to_string(&mut ...
Rust
0
EY>"); let output = h2b("dda97ca4864cdfe06eaf70a0ec0d7191"); let aes = Aes192::new(key); assert_eq!(output, aes.permute(input)); let key = &h2b("<KEY>"); let output = h2b("69c4e0d86a7b0430d8cdb78070b4c55a"); let aes = Aes128::new(key); assert_eq!(output, aes.perm...
Rust
0
_ => 0, } }) .sum::<usize>() }) .sum(); println!("{}", result); } #[derive(Debug)] pub struct Data { rules: HashMap<String, ((usize, usize), (usize, usize))>, your_ticket: Vec<usize>, nearby_tickets: Vec<Vec<usize...
Rust
0
from farm.modeling.adaptive_model import AdaptiveModel from farm.conversion.transformers import Converter from farm.data_handler.processor import Processor from farm.infer import Inferencer import pprint from transformers.pipelines import pipeline from pathlib import Path #############################################...
Python
1
'_>) -> fmt::Result { self.0.fmt_metrics(f)?; self.1.fmt_metrics(f)?; Ok(()) } } impl FmtMetrics for () { fn fmt_metrics(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result { Ok(()) } } use crate::tester::ZekeTester; use anyhow::Result; use assert_fs::prelude::*; use std::str...
Rust
0
# Add anomalous volume anomaly_event = Event( event_type=EventType.TRADE_EXECUTED, data={"symbol": "AAPL", "volume": 10000}, # 10x normal ) is_anomaly = self.detector.detect_volume_anomaly(anomaly_event) assert is_anomaly == True def test_frequency_ano...
Python
1
Error::GenerateKeyPairFailed(result)); } if public_key_handle == pkcs11_sys::CK_INVALID_OBJECT_HANDLE { return Err(GenerateKeyPairError::GenerateKeyPairDidNotReturnHandle( "public", )); } if private_key_handle == pkcs11_sys::CK_INVALID_OBJECT_HANDL...
Rust
0
({firstInstance})') seriesDataset.Modality = 'OT' try: # Required (type 2) field, but we don't disqualify the series if it does not have it seriesDataset.SeriesNumber = dataset.SeriesNumber except AttributeError as e: ...
Python
1
import torch import torch.nn as nn import torch.nn.functional as F class LEAM(nn.Module): def __init__(self, text_vocab, label_vocab, vec_dim, label_size, hidden_size, r): super(LEAM, self).__init__() self.text_embedding = nn.Embedding(len(text_vocab), vec_dim) self.text_embedding.weight.dat...
Python
1
import os # clear terminal def clear(): os.system('cls' if os.name == 'nt' else 'clear') clear() # you could binary tree it # but I'm into the idea of just # using dictionaries as adjacency lists low_adj = {} high_adj = {} values = {} # recursive function to move values around def add_or_move_values(values, node...
Python
1
degrees(self) -> f32 { let unnormalized_degrees = self.unnormalized_radians.to_degrees(); if unnormalized_degrees < 0.0 { unnormalized_degrees + 360.0 } else { unnormalized_degrees } } } <gh_stars>1-10 use regex::Regex; use slack; use error; use brain::{Comma...
Rust
0
t += 1 lower -= (upper-lower) else: u_steps_out += 1 upper += (upper-lower) else: while dir_logprob(lower) > llh_s and \ l_steps_out < max_steps_out: ...
Python
1
# note: for raising custom exceptions directly in ImGui code ('PYIMGUI_CUSTOM_EXCEPTION', None) ] + os_specific_macros + general_macros, include_dirs=['imgui', 'config-cpp', 'imgui-cpp', 'ansifeed-cpp'], ), ] setup( name='imgui', version=VERSION, packages=find_packages('...
Python
1
} #[test] fn deal_into_new_stack_forward_and_reverse() { test_reverse("deal into new stack"); } #[test] fn cut_3_cards_forward_and_reverse() { test_reverse("cut 3"); } #[test] fn cut_minus_4_cards_forward_and_reverse() { test_reverse("cut -4"); } #[tes...
Rust
0
_string_pretty(&isf).unwrap(); let isf2 = serde_json::from_str(&isf_string).unwrap(); assert_eq!(isf, isf2); } } } <filename>src/nodes/activation.rs use ndarray::{ArrayD, ArrayViewD}; use nodes::Operation; /// Elementwise Activation, which could be leaky relu, sigmoid or tanh #[deri...
Rust
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # MolMod is a collection of molecular modelling tools for python. # Copyright (C) 2007 - 2019 Toon Verstraelen <Toon.Verstraelen@UGent.be>, Center # for Molecular Modeling (CMM), Ghent University, Ghent, Belgium; all rights # reserved unless otherwise stated. # # This file ...
Python
1
e_files = os.listdir(os.path.join(tmpdir, "images")) self.assertEqual(set(image_files), {"hovercraft_logo.png"}) def test_mathjax(self): with TemporaryDirectory() as tmpdir: sys.argv = [ "bin/hovercraft", os.path.join(TEST_DATA, "math.rst"), ...
Python
1
] use std::fmt; use colored::Colorize; use super::{Glitch, border_down}; #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub enum Flaw { GettingWrongPath { msg: Option<String>, }, GettingNoEntry { msg: Option<String>, }, ReadingEmptyFile { msg: Option<String>, }...
Rust
0
# -- Ford-Fulkerson algorith --- class Graph: def __init__(self, graph): self.graph = graph self.ROW = len(graph) def searching_algo_BFS(self, s, t, parent): visited = [False] * (self.ROW) queue = [] queue.append(s) visited[s] = True while queue: ...
Python
1
October", 10 => "November", 11 => "December", _ => return Err(()), } .to_string()) } /// Will get an english three-letter abbreviation for a zero-indexed month. /// Returns an error if month out of range. pub fn get_month_abbr(month: u8, dot: bool) -> Result<String, ()> { let mut re...
Rust
0
root_id: None, link_list : Vec::new() } } /// Returns a link, if there is one, between node a and node b, identified by their ids. /// /// # Example /// ``` /// use rust_algorithms::spanningtree::*; /// let mut tree: Tree = Tree::new(); /// tree.add_lin...
Rust
0
cfg_attr(not(test), no_std)] #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))] compile_error!( "The TSC crate only supports the \"x86\" and \"x86_64\" architectures" ); extern crate test; use core::ops; #[cfg(target_arch = "x86")] use core::arch::x86 as arch; #[cfg(target_arch = "x86_64")] use core:...
Rust
0
} } let file = pkg_dir.join(file); let mut file = match tokio::fs::File::open(file).await { Ok(file) => file, Err(_) => return Err(warp::reject::not_found()), }; let mut contents =...
Rust
0
to metric using f, see Thomson et al. ret[0] = (sample[0] - ux) * sample[2] / fx ret[1] = (uy - sample[1]) * sample[2] / fy ret[2] = sample[2] return ret def normalizeZeroOne(sample): imgD = np.asarray(sample.dpt.copy(), 'float32') imgD[imgD == 0] = sample.com[2] + (sample.config['cub...
Python
1
: self } } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.0.bits(bits); self } } #[doc = "Oscilator control register 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::...
Rust
0
WITNESS_HEADER, "The wrapped bytes should have DAS header."); let raw = witness.as_slice().get(7..11).unwrap(); let data_type = u32::from_le_bytes(raw.try_into().unwrap()); assert_eq!( data_type, DataType::AccountCellData as u32, "The wrapped bytes should have DAS data type." );...
Rust
0
# Generated by Django 5.0.4 on 2024-12-16 11:41 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ('courses', '0002_initial'), ] operations = [ migrations.CreateModel( name='S...
Python
1
nput_kwargs.get("attention_mask") if attention_mask is None: # build it batch_size, sequence_len, _ = hidden_states.size() num_heads = self.model.config.num_attention_heads causal = torch.triu( hidden_states.new_full((sequence_len, sequence_len), float("-inf"...
Python
1
} } #[test] fn test_set_blkio_read_bps() { let (tmp, throttle) = setup("test_set_blkio_read_bps", BLKIO_THROTTLE_READ_BPS); let blkio = BlockIoBuilder::new() .with_read_bps(vec![LinuxThrottleDevice { major: 8, minor: 0, rate: 10...
Rust
0
loned(); } else { // Shouldn't actually be necessary, as it would be the last itme break; } } } // Any leftover range can then be inserted as a "last gap" self.map.insert(Key(range), value); } /// Remov...
Rust
0
C as Context>::Ok, <C as Context>::Error>; /// Specifies the arguments to a command, /// plus its metadata and executable function. pub struct CommandSpec<C: Context> { /// Argument nodes to this command. This is a list, /// not a graph. pub arguments: Vec<Argument<C>>, /// Description of this command,...
Rust
0
ong_help = r#"Optional. The base branch for the PR. If not specified, inferred from the head branch name via pattern matching, or `master`."# )] base: Option<String>, #[structopt( short = "H", long = "head", help = "Optional. The head branch for the PR. [defa...
Rust
0
"""empty message Revision ID: a10b8ca51e91 Revises: e88834405416 Create Date: 2024-07-20 17:11:30.240115 """ from typing import Sequence, Union from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision: str = "a10b8ca51e91" down_revision: Union[str, None] = "e88834405416" br...
Python
1
h("/static/"): return True # 檢查文檔相關路徑 if any(doc_path in path for doc_path in ["/docs", "/redoc", "/openapi"]): return True return False def _detect_version( self, request: Request ) -> Tuple[str, VersionDetectionMethodEnum]: """ 檢測 API ...
Python
1
} if let Some(attester) = attester { conf.attester_type[..attester.len()].copy_from_slice(attester.as_bytes()); } if let Some(verifier) = verifier { conf.verifier_type[..verifier.len()].copy_from_slice(verifier.as_bytes()); } conf.cert_algo = ENCLA...
Rust
0
ty), lit_uint(u64, uint_ty), lit_int_unsuffixed(i64), lit_float(@~str, float_ty), lit_nil, lit_bool(bool), } // NB: If you change this, you'll probably want to change the corresponding // type structure in middle/ty.rs as well. #[auto_serialize] type mt = {ty: @ty, mutbl: mutability}; #[auto_seria...
Rust
0
region.base_address(); let mut len = region.length(); total += len; if region.base_address() < kernel_start_usize as u64 && region.base_address() + region.length() >= kernel_start_usize as u64 { // regions below 1M are reserved for IO devices add_region(0x100000, kernel_start_usize -...
Rust
0
69i32.to_be_bytes(), ); expected.set_seq_id(0); test_packet("tests/raw/int32be.packet", expected, false); } #[test] fn must_parse_json() { test_packet( "tests/raw/json.packet", Packet::new( Operation::RoomEnterResponse, Protocol::Json, serde_json::to_...
Rust
0
t call_hash = blake2_256(&call); let timepoint = Multisig::<T>::timepoint(); // Create the multi let o = RawOrigin::Signed(caller.clone()).into(); Multisig::<T>::as_multi(o, s as u16, signatories.clone(), None, call.clone(), true, 0)?; assert!(Multisigs::<T>::contains_key(&multi_account_id, call_hash)); ass...
Rust
0
()); } #[test] #[should_panic] fn zero_sized_types_02() { Arena::new().alloc_array((), 0); } #[test] #[should_panic] fn zero_sized_types_03() { Arena::new().copy_slice(&[()]); } #[test] #[should_panic] fn zero_sized_types_04() { Arena::new().alloc_align((), 4); } #[test] #[should_panic] fn zero_sized_ty...
Rust
0
import os from jinja2 import Template import glob2 as glob from funcs import funcs class pipelines: def __init__(self, git): self.git = git self.setting = funcs.getSetting() def createPipelines(self): pipelinePath = "gitlab-pipeline/user-pipelines" jinjaPath = "gitlab-pipelin...
Python
1
ptionally resets the state /// buffer. fn state_transition( &mut self, new_state: State, expected_len: usize, resize: bool, ) -> Result<()> { // Some states don't need the state buffer, so don't resize it if not // necessary. if resize { // A peer can influence th...
Rust
0
/// Hashing to curve failed #[error("Could not hash to curve")] HashToCurveError, /// There must be the same number of keys and messages #[error("there must be the same number of keys and messages")] UnevenNumKeysMessages, /// Serialization error in Zexe #[error(transparent)] Ser...
Rust
0
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
Python
1
from pygments.lexer import RegexLexer from pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Literal, Punctuation, Generic, Other, Error # Many examples are here https://bitbucket.org/birkenfeld/pygments-main/src/default/pygments/lexers/ class PinePygmentsLexer(RegexLexer): name =...
Python
1
lient() rv = client.get('/docs') assert rv.status_code == 200 assert ui_name[1] in rv.data def test_openapi_blueprint_url_prefix(app): assert app.openapi_blueprint_url_prefix is None prefix = '/api' app = APIFlask(__name__, openapi_blueprint_url_prefix=prefix) assert app.openapi_blueprin...
Python
1
as f32; let stddev = stats.variance.sqrt() as f32; if stddev == 0.0 { return 0.0; } match NotNan::new((val - mean) / stddev) { Ok(out) => return out.into_inner(), Err(...
Rust
0
_fn(instance, args, dest)? { ecx.goto_block(ret)?; // fully evaluated and done return Ok(None); } } // This is a const fn. Call it. Ok(Some(match ecx.load_mir(instance.def) { Ok(mir) => mir, Err(err) => { if let ...
Rust
0
]]), ), ], ) def test_create_causal_mask(input_ids, attention_mask, expected_causal_mask): causal_mask = create_causal_mask(input_ids, attention_mask) assert numpy.array_equal(causal_mask, expected_causal_mask[None, None, ...]) @pytest.mark.parametrize( "cache_shape, kv_cache_data_type, output...
Python
1
CAPS: ::c_int = 28; pub const LINECAPS: ::c_int = 30; pub const POLYGONALCAPS: ::c_int = 32; pub const TEXTCAPS: ::c_int = 34; pub const CLIPCAPS: ::c_int = 36; pub const RASTERCAPS: ::c_int = 38; pub const ASPECTX: ::c_int = 40; pub const ASPECTY: ::c_int = 42; pub const ASPECTXY: ::c_int = 44; pub const LOGPIXELSX: :...
Rust
0
down = [downrelu] + downconv up = [uprelu] + upconv if norm_layer is not None: up += [norm_layer(outer_nc)] else: upconv = upsampleLayer( inner_nc * 2, outer_nc, upsample=upsample, padding_type=padding_type) down = [downrelu] ...
Python
1
def erotus(x, y): return x-y
Python
1
c_void, ) -> bool; pub fn mnl_attr_put_u8_check(nlh: *mut nlmsghdr, buflen: usize, type_: u16, data: u8) -> bool; pub fn mnl_attr_put_u16_check(nlh: *mut nlmsghdr, buflen: usize, type_: u16, data: u16) -> bool; pub fn mnl_attr_put_u32_check(nlh: *mut nlmsghdr, buflen: usize, type_: u16, data...
Rust
0
[2] as i32 * 10 + digits[3] as i32; let year = if let Some(b) = self.advance_if(u8::is_ascii_digit) { let new_year = year * 10 + (b - b'0') as i32; i16::try_from(new_year)? } else { year as i16 }; Ok(if negative { -year } else { year }) } ///...
Rust
0