text
string
label_name
string
labels
int64
symmetric difference let e_symmetric_diff = (e1 | e2) - (e1 & e2); let elems = e_symmetric_diff.iter().collect(); assert_eq!(vec![A,B], elems) } #[test] #[should_fail] fn test_overflow() { #[allow(dead_code)] #[repr(uint)] enum Bar { V00, V01...
Rust
0
self.fuel > 0 { self.fuel -= 1; } self.fuel == 0 } pub fn fuel(&self) -> u32 { self.fuel } } fn create_frontier(config: &Config) -> Vec<Road> { let mut vec: Vec<Road> = Vec::new(); let mut rng = thread_rng(); let road_type = RoadType::Large; let a = P...
Rust
0
put.len() { assert_eq!(input[idx], output[idx]); } } #[test] fn read_write_tail_test() { let mut rb = RingBuffer::new(1).unwrap(); let input: Vec<_> = (0..8192).map(|i| (i & 0xff) as u8).collect(); let written = rb.write_at_tail(&input[..]); assert_eq!(written, 4095); let mut output: Ve...
Rust
0
let (sequence, remaining) = u16::try_parse(remaining)?; let (length, remaining) = u32::try_parse(remaining)?; let (vendor_length, remaining) = u8::try_parse(remaining)?; let (model_length, remaining) = u8::try_parse(remaining)?; let (num_hsync, remaining) = u8::try_parse(remaining)?...
Rust
0
import streamlit as st import os st.set_page_config( page_title="AI Interviewer", page_icon="🎤", layout="wide" ) st.title("AI Интервьюер") st.write("Добро пожаловать в приложение AI Интервьюер. Пожалуйста, выберите интерфейс:") col1, col2 = st.columns(2) with col1: st.subheader("Пользовательский ин...
Python
1
ain(&mut c_app, c_args.as_ptr(), arguments.len(), app as *mut c_void) } ) // } // pub fn clingo_main( // application: *mut clingo_application_t, // arguments: *const *const ::std::os::raw::c_char, // size: usize, // data: *mut ::std::os::raw::c_void, // ) -> ::std::os::raw::c_int...
Rust
0
.trim() .splitn(2, "\n") .map(|line| line.chars().last().unwrap().to_digit(10).unwrap() as u64); return [nums.next().unwrap(), nums.next().unwrap()]; } trait DiceRoller { fn roll(&self, times: usize) -> u64; } struct DeterministicDiceRoller<T: Iterator<Item = u64>> { iter: T, } im...
Rust
0
.sh", gen_rand_str()); create_file("echo 'hello world'\nsleep 10 &\ndate", filename.as_str()); let ret = new(filename.as_str(), &username(), CMD_TYPE, "./", 6, 1024); let mut cmd = ret.unwrap(); let ret = cmd.run().await; assert!(ret.is_ok()); lo...
Rust
0
<path>/host-<id>/<request>`.") .long("path") .takes_value(true) .default_value(&path)) .arg(Arg::with_name("port") .help("Port.") .short("p") .long("port") .takes_value(true) .default_value("59583")) .arg(Arg...
Rust
0
center(new_center); box_state.rotate(dt as f32 / 1000.0); } fn is_inside_world(point: P) -> bool { let (x, y) = point; (x > 0 && x <= GRID_WIDTH as i32) && (y > 0 && y <= GRID_HEIGHT as i32) } /// Handle when bullets miss i.e. reach edge of world without hitting anything - remove them. fn handle_bullet_m...
Rust
0
om_slice(&data); } } impl NebulaContract { pub fn add_pulse( &mut self, data_hash: Vec<u8>, last_pulse_id: u64, ) -> Result<(), NebulaError> { let new_pulse_id = last_pulse_id + 1; self.pulses_map.insert( Pulse { data_hash, },...
Rust
0
""" Write a function that takes in a list and an element and inserts the element before each element in the list, and returns the resulting list. assert insert_element(['Red', 'Green', 'Black'],'c')==['c', 'Red', 'c', 'Green', 'c', 'Black'] """ def insert_element(list, element): new_list = [] for i in range(le...
Python
1
th)[0] name = '%06d'%i webpage.add_header(name) ims, txts, links = [], [], [] ims_dict = {} for label, im_data in visuals.items(): im = util.tensor2im(im_data) image_name = '%s_%s.png' % (name, label) save_path = os.path.join(image_dir, image_name) util.save_image(im...
Python
1
Cipher::SecurityQuestions { salt, mem_limit, ops_limit, question_list, header, cipher, } => { // this is a SecurityQuestions type, emit that out...
Rust
0
mmand) = command.command() { command = new_command; if let Some(name) = new_command.command_name() { command_str.push(' '); command_str.push_str(name); } } else { break; } } println!("cargo-cocoapods -- <NAME> <htt...
Rust
0
int("Running setup_module ...") setup_function = get_setup() if setup_function: try: setup_function() print("Setup successful.") except Exception: setup_function() pass else: print("No setup_module()") if DEEPSPEED_MODE and not am_f...
Python
1
background-color: #27AE60; color: white; border-radius: 8px; } QPushButton:hover { background-color: #2ECC71; } """) else: self.gamepad_toggle_button.setText("GAMEPA...
Python
1
asyncio.Future[bool]"] = None ) -> None: if waiter is None: waiter = self._notify_waiter if waiter is not None: set_result(waiter, True) if waiter is self._notify_waiter: self._notify_waiter = None def init_signals(self) -> None: # Set up sig...
Python
1
); } #[test] fn new_with_at_symbol_in_context() { let delta = Delta::new("@@ path:1 @@ Context@@", 10, 12, 3, 4); assert_eq!(delta.context(), "Context@@"); assert_eq!(delta.old_start(), 10); assert_eq!(delta.new_start(), 12); assert_eq!(delta.old_lines(), 3); assert_eq!(delta.new_lines(), 4); } #[tes...
Rust
0
_API_GET_SCHEDULER_EVENT, req, opt) } pub fn get_scheduler_event_async(&self, req: &super::scheduler_monitor::SchedulerEventReq) -> ::grpcio::Result<::grpcio::ClientUnaryReceiver<super::scheduler_monitor::SchedulerEventResp>> { self.get_scheduler_event_async_opt(req, ::grpcio::CallOption::default()) ...
Rust
0
this apple is sour"); let result = Solution::uncommon_from_sentences(s1, s2); assert!(result == vec!["sweet", "sour"] || result == vec!["sour", "sweet"]); let s1 = String::from("apple apple"); let s2 = String::from("banana"); assert_eq!(Solution::uncommon_from_sentences(s1, s2),...
Rust
0
let _pair = store .read() .key_pair::<sr25519::AppPair>( &sr25519::Public::from_ss58check(account).unwrap().into(), ) .unwrap(); drop(store); _pair } } } fn get_block_number(api: &Api<sr...
Rust
0
Else => write!(f, "{}", ELSE_KEYWORD), Self::Equals => write!(f, "="), Self::False => write!(f, "{}", FALSE_KEYWORD), Self::GreaterThan => write!(f, ">"), Self::GreaterThanOrEqualTo => write!(f, ">="), Self::Identifier(name) => write!(f, "{}", name), ...
Rust
0
<unsafe extern "C" fn(*mut GVfs, *const c_char, *mut GFileInfo, GFileQueryInfoFlags, *mut GCancellable, *mut *mut glib::GError) -> gboolean>, pub local_file_removed: Option<unsafe extern "C" fn(*mut GVfs, *const c_char)>, pub local_file_moved: Option<unsafe extern "C" fn(*mut GVfs, *const c_char, *const c_char)...
Rust
0
let mut file_str = String::new(); file_str.push(chars[0]); let mut file: File = char_to_file(&file_str); Position(file, rank) } pub fn from_pgn_list(s: &str) -> Vec<Position> { s.replace(" ", "").split(",").map(|pgn| { let chars = pgn.chars().collect::<Vec<c...
Rust
0
Donkey = 114, DragonFireball = 115, Drowned = 116, ElderGuardian = 117, EndCrystal = 118, EnderDragon = 119, Enderman = 120, Endermite = 121, Evoker = 122, EvokerFangs = 123, ExperienceOrb = 124, EyeOfEnder = 125, Falli...
Rust
0
ONE) .set(STROKE_ATTR, self.stroke_color.clone()) .set(STROKE_WIDTH_ATTR, DEFAULT_LINE_STROKE_WIDTH) .set(D_ATTR, data); res.append(line); res } } #[cfg(test)] mod tests { use super::*; use crate::Color; #[test] fn line_basic() { let ex...
Rust
0
* job_bytes * 8.0); println!("#elapsed time {}s", end.as_secs()); std::process::exit(0) } /////////////////////////////////////// #[derive(Copy, Clone)] enum RecvRes { Done, Error, NeedsMore(usize), } #[derive(Copy, Clone, Debug)] #[repr(u8)] enum Io { Read, Write, ReadWrite } fn run_bad_worke...
Rust
0
rams": { "min_X": 0.5, "max_X": 1.5, # Uniform cost range [cite: 1] "min_R": 1.0, "max_R": 3.0, # Uniform reward range [cite: 1] "correlation": 0.0, # No correlation for this specific uniform arm [cite: 1] # True means and variances for uniform distributions ...
Python
1
""" Reset a deskpro ticket and requeue for publishing. """ import re from django.core.management.base import BaseCommand from peeringdb_server.models import DeskProTicket class Command(BaseCommand): help = "Reset a deskpro ticket and queue again for publish" def add_arguments(self, parser): parser...
Python
1
from django.db import models from ckeditor.fields import RichTextField from django.contrib.auth.models import User from members.models import Group import uuid class Event(models.Model): name = models.CharField(verbose_name='Name', max_length=100) creator = models.ForeignKey(User, on_delete=models.PROTECT, re...
Python
1
ader in train_loader_list: train_steps += len(loader) # 用于在训练深度学习模型时实现早期停止的功能。早期停止是一种防止模型过拟合的策略,具体来说,当验证损失在一段时间内没有显著改善时,训练过程将被停止。 early_stopping = EarlyStopping(accelerator=accelerator, patience=args.patience) trained_parameters = [] for p in model.parameters(): ...
Python
1
ct, op: Option<Operator>, rhs: Option<Box<Unit<'a>>>) -> Self { if op.is_some() && rhs.is_none(){ panic!{"operator but no RHS"}} Self{ varibale: var, lhs: lhs, op: op, rhs: rhs } } fn eval(&self, value: f) -> f { if l...
Rust
0
<span class="mdiv"> <a target="_blank" href="https://github.com/EnormousCloud/api3-dao-tracker" > "Github Source" </a> </span> ...
Rust
0
import os import unittest import tensorflow as tf from transformers_keras.token_classification.crf_models import ( AlertCRFForTokenClassification, BertCRFForTokenClassification, CRFModel, ) class CRFModelsTest(unittest.TestCase): """CRF models test.""" def test_crf_model(self): sequence...
Python
1
"""Cascade RCNN with ConvNeXt-T, 1x schedule, FP16.""" _base_ = [ "../_base_/models/cascade_rcnn_r50_fpn.py", "../_base_/datasets/bdd100k.py", "../_base_/schedules/schedule_1x.py", "../_base_/default_runtime.py", ] # please install mmcls>=0.22.0 # import mmcls.models to trigger register_module in mmcl...
Python
1
into it? This is actually a /// very common design pattern. It's called an immutable/persistent data structure. You build a b-tree, and when you /// write a record, you create a new copy of the leaf pointing to that record, and the parent node pointing to that, and /// so on up to the root node. The whole thing is bea...
Rust
0
d: o.back_url = d['back_url'] if 'ext_info' in d: o.ext_info = d['ext_info'] if 'jump_type' in d: o.jump_type = d['jump_type'] if 'out_order_no' in d: o.out_order_no = d['out_order_no'] if 'partner_id' in d: o.partner_id = d['pa...
Python
1
e S: ValidateBlob, P: ValidateBlob, { const BLOB_LEN: usize = <SumTreeData<T, S, P> as ValidateBlob>::BLOB_LEN + <SumTreeData<T, S, P> as ValidateBlob>::BLOB_LEN; type Error = ValidateInnerBlobError<S::Error, P::Error>; fn validate_blob<'a>(mut blob: BlobValidator<'a, Sel...
Rust
0
from database import db from app.models.gig_ads import GigAd from sqlalchemy.exc import SQLAlchemyError def create_gig_ad(performer_id, data): try: gig_ad = GigAd( performer_id=performer_id, title=data["title"], description=data.get("description"), gig_type=d...
Python
1
from __future__ import absolute_import, division, print_function from iotbx import wildcard def exercise(): assert wildcard.is_match(string="", pattern="") assert wildcard.is_match("", "*") assert wildcard.is_match("a", "?") assert wildcard.is_match("a", "[a-z]") assert wildcard.is_match("wildcard", "wi*card...
Python
1
trim() { "/exit" | "/quit" | "" => break, "/tokens" => { println!("Tokens:"); for token in content.tokens() { println!("{}", token); } println!(); } "/files" => { pri...
Rust
0
= 1 else "worker") @tf_export("experimental.dtensor.full_job_name", v1=[]) def full_job_name(task_id: Optional[int] = None) -> str: """Returns the fully qualified TF job name for this or another task.""" # If task_id is None, use this client's ID, which is equal to its task ID. if task_id is None: task_id =...
Python
1
from time import sleep from math import sqrt n = int(input("Input your number:")) t = int(input("Input your time:")) n2 = sqrt(n) sleep(t / 1000) print(f"Square root of {n} after {t} miliseconds is {n2}")
Python
1
# cgbookstore/apps/chatbot_literario/services/functional_chatbot.py import logging import re from typing import List, Any, Dict, Optional from django.db.models import Q logger = logging.getLogger(__name__) class FunctionalChatbot: """ Chatbot "stateless" que usa o banco de dados para manter o contexto. ...
Python
1
3v2` frame /// /// ## Outdated Frames /// /// ### ID3v2.2 /// /// `ID3v2.2` frame IDs are 3 characters. When reading these tags, [`upgrade_v2`] is used, which has a list of all of the common IDs /// that have a mapping to `ID3v2.4`. Any ID that fails to be converted will be stored as [`FrameID::Outdated`], and it must ...
Rust
0
assert_eq!(res, expect); } { let res = f("7".to_string()).into_iter().collect::<HashSet<_>>(); let expect = ["p", "q", "s", "r"].iter().map(|s| s.to_string()).collect::<HashSet<_>>(); assert_eq!(res, expect); } { let res = f("".to_st...
Rust
0
Offset. If endOffset is also set, the objects listed will have names between startOffset (inclusive) and endOffset (exclusive). #[serde(rename = "startOffset")] pub start_offset: Option<String>, /// The project to be billed for this request. Required for Requester Pays buckets. #[serde(rename = "userPro...
Rust
0
K_HEADERS': '', # 自定义通知 请求头 'WEBHOOK_METHOD': '', # 自定义通知 请求方法 'WEBHOOK_CONTENT_TYPE': '', # 自定义通知 content-type 'NTFY_URL': '', # ntfy地址,如https://ntfy.sh 'NTFY_TOPIC': '', # ntfy的消息应用topic 'NTFY_PRIORITY':'3', #...
Python
1
(reqwest::Error), #[error("Authentication with iRacing failed")] AuthenticationFailure(#[from] AuthError), } <gh_stars>0 pub mod main; #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] pub enum GameState { Main, } mod with_arity_zero; use super::*; use proptest::strategy::Strategy; #[test] fn without_a...
Rust
0
note="District Office", ) org.add_source(url) # membership td_text = list() for td in row[1].xpath("div") + row[2].xpath("div"): td_text += td.itertext() members = list( value ...
Python
1
AW_EVENT ) expected_msg = ( f'Specified timeout {big_timeout_sec} is longer than max timeout ' f'{rpc_max_timeout_sec}.' ) with self.assertRaisesRegex(errors.CallbackHandlerBaseError, expected_msg): handler.waitAndGet('ha', big_timeout_sec) def test_wait_for_event(self): ha...
Python
1
# Import the Pandas module. import pandas as pd # Create a Series for each column. bornSeries = pd.Series({'andy': 1964, 'jayne': 1965, 'em': 1997, 'tom': 1997}) heightSeries = pd.Series({'andy': 167, 'jayne': 170, 'em': 165, 'tom': 177}) weightSeries = pd.Series({'andy': 60.0, 'jayne': 65.0, 'em': 58.0, 'tom':...
Python
1
sample } } else if sample < min_diff { start_value - sample } else if sample < max_diff { start_value + sample } else if rand::random() { min } else { max - 1 } }<filename>src/device.rs use crate::{ audio_endpoint_volume::AudioEndpointVolume, audio_se...
Rust
0
########################################################################## # # Copyright (c) 2014, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistribu...
Python
1
lf, lua: &'lua Lua) -> Result<Value<'lua>> { (&self).to_lua(lua) } } impl<'lua, T> ToLua<'lua> for &[T; $N] where T: Clone + ToLua<'lua>, { fn to_lua(self, lua: &'lua Lua) -> Result<Value<'lua>> { ...
Rust
0
YR::_100 } #[doc = "Checks if the value of the field is `_101`"] #[inline] pub fn is_101(&self) -> bool { *self == ADC_SUPPLYR::_101 } } #[doc = "Possible values of the field `ADC_SUPPLYEN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ADC_SUPPLYENR { #[doc = "Disable internal supp...
Rust
0
) -> Result<Weight, (MessageId, Weight)>; } /// An implementation of a sink that just swallows the message without consuming any weight. Returns /// `Some(0)` indicating that no messages existed for it to process. impl UmpSink for () { fn process_upward_message( _: ParaId, _: &[u8], _: Weight, ) -> Result<We...
Rust
0
Config<'a, T> { self.config } } /// This is the internally used data-structure, storing the current state during calculation, as /// well as the final result, as returned by the API. /// All mutations are done in this structure, making [`KMeans`] immutable, and therefore allowing /// it to be used in parallel, withou...
Rust
0
31 const GAS_MULTIPLIER: u64 = 140_000_000; fn main() { const MAX_REWARDS: u64 = 1000; const STAKE: u64 = 100000; const ENGAGEMENT: u64 = 5000; let mut deps = mock_instance(WASM, &[]); let max_rewards = Uint64::new(MAX_REWARDS); let a = Decimal::from_ratio(37u128, 10u128); let p = Decima...
Rust
0
elements_sequence = input().split() moves = 0 while True: command = input() if command == "end": print("Sorry you lose :(") for element in elements_sequence: print(element, end=" ") break moves += 1 indexes = list(map(int, command.split())) index_1 = indexes...
Python
1
_pattern").unwrap(); let mut report = xmler::fresh_report(); println!("Processing all files that match your glob pattern..."); xmler::process(glob_pattern, &mut report); println!( " Report: * {} Page URLs", report.page_urls.len() ); let page_urls_set: HashSet<Stri...
Rust
0
import re import math instructions, queries = open(0).read().split('\n\n') rules = {} def is_accepted(x, m, a, s, rule): if len(rule) == 1: if rule[0][0] in rules: return is_accepted(x, m, a, s, rules[rule[0][0]]) return rule[0][0] == 'A' condition, trueval = rule[0] if eval(co...
Python
1
L: u32 = 2; pub const DPI_SUBSCR_PROTO_HTTP: u32 = 3; pub const DPI_SUBSCR_QOS_RELIABLE: u32 = 1; pub const DPI_SUBSCR_QOS_DEREG_NFY: u32 = 2; pub const DPI_SUBSCR_QOS_ROWIDS: u32 = 4; pub const DPI_SUBSCR_QOS_QUERY: u32 = 8; pub const DPI_SUBSCR_QOS_BEST_EFFORT: u32 = 16; pub const DPI_VISIBILITY_IMMEDIATE: u32 = 1; p...
Rust
0
registers. */ pub fn rreg(&self, reg: u32) -> u32 { match reg { AI_REG_DRAM_ADDR => { self.dram_addr }, AI_REG_LEN => { self.len }, AI_REG_CONTROL => { self.control }, AI_REG_STATUS => { self.stat...
Rust
0
ault> { grant: &'a Grant<T>, subiter: core::iter::FilterMap< core::slice::Iter<'a, Option<&'static dyn ProcessType>>, fn(&Option<&'static dyn ProcessType>) -> Option<&'static dyn ProcessType>, >, } impl<T: Default> Iterator for Iter<'a, T> { type Item = AppliedGrant<T>; fn next(&mu...
Rust
0
None w8fjb9y1ml1 //= False def u5ya9e1iwrg(awoaw2c3y4i: x0aq30_o094): return 0.0 from tg3b8saxjf9 import yiltx39pq73, wnbes1ui2f3, zuljuefihyr as y8jwdzkh9gu, jkqnrk9jyx6, aavynnoo77d as gpjg6h34as3, modv66dpzgm, l99h9vph9yk as xy4wkw255q_, h431pyo1dbx as vvzrod0v38v, r577u5gw9qw, eteozj7jdm5 pass ...
Python
1
import gc import logging import os import hydra import torch import wandb from omegaconf import OmegaConf from torch.utils.tensorboard import SummaryWriter from tqdm import tqdm logger = logging.getLogger(__name__) @hydra.main(version_base="1.3", config_path="conf") def main(cfg): OmegaConf.resolve(cfg) # reso...
Python
1
# Copyright (c) OpenMMLab. All rights reserved. from unittest.mock import MagicMock, patch import mmcv import torch import torch.nn as nn from mmcv.parallel import (MMDataParallel, MMDistributedDataParallel, is_module_wrapper) from mmseg import digit_version from mmseg.utils import build_dd...
Python
1
}, index=Index(int), strict=True, coerce=True, ) RAW_PREDICTION_SCHEMA = DataFrameSchema( columns={ "date": Column(datetime), "year": Column(int, required=False), "day_of_week": Column(str, checks=Check.isin(DAYS_OF_WEEK)), "week_of_year": Column(int, checks=Check.isin(...
Python
1
/// also mount a login handler if `login` is `Some`. pub fn fairing( adapter: A, callback: C, config_name: &str, callback_uri: &str, login: Option<(&str, Vec<String>)>, ) -> impl Fairing { // Unfortunate allocations, but necessary because on_attach requires 'stati...
Rust
0
�蓝:作业效率1.5倍 Malleable, // 紫:技能效果持续增加两回合 Primed, } impl From<&Condition> for &str { fn from(c: &Condition) -> Self { match c { Condition::Normal => "normal", Condition::Good => "good", Condition::Excellent => "excellent", Condition::Poor => "poor",...
Rust
0
&str) { let mut waits: Vec<Tile> = divide(&tiles_from_string(tiles_str)).iter().flat_map(|d| d.waits()).collect(); waits.sort(); waits.dedup(); assert_eq!(waits, tiles_from_string(expected_waits_str)); } fn d(pair: &str, melds: &[&str], remaining: &str) -> Division...
Rust
0
import pathlib import site import unittest from enmapbox import DIR_ENMAPBOX from enmapbox.gui.enmapboxgui import EnMAPBox from enmapbox.gui.applications import EnMAPBoxApplication from enmapbox.testing import EnMAPBoxTestCase from qgis.PyQt.QtWidgets import QWidget site.addsitedir(pathlib.Path(DIR_ENMAPBOX) / 'corea...
Python
1
.predict_value(problem), } } // Predict the value for one problem. fn predict_value(&self, problem: &mut Problem<$v32>) -> Result<(), Error> { match self.svm_type { SVMType::CSvc | SVMType::NuSvc => { // Compute kernel, decision value...
Rust
0
put = State::<4>::from_input(TEST_INPUT_P2); assert_eq!(solve(input, State::final_state()), 44169); } } use super::utils::*; use super::{AnnoyIndex, IndexType}; use crate::internals::mmap_ext::*; use crate::types::node::*; use memmap2::MmapOptions; use std::error::Error; use std::fs; use std::fs::File; use ...
Rust
0
# Exercice 1 : Température minimale def annee_temperature_minimale(temp, annees) : n = len(temp) i_min = 0 for i in range(n) : if temp[i] < temp[i_min] : i_min = i return (temp[i_min], annees[i_min]) t_moy = [14.9, 13.3, 13.1, 12.5, 13.0, 13.6, 13.7] annees = [2013, 2014, 2015, 2...
Python
1
# Import libraries import argparse import glob import os import mlflow import pandas as pd from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split # define functions def main(args): # TO DO: enable autologging mlflow.autolog() # read data df = get_csv...
Python
1
let #inner_name = #name.get(#idx); #vec_name.push(&#inner_conversion); } }); quote! { { let mut #vec_name = vec![]; #(#convs)* #...
Rust
0
e fn serialize<W: Write>(&self, writer: &mut W) -> io::Result<()>; /// Deserialize fn deserialize<R: Read>(reader: &mut R) -> io::Result<Self>; } /// `FixedSize` marks a `BinarySerializable` as /// always serializing to the same size. pub trait FixedSize: BinarySerializable { const SIZE_IN_BYTES: Ulen;...
Rust
0
s(0).expect("It should contains an order"); assert_eq!(order, Order { owner: ALICE, from_cid: DOT, from_bal: 2, to_cid: BTC, to_bal: 1, status: OrderStatus::Alive, executed_with: None, created_at: 1_u64.into(), cancelled_at: None, executed_at: None }); // Verify event emitted asse...
Rust
0
{ let street_details = street.get_street_details().unwrap(); let suburb = street_details.get_suburb(); let asset = street.asset.borrow(); let building_num = asset.house_num(); // current building num cannot be > 1 of lowest number of buildings on street // ie, if we're b...
Rust
0
from solution import * from solution import TreeNode, vertical_order_traversal # Example tree # 3 # / \ # 9 20 # / \ # 15 7 node_3 = TreeNode(3) node_9 = TreeNode(9) node_20 = TreeNode(20) node_15 = TreeNode(15) node_7 = TreeNode(7) node_3.left = node_9 node_3.right = node_20 node_20.left = node_...
Python
1
## @package diagnose_protobuf # Module scripts.diagnose_protobuf """Diagnoses the current protobuf situation. Protocol buffer needs to be properly installed for Caffe2 to work, and sometimes it is rather tricky. Specifically, we will need to have a consistent version between C++ and python simultaneously. This is a co...
Python
1
line = String::with_capacity(s.len()); format!("{} ", s).chars().fold(None, |prev, b| { if let Some(a) = prev { push_content!(|b| b == CH_VOICED_HALF, VOICED_HALVES, line, a, b); push_content!(|b| b == CH_SEMIVOICED_HALF, SEMIVO...
Rust
0
predicted_state = self.predict(self.state, delta_t_s, use_jacobian=use_jacobian) # Update the state with the observations, if we have any for observation in current_obs: predicted_state = self.update(observation, predicted_state, use_jacobian=use_jacobian) # Set the...
Python
1
: f64, #[param(default = 3.5, range = 0.0..=8.0)] decay_min: f64, #[param(default = 534)] seed: u64, #[param(default = 4)] flower_count: u64, #[param(default = true)] dir_toggle: bool, } impl Manifold { fn flower( &self, center: Point, n: u64, rin...
Rust
0
import os import torch from torchvision import transforms from PIL import Image from diffusers import AutoencoderKL from diffusers.image_processor import VaeImageProcessor image_processor = VaeImageProcessor(vae_scale_factor=0.1825) model_path = "./sd-vae-ft-mse" model = AutoencoderKL.from_pretrained(model_path, local...
Python
1
iption": "Check file reputation using available threat intelligence services such as VirusTotal", "suggestions": {}, "create_time": "2022-03-07T05:17:39.396788Z", "modified_time": "2022-03-07T05:17:39.396969Z", "is_note_required": true, "sla": null, "sla_type": "minutes"}, {"id": 149, "name": "Geolocate IP Address", "o...
Python
1
class Solution: def minimumTeachings(self, n: int, languages: List[List[int]], friendships: List[List[int]]) -> int: b = set() for i, j in friendships: f = any(k in languages[i-1] for k in languages[j-1]) if not f: b.add(i) b.add(j) ...
Python
1
from typing import Union import torch import torch.nn.functional as F from torch import nn class AppearanceModel(nn.Module): def __init__( self, n_input_dims: int = 1, n_grayscale_factors: int = 3, n_gammas: int = 1, n_neurons: int = 32, n_h...
Python
1
val, type_ = self._tokenvalue(braceorEOFtoken),\ self._type(braceorEOFtoken) if val != u'}' and type_ != 'EOF': ok = False self._log.error(u'CSSFontFaceRule: No "}" after style ' u'declaration found: %r' ...
Python
1
new_test_ext().execute_with(|| { assert!(!Bridge::chain_whitelisted(0)); assert_ok!(Bridge::whitelist_chain(Origin::root(), 0)); assert_noop!( Bridge::whitelist_chain(Origin::root(), ChainIdentifier::get()), Error::<Test>::InvalidChainId ); assert_events(vec![Event::Bridge(pallet_bridge::Event::ChainW...
Rust
0
1', Deterministic(value=100)) distributions.add_distribution('param2', Normal(mean_val=50, std_val=0.1)) # Very low variance # The simulation should converge well before 100k iterations # This is a conceptual test - actual implementation would need to track iterations def test...
Python
1
raise ValidationError({'username': 'User with this username does not exist.'}) # Check if the user already belongs to an institute if hasattr(user_to_add, 'userprofile') and user_to_add.userprofile.institute: raise ValidationError({'username': 'This user already belongs to anothe...
Python
1
VALID_EYE_COLORS: [&str; 7] = ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"]; struct Passport<'a>(HashMap<&'a str, &'a str>); impl<'a> Passport<'a> { pub fn is_valid(&self) -> bool { ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"] .iter() .all(|field| self.0.contains_key(fiel...
Rust
0
import asyncio from crawlee.crawlers import ParselCrawler, ParselCrawlingContext from crawlee.proxy_configuration import ProxyConfiguration from crawlee.sessions import SessionPool async def main() -> None: # To use the proxy IP session rotation logic, you must turn the proxy usage on. proxy_configuration = ...
Python
1
ttl = int(self.config_manager.get_ttl()) return ttl @Metrics.track_sync_fnc_exec def replace(self, endpoint, params, new_data, primary_key=['id']): key = self._get_key(endpoint, params) return self._replace(key, new_data=new_data, ttl=self._get_ttl_from_endpoint(endpoint), primary_key...
Python
1
neighbor_C = self._contacts(D_neighbors, E_idx, mask_neighbors) # Pack V = mask.unsqueeze(-1) * torch.ones_like(AD_features) neighbor_C = neighbor_C.expand(-1,-1,-1, int(self.num_positional_embeddings / 2)) neighbor_HB = neighbor_HB.expand(-1,-1,-1, int(self.nu...
Python
1
peer.addresses = vec![other_addr_4.clone(), other_addr_5]; // The peer issues a new, smaller set of listen addrs. let update = hashmap! {other_peer_id => peer}; mock.send_update_discovered_peers(DiscoverySource::OnChainValidatorSet, update) .await; // After updating the ...
Rust
0