text
stringlengths
8
4.13M
use std::io; use std::os::unix::io::{AsRawFd, RawFd}; use std::os::unix::net::{self, SocketAddr}; use std::path::Path; use std::task::{Context, Poll}; use crate::io::Async; #[derive(Debug)] pub struct UnixDatagram { inner: Async<net::UnixDatagram>, } impl UnixDatagram { pub fn bind<P: AsRef<Path>>(path: P) -...
#[doc = "Reader of register WF28"] pub type R = crate::R<u8, super::WF28>; #[doc = "Writer for register WF28"] pub type W = crate::W<u8, super::WF28>; #[doc = "Register WF28 `reset()`'s with value 0"] impl crate::ResetValue for super::WF28 { type Type = u8; #[inline(always)] fn reset_value() -> Self::Type {...
use std::mem; use geometry::vector::Vector; use geometry::line_segment::LineSegment; use ui; #[derive(Clone,Debug,PartialEq)] pub struct LineSegments(pub Vec<LineSegment>); #[derive(Clone,Debug)] pub struct LineSegmentRefs<'a>(pub Vec<&'a LineSegment>); impl LineSegments { pub fn push(&mut self, other: LineSeg...
use partial_renderer::{ReadSize, DomServerRenderer}; pub fn render_to_string(element: ()) -> Vec<u8> { DomServerRenderer::new(vec![element], false) .read(ReadSize::Infinity) } pub fn render_to_static_markup(element: ()) -> Vec<u8> { DomServerRenderer::new(vec![element], true) .read(ReadSize:...
// //! Copyright 2020 Alibaba Group Holding Limited. //! //! 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 ...
// Simplicity lifting to miniscript semantic representation // Written in 2020 by // Sanket Kanjalkar <sanket1729@gmail.com> // To the extent possible under law, the author(s) have dedicated all // copyright and related and neighboring rights to this software to // the public domain worldwide. This software is dist...
// Copyright 2020 Datafuse Labs. // // 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 ...
use worker::*; #[durable_object] pub struct Counter { count: usize, state: State, initialized: bool, env: Env, } #[durable_object] impl DurableObject for Counter { fn new(state: State, env: Env) -> Self { Self { count: 0, initialized: false, state, ...
mod errors; mod parser; use clap::{App, Arg}; use async_std::fs::{DirBuilder, File}; use async_std::prelude::*; use reqwest::header::*; use reqwest::RedirectPolicy; use std::env; #[tokio::main] pub async fn main() -> Result<(), Box<dyn std::error::Error>> { let (year, day) = bootstrap()?; println!("Scaffold!: year...
fn main() { let a = " "; let len = a.len(); println!("a is : {} and its lenght is : {}", a, len) // let a = 6; // { // let a = 10; // println!("value of a is : {}", a); // } // println!("value of a is : {}", a); }
pub use crate::imp::structs::json_file::JsonFile as JsonFile; pub use crate::imp::structs::json_file::JsonDir as JsonDir; pub use crate::imp::structs::root_obj::RootObject as RootObject; pub use crate::imp::structs::rust_value::RustMemberType as RustMemberType; pub use crate::imp::structs::qv::Qv as Qv; pub use crate::...
use chrono::Timelike; use futures_util::{future::ready, stream::StreamExt}; use gloo::timers::future::IntervalStream; use wasm_bindgen::prelude::*; use wasm_bindgen_futures::spawn_local; #[wasm_bindgen(start)] pub fn main() { console_error_panic_hook::set_once(); let document = web_sys::window().unwrap_throw(...
struct Solution; use std::usize; impl Solution { fn common_chars(a: Vec<String>) -> Vec<String> { let n = a.len(); let mut counts: Vec<Vec<usize>> = vec![vec![0; 256]; n]; for i in 0..n { let w = &a[i]; for c in w.chars() { counts[i][c as usize] += 1...
use std::sync::mpsc::{Sender, channel}; use std::sync::Mutex; use std::thread::{spawn}; use ws::{Handler as WsHandler, WebSocket}; pub struct WsServer { } lazy_static! { static ref SENDER: Mutex<Sender<String>> = Mutex::new(WsServer::start_ws()); } impl WsServer { fn start_ws() -> Sender<String> { le...
pub mod draw_map; pub mod interp; pub mod pix; pub mod rotation; pub mod utils; pub use self::interp::get_interpol_ring; pub use self::pix::{pix2ang_ring, pix2vec_ring}; pub use self::utils::{npix2nside, nside2npix};
#[macro_use] extern crate log; extern crate env_logger; extern crate futures; extern crate messagebird_async; extern crate tokio_core; use futures::future::Future; use messagebird_async::errors::*; use messagebird_async::sms; use messagebird_async::sms::*; fn main() -> Result<(), MessageBirdError> { env_logger::i...
/// An error encountered when choosing or applying a Wasm mutation. #[derive(thiserror::Error, Debug)] #[error(transparent)] pub struct Error { kind: Box<ErrorKind>, } impl Error { /// Construct a new `Error` from an `ErrorKind`. pub fn new(kind: ErrorKind) -> Self { kind.into() } /// Cons...
//! A verbosity log for controlled output logging. //! This will log any log messages that are less than or equal to the logging level. //! Log level 0 is considered off and can not be logged to. //! This always logs at the info level of logging using the log crate. #[macro_export] pub static mut log_level: usize = 0;...
fn main() { let mut result = 0; for i in 0..1000 { if i % 3 == 0 || i % 5 == 0 { result += i; } } println!("{}", result); }
use std::fmt; use machine::{Result, fatal_error}; use machine::program::{Name, Frame}; #[derive(PartialEq, Eq, Clone, Copy)] pub enum Value<'p> { Int(i64), Bool(bool), Closure(Closure<'p>), } #[derive(PartialEq, Eq, Clone, Copy)] pub struct Closure<'p> { pub arg: Name, pub frame: &'p Frame, p...
use std::iter::Peekable; use crate::{ ir::{self, Variable}, lexer::{Token, TokenMetadata}, }; use super::{datatype, func_args, statements}; /// Parses the Token-Stream into a single Function defined in the Program /// /// # Example /// ```rust /// # use compiler::lexer::{Token, TokenMetadata, Keyword}; /// #...
use datafusion::{ arrow::{ array::{self, *}, datatypes::DataType, }, error::{DataFusionError, Result}, }; use std::sync::Arc; macro_rules! if_then_else { ($BUILDER_TYPE:ty, $ARRAY_TYPE:ty, $BOOLS:expr, $TRUE:expr, $FALSE:expr) => {{ let true_values = $TRUE .as_ref() ...
use std::sync::Arc; use nimiq_blockchain::Blockchain; use nimiq_blockchain_interface::AbstractBlockchain; use nimiq_blockchain_proxy::BlockchainProxy; use parking_lot::RwLock; use prometheus_client::registry::Registry; use crate::NumericClosureMetric; pub struct BlockMetrics {} impl BlockMetrics { pub fn regist...
use std::net::{UdpSocket}; use std::time::Instant; fn main() -> std::io::Result<()> { { let socket = UdpSocket::bind("169.254.205.169:35")?; let _ = socket.set_read_timeout(None); let dst = "169.254.205.2:56928"; let send_buf = vec![0xAA]; let mut rec_buf = vec![0; 10]; ...
use chrono::{DateTime, Duration, NaiveDateTime, Utc}; use cron_parser::parse; use std::collections::HashMap; use super::offer; use super::treat; //Order Tuple pub struct Tuple { pub name: String, pub unit: u32, } pub struct Order { pub tuple: Vec<Tuple>, pub total_price: f32, } pub fn calculate_pric...
// Copyright 2020 The Jujutsu Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed t...
use super::Property; use super::*; #[derive(Clone, Debug, PartialEq)] pub(crate) struct StyleRule { pub(crate) id: Rule, pub(crate) selectors: Vec<Selector>, pub(crate) properties: Vec<Property>, } // impl std::fmt::Display for StyleRule { // fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fm...
use crate::http_info; use reqwest::header; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::fs; use std::time::Duration; pub const COIN_GECKO_API: &'static str = "https://api.coingecko.com/api/v3"; #[derive(Debug, Serialize, Deserialize)] pub struct Coin { id: String, symbol: Strin...
use sha3::{Digest, Sha3_256}; pub const SEED_SIZE: usize = 256; pub const EXAMPLE_SEED: [u32; SEED_SIZE] = [ 0xc2ba_7ec5, 0x8570_291c, 0xc019_03b4, 0xb3b6_3b5e, 0x60a1_5a04, 0x49cb_3889, 0x8656_014b, 0x4489_160e, 0x4cfc_5c82, 0x4b50_a3c8, 0x842d_828e, 0x9b2d_83d5, 0...
extern crate libc; use linking::{rust_l, rust_w}; use self::libc::c_int; #[link(name = "test")] extern "C" { #[no_mangle] fn l() -> c_int; #[no_mangle] fn w() -> c_int; } pub fn test_linking() { let mut ret = unsafe { l() }; let mut rust_ret = unsafe { rust_l() }; ...
#![cfg_attr(rustfmt, rustfmt::skip)] #![allow(unused)] #![warn(unused_must_use)] use super::*; pub(in crate) use extension_traits::*; mod extension_traits; pub(in crate) use macros::*; mod macros; pub(in crate) use mb_file_expanded::*; mod mb_file_expanded; pub(in crate) use trait_impl_shenanigans::*; mod trait_im...
struct Disc { index: u32, start: u32, size: u32, } impl Disc { fn new(index:u32,size:u32,start:u32) -> Disc { Disc{index,size,start} } fn init() -> Vec<Disc> { vec![ Disc::new(1,13,1), Disc::new(2,19,10), Disc::new(3,3,2), Disc::new(4,7,1), Disc::new(5,5,3), Disc::new(6,17,5), ] } fn...
use std::ops::Add; #[derive(Debug, Clone, Copy, Hash)] pub struct Hex { pub q: i64, pub r: i64, pub s: i64, } impl PartialEq for Hex { fn eq(&self, other: &Self) -> bool { self.q == other.q && self.r == other.r && self.s == other.s } } impl Eq for Hex {} #[derive(Debug, Clone, Copy)] pub ...
use async_std::{ io::BufReader, net::{TcpListener, TcpStream}, prelude::*, task, }; use std::{env, io, thread}; pub mod util; use crate::util::event::{Event, Events}; use async_std::sync::{Arc, Mutex}; use serde::Deserialize; use serde_json::{Map, Value}; use std::collections::HashMap; use std::error:...
use crate::util::tree::*; use std::cell::RefCell; use std::rc::Rc; struct Solution; impl Solution { pub fn path_sum(root: Option<Rc<RefCell<TreeNode>>>, sum: i32) -> Vec<Vec<i32>> { let mut res = vec![]; Self::help(&root, sum, 0, vec![], &mut res); res } fn help( node: &Opt...
use crate::*; mod terrain; pub use terrain::*; mod building; pub use building::*; mod item; pub use item::*; mod bag; pub use bag::*; mod unit; pub use unit::*; pub trait GameObject { fn get_texture_id(&self) -> TextureId; fn get_hue(&self) -> Option<Color> { None } fn get_relative_pos(&self) -> Vec2f; // posi...
use std::collections::BTreeMap; use nimiq_keys::Address; use nimiq_primitives::{ coin::Coin, policy::Policy, slots_allocation::{Validators, ValidatorsBuilder}, }; use nimiq_vrf::{AliasMethod, VrfSeed, VrfUseCase}; pub use receipts::*; use serde::{Deserialize, Serialize}; pub use staker::Staker; pub use sto...
//! This example demonstrates performing a DMA read into a stack buffer. #![no_std] #![no_main] use cortex_m_rt::entry; use cortex_m_semihosting::hprintln; use dma_poc::Transfer; #[entry] fn main() -> ! { let src = b"THIS IS DMADATA!"; let mut dst = [0; 16]; // Note: This is only safe as long as we don'...
/*! Traits and utilities for accessing and manipulating paths embedded in a graph. The interfaces for working with the paths of an entire graph are defined in [`embedded_paths`], while [`path`] deals with single paths, and references to paths. */ pub mod embedded_paths; pub mod path; pub mod occurrences; pub use ...
//! Generic implementation of CTR mode for block cipher with 128-bit block size. use cipher::{ block::{Block, BlockCipher, NewBlockCipher, ParBlocks}, generic_array::{ typenum::{Unsigned, U16}, ArrayLength, GenericArray, }, stream::{ FromBlockCipher, LoopError, OverflowError, Se...
/* * @Author: KuuwangE [admin@kuuwang.com] OR ShellcodeSniper [shellcodesniper@icloud.com] * @Date: 2021-08-03 16:17:18 * @Last Modified by: KuuwangE * @Last Modified time: 2021-08-03 16:17:18 */ pub fn to_string(s: &str) -> String { String::from_utf8(s.as_bytes().to_vec()) .unwrap_or(String::from("")...
use std::pin::Pin; pub(crate) struct LazyPin<T> { value: Box<T>, pinned: bool, } impl<T> LazyPin<T> { pub fn new(value: T) -> LazyPin<T> { LazyPin { value: Box::new(value), pinned: false, } } pub fn pinned(&mut self) -> Pin<&mut T> { self.pinned = t...
use super::common::*; use crate::{ui::util::Y_PADDING, RSError}; use std::cmp::{max, min}; pub async fn scroll_handler(msg: &Action, state: &mut RSState) -> Result<RedrawType, RSError> { let (_, term_h) = crossterm::terminal::size()?; match msg { Action::EntryRemoved(_) | Action::EntryUpdate...
#[macro_use] extern crate diesel; use diesel::pg::PgConnection; use diesel::prelude::*; use dotenv::dotenv; use sodiumoxide::crypto::{box_ as abox, sealedbox, secretbox}; use std::env; pub mod error; pub mod models; pub mod plain; pub mod schema; pub mod user_key; pub fn master_key() -> secretbox::Key { let arch...
use shogi::state::*; use shogi::position::*; use shogi::move_encode::*; use shogi::movable::*; use shogi::piece::*; impl State { pub fn opponent_king_is_capturable(&mut self) -> bool { let opponent_king = if self.color { Piece::king } else { Piece::King }; let moves = self.legal_move(); for...
use std::net::{IpAddr, SocketAddr, TcpListener, TcpStream}; use std::str::FromStr; use std::io::{Read, Write}; use error::Error; #[derive(Debug)] pub struct Server { host: IpAddr, port: u16, addr: SocketAddr, } impl Server { pub fn new(host: &str, port: u16) -> Result<Server, Error> { let hos...
pub const BORDER: i32 = 1; // border width pub const SCALE: i32 = 10; // window scale pub const W: i32 = 100; // board width pub const H: i32 = 70; // board height pub const WH: i32 = (H + BORDER * 2) * SCALE; // window height pub const WW: i32 = (W + BORDER * 2) * SCALE; // window width pub const FRAMERATE: u32 = 3...
use matrix::Matrix; // TODO: Be damn sure to work towards making the consumption of a dataset // more idiomatic. This is disgusting af. /// This encapsulates data to be passed into the Model to be learned with. pub struct Batch { pub size: usize, pub input: Matrix, pub target: Matrix } /// This trait all...
use crate::*; pub struct TakeCommand; impl PipelineElement for TakeCommand { fn start(&self, args: CommandArgs) -> ValueIterator { if let Value::SmallInt(n) = &args.args[0] { Box::new(args.input.take(*n as usize)) } else { Box::new(args.input.take(0)) } } }
use std::collections::HashMap; const INPUT: &str = include_str!("input/7.txt"); mod parse { use std::collections::HashMap; use nom::{ branch::alt, bytes::complete::tag, character::complete::{alpha1, char as exact_char, newline}, combinator::{eof, map}, multi::separated...
// Copyright 2015-2018 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
use std::collections::HashSet; use std::env; use std::fs::File; use std::io; use std::io::BufRead; #[macro_use] extern crate text_io; const FABRIC_SIZE: usize = 1000; fn main() { let args = env::args().collect::<Vec<String>>(); if args.len() < 3 { panic!("Not enough arguments") } let input_fi...
use super::Context; use crate::swcify::Swcify; use swc_babel_ast::BlockStatement; use swc_babel_ast::BreakStatement; use swc_babel_ast::ClassDeclaration; use swc_babel_ast::ContinueStatement; use swc_babel_ast::DebuggerStatement; use swc_babel_ast::DeclareClass; use swc_babel_ast::DeclareExportAllDeclaration; use swc_b...
pub mod claim; pub mod claim_config; pub mod claim_error; mod jwt_numeric_date; #[macro_use] extern crate log; use claim_config::ClaimConfiguration; use claim_error::JwtCustomError; pub fn get_value_from_key(key: &str) -> Option<String> { match dotenv::var(key) { Ok(value) => Some(value), Err(_) ...
//! A big integer library with good performance. //! //! The library implements efficient large integer arithmetic in pure Rust. //! //! The two integer types are [UBig](struct.UBig.html) (for unsigned integers) //! and [IBig](struct.IBig.html) (for signed integers). //! //! ``` //! # use ibig::ParseError; //! use ibig...
use crate::consts::*; use bevy::{ input::{keyboard::KeyCode, Input}, prelude::*, }; use core::f32::consts::PI; use serde_derive::{Deserialize, Serialize}; use std::fs::File; use std::io::prelude::*; #[derive(Clone, Copy, Debug, PartialEq, Deserialize, Serialize)] pub enum Directions { Up, Down, Lef...
use crate::config::HashConfig; use anyhow::{anyhow, Result}; use argon2::{Config, ThreadMode, Variant, Version}; use rand::{rngs::OsRng, Rng}; use tokio::task; /// Hashes a password #[tracing::instrument(level = "debug")] pub async fn hash(password: &str, config: &'static HashConfig) -> Result<String> { let passwo...
pub struct Strenght { pub s: i16, pub h: i16, } #[derive(PartialEq)] pub struct Pos{ pub x: i32, pub y: i32, } pub struct Dir{ pub vx: i32, pub vy: i32, }
use crate::bytecode::Bytecode; use crate::context::{BlockContext, CallContext}; use crate::execution_error::ExecutionError; use crate::opcode_handlers::{execute_opcode, ExecutionStatus, StepResult}; use crate::vm::VmState; #[derive(Debug)] pub struct ExecutionResult { pub return_data: Vec<u8>, pub error: Opti...
extern crate rand; use std::env; use std::fs; use rand::prelude::*; use permutohedron::heap_recursive; use std::time::{{Instant}}; fn main() { let args: Vec<String> = env::args().collect(); let filename = &args[1]; let start_timer = Instant::now(); let cities_map = get_cities_from_file(filename); ...
use std::rc::Rc; use styled_buffer::*; use compiler_message::*; use codemap::{self, Span, CharPos, FileMap}; struct FileWithAnnotatedLines { file: Rc<FileMap>, lines: Vec<Line>, } #[derive(Clone, Debug, PartialOrd, Ord, PartialEq, Eq)] struct Line { // Use a span here as a way to acquire this line later ...
mod blake; mod hashes; mod secp256k1_lock; pub use blake::{blake160, blake256}; pub use hashes::hashes; pub use secp256k1_lock::secp256k1_lock; use ckb_app_config::ExitCode; use faster_hex::hex_decode; fn canonicalize_data(data: &str) -> &str { let data = data.trim(); if data.len() >= 2 && &data.as_bytes()[....
fn main() { is_sum_of_cubes("00 9026315 -827&()"); // "0 0 Lucky" // is_sum_of_cubes("0 9026315 -827&()"); // "0 0 Lucky" is_sum_of_cubes("Once upon a midnight dreary, while100 I pondered, 9026315weak and weary -827&()"); // "Unlucky" } extern crate regex; use regex::Regex; fn is_sum_of_cubes(s: &str) -> String...
use rand::Rng; use rand::rngs::ThreadRng; use std::collections::HashMap; use super::player::*; use super::interaction; use super::render; use super::itens; use super::attributes::{Stats, VitalPoints}; // used implictly by strum... use std::str::FromStr; use std::string::ToString; pub struct Onboarding { rng: Thr...
use std::fs; use std::path::PathBuf; use crate::{Error, Result}; use directories::ProjectDirs; const SESSION_FILE: &str = "session.json"; pub(crate) struct Directories { pub(crate) session_file: PathBuf, } impl Directories { pub(crate) fn new() -> Result<Self> { let dirs = ProjectDirs::...
use rand::rngs::StdRng; use rand::{thread_rng, Rng, SeedableRng}; pub trait Generates<T> { fn generate(&mut self) -> T { self.rng_generate(&mut thread_rng()) } fn rng_generate<TRng>(&mut self, rng: &mut TRng) -> T where TRng: Rng; fn seed_generate(&mut self, seed: &[u8; 32]) -> T ...
use std::future::Future; use std::pin::Pin; use std::task::Context; use tokio::io::AsyncRead; use tokio::macros::support::Poll; // ReadAll is an example Future that reads all the bytes from the provided AsyncRead struct, // converts them to UTF-8, and returns them as a string. struct ReadAll<'a, T> where T: AsyncRead...
#![feature(custom_derive, plugin)] #![plugin(serde_macros)] extern crate flate2; extern crate serde_json; extern crate serde; // use std::path::Path; // use std::fs::File; // use std::io; use std::io::{Read,Write}; use std::error::Error; use serde_json::to_string_pretty; use flate2::read::GzDecoder; #[derive(Debug,...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2 mod api_registry; mod extractors; pub mod module; mod rate_limit_middleware; pub mod service;
//! //! # Kafka - Processing //! //! Sends Create Topic request to Kafka Controller //! use std::net::SocketAddr; use std::io::Error as IoError; use std::io::ErrorKind; use log::trace; use types::defaults::KF_REQUEST_TIMEOUT_MS; use kf_protocol::message::topic::CreatableTopic; use kf_protocol::message::topic::{KfCre...
// Project Euler: Problem 40 fn main() { let mut string = String::new(); for n in 1..187500 { string.push_str(n.to_string().as_str()); } let d1 = string.remove(0).to_digit(10).unwrap(); let d10 = string.remove(10 - 2).to_digit(10).unwrap(); let d100 = string.remove(100...
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ pub mod batcher_worker; pub mod command_construction_worker; pub mod compression_worker; pub mod coordinator; pub mod prefetch_wo...
#[doc = r"Register block"] #[repr(C)] pub struct APPROTECT { #[doc = "0x00 - This register locks the APPROTECT.DISABLE register from being written to until next reset."] pub lock: LOCK, #[doc = "0x04 - This register disables the APPROTECT register and enables debug access to non-secure mode."] pub disab...
use serde_derive::Serialize; use std::fs::File; use std::io::{self, Write}; use std::path::Path; use std::process::exit; use super::Opt; #[derive(Serialize)] struct Output { grade: u32, #[serde(rename = "max-grade")] max_grade: u32, explanation: String, } fn write_file<P: AsRef<Path>>(file: P, output...
//! # rkyv //! //! rkyv (*archive*) is a zero-copy deserialization framework for Rust. //! //! It's similar to other zero-copy deserialization frameworks such as //! [Cap'n Proto](https://capnproto.org) and //! [FlatBuffers](https://google.github.io/flatbuffers). However, while the //! former have external schemas and ...
mod interface; mod ppu; pub use self::interface::{PpuInterface}; pub use self::ppu::{Ppu};
use std::future::Future; use std::io; use std::path::Path; use std::pin::Pin; use std::task::{Context, Poll}; use bytes::BufMut; use futures_core::ready; pub use buffered::{BufferedSocket, WriteBuffer}; use crate::io::ReadBuf; mod buffered; pub trait Socket: Send + Sync + Unpin + 'static { fn try_read(&mut sel...
use smoke::async::Task; use smoke::async::{ ThreadScheduler, SyncScheduler, ThreadPoolScheduler }; /// creates a task that will pass. fn create_ok_task() -> Task<i32> { Task::delay(1).map(|_| 1) } /// creates a task that will panic. fn create_panic_task() -> Task<i32> { Task::delay(1).map(|_| 1).then(|_| Ta...
use crate::debugger; use anyhow::{anyhow, Result}; use async_jsonrpc_client::Output; use gw_config::DebugConfig; use gw_rpc_client::rpc_client::RPCClient; use gw_types::packed::Transaction; use serde::de::DeserializeOwned; use serde_json::from_value; use std::path::Path; // convert json output to result pub fn to_resu...
use token; use dispatch; use dispatch::Dispatch as Dispatch; use dispatch::InvokeReceivier as InvokeReceivier; use common::ParseError as ParseError; use arguments::Argument as Argument; use type_name; use type_name::TypeName as TypeName; use constant::Constant as Constant; #[test] fn self_dispatch() { let tokens =...
use std; use std::collections::HashMap; use datastore::{Entity, Value}; use serde_ds::de; use serde_ds::Error; #[test] fn test_deserialize_ints() { let input = Value::from(42); // Signed integer types let res_i8: i8 = de::from_value(input.clone()).expect("i8 deserialization failed"); assert_eq!(42, r...
#![allow(dead_code)] use std::fmt; use thiserror::Error; use serde::{Serialize, Deserialize}; pub type MessageOpcode = u16; #[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)] pub enum MessageType { ReadRequest, WriteRequest, Data, Acknowledgement, Error } impl MessageType { ...
use std::borrow::Borrow; use anyhow::{Context, Result}; use clap::{clap_app, ArgMatches}; use symbolic::common::{ByteView, Language, Name, NameMangling}; use symbolic::debuginfo::{Function, Object}; use symbolic::demangle::{Demangle, DemangleOptions}; fn print_name<'a, N: Borrow<Name<'a>>>(name: Option<N>, matches: ...
#[macro_use] extern crate criterion; extern crate lalrpop_lambda; use criterion::Criterion; use lalrpop_lambda::Expression; fn compare_benchmark(c: &mut Criterion) { c.bench_function_over_inputs("native addition", |b, &n| { b.iter(|| { n + n }) }, &[0,1,2,4,8,16,32]); c.bench_...
//use actix_web::middleware::session::RequestSession; use actix_web::{Error, Form, FromRequest, HttpRequest, HttpResponse, Path}; use std::marker::PhantomData; // HttpMessage, Query, Json }; use futures::future::Future; // use actix_web::AsyncResponder; use ::uuid::Uuid; // use pretty_env_logger; use chrono::{DateTime...
#[cfg(any(feature = "strobe", feature = "identity", feature = "blake3"))] macro_rules! derive_write { ($name:ident) => { impl<const S: usize> core2::io::Write for $name<S> { fn write(&mut self, buf: &[u8]) -> core2::io::Result<usize> { use multihash_derive::Hasher as _; ...
// Copyright 2019 Conflux Foundation. All rights reserved. // Conflux is free software and distributed under GNU General Public License. // See http://www.gnu.org/licenses/ use super::super::{ trie_proof::TrieProofNode, CompressedPathRaw, CompressedPathTrait, TrieNodeTrait, TrieProof, VanillaChildrenTable, }; ...
use alloc::boxed::Box; use collections::Vec; use io::*; use void::*; pub trait Driver { fn init(&mut self); } pub trait DriverManager { fn get_drivers(&mut self) -> Vec<Box<NetworkDriver + 'static>>; } pub trait NetworkDriver: Driver { fn address(&mut self) -> [u8; 6]; fn put_frame(&mut self, buf: &[...
use std::sync::Arc; use async_trait::async_trait; use bincode::serialize; use futures::TryFutureExt; use log::warn; use overlord::types::{AggregatedVote, SignedChoke, SignedProposal, SignedVote}; use overlord::Codec; use rlp::Encodable; use serde::{Deserialize, Serialize}; use common_apm::muta_apm; use protocol::tra...
#[macro_use] extern crate structopt; #[macro_use] extern crate failure; extern crate itertools; extern crate lalrpop_util; extern crate rand; extern crate regex; extern crate string_cache; extern crate dgen; mod cli_opts; use self::cli_opts::{CliOptions, SubCommand}; use dgen::program::Program; use dgen::interpreter:...
use std::cmp; use std::fmt; use super::Vector; use math::Scalar; #[derive(Debug, Copy, Clone)] pub struct Point { pub pos: Vector, } impl fmt::Display for Point { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Point({}, {})", self.pos.x, self.pos.y) } } impl cmp::PartialEq for...
use crate::*; use power_env; pub fn debug(string: &str) { unsafe { power_env::debug(string.len(), string.as_ptr()); } } pub fn flush() { unsafe { power_env::flush(); } } pub fn write<T1, T2>(key: &T1, value: &T2) where T1: ?Sized + Serialize, T2: ?Sized + Serialize, { let...
use amethyst::ecs::{Entities, Join, Read, ReadExpect, ReadStorage, Resources, System, SystemData, Write, WriteStorage}; use amethyst::input::InputHandler; use amethyst::shrev::{EventChannel, ReaderId}; use crate::components::{Block, RandomStream, RotationCenter, SpawnTimer}; use crate::constants::{ARENA_WIDTH, WALL_KI...
#![feature(fn_traits)] use libmprompt_sys::mprompt; use libmprompt_sys::mprompt::mp_yield; use std::ptr::NonNull; use crate::internal::{__invoke_closure, __return_one}; use crate::prompt::{Prompt, PromptInstance}; pub mod message; pub mod prompt; mod internal; #[derive(Copy, Clone)] pub struct ResumeHandle { inn...
use std::fmt; #[derive(Debug, PartialEq, Clone)] enum MapItem { T, // # O, // . } struct TreeMap { pub width: usize, pub height: usize, pub pattern: Vec<Vec<MapItem>>, } impl TreeMap { fn from_input(input: &str) -> Self { fn string_to_map(input: &str) -> Vec<MapItem> { inp...
use regex::Regex; use std::collections::HashMap; fn check_password(password: &str, advanced: bool) -> bool { // println!("P: {}", password); let mut checking = HashMap::new(); checking.insert("byr", false); checking.insert("iyr", false); checking.insert("eyr", false); checking.insert("hgt", fal...
use specs::{self, Join}; use graphics::{self, Graphics}; use opengl_graphics::GlGraphics; use world::World; use ecs::component; use cgmath; pub struct RenderGraphic { entity: specs::Entity, pos: cgmath::Vector2<f64>, state: RenderGraphicState, } #[derive(Clone)] pub struct RectangleGraphic { pub rec...
pub mod city_list; pub mod fetch; pub mod future; pub mod search_city_list;
use core::fmt; /// Error indicating that an invalid value was used for number of block bytes /// used for message processing. /// /// The alue should be between greater than 0 and less or equal to cipher block size. #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub struct InvalidS; impl fmt::Display for InvalidS { ...
//@compile-flags: -Zmiri-strict-provenance #![feature(strict_provenance)] fn main() { let addr = &0 as *const i32 as usize; let _ptr = std::ptr::from_exposed_addr::<i32>(addr); //~ ERROR: integer-to-pointer casts and `ptr::from_exposed_addr` are not supported }