text
stringlengths
8
4.13M
use proconio::{fastout, input}; use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign}; const MOD: i64 = 1_000_000_007; #[derive(Debug, PartialEq, Clone)] struct Mint(i64); impl Mint { fn new(x: i64) -> Self { Self((x % MOD + MOD) % MOD) } fn pow(mut self, t: i64) ->...
#[macro_use] extern crate clucolor; mod macros; mod macros_init; mod def_static_log; pub mod log_core; pub mod log_union; pub mod log_shape; mod log_write; mod log_file; pub use self::log_file::*; use crate::log_core::LogStatic; use std::sync::Once; use std::sync::ONCE_INIT; pub use self::log_write::*; sta...
use std::marker::PhantomData; use std::any::{Any}; use std::rc::Rc; use std::sync::atomic::AtomicIsize; use observable::*; use subscriber::*; use unsub_ref::UnsubRef; use std::sync::Arc; use std::sync::atomic::Ordering; pub struct SkipOp<Src, V> where Src : Observable<V> { source: Src, total: isize, Phant...
pub fn delete_duplicates(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> { let mut dummy = Box::new(ListNode { val: 0, next: head, }); fn recursive_remove(head: &mut Box<ListNode>) { if let Some(mut reference) = head.next.take() { while let Some(next) = reference.n...
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ use serde::Deserialize; use serde::Serialize; use crate::filter::Filter; #[derive(Clone, Default,...
#![forbid(unsafe_code)] #![doc(html_favicon_url = "https://raw.githubusercontent.com/kyleu/rustimate/master/crates/assets/embed/favicon.ico")] #![doc(html_logo_url = "https://raw.githubusercontent.com/kyleu/rustimate/master/crates/assets/embed/favicon.png")] #![doc(issue_tracker_base_url = "https://github.com/kyleu/rus...
//! An isotropic scattering function, to be used with a volume. use crate::{ hittable::HitRecord, material::{Scatter, ScatterType}, ray::Ray, texture::Texture, vec3::Vec3, }; use rand::prelude::*; /// An isotropic scattering function. Rays have a chance of scattering, and will /// scatter in a uni...
//use rand::Rng; use crate::vector::Vector; #[derive(PartialEq)] pub enum BulletType { Player(bool), Swarm, } pub struct Bullet { pub location: Vector, pub bullet_type: BulletType, speed: f64, } impl Bullet { pub fn new(spawn_location: Vector, bullet_type: BulletType, speed: f64) -> Bullet { Bullet { ...
extern crate csv; extern crate rand; #[macro_use] extern crate serde_derive; use std::error::Error; use std::io; use std::process; use std::fmt; // #[macro_use] // extern crate rust_nn; #[macro_export] macro_rules! matrix { [$name: ident, $rows:expr; $columns:expr] => { pub struct $name { da...
#[derive(Clone, Debug, PartialEq, Eq, Copy, PartialOrd, Ord, Hash)] #[repr(i32)] pub enum Register { RAX = 0, RCX = 1, RDX = 2, RBX = 3, RSP = 4, RBP = 5, RSI = 6, RDI = 7, R8 = 8, R9 = 9, R10 = 10, R11 = 11, R12 = 12, R13 = 13, R14 = 14, R15 = 15, RIP...
use crate::core::clients::{StorageAccountClient, StorageClient}; use crate::table::requests::ListTablesBuilder; use bytes::Bytes; use http::method::Method; use http::request::{Builder, Request}; use std::sync::Arc; use url::Url; pub trait AsTableServiceClient { fn as_table_service_client(&self) -> Result<Arc<Table...
#[derive(Debug)] struct Printable(i32); #[derive(Debug)] struct Deep(Printable); #[derive(Debug)] struct Person<'a> { name: &'a str, age: u8 } fn main() { println!("{:?} months in a year", 12); println!("{1:?} {0:?} is the {actor:?} name", "Slater", "Christian", actor="actor's"); println...
use std::sync::Arc; use crate::_utils::error::SecurityError; #[derive(Debug)] pub struct RateLimitConstraint { pub id: String, pub max_requests: u32, pub duration_ms: u32, } pub struct SecurityService { rate_limit_kv_db: Arc<sled::Db>, } impl SecurityService { pub fn new(rate_limit_kv_db: Arc<sled::Db>) -...
#![doc = "generated by AutoRust 0.1.0"] #![allow(unused_mut)] #![allow(unused_variables)] #![allow(unused_imports)] use crate::models::*; use reqwest::StatusCode; use snafu::{ResultExt, Snafu}; pub mod operations { use crate::models::*; use reqwest::StatusCode; use snafu::{ResultExt, Snafu}; pub async f...
pub(crate) mod value_objects; use std::fmt::Debug; use serde::{Deserialize, Serialize}; use crate::domain::value_objects::{ CreatedAt, CreatedBy, Datasets, EndDate, Funders, Grants, HowToCite, Shortcode, StartDate, TeaserText, ID, }; #[derive(Debug, Default, PartialEq, Deserialize, Serialize)] pub struct Me...
use serde::{Deserialize, Serialize, Serializer, Deserializer}; use serde::de::{self, Visitor, Error}; use std::str::FromStr; #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Ticker { pub high: String, pub last: String, pub timestamp: String, pub bid: String, pub vwap: ...
extern crate clap; use std::path::Path; use clap::Arg; use crate::app::App; mod app; mod git; mod svn; mod utils; fn main() { let version = env!("CARGO_PKG_VERSION"); let matches = clap::App::new("teamscale-timestamp") .version(version) .about("Tries to determine the value for the ?t= param...
use days::day10::part2::parse as knot_hash; fn to_bits(byte: u32) -> Vec<bool> { let byte = byte.to_le(); (0..4) .map(|n| byte & (1 << n) != 0) .rev() // TODO: Not fair .collect::<Vec<_>>() } pub fn parse(input: &str) -> usize { (0..128) .map(|line| format!("{}-{}", input,...
use std::borrow::Cow; use std::collections::HashMap; use std::collections::HashSet; use std::path::Path; use std::sync::Arc; use gtk::prelude::*; use webkit2gtk as webkit; use webkit2gtk::{SettingsExt, WebViewExt}; use pulldown_cmark as md; use syntect::dumps::from_binary; use syntect::highlighting::{Theme, ThemeSe...
// Copyright (C) 2021 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.apache.org/licenses/LICENSE-2.0 ...
pub struct Zigzag { i: usize, j: usize, cur: usize, // index by 0 max: usize, // index by 1 blocksize_x: usize, // width blocksize_y: usize, // height } impl Zigzag { pub fn new(max: usize, blocksize_x: usize, blocksize_y: usize) -> Self { Self { i: 1, ...
//! # Mnemonic sentence generation errors use failure::Fail; use std::{error, fmt, io}; /// `Mnemonic` generation errors #[derive(Debug, Fail)] pub enum Error { /// Mnemonic sentence generation error #[fail(display = "Mnemonic generation error: {}", _0)] MnemonicError(String), /// BIP32 key generatio...
extern crate libc; use std::mem; use std::ptr; // Internal node struct Node<T> { data: T, next: *mut Node<T>, prev: *mut Node<T> } // Struct that holds a doubly-linked list pub struct List<T> { head: *mut Node<T>, tail: *mut Node<T> } impl<T> List<T> { pub fn new() -> List<T> { let p...
use crate::{Event, EventSender, EventSenderError, SenderResult, EXT_PARTITIONKEY}; use async_trait::async_trait; use cloudevents::{ binding::rdkafka::{FutureRecordExt, MessageRecord}, event::ExtensionValue, AttributesReader, }; use drogue_cloud_event_common::config::KafkaConfig; use rdkafka::{ error::Ka...
use crate::float::Float; use crate::matrix::M2; use crate::numeric::Numeric; use crate::vector::{Cross, FloatVector, Vector, V2, V3}; use std::ops::{Add, Deref, Div, Mul, Sub}; impl<T> Deref for V2<T> where T: Numeric, { type Target = [T; 2]; fn deref(&self) -> &Self::Target { &self.0 } } imp...
use std::io::{stdin, Read, StdinLock}; use std::str::FromStr; #[allow(dead_code)] struct Scanner<'a> { cin: StdinLock<'a>, } #[allow(dead_code)] impl<'a> Scanner<'a> { fn new(cin: StdinLock<'a>) -> Scanner<'a> { Scanner { cin: cin } } fn read<T: FromStr>(&mut self) -> Option<T> { let t...
use std::io::{Result, Write}; use pulldown_cmark::{Event, Tag}; use crate::gen::{State, States, Generator, Document}; #[derive(Debug)] pub struct Paragraph; impl<'a> State<'a> for Paragraph { fn new(tag: Tag<'a>, gen: &mut Generator<'a, impl Document<'a>, impl Write>) -> Result<Self> { Ok(Paragraph) ...
use crate::{ endpoints::{ params::{DeleteParams, ListParams}, streamer::ArrayStreamer, }, service::{management::ManagementService, PostgresManagementService}, WebData, }; use actix_web::{http::header, web, web::Json, HttpRequest, HttpResponse}; use drogue_client::registry; use drogue_clo...
use std::cmp::PartialEq; use std::mem::transmute; /// [`Tag`] is a four-state `Enum` that can be embedded in a pointer as the two least /// significant bits of the pointer value. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Tag { /// None tagged. None, /// The first bit is tagged. First, /...
use std::io::Write; use std::iter::FromIterator; use crate::binary::*; pub struct BinaryStream { buffer: Vec<u8>, offset: usize, } impl BinaryStream { pub fn new(buffer : Vec<u8>, offset : usize) -> BinaryStream{ return BinaryStream { buffer, offset }; } pub fn reset(&mut self) { self.rewind(); sel...
use super::decode_pixel; // use the super keyword to get other files. use self::decode_pixel::DecodePixel; // repl is weird, so you have to put self before the filename. use self::decode_pixel::DecodePixelFuncs; use super::errors; use self::errors::_Err; use std::env; // get current_dir use std::path::PathBuf; // work...
use clap::{App, Arg}; use std::{convert::TryFrom, fs::File, io::BufReader}; use pcap_parser_xyz as pcap; mod from_bytes_iter; use from_bytes_iter::*; mod types; use types::*; mod out_stream; use out_stream::*; fn main() { let matches = App::new("Quote Parser") .version("1.0") .author("andrassy_...
//! Sky setup. use arctk::{access, clone, math::Pos3}; use palette::{Gradient, LinSrgba}; /// Sky properties. pub struct Sky { /// Sky brightness fraction. brightness: f64, /// Sun position when calculating sun shadows [m]. sun_pos: Pos3, /// Sun angular radius when calculating soft shadows [rad]....
use wasm_bindgen::prelude::*; mod encoder; use encoder::*; mod errors; #[macro_use] extern crate error_chain; #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; pub fn set_panic_hook() { #[cfg(feature = "console_error_panic_hook")] console_error...
use crate::job::{Ctx, OneShotCtx}; use crate::os::Os; use crate::Result; use moby::{ContainerOptions, Docker}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::convert::AsRef; use std::fs::{self, File}; use std::path::{Path, PathBuf}; use std::sync::{Arc, RwLock}; use std::time::{SystemTime...
pub use super::{sync::Listener, sync::SyncDispatcherRequest}; use std::{collections::HashMap, hash::Hash, rc::Weak}; use super::RwLock; pub mod dispatcher; pub mod priority_dispatcher; pub use dispatcher::Dispatcher; pub use priority_dispatcher::PriorityDispatcher; type EventFunction<T> = Vec<Box<dyn Fn(&T) -> Optio...
/* Write a function which takes a number and returns the corresponding ASCII char for that value. Example: get_char(65) # => 'A' For ASCII table, you can refer to http://www.asciitable.com/ */ fn main() { println!("{}", get_char(55)); } fn get_char(c:i32) -> char { let u8:u8 = c as u8; return u8 as cha...
use std::{ ffi::c_int, io::{self, Read, Write}, os::unix::{net::UnixStream, process::CommandExt}, process::Command, }; use super::{ event::PollEvent, event::{EventRegistry, Process, StopReason}, io_util::was_interrupted, terminate_process, ExitReason, HandleSigchld, ProcessOutput, }; us...
/// Return codes used by resource managers. #[derive(Clone, Debug)] pub enum ReturnCode { /// A rollback was caused by an unspecified reason. RollbackUnspecified, /// A rollback was caused by a communication failure. RollbackCommunicationFailure, /// A deadlock was detected. RollbackDeadlock, ...
use nix::sys::termios::*; use std::{os::unix::io::AsRawFd, path::Path}; use tokio::{ fs::*, net::TcpStream, prelude::*, time::{self, Duration, Instant}, }; const DEVICE: &str = "/dev/ttyACM0"; const BUF_SIZE: usize = 22; const TCP_ADDR: &str = "127.0.0.1:55555"; #[tokio::main] async fn main() { l...
use tsukuyomi::{endpoint, server::Server, vendor::http::StatusCode, App}; fn main() -> Result<(), exitfailure::ExitFailure> { std::env::set_var("RUST_LOG", "info"); pretty_env_logger::try_init()?; let log = logging::log("request_logging"); let app = App::build(|mut scope| { scope.with(&log).d...
pub fn to_vec<'a>( output: &'a mut Vec<u8>, serialize: impl FnOnce(AttributeSerializer<'a>) -> Option<()>, ) -> Option<()> { serialize(AttributeSerializer::new(output)) } pub struct AttributeSerializer<'a> { output: &'a mut Vec<u8>, last_key: Vec<u8>, } impl<'a> AttributeSerializer<'a> { fn ne...
#[doc = "Register `GICH_HCR` reader"] pub type R = crate::R<GICH_HCR_SPEC>; #[doc = "Register `GICH_HCR` writer"] pub type W = crate::W<GICH_HCR_SPEC>; #[doc = "Field `EN` reader - EN"] pub type EN_R = crate::BitReader; #[doc = "Field `EN` writer - EN"] pub type EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>...
pub mod ftdi; pub mod constants_test; #[cfg(test)] mod tests { use crate::ftdi::ftdi_context::ftdi_context; use crate::ftdi::ftdi_device_list::ftdi_device_list; use crate::ftdi::ftdi_context::FtdiContextError; use snafu::{GenerateBacktrace}; #[test] fn create_new_ftdi_context() { let f...
use super::toml_to_struct::Dependency; use super::toml_to_struct::DependencyLocation; use std::path::Path; use std::path::PathBuf; use std::fs; use fs_extra::dir; use std::env; #[derive(Debug)] pub enum DependencyFail { FailedToGet(String), ModuleDoesNotExist(String), PathDoesNotExist(String), RepoDoesNotExist...
// https://www.codewars.com/kata/54e320dcebe1e583250008fd use std::collections::HashMap; use std::char; const ASCII_ARRAY: [char; 36] = [ '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H', 'I','J','J','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z' ]; fn factorial(n: u64, map: &...
use serde::{Deserialize, Serialize}; use rstreams::{events::Event, BotInvocationEvent, LeoReadOptions, LeoSdk, AllProviders, LeoWriteOptions, Error}; use rstreams::aws::AWSProvider; use rusoto_signature::Region; use lambda::{run, handler_fn}; use rstreams::events::WriteEvent; pub struct ExampleSdkConfig; impl Example...
use rand::distributions::{Distribution, Uniform}; use std::io::*; const CHOICES: &[&str] = &["rock", "paper", "scissors"]; fn main() { let mut rng = rand::thread_rng(); let rand_indices = Uniform::from(0..3); loop { print!("\x1b[92mRock, paper, scissors? \x1b[0m"); stdout().flush().unwrap(); let mut input ...
use specs::Join; pub struct TeleportSystem; impl<'a> ::specs::System<'a> for TeleportSystem { type SystemData = ( ::specs::ReadStorage<'a, ::component::Teleport>, ::specs::ReadStorage<'a, ::component::Proximitor>, ::specs::Fetch<'a, ::resource::Activated>, ::specs::FetchMut<'a, ::r...
use std::cmp::{ min, max }; use cgmath::prelude::*; use cgmath::{ Rad, Deg }; use num; use crate::prelude::*; use crate::math::*; use crate::interaction::SurfaceInteraction; use super::{ Shape, ShapeData }; #[derive(Clone, Debug)] pub struct Sphere { radius: Float, z_min: Float, z_max: Float, theta_m...
use proconio::{fastout, input}; const MOD: i64 = 1_000_000_000 + 7; #[fastout] fn main() { input! { s: i64, }; let mut dp: Vec<i64> = vec![0; s as usize + 1]; let mut x = 0; dp[0] = 1; for i in 3..s as usize + 1 { x += dp[i - 3]; x %= MOD; dp[i] = x; } ...
use bfg_prolog::ast; use bfg_prolog::ast::{Assertion, Clause}; use bfg_prolog::solve_toplevel; use lalrpop_util::lalrpop_mod; use std::fs::read_to_string; lalrpop_mod!(pub parser); fn read_source_code(path: &str) -> Vec<Assertion> { let s = read_to_string(String::from(path)).unwrap(); parse_code(&s) } fn par...
use crate::config::{BlogConfig, BlogLog, ExifConfig}; use crate::models::{Category, CategoryKind, PhotoPath, Post, TagPhotos}; use chrono::{DateTime, FixedOffset}; use hashbrown::HashMap; use std::collections::BTreeMap; /// Ephemeral struct to compute and capture chronological post order struct KeyTime { /// Post ...
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::cell::Cell; #[derive(Clone)] pub struct GetName { string: Vec<u8>, unescape: fn(String) -> String, } impl GetName { ...
/// # 121. Best Time to Buy and Sell Stock /// /// Say you have an array for which the ith element is the price of /// a given stock on day i. If you were only permitted to complete at most /// one transaction (i.e., buy one and sell one share of the stock), design /// an algorithm to find the maximum profit. Note that...
extern crate utils; use std::env; use std::str::FromStr; use std::num::ParseIntError; use std::io::{self, BufReader}; use std::io::prelude::*; use std::fs::File; use utils::*; type Input = Vec<Instruction>; #[derive(Copy, Clone, Debug)] enum Action { N, S, E, W, L, R, F } #[derive(Debug)] struct Instruction { ...
use crate::lags::interface::NanoSecondGenerator; use crate::types::{DateTime, NonZeroU64, StdRng}; pub struct ConstNanoSecondGenerator(pub NonZeroU64); impl const NanoSecondGenerator for ConstNanoSecondGenerator { fn gen_ns(&mut self, _: &mut StdRng, _: DateTime) -> Option<NonZeroU64> { Some(self.0) } } const _O...
use futures::{Future, Poll, Async, Stream}; use hyper::{Body, Error, Request, Response, body::Chunk}; use tower_service::Service; pub struct Collect<S> { inner: S, } pub struct CollectFuture { concat: Concat2<Chunk>, } impl<S> Collect<S> { pub fn new(inner: S) -> Self { Collect { inner } } } ...
use actix::Actor; use actix_web::{middleware, web, App, HttpServer}; use std::sync::Mutex; use structopt::StructOpt; mod api; mod client; mod db; mod mock; mod server; mod utils; mod websocket; #[actix_rt::main] async fn main() -> std::io::Result<()> { std::env::set_var("RUST_LOG", "info"); pretty_env_logger::...
///// chapter 3 "using functions and control structures" ///// program section: ///// main function // fn main() { 'outer: loop { println!("entered the outer dungeon - "); 'inner: loop { println!("entered the inner dungeon - "); println!("still in inner dungeon - "); ...
use crate::common::did::DidValue; use crate::ledger::PreparedRequest; use crate::tests::utils::constants::TRUSTEE_SEED; use crate::utils::base58::ToBase58; use ursa::keys::{KeyGenOption, PrivateKey, PublicKey}; use ursa::signatures::ed25519::Ed25519Sha512; use ursa::signatures::SignatureScheme; pub struct Identity { ...
/// An enum to represent all characters in the Tags block. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum Tags { /// \u{e0001}: '󠀁' LanguageTag, /// \u{e0020}: '󠀠' TagSpace, /// \u{e0021}: '󠀡' TagExclamationMark, /// \u{e0022}: '󠀢' TagQuotationMark, /// \u{e0023}: '...
// Copyright 2021 Contributors to the Parsec project. // SPDX-License-Identifier: Apache-2.0 //! Object types (including Attributes) use crate::error::{Error, Result}; use crate::mechanism::MechanismType; use crate::types::{Date, Ulong}; use cryptoki_sys::*; use log::error; use std::convert::TryFrom; use std::convert:...
use nix::errno::Errno; use nix::libc::c_int; use nix::sys::signal::{SIGCHLD, SIGINT, SIGTERM}; use nix::sys::wait::WaitStatus::{Exited, Signaled, StillAlive}; use nix::sys::wait::{waitpid, WaitPidFlag}; use nix::Error; use signal::trap::Trap; /// It waits for an incoming Termination Signal like Ctrl+C (SIGINT), SIGTER...
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StorageAccountCheckNameAvailabilityParameters { pub name: String, #[serde(rename = "type", default, skip_se...
//! //! # Example //! //! The following example is obviously overly simplistic, but gives an idea of how one might use //! this library. In a real-world application, one might have the generator function call an //! over-the-network service to get some session key. //! //! ``` //! extern crate timed_cache; //! //! ...
extern crate rustc_serialize; extern crate num_rational; pub mod bitwise; pub mod cryptanalysis; pub mod crypto; pub mod challengeinfo; // Challenge sets go here. pub mod set1;
/* Copyright (c) 2020-2021 Alibaba Cloud and Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ struct EnclaveTlsRef(Opaque); unsafe impl ForeignTypeRef for EnclaveTlsRef { type CType = enclave_tls_handle; } #[derive(Clone)] struct EnclaveTls(NonNull<enclave_tls_handle>); unsafe impl Send for Encla...
#[doc = "Reader of register DIVIDER"] pub type R = crate::R<u32, super::DIVIDER>; #[doc = "Writer for register DIVIDER"] pub type W = crate::W<u32, super::DIVIDER>; #[doc = "Register DIVIDER `reset()`'s with value 0"] impl crate::ResetValue for super::DIVIDER { type Type = u32; #[inline(always)] fn reset_va...
use serde_json::Value as JsonValue; use crate::lib::{ types::Result, ethereum_keys::EthereumKeys, }; pub fn generate_vanity_address(prefix_hex: String) -> Result<JsonValue> { Ok(EthereumKeys::new_vanity_address(prefix_hex)?.to_json()) }
use std::sync::mpsc::{self}; use std::io::{self}; use std::thread; use std::sync::{Arc, Mutex}; use crate::db::blockDb::{BlockDb}; use crate::blockchain::blockchain::{BlockChain}; use crate::mempool::mempool::{Mempool}; use crate::mempool::scheduler::{self, get_curr_slot}; use super::message::{Message, TaskRequest, P...
#[doc = "Register `CR` reader"] pub type R = crate::R<CR_SPEC>; #[doc = "Register `CR` writer"] pub type W = crate::W<CR_SPEC>; #[doc = "Field `EN` reader - AES enable"] pub type EN_R = crate::BitReader<EN_A>; #[doc = "AES enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum EN_A { #[...
use std::io::Write; pub fn warn(s: &str) { #[cfg(feature = "color")] warn_color(s); #[cfg(not(feature = "color"))] warn_no_color(s); } fn warn_no_color(s: &str) { let mut stderr = std::io::stderr(); writeln!(&mut stderr, "Warning: {}", s).unwrap(); } #[cfg(feature = "color")] fn warn_color(s:...
//! # The table //! //! ``` #![doc = static_table::static_table!([ ["a", "b", "result"], ["1", '2', '3'], ["2", '2', '4'] ])] //! ``` /// Add joins 2 integers together to get a sum. /// /// ``` #[doc = static_table::static_table!([ ["a", "b", "result"], ["1", '2', '3'], ["2", '2', '4'] ])] ///...
#[doc = "Register `RX_ORDEXT2` reader"] pub type R = crate::R<RX_ORDEXT2_SPEC>; #[doc = "Register `RX_ORDEXT2` writer"] pub type W = crate::W<RX_ORDEXT2_SPEC>; #[doc = "Field `RXSOPX2` reader - RXSOPX2"] pub type RXSOPX2_R = crate::FieldReader<u32>; #[doc = "Field `RXSOPX2` writer - RXSOPX2"] pub type RXSOPX2_W<'a, REG...
// static lifetime static NUM: i32 = 18; // returns a reference to NUM // where its static lifetime is coerced to that of input argument fn coerce_static<'a>(_: &'a i32) -> &'a i32 { &NUM } fn main() { { let static_string = "I'm in read-only memory"; println!("static_string: {}", static_string...
pub mod token_renewer;
use super::*; use futures_util::{ io::{AsyncRead, Result as FuturesResult}, task::{Context, Poll}, Stream, }; use std::pin::Pin; impl<B: AsyncRead + Unpin> AsyncRead for Multipart<B> { fn poll_read( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8], ) -> Poll<Fu...
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. extern crate fidl_fuchsia_auth; extern crate fuchsia_async as async; extern crate futures; use super::dev_auth_provider::AuthProvider; use fidl::endpoints...
mod linked_list; pub use linked_list::{LinkedList, ListNode}; mod tree; pub use tree::{AvlTree, TreeNode}; mod nlvec; pub use nlvec::NLVec; mod nlvecmap; pub use nlvecmap::NLVecMap;
use super::{ constants::{MAX, MIN}, traits::ByteRotator, utils::parse_to_path, }; use std::fs::File; use std::io::{BufReader, Read, Write}; use std::path::Path; /// FileEncoder has fields for a path (to a file) and rot_by which signifies by how many bytes /// it should shift each original byte. pub struct FileEn...
use failure::Fail; use secp256k1::Error as SecpError; #[derive(Debug, PartialEq, Eq, Fail)] pub enum Error { #[fail(display = "invalid privkey")] InvalidPrivKey, #[fail(display = "invalid pubkey")] InvalidPubKey, #[fail(display = "invalid signature")] InvalidSignature, #[fail(display = "inv...
use std::fs; fn get_total_characters_len(l: &str) -> usize { let l = &l[1..l.len() - 1]; let mut count = 0; let mut current_pos = 0; while current_pos < l.len() { if l.chars().nth(current_pos).unwrap() == '\\' { if l.chars().nth(current_pos + 1).unwrap() == 'x' { cur...
use super::screen::Screen; use quicksilver::geom::Rectangle; use quicksilver::graphics::Font; use quicksilver::graphics::FontStyle; use quicksilver::graphics::Image; use quicksilver::lifecycle::Window; use quicksilver::prelude::Img; use quicksilver::Result; use super::in_game::InGameScreen; use crate::player::check_mu...
// This file is part of rdma-core. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/rdma-core/master/COPYRIGHT. No part of rdma-core, including this file, may be copied, modified, propagated, or distributed ...
// Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>,...
use utils; pub fn find_nth_ordering(n: u64, digits: Vec<u32>, seq_length: usize) -> Vec<u32>{ let num_orderings = utils::factorial(seq_length as u64 - 1); if seq_length == 1 { return vec![digits[n as usize]]; } for (index, &digit) in digits.iter().enumerate(){ if (index as u64 + 1)...
use std::cell::{Cell, RefCell}; use std::rc::Rc; use gdk; use gdk::{Display, WindowExt}; use gtk::{GLAreaExt, WidgetExt}; use servo::BrowserId; use servo::compositing::compositor_thread::EventLoopWaker; use servo::compositing::windowing::WindowMethods; use servo::euclid::{Point2D, ScaleFactor, Size2D, TypedPoint2D, Ty...
fn main() { println!("Hello, world! My name "); }
pub mod camera; pub mod player_parts; pub mod tile; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum EntitySpriteRender { Player(player_parts::PlayerParts,), Ore(tile::TileTypes,), } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum EntityError { #[al...
fn main() { let preamble_len = 25; let mut input = String::from_utf8(std::fs::read("input/day9").unwrap()) .unwrap() .split_terminator("\n") .map(|n| n.parse().unwrap()) .collect::<Vec<u64>>(); let (buf, input) = input.split_at_mut(preamble_len); let answer = input ...
#![feature(proc_macro_hygiene)] #![cfg_attr(not(feature = "std"), no_std)] use ink_core::{memory::string::String, storage}; use ink_lang2 as ink; #[cfg(feature = "ink-as-dependency")] pub use crate::mintable::Mintable; #[ink::contract(version = "0.1.0")] mod mintable { #[ink(storage)] struct Mintable { ...
use std::{thread, time::Duration}; use reqwest; fn main() { loop { let gps = reqwest::get("http://34.217.11.6:8080/7ff796351a7c446795b5a0babd1dc50a/get/V3") .unwrap() .text() .unwrap(); println!("GPS: {:?}", gps); thread::sleep(Duration::from_millis(1000)); } }
use proconio::input; fn main() { input! { s:String, } let ans = if s.len() == 2 { s } else { s.chars().rev().collect() }; println!("{}", ans); }
use std::fs::{OpenOptions}; use std::path::Path; use std::io::{Read, Write}; use std::convert::TryInto; use crate::args::{FileParser}; use std::error::Error; pub struct ThetaFileArg; impl FileParser<'_> for ThetaFileArg { const NAMES: &'static [&'static str] = &["-f", "--file"]; const DESCRIPTION: &'static st...
use std::fs::File; use std::io::Write; use std::path::{Path, PathBuf}; use serde::{Deserialize, Serialize}; use super::path::ConfigPath; use super::FileError; use crate::config::Permission; use crate::defaults; #[inline(always)] fn cache_dir_default() -> ConfigPath { defaults::cache_dir().expect("cache dir") } ...
use mind_the_gap::mnemonic::MnemonicSeed; use mind_the_gap::openpgp::SeededEd25519Cert; use std::fs; use sequoia_openpgp::serialize::SerializeInto; use chrono::{NaiveDate, Utc, LocalResult, TimeZone, DateTime }; use clap::{App, Arg}; // Helper trait for simple error reporting trait ResultErrToString<T> { fn ma...
use std::time::Duration; use crate::{ bson::{doc, Document}, bson_util, cmap::StreamDescription, operation::{ test::{self, handle_response_test}, Find, Operation, }, options::{CursorType, FindOptions, Hint, ReadConcern, ReadConcernLevel}, Namespace, }; fn build_test...
use super::{Token, TokenType}; use super::literal::Literal; use std::{collections::HashMap, str::FromStr}; pub struct Scanner { source: String, start: usize, current: usize, line: usize, sym_keywords: HashMap<String, TokenType>, an_keywords: HashMap<String, TokenType> } impl Scanner { pu...
// Copyright (c) 2019 Chaintope Inc. use crate::errors; use crate::serialize::{ByteBufVisitor, HexStrVisitor}; use redis::{Client, Commands, ControlFlow, PubSubCommands, RedisError}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::cmp::Ordering; use std::fmt::{Debug, Display}; use std::sync::mp...