text
stringlengths
8
4.13M
use anyhow::Result; use clap::{crate_authors, crate_description, crate_name, crate_version, App, Arg, ArgMatches}; use flate2::read::GzDecoder; use log::{error, info}; use reqwest; use serde_json::Value; use simple_logger::SimpleLogger; use std::{env, fs::File, io::prelude::*, path::Path, process}; use tar::Archive; us...
mod server; pub use self::server::DexDataServer; mod worker; pub use self::worker::DexDataWorker; mod response; pub use self::response::TestPayload; pub use self::response::create_json_response; mod rpc;
//! //! Count and Say //! //! https://leetcode.com/problems/count-and-say/ //! //! The count-and-say sequence is the sequence of integers with the first five terms as following: //! //! ```text //! 1. 1 //! 2. 11 //! 3. 21 //! 4. 1211 //! 5. 111221 //! ``` //! //! `1` is read off as `"one 1"` or `11`. //! //! `11`...
use futures::future; use futures::stream::StreamExt; use futures::FutureExt; use std::io::{self, BufReader}; use std::net::ToSocketAddrs; use tokio_stream::wrappers::TcpListenerStream; use tokio_util::sync::ReusableBoxFuture; use async_trait::async_trait; use hyper::server::conn::Http; use hyper::server::Builder; use ...
use std::{ collections::HashMap, fmt::{Debug, Display}, hash::Hash, io::{self, Write}, ops::Add, }; /// Runs the A* search algorithm on `initial_state` using `heuristic` to estimate the remaining /// distance. If this function returns `None`, then there is no path from `initial_state` to a /// stat...
pub type EpochNumber = String; pub type Slot = String; pub type ChainLength = String; pub type PoolId = String; pub type Value = String; pub type VotePlanId = String; use graphql_client::GraphQLQuery; #[derive(GraphQLQuery)] #[graphql( query_path = "resources/explorer/graphql/address.graphql", schema_path = "...
// 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 distributed without // any warranty. // // You should have received a copy of the CC0 Public Domain Dedication // along with this sof...
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Power control register"] pub pwrctl: PWRCTL, #[doc = "0x04 - Clock control register"] pub clkctl: CLKCTL, #[doc = "0x08 - Command argument register"] pub cmdagmt: CMDAGMT, #[doc = "0x0c - Command control registe...
/// Comamand parse errors. #[derive(Debug, PartialEq)] pub enum CommandParseError { EmptyCommand, InvalidArgCount, InvalidAddressCond, InvalidCommandName, }
#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ControllerSetting { ParrotController, VirtualController } impl ControllerSetting { pub fn all() -> [ControllerSetting; 2] { [ ControllerSetting::ParrotController, ControllerSetting::VirtualController, ] } } i...
use phi::Phi; use phi::data::Rectangle; use phi::gfx::{AnimatedSprite, AnimatedSpriteDescr, Renderable}; use super::GameObject; const EXPLOSIONS_WIDE: usize = 5; const EXPLOSIONS_HIGH: usize = 4; const EXPLOSIONS_TOTAL: usize = 17; const EXPLOSION_SIDE: f64 = 96.0; const EXPLOSION_FPS: f64 = 16.0; const EXPLOSION_D...
use crate::view::Presenter; use crate::app::{App, QuitApp}; use crate::service::message::MessageService; use crate::service::task::{Task, RunTask}; use crate::view::file_tree::AddRootNode; use gtk::{MenuBar, MenuItem, Menu, SeparatorMenuItem, FileChooserDialog, FileChooserAction, ResponseType}; use gtk::prelude::*; us...
pub(crate) const APP_USAGE: &'static str = "Hacspec 0.1.0 Hacspec Developers Typechecker and compiler for the Hacspec subset of Rust USAGE: cargo hacspec [FLAGS] [OPTIONS] <CRATE> FLAGS: -v Verbosity OPTIONS: -o <FILE> Name of the F* (.fst), Easycrypt (.ec), or Coq (.v) output file ...
use crate::prelude::*; use std::ops::Deref; pub trait FileName: Sized + Default + Deref<Target = str> + Into<String> {} impl<T> FileName for T where T: Sized + Default + Deref<Target = str> + Into<String> {} pub trait RemotePath: Sized { type Name: FileName; type Qual: Qualified; type Unqual: Unqualified...
use crate::Entity; use std::any::{Any, TypeId}; use std::fmt::Debug; /// Determines how the event propagates through the tree #[derive(Debug, Clone, PartialEq)] pub enum Propagation { /// Events propagate down the tree to the target entity, e.g. from grand-parent to parent to child (target) Down, /// Even...
use std::iter::IntoIterator; use std::time::Duration; use std::default::Default; use hyper; use hyper::header::ContentType; use url::form_urlencoded; use itertools::Itertools; use serde_json as json; use chrono::{self, UTC}; use std::borrow::BorrowMut; use std::io::Read; use std::i64; use types::{ApplicationSecret, T...
// Copyright Colin Sherratt 2015 // // 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 o...
//! A common library for utility functions. pub mod account_create; pub mod account_issue; pub mod account_transfer; pub mod chain_setup; pub mod errors; mod harness; pub mod justify; pub mod validate; use base64; use codec::{Decode, Encode}; use cryptography::{ asset_proofs::CipherText, mercat::{ Acc...
struct Solution; impl Solution { fn solve(board: &mut Vec<Vec<char>>) { let n = board.len(); if n == 0 { return; } let m = board[0].len(); let mut visited = vec![vec![false; m]; n]; for i in 0..n { for j in 0..m { if i == 0 || ...
/* * Copyright 2018-2019 TON DEV SOLUTIONS LTD. * * Licensed under the SOFTWARE EVALUATION License (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of the * License at: https://ton.dev/licenses * * Unless required by applicable law or agreed to in writing, softw...
//! ## `Spawn Account` Receipt Binary Format Version 0 //! //! On success (`is_success = 1`) //! //! ```text //! +---------------------------------------------------------+ //! | | | | | //! | tx type | version | is_success | Account Address | //! | (1 byte) | (...
use crate::ast::*; impl SyntaxNode { /// Create a borrowing iterator over this &[SyntaxNode] and all it's children (and their children, ...). /// It visits in a pre-order tree traversal: /// 1. visits the node itself /// 2. visits all the child nodes pub fn iter(&self) -> AstIterator<SyntaxNode> { ...
pub mod ack_nack; pub mod data; pub mod data_frag; pub mod gap; pub mod heartbeat; pub mod heartbeat_frag; pub mod nack_frag; pub mod info_destination; pub mod info_reply; pub mod info_source; pub mod info_timestamp; pub mod submessage; pub mod submessage_elements; pub mod submessage_flag; pub mod submessage_header; ...
use errno::{set_errno, Errno}; use std::fmt::{Debug, Display}; use cosmwasm_vm::errors::Error as CosmWasmError; use snafu::Snafu; use crate::memory::Buffer; #[derive(Debug, Snafu)] #[snafu(visibility = "pub")] pub enum Error { #[snafu(display("Wasm Error: {}", source))] WasmErr { source: CosmWasmErro...
pub use super::{roll, Rollable};
//! An asynchronous/buffered log event pipeline from producers to a single dispatching consumer. //! Currently based on `std::sync::mpsc`, but highly likely this will change. pub mod ambient; mod async; pub mod builder; pub mod chain; pub mod reference;
use std::sync::{Arc, Mutex}; use std::os::unix::net::UnixStream; use std::thread; use std::io::{Write, BufReader, BufRead}; use bus::{Bus, BusReader}; use std::time::Duration; use crate::signaldresponse::SignaldResponse; use crate::signaldresponse::ResponseType::BusUpdate; use crate::signaldrequest::SignaldRequest; use...
use serde::{Serialize, Deserialize}; #[derive(Debug, Serialize, Deserialize)] pub struct SimpleMessage<T> { code: u8, code_message: String, kind: u8, kind_message: String, data: T } impl<U> SimpleMessage<U> { pub fn new( code: u8, code_message: String, kind: u8, ...
use failure::Error; use url::Url; use serde_json; use reqwest; use reqwest::header::{HeaderMap, HeaderValue}; use config; use messages; /// A client to the web interface #[derive(Fail, Debug)] pub enum ClientError { #[fail(display = "Username or password was incorrect")] InvalidLogin, #[fail(display = ...
use std::mem; use std::ops::{Deref, DerefMut, Index, IndexMut}; use std::slice; use util::{Nullable, PrefixPtr, mk_slice, mk_slice_mut}; /// Safe C-like array. The length is stored in an additional metadata field just before the first /// array element. /// /// Unlike `CBlockPtr`, `CArray` maintains ownership of it...
use std::collections::HashMap; use crate::parser::*; // performs a topological sort on a list of modules, returning the sorted list pub fn order_modules(mods: Vec<Module>) -> Vec<Module> { // modules with no further dependencies let mut ready: Vec<String> = Vec::new(); let mut modules: HashMap<String, Mo...
// Copyright 2019 Boyd Johnson // // 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...
//! Intrinsics for arithmetic functions use serde_json::Number; use crate::eval::{ emit::Emitter, error::ExecutionError, machine::intrinsic::{CallGlobal2, IntrinsicMachine, StgIntrinsic}, memory::{mutator::MutatorHeapView, syntax::Ref}, }; use super::support::{machine_return_bool, machine_return_num,...
use super::cycles::CyclePermutation; use crate::perm::{impls::standard::StandardPermutation, Permutation}; /// A permutation, that is on the integral set [1, n]. /// It is called classical as classically this is how permutations are stored #[derive(Debug, PartialEq)] pub struct ClassicalPermutation(StandardPermutation...
use crate::common::*; pub(crate) trait CommandExt { fn export_environment_variables<'a>( &mut self, scope: &BTreeMap<&'a str, (bool, String)>, dotenv: &BTreeMap<String, String>, ) -> RunResult<'a, ()>; } impl CommandExt for Command { fn export_environment_variables<'a>( &mut self, scope: &BT...
//! local-ip-resolver //! ================= //! //! simple interface to get the current ip address used //! to communicate to a remote host. //! #[cfg(windows)] mod win; #[cfg(windows)] pub use win::*; type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>; #[cfg(any(target_os = "macos", target_os = "fr...
use crate::sign_common::{complete_tx, p2pkh_spend_with_signature}; use crate::sign_params::{OutputDestination, SendingOutputInfo, SpendingInputInfo, UtxoSignTxParams}; use crate::{TxProvider, UtxoSignTxError, UtxoSignTxResult}; use chain::{Transaction as UtxoTx, TransactionOutput}; use common::log::debug; use crypto::t...
mod fast_input; use fast_input::{Str, FastInput}; mod union_find; use union_find::UnionFind; use std::collections::HashMap; use std::io::{stdout, Write, BufWriter}; fn main() { let inp = FastInput::new(); let n = inp.next(); let mut bmap = HashMap::with_capacity(200_000); let mut size = vec![1; 200_00...
use std::net::{IpAddr, SocketAddr}; use tokio::io as tio; use tokio::io::{AsyncWriteExt, AsyncBufReadExt, BufReader}; use tokio::net::{TcpListener, TcpStream}; pub struct DummyEmulator { listener: TcpListener, } impl DummyEmulator { pub async fn start(addr: IpAddr) -> Self { let listener = TcpListene...
use super::*; pub use bit_set::BitSet; pub use std::collections::BTreeMap; pub use std::collections::BTreeSet; pub use std::collections::HashMap; pub use std::collections::HashSet; pub use std::collections::VecDeque; use serde::Serialize; pub type NodeId = usize; // internal and possibly different between runs pub t...
use std::collections::HashMap; use std::str::FromStr; use datis_core::rpc::*; use datis_core::station::*; use datis_core::tts::TextToSpeechProvider; use hlua51::{Lua, LuaFunction, LuaTable}; use regex::{Regex, RegexBuilder}; pub struct Info { pub stations: Vec<Station>, pub gcloud_key: String, pub aws_key...
/** * Storage constants for zome entry & link type identifiers * * Used by modules interfacing with the underlying Holochain storage system directly. * * @package agent registration zome * @author pospi <pospi@spadgos.com> * @since 2020-03-22 */ pub const AGENT_ROOT_ANCHOR_ID: &str = "registered_agents_root...
// Unix specific functions that parse ANSI escape sequences from the stdin // bytestream and map to the proper input event. use crate::common::enums::{ InputEvent::{*, self}, KeyEvent::*, MouseEvent::*, MouseButton }; // Reference: redox-os/termion/blob/master/src/event.rs pub fn parse_event<I>(item: u8, ite...
use serde::{Deserialize, Serialize}; use crate::execution_plans::{ClassesMapExecutionPlan, ExecutionPlan}; use crate::lang::Description; use crate::writers::stream_writer::stream_writer::WriteResult; use crate::writers::stream_writer::OutputFormat; pub mod classes_map; pub mod preprocessing; #[derive(Deserialize, Se...
#[derive(Debug)] pub enum SchemaFileProblem { NoComponents, WrongNumberOfComponents, InvalidUTF8, InvalidPath, } impl std::fmt::Display for SchemaFileProblem { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let error_description = match self { SchemaFilePro...
pub mod fftwrap; pub mod smallft;
use indoc::formatdoc; pub use martin::args::Env; use martin::pg::TableInfo; use martin::{Config, IdResolver, Source, Sources}; use crate::mock_cfg; // // This file is used by many tests and benchmarks. // Each function should allow dead_code as they might not be used by a specific test file. // pub type MockSource =...
mod initialize; pub use initialize::post_initialize; mod index; pub use index::get_index;
/* The MIT License (MIT) Copyright (c) 2015 Brian Martin See LICENSE.txt for full license. */ #[macro_use] extern crate log; extern crate time; extern crate mio; use log::{Log, LogLevel, LogLevelFilter, LogMetadata, LogRecord}; use mio::*; use mio::buf::{ByteBuf, MutByteBuf}; use mio::tcp::*; use mio::util::Slab; ...
pub mod control; pub mod group; pub mod group_member; pub mod key; pub mod rule; use std::collections::HashMap; use std::marker::PhantomData; use actix_web::middleware::identity::RequestIdentity; use actix_web::middleware::{Middleware, Started}; use actix_web::{FromRequest, HttpRequest, HttpResponse}; use diesel::pr...
// Make sure we find these even with many checks disabled. //@compile-flags: -Zmiri-disable-alignment-check -Zmiri-disable-stacked-borrows -Zmiri-disable-validation fn main() { let p = { let b = Box::new(42); &*b as *const i32 as *const () }; let _x = unsafe { *p }; //~ ERROR: has been free...
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { _reserved0: [u8; 0x0100], #[doc = "0x100 - An FPUIOC exception triggered by an invalid operation has occurred in the FPU"] pub events_invalidoperation: EVENTS_INVALIDOPERATION, #[doc = "0x104 - An FPUDZC exception triggered by a floating-p...
use rppal::pwm; use std::thread; use std::time::Duration; fn main() { const T: u64 = 425; //us let code = [0xaa, 0x5a, 0x8f, 0x30, 0xf5, 0x01];//カスタマーコード // let code = [0xaa, 0x5a, 0x8f, 0x12, 0x16, 0xd1];//電源 let pwm = pwm::Pwm::new(pwm::Channel::Pwm0).expect("PWM error"); pwm.set_frequency(38_000....
use crate::hittable::HitRecord; use crate::ray::Ray; use crate::vec3::Vec3; use super::{Material, MaterialT}; /// Material that absorbs all incoming rays #[derive(Debug, Clone)] pub struct Void; impl Void { /// Return a new Void material pub fn new_material() -> MaterialT { Void.into() } } impl ...
use crate::error::Error; use crate::hasher::Digest; #[cfg(feature = "std")] use core::convert::TryInto; use core::fmt::Debug; /// Trait for reading and writhing Multihashes. /// /// It is usually derived from a list of hashers by the [`Multihash` derive]. /// /// [`Multihash` derive]: crate::derive pub trait Multihash...
//! calculate the direction of some certain pixel use super::utils::{ isqrt, nside2npix, ring2xyf64, xyf2ring64, NB_FACEARRAY, NB_SWAPARRAY, NB_XOFFSET, NB_YOFFSET, }; use crate::coordinates::{SphCoord, Vec3d}; use num::traits::float::{Float, FloatConst}; fn pix2ang_ring_z_phi<T>(nside: usize, pix: usize) -> (T, ...
// Sparc lacks `FICLONE`. #[cfg(all(linux_kernel, not(any(target_arch = "sparc", target_arch = "sparc64"))))] #[test] fn test_ioctl_ficlone() { use rustix::io; let src = std::fs::File::open("Cargo.toml").unwrap(); let dest = tempfile::tempfile().unwrap(); let dir = tempfile::tempdir().unwrap(); let...
use std::collections::HashMap; static mut PRIMITIVE_TYPES: Option<PrimitiveTypes> = None; pub struct PrimitiveTypes { data: HashMap<&'static str, &'static str>, } impl PrimitiveTypes { pub fn instance() -> Option<&'static PrimitiveTypes> { unsafe { if PRIMITIVE_TYPES.is_none() { ...
use crate::Context; use ockam_core::{async_trait, compat::boxed::Box}; use ockam_core::{Address, AsyncTryClone, Message, Result}; /// Wrapper for `Context` and `Address` pub struct Handle { ctx: Context, address: Address, } #[async_trait] impl AsyncTryClone for Handle { async fn async_try_clone(&self) -> ...
use permutations::PERMUTATIONS; use smoothing::smooth_p5; const ALMOST_ONE_F32: f32 = 0.999_999_94; pub fn perlin_1d(x: f32) -> f32 { let x0 = x.floor(); let x0i = rem_pos(x0 as isize + 0, PERMUTATIONS.len() as isize); let x1i = rem_pos(x0 as isize + 1, PERMUTATIONS.len() as isize); let gi0 = PERMUT...
#![feature(custom_attribute)] #![allow(dead_code, unused_attributes)] // error-pattern:assertion failed #[miri_run] fn slice() -> u8 { let arr: &[_] = &[101, 102, 103, 104, 105, 106]; arr[5] } fn main() {}
mod delete; mod get; mod set; pub use delete::delete; pub use get::get; pub use set::set;
use std::default::Default; use html5ever::{parse_fragment, serialize, namespace_prefix, namespace_url, ns, local_name}; use html5ever::serialize::{SerializeOpts, TraversalScope}; use html5ever::driver::ParseOpts; use html5ever::rcdom::{RcDom}; use html5ever::tendril::TendrilSink; use html5ever::tokenizer::TokenizerOpt...
use crate::trace::trace::BlockExecTraces; use cfx_internal_common::{DatabaseDecodable, DatabaseEncodable}; use cfx_types::{Bloom, H256, U256}; use malloc_size_of::{MallocSizeOf, MallocSizeOfOps}; use malloc_size_of_derive::MallocSizeOf as DeriveMallocSizeOf; use primitives::BlockReceipts; use rlp::{Decodable, DecoderEr...
/// This example shows how to use unix sockets in conjuction with serde (and json) to /// communicate easily. /// /// In this example, a listener waits for newline-delimited messages in a spawned thread. /// If the message is `Msg::Msg`, it simply echoes the contents. /// If the message is `Msg::Close` it closes the co...
mod compile; pub use self::compile::*; use std::error; use std::fmt; use std::os::raw::c_int; use crate::ERROR_CALLBACK_ERROR; use crate::ERROR_CORRUPT_FILE; use crate::ERROR_COULD_NOT_ATTACH_TO_PROCESS; use crate::ERROR_COULD_NOT_MAP_FILE; use crate::ERROR_COULD_NOT_OPEN_FILE; use crate::ERROR_COULD_NOT_READ_PROCES...
pub const CHAR_W: usize = 3; pub const CHAR_H: usize = 4; pub const ZERO: &'static str = " _ \n| |\n|_|\n "; pub const ONE: &'static str = " \n |\n |\n "; pub const TWO: &'static str = " _ \n _|\n|_ \n "; pub const THREE: &'static str = " _ \n _|\n _|\n "; pub const FOUR: &'static str = " \n|_|\n |\n ...
use crate::{HashM, HashMt}; use crate::error::Result; use crate::imp::json_to_rust::names::Names; use crate::imp::structs::ref_def_obj::RefDefObj; use crate::imp::structs::ref_value::RefSabValue; use crate::imp::structs::qv::Qv; pub fn adjust_mut_list_item_ref(def : &RefDefObj, old_ref : HashM<String, RefSabValue>, _n...
#[cfg(test)] mod tests { #[test] fn it_works() { assert_eq!(2 + 2, 4); } } extern crate chrono; #[macro_use] extern crate enum_primitive; extern crate num; //extern crate eclectic; pub mod timeseries; pub mod tuple_indexed; pub mod file_utils; pub mod collections; pub mod stopwatch; use byteorde...
//! Module for for authentication, api clients and response parsing. pub mod apiclient; pub mod auth; pub mod endpoint; mod reqwest_utils; pub mod response; use crate::framework::{apiclient::HerokuApiClient, auth::AuthClient, response::match_response}; use failure::Fallible; use reqwest_utils::match_reqwest_method; u...
pub fn add1(x:i32, y:i32) -> i32 { return x + y ; } pub fn sub1(x: i32, y:i32) -> i32 { return x - y ; }
extern crate core; extern crate minifb; extern crate prodbg_api; extern crate bgfx; extern crate imgui_sys; extern crate settings; extern crate renderer; extern crate project; #[macro_use] extern crate serde_macros; pub mod windows; pub mod menu; pub mod statusbar; mod dir_searcher; // use renderer::Renderer; use co...
extern crate custom_error; use self::custom_error::custom_error; use crate::common::configuration::jormungandr_config::JormungandrConfig; use crate::common::file_utils; use crate::common::jcli_wrapper; use crate::common::jormungandr::{commands, process::JormungandrProcess}; use crate::common::process_assert; use crat...
trait Animal { fn make_sound(&self) -> String; } struct Cat; impl Animal for Cat { fn make_sound(&self) -> String { "meow".to_string() } } struct Dog; impl Animal for Dog { fn make_sound(&self) -> String { "woof".to_string() } } fn main () { let dog: Dog = Dog; let cat: Ca...
use proconio::input; fn main() { input! { n: u32, a: u32, b: u32, } let mut available_num: Vec<u32> = Vec::new(); for i in 0..(n + 1) { let num: Vec<_> = i .to_string() .chars() .map(|a| a.to_digit(10).unwrap()) .collect(...
#![feature(range_contains)] use std::char; extern crate md5; fn has_5_consec_zeroes(s: &str) -> bool { // remember the "-> bool" part,otherwise it returns default (); let zero = char::from_digit(0, 10).unwrap(); // convert digit to char. https://doc.rust-lang.org/std/char/fn.from_digit.html if (s.chars(...
extern crate sdl2; use crate::nes::cartridge; use sdl2::render::WindowCanvas; use sdl2::pixels::Color; use sdl2::rect::Point; struct Registers { v: u16, t: u16, x: u8, w: bool, vram_read_buffer: u8, bg_pattern_upper: u16, bg_pattern_lower: u16, bg_attribute_latch: u8, bg_attribute...
pub mod client; pub mod player;
use std::string::ToString; struct Circle { radius: i32, } impl ToString for Circle { fn to_string(&self) -> String { format!("Circle of radius {:?}", self.radius) } } fn main() { let circle = Circle { radius: 6 }; println!("{}", circle.to_string()); }
#![crate_name="sendfile"] #![feature(asm)] use std::io::{Read, Write, Result}; use std::os::unix::io::AsRawFd; /// Sends `count` bytes directly from `source` to `sink`, bypassing userspace /// When successful, the call returns a `Result` with the number of bytes sent, /// When the call fails, returns a `Result` with ...
#![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(unused_assignments)] #![allow(dead_code)] #![allow(unused_must_use)] #![allow(unused_variables)] #![allow(unused_parens)] #![allow(unused_mut)] pub mod chou_orlandi; mod dummy_garbler; mod evaluator; mod garbler; use fancy_garbling::{circuit::Circui...
use std::error::Error as StdError; use std::fmt; use std::str; use std::time::{SystemTime, Duration, UNIX_EPOCH}; #[cfg(target_os="cloudabi")] mod max { pub const SECONDS: u64 = ::std::u64::MAX / 1_000_000_000; #[allow(unused)] pub const TIMESTAMP: &'static str = "2554-07-21T23:34:33Z"; } #[cfg(all( ta...
#![no_std] #![no_main] #[macro_use] extern crate user_lib; use user_lib::{ open, close, read, write, OpenFlags, }; #[no_mangle] pub fn main() -> i32 { let test_str = "Hello, world!"; let filea = "filea\0"; let fd = open(filea, OpenFlags::CREATE | OpenFlags::WRONLY); assert!(fd > 0...
pub const MASS_LIST: &'static str = include_str!("mass-list.txt"); fn fuel_for_mass(mass: isize) -> isize { let fuel_needed: isize = mass / 3 - 2; if fuel_needed > 0 { fuel_needed + fuel_for_mass(fuel_needed) } else { 0 } } pub fn part1() { let mut fuel_needed = 0; for line...
extern crate futures; extern crate itertools; extern crate serde_json; extern crate spoolq; use std; use std::collections::HashMap; use std::os::unix::fs::OpenOptionsExt; use self::futures::sync::mpsc; use super::*; pub struct Agent<S: runtime::Storage> { matches: Vec<runtime::Match>, st: runtime::State<S>,...
use rusqlite::{ Connection, Result }; use rusqlite::NO_PARAMS; use rusqlite::types::Value as SQLValue; use rocket::request::FromForm; #[derive(FromForm)] pub struct CardSets { pub name: String, pub release: Option<String>, } #[derive(FromForm)] pub struct Users { pub email: String, pub name: Option<S...
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::account_address::{AccountAddress, ADDRESS_LENGTH}; use crypto::{test_utils::TEST_SEED, HashValue, *}; use failure::Error; use rand::{rngs::StdRng, SeedableRng}; use std::convert::TryFrom; /// ValidatorSigner associates an a...
use std::process::Command; use std::thread; use std::time::Duration; fn main() { println!("Lets make our child process do some work!"); thread::sleep(Duration::from_millis(100)); // We can also spawn a process, do something else, then wait on output let process_name = "ls"; let args = ["-a", "-t"]...
//! Benchmarking setup for pallet-board use super::*; #[allow(unused)] use crate::Pallet as Template; use frame_benchmarking::{account, benchmarks, impl_benchmark_test_suite, whitelisted_caller}; use frame_system::RawOrigin; benchmarks! { observe_user { let s in 0 .. 100; let caller: T::AccountId = whitelisted...
use sdl2::pixels::Color; #[derive(Debug, Clone, Copy)] pub enum Type { Black = 0, Green = 1, Brown = 2, Blue = 3, White = 4, End = 5, // not a real texture, please don't use } impl Default for Type { fn default() -> Type { Type::Black } } pub fn get(color_type: Type) -> Color ...
// todo add doccomments use std::collections::{BTreeSet, HashMap, HashSet}; use once_cell::sync::Lazy; pub use func_inject::{FuncFactory, FUNC_INJECT_MANUAL}; use crate::element::ExcludeKind; use crate::type_ref::{TypeRef, TypeRefDesc}; use crate::{CompiledInterpolation, ExportConfig, FuncId, StrExt}; mod func_inj...
/** * [34] Find First and Last Position of Element in Sorted Array * * Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. * * Your algorithm's runtime complexity must be in the order of O(log n). * * If the target is not found in the array, r...
use syn::{Body, VariantData, MacroInput, Ident, Field, Visibility, MetaItem}; use syn::Lit; use quote; /// Representing the struct we are deriving pub struct Struct { /// The input struct name pub name: Ident, /// The list of traits to derive passed to `soa_derive` attribute pub derives: Vec<String>, ...
// This module uses the standard `log` crate. use log::{debug, error, info, trace, warn}; use std::thread; pub fn error() { error!("using_log {}", 1); } pub fn warn() { warn!("using_log {}", 1); } pub fn info() { info!("using_log {}", 1); } pub fn debug() { debug!("using_log {}", 1); } pub fn trace...
use std::io::{self, Write}; use crate::error::{FormatContext, FormatError}; use crate::prim::{ReadCursor, WriteCursor}; /// A skip list reader. /// /// A skip list reader fundamentally supports one option: it can efficiently /// searched an ordered sequence of values. It does this by associating values /// with offse...
use crate::prelude::*; pub fn map_render( player_fov_query: Query<&FieldOfView, With<Player>>, (map, camera, theme): (Res<Map>, Res<Camera>, Res<Box<dyn MapTheme>>), ) { let mut draw_batch = DrawBatch::new(); draw_batch.target(0); let player_fov = player_fov_query.single(); for y in camera.to...
//! I/O port functionality. /// Write 8 bits to port #[inline] pub unsafe fn outb(port: u16, val: u8) { asm!("outb %al, %dx" :: "{dx}"(port), "{al}"(val)); } /// Read 8 bits from port #[inline] pub unsafe fn inb(port: u16) -> u8 { let ret: u8; asm!("inb %dx, %al" : "={ax}"(ret) : "{dx}"(port) :: "volatile...
use std::thread::spawn; fn initialize() { initialize_inner(&mut || false) } fn initialize_inner(_init: &mut dyn FnMut() -> bool) {} fn main() { let j1 = spawn(initialize); let j2 = spawn(initialize); j1.join().unwrap(); j2.join().unwrap(); }
mod common; #[cfg(not(feature = "blocking"))] mod async_bridge; #[cfg(feature = "blocking")] mod blocking;
mod day7 { use std::collections::HashMap; // use std::collections::HashSet; lazy_static! { static ref HASHMAP: HashMap<char, i32> = { let mut m = HashMap::new(); "abcdefghijklmnopqrstuvwxyz" .to_uppercase() .chars() .enumerate()...