text
stringlengths
8
4.13M
// Copyright (C) 2021, Kisio Digital and/or its affiliates. All rights reserved. // // This file is part of Navitia, // the software to build cool stuff with public transport. // // Hope you'll enjoy and contribute to this project, // powered by Kisio Digital (www.kisio.com). // Help us simplify mobility and open publ...
#[derive(Default)] struct MyHashSet { table: Vec<bool>, } impl MyHashSet { fn new() -> Self { MyHashSet { table: vec![false; 1_000_000], } } fn add(&mut self, key: i32) { self.table[key as usize] = true; } fn remove(&mut self, key: i32) { self.table[k...
const FORBIDDEN_INTROS: [&'static str; 3] = ["wip", "fixup!", "squash!"]; const FORBIDDEN_MESSAGES: [&'static str; 1] = ["tmp"]; const MAGIC_IGNORE_LABEL: &str = "prgnome ignore"; const FORBIDDEN_LABELS: [&'static str; 8] = [ "work in progress", "wip", "in progress", "dont merge", "do not merge", ...
// //! 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 by appl...
fn main() { let mut pals = vec![]; for a in (500..=999).rev() { for b in (a..=999).rev() { let mul = a * b; if as_string(mul) == as_string_reversed(mul) { pals.push(mul); } } } println!("{:?}", pals.iter().max()); } fn as_string(n: u32) -> String { format!("{}", n) } fn as_string_reversed(n: u32...
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use s2n_tls::{ config, connection::Builder, error::Error, security::{DEFAULT, DEFAULT_TLS13}, }; use s2n_tls_tokio::{TlsAcceptor, TlsConnector, TlsStream}; use std::time::Duration; use tokio::{ ...
//use serde; //use serde_json; pub mod cbor; use tokio_serde_cbor::{Codec}; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Handshake { pub name: String, } impl Handshake { pub fn new<S: Into<String>>(name: S) -> Handshake { Handshake { name: name.into() } } } pub type HandshakeCodec = C...
// Attribute IO code to AxlLind @ https://github.com/AxlLind/easy_io // Testing code for a simple problem on Kattis :) #![allow(dead_code)] use std::io::{self, Read, Stdin, Write, Stdout, Result}; use std::fs::{File, OpenOptions}; use std::fmt::{Display}; use std::char; use std::cmp::min; const EOF: &str = "InputReade...
#![no_std] extern crate panic_semihosting; pub mod button; pub mod context; pub mod delay; pub mod display; pub mod macros; pub mod serial; pub mod syscall; //pub mod schedule;
fn main() { let mut s = String::new(); std::io::stdin().read_line(&mut s).unwrap(); let input:Vec<i32> = s.split_whitespace().map(|x| x.parse::<i32>().unwrap()).collect(); strings = vec!["ABC","ARC","AGC"]; let x = match input{ 0...1199 => 0, 1200...2799 => 1, _ => 2, };...
use std::{default::Default, time::Duration}; /// Contains Config properties which will be used by a Server or Client #[derive(Clone, Debug)] pub struct Config { /// The duration between each tick to be emitted by the Server (Client does /// not emit Tick events just yet) pub tick_interval: Duration, //...
//! Configuration for the `YubiHSM` backend use crate::chain; use abscissa_core::secret::{CloneableSecret, DebugSecret, ExposeSecret, Secret}; use serde::Deserialize; use tendermint::net; use yubihsm::Credentials; use zeroize::Zeroize; /// The (optional) `[providers.yubihsm]` config section #[derive(Clone, Deserializ...
use regex::Regex; use std::collections::HashSet; pub fn solve(input: &str) -> usize { let re = Regex::new(r"^#(\d+) @ (\d+),(\d+): (\d+)x(\d+)$").unwrap(); let mut claims = vec![]; for line in input.lines() { let captures = re.captures(line).unwrap(); let id = captures.get(1).unwrap().as_s...
fn main() { println!("Hello, Turtle!"); }
pub fn bar() { println!("Sub module bar"); }
pub fn reply(msg: &str) -> &str { let msg = msg.trim(); if msg.is_empty() { "Fine. Be that way!" } else if query(msg) && shout(msg) { "Calm down, I know what I'm doing!" } else if query(msg) { "Sure." } else if shout(msg) { "Whoa, chill out!" } else { ...
use std::io::{self, Read}; use std::collections::{BTreeMap, BTreeSet}; use std::time::SystemTime; use regex::Regex; #[cfg(test)] mod tests { use super::*; // use std::io::prelude::*; use std::fs; #[test] fn input1() -> std::io::Result<()> { let contents = fs::read_to_string("./input_test...
extern crate rusoto_dynamodb; extern crate base64; use morocco::{MoroccoError, PutResult, DeletionResult}; use aws::Item; use self::rusoto_dynamodb::*; use self::base64::{encode, decode}; pub struct DynamoOps { table_name: String, dynamo_client: Box<DynamoDb> } impl DynamoOps { pub fn new(table_name: S...
#[repr(u32)] #[derive(Debug)] pub enum ResourceReturnType { NotApplicable = 0, UNorm = 1, SNorm = 2, SInt = 3, UInt = 4, Float = 5, Mixed = 6, Double = 7, Continued = 8 } pub mod rdef; pub mod isgn; pub mod shex; pub mod stat; pub mod builder; pub use self::rdef::*; pub use self::i...
use std::{ ffi::OsStr, fs::{read_dir, File}, io::{BufReader, Read}, path::{Path, PathBuf}, }; mod frontmatter; mod markdown_options; pub use crate::article::frontmatter::Frontmatter; use crate::git::Git; use crate::view::CodeContainer; use chrono::{DateTime, TimeZone, Utc}; use git2::Commit; use url::...
use crate::syntax::IdentifierIndex; use crate::value::implement::*; use std::iter::FromIterator; use std::fmt; /// /// A discrete series of values. /// /// Note: Tuples are generally stored in *reverse* order, since the typical /// operation for a tuple is to take the first value and return the next. /// #[derive(Debu...
use std::fs; use std::time; mod day03; fn main() { let input = fs::read("./src/day03/input.txt").expect("Unable to read input file"); let start = time::Instant::now(); let map = day03::Map{data: input, width: 31}; let slope_3_1_tree_count = day03::count_encountered_trees(&map, (3, 1)); let...
pub mod hlg;
#[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Debug, Default, Clone, PartialEq)] pub struct PostprocessConfig { /// Convenience field for [g_code::emit::FormatOptions] field #[cfg_attr(feature = "serde", serde(default))] ...
mod frame; mod grid; use std::time::Duration; use crossterm::*; use crossterm::{style::Color, Result}; use event::{read, Event, KeyCode}; use frame::Frame; use grid::Input; fn main() -> Result<()> { let mut g = grid::Grid::new(40, 10); let f = Frame::fill(40, 10, ' ', Color::Black, Color::Black); frame::...
//! Example app using Tokio. #[cfg(feature = "with-tokio")] mod tokio_integration { use async_channel_abs::{App, Tokio}; #[tokio::test] async fn tokio_app() { let (app, driver) = App::<Tokio>::new("Hello Tokio!"); let driver_handle = tokio::spawn(async move { driver.run().await }); ...
// materials/dielectric.rs - Dielectric materials. // Written by quadfault // 10/24/18 use rand::prelude::*; use crate::models::HitResult; use crate::math::{ Ray, Vector }; use super::{ Material, ScatterResult, reflect, refract, schlick }; pub struct Dielectric { refractive_index: f64, } impl Dielectric { ...
use clap::crate_name; use clap::derive::IntoApp; use clap_generate::{generate, generators}; use std::env; use std::fs::{self, File}; use std::path::Path; // This file must export a struct named `Args` with `#[derive(Clap)]`. include!("src/cli.rs"); fn main() { let mut app = Args::into_app(); let name = crate_...
use gfx_hal::Instance; #[cfg(windows)] pub fn get_gpu_names() -> Vec<String> { let instance = gfx_backend_dx11::Instance::create("ALVR", 0).unwrap(); let adapters = instance.enumerate_adapters(); adapters .into_iter() .map(|a| a.info.name) .collect::<Vec<_>>() }
mod host_index; mod log_detail; mod repo_index; mod rev_detail; pub use self::host_index::*; pub use self::log_detail::*; pub use self::repo_index::*; pub use self::rev_detail::*;
use warp::{ Filter, Reply, Rejection }; pub fn routes() -> impl Filter<Extract = (impl Reply,), Error = Rejection> + Clone { let global_file_service = warp::path("global").and(warp::fs::dir("global")); return global_file_service; }
#![allow(unused_imports)] #![allow(dead_code)] //sextern crate std; extern crate scorus; use num::traits::float::Float; use num::traits::FloatConst; use quickersort::sort_by; use rand::{distributions::Uniform, Rng}; use scorus::linear_space::type_wrapper::LsVec; use scorus::mcmc::ensemble_sample::{sample_pt, UpdateFla...
pub fn get_member(){ }
// Copyright 2020 Lukas Pustina // // 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 wr...
#![windows_subsystem = "windows"] use ct_lib::bitmap::*; use ct_lib::system; use ct_lib::system::PathHelper; use ct_lib::serde_derive::Deserialize; use ct_lib::log; use rayon::prelude::*; use std::{collections::HashMap, fs::File}; mod main_launcher_info; //////////////////////////////////////////////////////////...
extern crate pest; #[macro_use] extern crate pest_derive; mod config; mod diagram; mod error; mod group; mod message; mod note; mod parser; mod participant; mod rendering; mod separator; /// Parses the supplied diagram string into SVG string. /// /// # Arguments /// /// * `content` - A string representing the diagram...
//! A simple RSA library. //! //! This library performs all the standard bits and pieces that you'd expect //! from an RSA library, and does so using only Rust. It's a bit slow at the //! moment, but it gets the job done. //! //! Key generation is supported, using either the native `OsRng` or a random //! number genera...
//! A Collection of Header implementations for common HTTP Headers. //! //! ## Mime //! //! Several header fields use MIME values for their contents. Keeping with the //! strongly-typed theme, the [mime](https://docs.rs/mime) crate //! is used, such as `ContentType(pub Mime)`. //pub use self::accept_charset::AcceptCha...
mod helper; #[cfg(test)] mod integration { use super::*; use helper::{compile_program, debug_address, debug_stack, execute_program}; use std::panic; #[test] pub fn test_memory_access_basic_test() { let jack_vm = execute_program( " push constant 10 pop lo...
use std::env; use std::io::*; use std::fs::File; fn translate(s : &str) -> &str { match s { "UUU" => "F", "CUU" => "L", "AUU" => "I", "GUU" => "V", "UUC" => "F", "CUC" => "L", "AUC" => "I", "GUC" => "V", "UUA" => "L", "CUA" => "L", ...
// Copyright 2020 EinsteinDB Project Authors & WHTCORPS INC. Licensed under Apache-2.0. use engine_lmdb::LmdbSnapshot; use violetabft::evioletabft_timeshare::MessageType; use violetabftstore::store::*; use std::time::*; use test_violetabftstore::*; /// Allow lost situation. #[derive(PartialEq, Eq, Clone, Copy)] enum ...
// Copyright 2019 WHTCORPS INC Project Authors. Licensed under Apache-2.0. // Various conversions between types that can't have their own // dependencies. These are used to convert between error_promises::Error and // other Error's that error_promises can't deplightlike on. use edb::Error as EnginePromisesError; use ...
#![cfg_attr(feature = "external_doc", feature(external_doc))] #![cfg_attr(feature = "external_doc", doc(include = "../readme.md"))] #![feature(drain_filter)] // The library version of this crate only exposes a subset of the features for the examples. #[macro_use] extern crate log; mod errors; mod nm; mod utils; pub...
mod universe; use cursive::Cursive; use cursive::views::{ TextView, LinearLayout, Button, DummyView }; use cursive::view::Identifiable; static WIDTH: u32 = 30; static HEIGHT: u32 = 30; fn main() { let mut main = Cursive::default(); let myuniverse = universe::Universe::new(WIDTH, HEIGHT); let grid = Tex...
use std::env::current_dir; use std::path::PathBuf; use std::fs::canonicalize; const RESOURCE_BASE_PATH: &str = "resources"; pub fn resource_path() -> PathBuf { match current_dir().and_then(canonicalize) { Ok(path) => path.join(RESOURCE_BASE_PATH), Err(_) => PathBuf::from(format!("./{}/", RESOURCE_...
use std::ptr; use std::sync::Mutex; use memory::Memory; lazy_static! { pub static ref RUST_MEMORY: Mutex<RustMemory> = Mutex::new(RustMemory{}); } pub struct RustMemory(); impl Memory<*mut u8> for RustMemory { unsafe fn read<T>(&self, ptr: *mut u8) -> T { ptr::read(ptr as *mut T) } unsafe fn ...
/// Operator /// /// # Description /// List of operator available in Markdown pub mod bytes { // Operator -> # pub const HEADING: u8 = 35; // Operator -> * pub const UNORDERED_MUL: u8 = 42; // Operator -> - pub const UNORDERED_MINUS: u8 = 45; // Operator -> + pub const UNORDERED_PLUS: u...
use crate::config; use crate::config::peer::AllowedIps; use crate::config::{PresharedKey, PublicKey}; use crate::lang; use crate::states::WgState; use crate::utils::FormInputResult; use crate::utils::FormOption; use askama::Template; use rocket::http::RawStr; use rocket::http::Status; use rocket::request::Form; use roc...
use chrono::prelude::*; use crate::{util, Sha256Hash, proofofwork}; pub const HASH_BYTE_SIZE: usize = 32; pub const HASH_BIT_SIZE: usize = 256; #[derive(Debug)] // #[derive(Default)] pub struct Block { timestamp: i64, data: Vec<u8>, prev_block_hash: Sha256Hash, hash: Sha256Hash, nonce: u64, } im...
#![feature(portable_simd)] use std::simd::*; fn main() { unsafe { let vec: &[i8] = &[10, 11, 12, 13, 14, 15, 16, 17, 18]; let idxs = Simd::from_array([9, 3, 0, 17]); let _result = Simd::gather_select_unchecked(&vec, Mask::splat(true), idxs, Simd::splat(0)); //~ERROR: pointer to 1 byte start...
use futures::future::Future as _; use futures::stream::Stream as _; use snafu::futures01::StreamExt as _; /// A wrapper around `Process` which listens for terminal resize signals and /// propagates the changes into the process running on the pty. /// /// This is useful for running subprocesses in a pty that will ultim...
//! A simple commandline application to act as a MERCAT account. //! Use `mercat_account --help` to see the usage. mod input; use env_logger; use input::{parse_input, CLI}; use log::info; use mercat_common::{ account_create::process_create_account, account_issue::process_issue_asset, account_transfer::{pr...
extern crate erdos; use std::{thread, time::Duration}; use erdos::dataflow::context::*; use erdos::dataflow::deadlines::*; use erdos::dataflow::operator::*; use erdos::dataflow::operators::*; use erdos::dataflow::state::TimeVersionedState; use erdos::dataflow::stream::*; use erdos::dataflow::*; use erdos::node::Node;...
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use crate::{ config::Config, connection::Connection, enums::Mode, error::Error, pool::{Pool, PooledConnection}, }; /// A trait indicating that a structure can produce connections. pub trait...
use std::io; fn main() { let mut line = String::new(); let mut pos = 0; let mut pic = vec![2; 25*6]; io::stdin().read_line(&mut line).expect("failed to read line"); for c in line.trim().chars() { match c { '0' => if pic[pos % (25*6)] == 2 {pic[pos % (25*6)] = 0}, '...
#![windows_subsystem = "windows"] extern crate actix_web; extern crate directories; extern crate exif; extern crate futures; extern crate image; extern crate jpeg_decoder; extern crate rayon; extern crate serde; extern crate serde_json; extern crate tinyfiledialogs; extern crate web_view; extern crate yore; #[macro_u...
fn main() { println!("The value is {}!", simple_bindgen::SIMPLE_VALUE); } #[cfg(test)] mod test { #[test] fn do_the_test() { assert_eq!(42, simple_bindgen::SIMPLE_VALUE); } }
extern crate image; use image::{RgbImage}; #[derive(Copy, Clone)] pub struct FastBitmap<'a> { pub img: &'a RgbImage, pub buffer: &'a RgbImage } impl FastBitmap <'_>{ pub fn new<'a>(path: &str) -> Self { let img = image::open(path).unwrap(); let mut buffer: RgbImage = image::ImageBuffer::...
use async_rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard}; use std::{ fmt::{Debug, Display, Formatter}, sync::Arc, }; // RwLock ensures this safeness for us unsafe impl<T: Send + ?Sized> Send for Handle<T> {} unsafe impl<T: Send + Sync + ?Sized> Sync for Handle<T> {} /// Reference-counted async RwLock pub...
use core::mem::size_of; use idt::IdtEntry; #[repr(C, packed)] pub struct DescriptorTablePointer { // Size of the DT. pub limit: u16, // Pointer to the memory region containing the IDT. pub base: *const IdtEntry, } impl DescriptorTablePointer { fn new(slice: &[IdtEntry]) -> Self { let len ...
use crate::WorldPoint; /// Normalized keypoint match #[derive(Debug, Clone, Copy, PartialEq, PartialOrd)] pub struct FeatureMatch<P>(pub P, pub P); /// Normalized keypoint to world point match #[derive(Debug, Clone, Copy, PartialEq, PartialOrd)] pub struct FeatureWorldMatch<P>(pub P, pub WorldPoint);
use crate::builder::TransportRpcModules; use crate::cors; use crate::errors::WsHttpSamePortError; use crate::jsonrpsee::http_client::{HttpClient, HttpClientBuilder}; use crate::jsonrpsee::server::{IdProvider, Server, ServerBuilder, ServerHandle}; use crate::jsonrpsee::ws_client::{WsClient, WsClientBuilder}; use crate::...
use std::fs::File; use std::path::{Path, PathBuf}; use std::sync::Arc; use anyhow::bail; use chrono::{DateTime, Utc}; use log::{info, trace}; use serde::{Deserialize, Serialize}; pub use actor::DumpActor; pub use handle_impl::*; use meilisearch_auth::AuthController; pub use message::DumpMsg; use tempfile::TempDir; us...
use std::default::Default; use std::collections::HashMap; static ABSOLUTE_ERROR: f64 = 1000000.0; #[derive(Default, Clone)] struct FastaData { id: String, dna_strand: String, } fn calc_percentage(input: &str) -> i32 { let count = input.chars().filter(|&c| c == 'G' || c == 'C').count(); (100.0 / inpu...
#[cfg(test)] extern crate speculate; #[path = "tsp.rs"] mod tsp; use crate::tsp::City; use crate::tsp::total_distance; use rand::{thread_rng, Rng}; use rand::rngs::ThreadRng; use std::cmp::Ordering; #[derive(Clone)] struct Individual { chromosome: Vec<usize>, fitness: f64, } impl Individual { fn new(chromosom...
use crate::app::App; use crate::common::{ColorLegend, Colorer}; use crate::layer::Layers; use ezgui::{ Btn, Color, Composite, EventCtx, GeomBatch, HorizontalAlignment, TextExt, VerticalAlignment, Widget, }; use geom::{Distance, Duration, PolyLine}; use map_model::IntersectionID; pub fn delay(ctx: &mut EventCtx...
use std::collections::VecDeque; use generators::Generator; use rand::{thread_rng, Rng}; use bit_vec::BitVec; use cbuffer::CircularBuffer; // Packet holds the value of the time unit that it was generated at and its length. #[derive(Clone, Copy, PartialEq, Debug)] pub struct Packet { pub time_generated: u32, pub...
/* * Copyright 2019 Joyent, Inc. */ #[macro_use] extern crate serde_json; pub mod buckets; pub mod client; pub mod meta; pub mod objects;
mod basic; mod context; mod r#static; use cqrs_core::{Command, CommandHandler, EventSink, EventSource, SnapshotSink, SnapshotSource}; #[doc(inline)] pub use self::{ basic::{ Basic, ExecAndPersistError, LoadError, LoadExecAndPersistError, LoadRehydrateAndPersistError, PersistError, }, conte...
use std::cmp::Ordering; #[derive(Copy, Clone)] pub struct Hash512(pub [u8; 64]); impl Default for Hash512 { fn default() -> Self { Hash512([0u8; 64]) } } impl AsRef<[u8]> for Hash512 { fn as_ref(&self) -> &[u8] { self.0.as_ref() } } impl PartialOrd for Hash512 { #[inline] fn ...
pub struct Solution {} impl Solution { pub fn max_product(words: Vec<String>) -> i32 { if words.len() <= 1 { return 0; } let mut bits = Vec::with_capacity(words.len()); for word in words { let len = word.len(); let mut bit = 0; for ch...
use machine::state::State; use machine::behavior::is::control::bnz; pub fn pbnz(state: &mut State, x: u8, y: u8, z: u8) { bnz(state, x, y, z); }
use hotpatch::*; /// There is a system of trust here /// Foo is assumed to be the same struct everywhere /// This may be possible to lock down even more with typeid, but that's WIP upstream pub struct Foo { pub description: &'static str, } #[patch] impl Foo { /// remember, #[patch] is top-level pub fn new...
use block_tools::{ auth::{optional_token, optional_validate_token}, blocks::Context, display_api::{component::menus::menu::MenuComponent, DisplayMeta, DisplayObject, PageMeta}, models::Block, LoopError, }; use crate::blocks::text_block::TextBlock; impl TextBlock { pub fn handle_page_display( block: &Block, ...
use std::collections::HashMap; pub fn word_count(s: &str) -> HashMap<String, u32> { let mut res = HashMap::new(); for w in s.replace(|c: char| !c.is_alphanumeric(), " ").split_whitespace() { *res.entry(w.to_lowercase().to_string()).or_insert(0) += 1; } res }
mod bt2100tf; use bt2100tf::hlg; use bt2100tf::hlg::DisplayProp; mod lut; fn main() { let display_prop = DisplayProp::new(1.2, 1000, 5); let lut = lut::LutBuilder::new().grid_num(33).finalize(); let mut sample_1d = lut.create_1d_sample(); let orig_1d = lut.create_1d_sample(); lut.normalize(&mut...
use crate::util::*; pub fn go(filename:&str) -> (String,String) { let payload:Vec<u8> = readfile(filename); let payloadstr:String = String::from_utf8(payload).unwrap(); let parts:Vec<&str> = payloadstr.split(',').collect(); let mut ints:Vec<i64> = Vec::new(); ints.resize(parts.len()-1, 0); for i in 0..pa...
#[cfg(feature = "serde_support")] #[macro_use] extern crate serde_derive; #[cfg(feature = "serde_support")] extern crate serde_json; extern crate syn; extern crate quote; #[derive(Debug, Clone)] #[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))] pub enum Visibility { Public, Crate, Rest...
use std::cell::Cell; use std::collections::HashMap; use std::fmt; use std::hash; use std::rc::Rc; #[derive(Clone)] pub struct Ident { name: Rc<str>, id: usize, data: Rc<IdentData> } // data for analysis passes // TODO: make generic somehow // (some kinda compile-time KV store with traits) pub struct Iden...
extern crate image as im; extern crate piston_window; use super::ppu::background::Background; use piston_window::*; pub fn render_backgound(background: &Background) { let colors: [(u8, u8, u8); 64] = [ (0x80, 0x80, 0x80), (0x00, 0x3D, 0xA6), (0x00, 0x12, 0xB0), (0x44, 0x00, 0x96), (0xA1, 0x00, 0...
extern crate rmdb; extern crate time; use rmdb::*; use rmdb::bplustree::*; use rmdb::storage::*; use rmdb::measurement::*; use time::*; use rmdb::utils::*; use std::thread; use std::sync::Arc; use std::rc::Rc; use std::fmt::Debug ; use std::env; fn main() { split_helper(&mut vec![7, 10, 13], &mut vec![1, 2, 3], &...
use js_sys::Uint8Array; use serde::{Deserialize, Serialize}; use wasm_bindgen::JsValue; /// Message Encoding and Decoding Format pub trait Codec { /// Encode an input to JsValue fn encode<I>(input: I) -> JsValue where I: Serialize; /// Decode a message to a type fn decode<O>(input: JsValue...
#![deny(warnings)] use actix_web::{ App, AsyncResponder, Error, HttpMessage, HttpRequest, HttpResponse, http, middleware, server, }; use env_logger; use futures::Future; use serde_derive::{ Serialize, Deserialize }; //TODO: use clap or something to make a nicer interface for this ...
extern crate bitset64; extern crate clap; extern crate env_logger; #[macro_use] extern crate log; extern crate mcmf; extern crate mzsp; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; use mcmf::*; use mzsp::MZSP; use std::collections::BTreeMap; use std::fs::File; fn main() { /...
//! Starts the facade services that allow us to test the Bluetooth stack #[macro_use] extern crate clap; use clap::{App, Arg}; #[macro_use] extern crate lazy_static; use bt_topshim::btif; use futures::channel::mpsc; use futures::executor::block_on; use futures::stream::StreamExt; use grpcio::*; use log::debug; use ...
use ckb_std::{ ckb_constants::Source, ckb_types::{packed::*, prelude::*}, high_level::{load_cell, load_input_since, load_witness_args, QueryIter}, }; use super::hash; use crate::error::Error; use alloc::vec::Vec; pub fn has_input_by_lock_hash(lock_hash: &[u8; 20]) -> bool { QueryIter::new(load_cell, S...
pub struct Solution {} impl Solution { pub fn max_profit(prices: Vec<i32>) -> i32 { prices .iter() .fold((0, None), |(mut profit, prev), price| { if let Some(prev_price) = prev { if price > prev_price { profit += price - pr...
mod format_w3c; pub use self::format_w3c::format_w3c;
use chrono::prelude::*; use serde::{Deserialize, Serialize}; use uuid::Uuid; use crate::types::{ConversationId, ProfileId}; #[derive(Serialize, Deserialize, Debug)] pub enum ChatType { #[serde(rename = "ONE_ON_ONE")] OneOnOne, } #[derive(Serialize, Deserialize, Debug)] pub enum ChatMessageType { #[serde(...
use iron::headers::ContentType; use iron::prelude::*; use iron::AfterMiddleware; use mime::Mime; /// Attempts to guess the content type of the response based on the /// requested URL. Existing content types will not be modified. pub struct GuessContentType { default: Mime, } impl GuessContentType { pub fn ne...
use std::sync::Arc; use parking_lot::RwLock as PLRwLock; use tokio::sync::RwLock; use utp_rs::socket::UtpSocket; use ethportal_api::types::distance::XorMetric; use ethportal_api::HistoryContentKey; use portalnet::{ discovery::{Discovery, UtpEnr}, overlay::{OverlayConfig, OverlayProtocol}, storage::{Portal...
// Copyright 2018 Lyndon Brown // // This file is part of the `gong` command-line argument processing library. // // Licensed under the MIT license or the Apache license (version 2.0), at your option. You may not // copy, modify, or distribute this file except in compliance with said license. You can find copies // of ...
use std::fmt; use async_trait::async_trait; use erased_serde::serialize_trait_object; use futures::future::BoxFuture; use serde::{ ser::{SerializeStruct, Serializer}, Deserialize, Serialize, }; use serde_json::json; use crate::{event::Event, pointer, HapType, Result}; mod generated; pub use generated::*...
use crate::world_node::{WorldNode, WorldNodeMutableRc}; use crate::id_controller::IdController; use std::collections::HashMap; ///A world containing World Objects organized in a tree hiararchy, with it's initial ///element being the root object. ///All World Objects must have different Ids. ///Cycles will cause the pro...
use pyo3::prelude::*; use pyo3::types::PyDict; use pyo3::wrap_pymodule; pub mod buf_and_str; pub mod datetime; pub mod dict_iter; pub mod misc; pub mod objstore; pub mod othermod; pub mod pyclass_iter; pub mod subclassing; use buf_and_str::*; use datetime::*; use dict_iter::*; use misc::*; use objstore::*; use otherm...
fn maj(ints: &[u16]) -> Option<u16> { let mut counter = 0; let mut maj = ints[0]; for &int in &ints[1..] { if counter == 0 { maj = int; } counter += if int == maj { 1 } else { -1 }; } if ints.iter().filter(|&&x| x == maj).count() * 2 <= ints.len() { None ...
use x86_64::structures::idt::Idt; use x86_64::structures::idt::ExceptionStackFrame; use memory::MemoryController; use x86_64::structures::tss::TaskStateSegment; use x86_64::VirtualAddress; const DOUBLE_FAULT_IST_INDEX: usize = 0 ; use spin::Once ; static TSS: Once<TaskStateSegment> = Once::new(); static GDT: Once<...
use pipe::pipe; use std::io::copy; use std::io::Cursor; use std::io::Read; use std::thread; pub fn diff(source: Vec<u8>, target: Vec<u8>) -> (Vec<u8>, usize) { // Calculate patch let (mut patch_reader, mut patch_writer) = pipe(); thread::spawn(move || { bidiff::simple_diff(&source[..], &target[..]...
use imap_proto::types::Quota as QuotaRef; use imap_proto::types::QuotaResource as QuotaResourceRef; use imap_proto::types::QuotaResourceName as QuotaResourceNameRef; use imap_proto::types::QuotaRoot as QuotaRootRef; /// <https://tools.ietf.org/html/rfc2087#section-3> #[derive(Debug, Eq, PartialEq, Hash, Clone)] pub en...
// Lumol, an extensible molecular simulation engine // Copyright (C) 2015-2016 G. Fraux — BSD license use rand::RngCore; use rand_distr::{Distribution, Uniform, UnitSphere}; use std::collections::BTreeSet; use std::f64; use std::usize; use log::warn; use log_once::warn_once; use soa_derive::soa_zip; use super::{MCD...