text
stringlengths
8
4.13M
pub const NUMENTS: usize = 1024;
use std::error::Error; use std::ffi::OsString; use std::fmt; use std::fmt::{Debug, Formatter}; use mysql_async::{FromRowError, Row}; use mysql_async::prelude::FromValue; use serde::{Deserialize, Serialize}; use crate::api::generic::ReadableError; pub mod connection_pool; pub mod paging; pub mod account_util; pub mod...
use serde::{Deserialize, Serialize}; use sha256::digest; const DIFFICULTY: &str = "0000"; const REWARD_AMOUNT: usize = 90; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Block { pub index: usize, pub previous_hash: String, pub timestamp: String, pub tx: Transaction, pub hash: String, ...
// This file is part of Substrate. // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // 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.a...
use serde_json::{Value, Map}; use Segment; use ResultSet; use std::process::Command; use themes::*; use std::str; use prompt::Prompt; pub struct StdoutSegment{ pub options: Option<Map<String, Value>> } impl Segment for StdoutSegment { fn compute(&self, prompt: &Prompt) -> ResultSet { if let Some(ref o...
use common::*; #[derive(Debug)] pub struct ToyFile { pub scenes: Vec<SceneData>, pub entities: Vec<EntityData>, pub meshes: Vec<MeshData>, } #[derive(Debug)] pub struct SceneData { pub name: String, pub entities: Vec<u16> } #[derive(Debug)] pub struct EntityData { pub name: String, pub mesh_id: u16, pub pos...
ApBegin(RS,CLSID_USSDAPP) WndBegin(USSD_WND_DUAL_SIM) WdgBegin(CLSID_VTMSIMSELECTION,DualSim) VtmCreateSimSelectionRC({0,TXT_LIL_N_USSD}) WdgEnd(CLSID_VTMSIMSELECTION,DualSim) WndEnd(USSD_WND_DUAL_SIM) WndBegin(USSD_WND_REPLY) WndSetAllSoftkeyRC({SK_OK_TEXT, SK_OK, SK_C...
use anyhow::{ensure, Context, Result}; use cargo_metadata::{Metadata, MetadataCommand, Package, PackageId}; use indexmap::{IndexMap, IndexSet}; use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use structopt::StructOpt; /// List the newly added dependencies a...
mod binary_heap; mod context; mod manager; mod pid; mod processor; mod stride_scheduler; mod switch; mod task; use switch::__switch; use task::{TaskControlBlock, TaskStatus}; use alloc::sync::Arc; use manager::fetch_task; use lazy_static::*; use crate::fs::{open_file, OpenFlags, remove_mailbox}; pub use context::Task...
ApBegin(QvgaP,CLSID_CALCULATORPLUSAPP) ApEnd(QvgaP,CLSID_CALCULATORPLUSAPP)
use crate::{HashM, HashMt}; use std::ptr::{null_mut}; use std::marker::PhantomData; use std::collections::VecDeque; unsafe impl<V> Send for LinkedMap<V> {} unsafe impl<V> Sync for LinkedMap<V> {} #[derive(Debug)] pub struct LinkedMap<V>{ map : HashM<u64, Box<MutNode<V>>>, first : *mut MutNode<V>, last : *...
use serde::Deserialize; #[allow(non_snake_case)] #[derive(Deserialize, Debug, Clone)] pub struct Location{ pub country: String, pub countryInfo: CountryInfo, pub cases: i32, pub todayCases: i32, pub deaths: i32, pub todayDeaths: i32, pub recovered: i32, pub active: i32, pub critica...
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::ISR { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W...
// -*- rust -*- type list = tag(cons(int,@list), nil()); fn main() { cons(10, @cons(11, @cons(12, @nil()))); }
use std::fs; use std::io; use std::path::{Path, PathBuf}; use tempfile::{tempdir, TempDir}; use fs::{Fs, OpenOptions}; /// Provides access to file I/O in a chroot-like temporary filesystem, located in the system's /// default temp directory. This temporary directory acts like the root of the filesystem: all /// abso...
use http::Request; use server::Server; mod http; mod server; // to find the server module in the server.rs file fn main() { // rust has two types of strings // String which is a string, it has dynamic length. // And &str is a string slice -> an immutable refrence to a part of a string, meaning it has a fi...
use env_logger; use log::info; use std::error::Error; use std::{ fs::File, io::{stdout, Write}, }; use structopt::StructOpt; use ongeki_data::{ AtokDictionaryEntry, CharactersDefinition, EmitDictionary, GeneralDefinition, MsimeDictionaryEntry, SkkDictionaryEntry, SongsDefinition, }; /// オンゲキ SKK 辞書生成ツ...
fn say_hello() { println!("Hello, World!\n"); } fn say_һello() { println!("Goodbye, World!\n"); } fn main() { say_һello(); }
use advent_of_code_2015::{read, parse_lines}; use itertools::Itertools; use nom::character::complete::alpha1; fn is_nice(input: &str) -> bool { has_voyels(input) && has_double(input) && !has_badies(input) } fn has_voyels(input: &str) -> bool { let mut voyels = 0; for c in input.chars() { if c == ...
// This is a part of Chrono. // See README.md and LICENSE.txt for details. //! A collection of parsed date and time items. //! They can be constructed incrementally while being checked for consistency. use super::{ParseResult, IMPOSSIBLE, NOT_ENOUGH, OUT_OF_RANGE}; use crate::naive::{NaiveDate, NaiveDateTime, NaiveTi...
extern crate clap; use clap::{Arg, App, value_t_or_exit}; use std::io::{BufWriter, Write}; use std::io; fn new_state(x: usize, y: usize) -> Vec<Vec<bool>> { let mut xs = Vec::<Vec<bool>>::with_capacity(x); // let mut is_even = true; for i in 0..x { let v = i == 2; xs.push((0..y).map(|_| v)...
use super::business_class::BusinessObject; use super::messagesets::*; use super::msgfactoryclass::*; use super::prodconditions::*; #[derive(Debug)] pub struct Prodmsgclass { // pub business_object: BusinessObject, pub the_msgfactory: Msgfactoryclass, } impl Prodmsgclass { pub fn new( //business_...
#[cfg(feature = "gst")] #[macro_use] extern crate failure; #[cfg(feature = "gst")] extern crate gstreamer as gst; #[cfg(feature = "gst")] extern crate gstreamer_app as gst_app; #[cfg(feature = "termion")] extern crate termion; extern crate image; /// The converters themselves pub mod converters; /// High-level interac...
extern crate advent_of_code_2017; extern crate clap; use clap::{Arg, App}; use advent_of_code_2017::*; macro_rules! day { ($day:ident => $path:expr) => ({ let file_contents = file_as_string($path); $day::from_str(&file_contents).run(); }) } pub fn main() { let matches = App::new("Advent ...
mod inp; use inp::Inp; use std::collections::HashSet; fn main() { let mut inp = Inp::new(); let (today, month) = { let mut l = inp.next_line().trim().split(' '); (l.next().unwrap().parse::<u16>().unwrap(), match l.next().unwrap() { "JAN" => 0, "FE...
// Topic: HashMap // // Requirements: // * Print the name and number of items in stock for a furniture store // * If the number of items is 0, print "out of stock" instead of 0 // * The store has: // * 5 Chairs // * 3 Beds // * 2 Tables // * 0 Couches // * Print the total number of items in stock // // Notes: /...
mod _schemas; use protobuf::Message; use _schemas::ping::*; fn main() { let client = nats::connect("nats://127.0.0.1:4222").unwrap(); let sub = client.subscribe("ping2").unwrap(); for msg in sub.messages() { let ping_request = PingRequest::parse_from_bytes(&msg.data).unwrap(); let mut p...
use failure::Error; use std::collections::HashMap; use std::rc::Rc; use IString; use { AnyFunction, Arguments, BuiltinFunctionPrototype, CreateFunctionResult, DataGenOutput, DynStringFun, FunctionPrototype, GenType, ProgramContext, RunnableFunction, }; fn create_env_map() -> HashMap<IString, IString> { le...
#[macro_use] extern crate failure; pub mod engine; use std::rc::Rc; fn main() { let sdl = Rc::new(sdl2::init().unwrap()); let video_subsystem = sdl.video().unwrap(); let gl_attr = video_subsystem.gl_attr(); gl_attr.set_context_profile(sdl2::video::GLProfile::Core); gl_attr.set_context_versio...
use common::{default_puzzle, Puzzle}; fn captcha(digits: Vec<u8>, distance: usize) -> u64 { let mut sum = 0; let len = digits.len(); for i in 0..len { let this = digits[i]; let next = digits[(i + distance) % len]; if this == next { sum += this as u64; } } ...
use super::fund::*; /*** --- Line --- ***/ #[derive(Debug)] pub struct Line { x1: u16, y1: u16, x2: u16, y2: u16, stroke: Stroke, } impl Line { pub fn new(x1: u16, y1: u16, x2: u16, y2: u16, stroke: Stroke) -> Line { Line { x1: x1, y1: y1, x2: x2, ...
use cgmath::MetricSpace; use formats::lev; use crate::context::Context; use crate::loader::{Loader, LoaderResult}; use crate::mesh::{Mesh, MeshBuilder, Vertex}; use level_geometry::triangulate_sector; pub struct Level { pub textures: Vec<wgpu::Texture>, pub mesh: Mesh, } impl Level { pub fn load(loader:...
extern crate tokio_service; extern crate hyper; extern crate futures; #[macro_use] extern crate log; mod message; mod request; mod response; pub use message::Message; pub use request::Request; pub use response::Response; pub use hyper::Error; pub use hyper::server::{Request as HyperRequest, Response as HyperResponse...
use std::time::Instant; #[derive(Debug, Clone)] pub struct Timer { start: Option<Instant>, end: Option<Instant>, } impl Timer { pub fn new() -> Self { Self { start: None, end: None, } } pub fn start(&mut self) { self.start = Some(Instant::now()); ...
#[doc = "Register `RESULT` reader"] pub struct R(crate::R<RESULT_SPEC>); impl core::ops::Deref for R { type Target = crate::R<RESULT_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<RESULT_SPEC>> for R { #[inline(always)] fn from(reader: crate::R...
pub mod cyclic_group; pub mod probability;
extern crate mio; extern crate chrono; use std::mem; use std::time::{Duration, Instant}; use std::str::FromStr; use std::net::SocketAddr; use mio::timer::{Timer}; #[derive(Debug, Eq, PartialEq, Hash, Clone)] pub enum SessionTimerPacketType { // [QoS.1.send] Receive PUBACK timeout RecvPubackTimeout, // [...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2 pub use self::gen_client::Client as NodeManagerClient; use crate::FutureResult; use openrpc_derive::openrpc; use starcoin_crypto::HashValue; use starcoin_service_registry::{ServiceInfo, ServiceStatus}; #[openrpc] pub trait NodeManage...
pub fn search(nums: &mut Vec<i32>, target: i32) -> i32 { let mut first: usize = 0; let mut last = nums.len() as usize; while first != last { let mut mid = (first + (last - first) >> 1) as usize; if nums[mid] == target { return mid as i32; } if nums[first] <= nums[mid] { i...
//! High-level APIs for libseccomp. mod libseccomp; use libseccomp::*; use std::ffi::CString; use std::ops::Deref; use std::os::unix::process::CommandExt as _; use std::process::Command; use nix; /// Syscall wrapper. pub struct Syscall(u32); impl Syscall { /// Resolve the name of a syscall. /// /// Pani...
use anyhow::Result; use ini_parser::Ini; use std::fs; fn main() -> Result<()> { let ini_str = fs::read_to_string("test.ini")?; let ini = Ini::parse(&ini_str)?; println!("{:?}", ini.get_section("author")); Ok(()) }
//! A vector which has gap inside the buf implemented with a growable ring buffer. use crate::raw_vec::RawVec; pub struct GapVec<T> { buf: RawVec<T>, head: usize, tail: usize, gap_begin: usize, gap_end: usize, }
use graph::*; use errors::*; use ops::interface::default::*; use super::super::ids; use std::ops::{Add, Neg, Sub, Mul, Div, DerefMut}; use std::convert::AsRef; //use std::borrow::Borrow; pub fn add<T1: AsRef<Expr>, T2: AsRef<Expr>>(arg0: T1, arg1: T2) -> Result<Expr> { let arg0 = arg0.as_ref(); let arg1 = arg...
// this is if you didnt care about object making a call, just something inside that object // like for example the id // traits have no idea about any ot fns or vars on the thing that called it. pub trait Ided { fn my_id(&self) -> i64; }
use async_trait::async_trait; use uuid::Uuid; use crate::{pairing::Pairing, server::ServerPersistence, Config, Result}; /// `Storage` is implemented by the data storage methods HAP supports. Currently, that's just `FileStorage`. #[async_trait] pub trait Storage: Send + Sync { /// Loads the `Config` from the `Stor...
use super::{Context, Module}; use crate::config::ModuleConfig; use crate::configs::env_var::EnvVarConfig; use crate::formatter::StringFormatter; use crate::segment::Segment; /// Creates `env_var_module` displayer which displays all configured environmental variables pub fn module<'a>(context: &'a Context) -> Option<M...
use diesel::query_dsl::RunQueryDsl; use reqwest::Client; use select::document::Document; use select::node::Node; use select::predicate::{Class, Name, Predicate}; use crate::IO; use crate::db::{Attribution, Conn}; use crate::wikidot::Wikidot; use crate::db::attribution; const URL: &str = "http://www.scp-wik...
use clap::{App, Arg}; #[derive(Debug)] pub struct Params { pub symbol: String, pub count: i32, pub exchange: String, } pub fn parse() -> Result<Params, ()> { let matches = App::new("Exchange Crawler") .version("1.0") .author("JeongTae <pjt3591oo@gmail.com>") .about("crawler execution options") ...
//! Allow a thread/task, crossing sync/async boundaries in either direction, to //! deliver an expected piece of data to another thread/task, with //! notification. //! //! These are simple channels used to deliver data from one endpoint to //! another, where the receiver will block until data has been delivered. mod ...
use bigdecimal::BigDecimal; use num_bigint::BigInt; use num_rational::BigRational; use num_traits::Pow; use core::ops::{Add, Div, Mul, Sub}; use serde::{Deserialize, Deserializer}; #[derive(Clone, Debug, Serialize)] pub struct MmNumber(BigRational); pub fn from_ratio_to_dec(r: &BigRational) -> BigDecimal { BigDec...
use std::collections::HashMap; fn part_1(input: i32) -> i32 { if input == 1 { 0 } else { let outer = (0i32..).map(|x| (2*x+1, (2*x + 1).pow(2))) .skip_while(|x| x.1 < input).nth(0).unwrap(); let pos = (outer.1 - input) % (outer.0 - 1); // distance from corner match o...
mod buf_read_iter; mod buf_read_or_reader; mod input_buf; mod input_source; use std::io; use std::io::BufRead; use std::io::Read; use std::mem; use std::mem::MaybeUninit; #[cfg(feature = "bytes")] use ::bytes::Bytes; #[cfg(feature = "bytes")] use crate::chars::Chars; use crate::coded_input_stream::buf_read_iter::Buf...
fn main() { proconio::input! { n: usize, mut x: usize, an: [usize; n], } // println!("{}", x); // println!("{:?}", an); let mut secrets = vec![0; n]; loop { // 秘密を話す相手 let a = an[x-1]; // 秘密を知っているかどうか let is_secrets = secrets[x-1]; //...
#![feature(phase)] #[phase(syntax)] extern crate log; #[phase(syntax)] extern crate oxidize_macros; extern crate oxidize; extern crate collections; extern crate log; extern crate sync; use oxidize::router::Router; use oxidize::common::{method}; use oxidize::{App, Config, Oxidize, Request, Response}; use oxidize::bac...
// This file is part of Substrate. // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // 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.a...
extern crate itertools; // use itertools::{kmerge, merge}; use itertools::Itertools; fn main() { // for elt in kmerge(vec![vec![0, 2, 4], vec![1, 3, 5], vec![6, 7]]) { // println!("{}", elt); // } // for elt in merge(&[1, 2, 3], &[2, 3, 4]) { // println!("{}", elt); // } // println!("---"); let ...
pub mod graph; pub mod adjacency_list; use graph::*; use adjacency_list::*; #[test] fn test_graph_contains_zero ( ) { let elements = vec![(0, 1), (1, 2), (1, 3), (3, 4), (0, 4)]; let g = adjacency_list::adj_list(elements.as_slice()); let v: i32 = 0; assert![ g.vertices().contains(&v) ]; } #[test] fn ...
use crate::parser::core::{capture, match_exact}; use crate::parser::util::optional_matches; use crate::parser::RouteParserToken; use nom::branch::alt; use nom::character::complete::char; use nom::combinator::{map, opt}; use nom::error::{context, VerboseError}; use nom::multi::many1; use nom::sequence::pair; use nom::IR...
#![allow(dead_code)] extern crate serde; extern crate serde_json; #[macro_use] extern crate serde_derive; extern crate time; extern crate curl; extern crate log; extern crate smpl_jwt; pub mod error; pub mod auth; pub mod scopes; pub mod credentials; use error::GOErr; use auth::{Token, JwtClaims}; use credentials::C...
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4}; use chrono::{Duration, UTC, DateTime}; use bt::{self, NodeId}; use net::IpAddr; /// Allows us to time travel into the future. pub fn travel_into_future(offset: Duration) -> DateTime<UTC> { UTC::now().checked_add(offset).unwrap() } /// Allows us to ti...
use crate::my_strategy::UnitOrder; use crate::DebugInterface; use itertools::{Itertools, MinMaxResult}; use model::*; use std::collections::HashMap; pub fn display_turret_fields(player_view: &PlayerView, debug_interface: &mut DebugInterface) { for turret in player_view.entities.iter().filter(|e| { use Enti...
use super::WindowMap; use rand; use smithay::wayland::compositor::{compositor_init, CompositorToken, SurfaceAttributes, SurfaceUserImplementation}; use smithay::wayland::shell::{shell_init, PopupConfigure, ShellState, ShellSurfaceRole, ShellSurfaceUserImp...
// This file is part of Substrate. // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // 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.a...
use part02::pokemon::Pokemon; pub struct Pokeball { pub pokemon: Pokemon, } impl Pokeball { pub fn new(pokemon_to_add: Pokemon) -> Pokeball { //Create the object & return. Pokeball { pokemon: pokemon_to_add, } } pub fn ouvrir(mut self) -> Pokemon { println!...
use crate::qrcode::detector::finder_pattern::FinderPattern; pub struct FinderPatternInfo { pub bottom_left: FinderPattern, pub top_left: FinderPattern, pub top_right: FinderPattern, }
use std::cmp::Ordering; #[derive(Clone, Debug)] pub struct Job { run_id: usize, job_id: usize, } impl Job { pub fn new(run_id: usize, job_id: usize) -> Self { Job { run_id, job_id } } } // manual ordering implemented because we want the jobs to sorted in reverse order impl PartialOrd for Job ...
use abscissa_core::{Command, Options, Runnable}; use ibc::ics02_client::client_state::ClientState; use ibc::ics24_host::identifier::{ChainId, ChannelId, PortId}; use ibc_proto::ibc::core::channel::v1::{ QueryPacketAcknowledgementsRequest, QueryUnreceivedAcksRequest, }; use ibc_relayer::chain::counterparty::channel...
use crate::battle::Battle; use super::{prep_cast, Spell}; #[derive(Debug, Clone)] pub struct MagicMissile; impl Spell for MagicMissile { fn cast(&self, battle: &mut Battle) -> Option<u32> { match prep_cast(battle, self.cost(), None) { true => { battle.boss.guard(4); ...
#[allow(unused_imports)] use std::cmp::{max, min}; #[allow(unused_imports)] use std::collections::{HashMap, HashSet}; #[allow(unused_imports)] use std::io::*; #[allow(unused_imports)] use std::str::*; #[allow(dead_code)] fn read<T: FromStr>() -> T { let cin = stdin(); let cin = cin.lock(); let s: String = ...
pub mod heap; pub mod representation; pub mod heap_size; pub mod gc_heap;
// * Daily Coding Problem November 23 2020 // * [Easy] -- Snapchat // * Given an array of time intervals (start, end) for classroom lectures (possibly overlapping), // * find the minimum number of rooms required. // ! Ex: [(30, 75), (0, 50), (60, 150)] ==> 2 classrooms fn rooms_needed(classes: &Vec<(u32, u32)>) -> ...
use std::sync::{Arc, Mutex}; use std::sync::mpsc; use std::time::Duration; use std::thread::{self, sleep}; use logic::Stage; use networking::UDPSocket; #[derive(Debug, Clone)] /// A struct that represents a chaser in the backend pub struct Chaser { /// A list of ids of switches, which are part of this chaser ...
use std::collections::BinaryHeap; impl Solution { pub fn last_stone_weight(stones: Vec<i32>) -> i32 { let mut max_heap = BinaryHeap::from(stones); while 2 <= max_heap.len() { let v1 = max_heap.pop().unwrap(); let v2 = max_heap.pop().unwrap(); let diff = (v1 - v2)...
use std::num; use std::net; #[derive(Debug)] pub enum IpError { ParseInt(num::ParseIntError), Format } impl From<num::ParseIntError> for IpError { fn from(err: num::ParseIntError) -> IpError { IpError::ParseInt(err) } } /// Format an ipv4 address string from /proc/net and returns a Ipv4Addr /...
use std::fs; // Problem: // This file contains numbers from 1 to 100_000, except for one number. // which number is missing? // https://gist.githubusercontent.com/knowitkodekalender/f962392f90e181377dd51de6abe3b480/raw/c0ef3c2762d3f7bf9016b06d2d6b1fdce58f36cd/numbers.txt fn main() { let numbers = fs::read_to_stri...
use crate::context::Web3Context; use crate::providers::{CallProvider, SendProvider}; use async_trait::async_trait; use std::marker::Unpin; use web3::contract::tokens::{Detokenize, Tokenize}; use web3::contract::Contract; use web3::contract::Options; use web3::transports::Http; use web3::types::{Address, TransactionRece...
use anyhow::Result; use iota_streams_ddml::{ command::{ sizeof, unwrap, wrap, }, io, }; pub trait ContentSizeof<F> { fn sizeof<'c>(&self, ctx: &'c mut sizeof::Context<F>) -> Result<&'c mut sizeof::Context<F>>; } pub trait ContentWrap<F, Store>: ContentSizeof<F> { fn wrap<'...
use std::fs::File; use std::io::Read; use std::iter::FromIterator; use std::str; fn spin(programs: &mut Vec<char>, size: usize) { for _ in 0..size { let foo = programs.pop().unwrap(); programs.insert(0, foo); } } #[test] fn test_spin() { let mut programs = vec!['a', 'b', 'c', 'd', 'e']; ...
extern crate bip_metainfo; extern crate walkdir; #[macro_use] extern crate clap; use std::fs::{self,File}; use std::path::PathBuf; use std::io::Read; use std::error::Error; use std::collections::LinkedList; use walkdir::WalkDir; use bip_metainfo::MetainfoFile; #[cfg(test)] mod tests { #[test] fn it_works() ...
use std::borrow::Borrow; use ark_crypto_primitives::crh::{ pedersen::{ constraints::{CRHGadget, CRHParametersVar}, Window, }, CRHSchemeGadget, }; use ark_ec::CurveGroup; use ark_ff::Field; use ark_r1cs_std::{ prelude::{AllocVar, AllocationMode, CurveVar, GroupOpsBounds}, uint8::UInt...
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::common; use move_core_types::{ account_address::AccountAddress, language_storage::{ModuleId, TypeTag}, }; use serde_generate::{ indent::{IndentConfig, IndentedWriter}, rust, CodeGeneratorConfig, }; use starcoi...
pub mod encdec { #![allow(arithmetic_overflow)] use bytes::Buf; use std::fs::File; use std::io::Cursor; use std::io::Read; use std::mem; use std::path::Path; use std::ptr; use std::str; pub trait Packet { fn get_header(&self) -> &MsgHeader; } //MsgHeader defines ...
use crate::service::{Service}; use crate::app::{App, AppContext}; use crate::service::message::MessageService; #[derive(Clone)] pub struct RunTask(pub &'static dyn Task); #[derive(Clone)] pub struct TaskService { app: App, } pub trait Task { fn run(&self, app: &App); } impl TaskService { fn run_task(&se...
/// file auth crypt using keystore type use blake2_rfc::blake2b::Blake2b as Blake2b; use rayon::prelude::*; use std::fs::OpenOptions; use std::io::Write; use std::time::Instant; use ::chashmap::CHashMap; use ::cipher::Cipher as Cipher; use ::key_store::KeyStore as KeyStore; // impl zeroing password type pub struct Cr...
pub fn step(v: f64, step: f64) -> f64 { (v / step).round() * step } pub fn map_range((ra, rb): (f64, f64), (ma, mb): (f64, f64), v: f64) -> f64 { let r = rb - ra; if r == 0.0 { return (ma + mb) / 2.0; } ma + (v - ra) / r * (mb - ma) } pub fn map_sin((ma, mb): (f64, f64), v: f64) -> f64 { ...
pub fn repeater(string: &str, n: u32) -> String { string.repeat(n as usize) } #[cfg(test)] mod tests { use super::*; #[test] fn basic_test() { assert_eq!(repeater("a", 5), "aaaaa"); assert_eq!(repeater("Na", 16), "NaNaNaNaNaNaNaNaNaNaNaNaNaNaNaNa"); assert_eq!(repeater("Wub ", ...
/// This file should not be changed use std::path::PathBuf; // the signature must be this /// Global IRust variables accessible to the script pub struct GlobalVariables { /// Current directory that IRust is in pub current_working_dir: PathBuf, /// Previous directory that IRust was in, this current director...
#![feature(proc_macro_hygiene, decl_macro)] use rocket::{get, response::Redirect, routes}; mod engines; use engines::{amazon, dev, docker, github, gmail, google, reddit, twitter, youtube}; #[get("/")] fn index() -> &'static str { "Hello, world!" } #[get("/search?<q>")] fn search(q: String) -> Redirect { let ...
use { crate::{ makepad_micro_serde::*, makepad_platform::*, makepad_collab_protocol::{CollabRequest, CollabClientAction}, makepad_collab_server::{CollabConnection, CollabServer}, }, std::{ env, io::{Read, Write}, net::{TcpListener, TcpStream}, ...
#[macro_use] extern crate serde_derive; extern crate rmp_serde as rmps; use crate::rmps::Serializer; use serde::Serialize; #[test] fn pass_unit_struct() { #[derive(Serialize)] struct Unit; let mut buf = Vec::new(); Unit.serialize(&mut Serializer::new(&mut buf)).unwrap(); // Expect: []. asse...
use clouseau::query::Context; use clouseau::*; use std::fmt::Debug; #[derive(Default, Debug, Queryable)] pub struct Custom { a: i64, b: String, #[clouseau(skip)] c: i64, } #[test] fn skipped_field_is_not_a_member() { let root = Custom { a: 4, b: String::from("hi"), c: 7, ...
use anyhow::Result; #[derive(Debug, PartialEq, Clone, Copy)] pub enum Command { MotorSpeedAndDirection, MotorMaxSpeed, SpeedDamping, I2CAddress, LoadDefaultValues, EncoderPosition, GotoPosition, RelativeGotoPosition, SpeedFeedbackGain, PGain, IGain, AutoCalibrateSpeedFee...
fn main() { let mut scan = Scanner::default(); let t: u64 = scan.next(); for _ in 0..t { let mut cnt = 0; let nrows: u64 = scan.next(); let _ncols: u64 = scan.next(); for _ in 1..nrows { let row: String = scan.next(); if row.chars().last().unwrap() == ...
use std::{ any::{type_name, Any, TypeId}, collections::HashMap, convert::TryFrom, fmt, marker::PhantomData, sync::{atomic::AtomicPtr, Arc}, }; use async_trait::async_trait; use cqrs_core::Event; #[async_trait(?Send)] pub trait EventHandler<Ev: ?Sized> { type Context: ?Sized; type Err; ...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use starcoin_crypto::HashValue; use starcoin_vm_types::vm_status::DiscardedVMStatus; use std::error::Error; use thiserror::Error; pub type ExecutorResult<T> = anyhow::Result<T, BlockExecutorError>; #[derive(Error, Debug)] pub enum...
// Lumol, an extensible molecular simulation engine // Copyright (C) 2015-2016 Lumol's contributors — BSD license //! Read static string using the XYZ file format, and create the corresponding //! system. use types::Vector3D; use sys::{System, Particle}; use sys::guess_bonds; /// Read the `content` string, assuming ...
//! Log Sequence Number (LSN) type for PostgreSQL Write-Ahead Log //! (WAL), also known as the transaction log. use bytes::BytesMut; use postgres_protocol::types; use std::error::Error; use std::fmt; use std::str::FromStr; use crate::{FromSql, IsNull, ToSql, Type}; /// Postgres `PG_LSN` type. #[derive(Clone, Copy, E...
use blend::Blend; use libflate::gzip::Decoder; use std::{ env, fs::File, io::{self, BufWriter, Read, Write}, path::{self, PathBuf}, }; fn print_blend(file_name: impl AsRef<str>) -> Result<(), io::Error> { let file_name = file_name.as_ref(); let base_path = path::PathBuf::from( env::var_...
//! rustdoc handler use super::pool::Pool; use super::file::File; use super::MetaData; use iron::prelude::*; use iron::{status, Url}; use iron::modifiers::Redirect; use router::Router; use super::match_version; use super::error::Nope; use super::page::Page; use rustc_serialize::json::{Json, ToJson}; use std::collecti...
// Copyright 2018-2021 Cargill Incorporated // // 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...