text
stringlengths
8
4.13M
pub fn square_of_sum(num: u64) -> u64 { (1..num+1) .fold(0, |acc, num| acc + num) .pow(2) } pub fn sum_of_squares(num: u64) -> u64 { (1..num+1) .map(|num| num.pow(2)) .fold(0, |acc, num| acc + num) } pub fn difference(num: u64) -> u64 { square_of_sum(num) - sum_of_squares(n...
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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 ...
use clap::{App, Arg}; use std::fs; mod git; mod web_dev; use git::{add_commit_push, make_github_repo}; use std::io::{Error, ErrorKind}; use web_dev::{create_web_dev_folder, open_stackoverflow}; #[tokio::main] async fn main() -> std::io::Result<()> { let matches = App::new("Ms.Hudson") .version("1.0") ...
// Copyright 2021 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to ...
use oauth2::{ reqwest::async_http_client, url::Url, AccessToken, ClientId, ClientSecret, CsrfToken, RedirectUrl, Scope, }; use openidconnect::{ core::{CoreClient, CoreIdToken, CoreProviderMetadata, CoreResponseType}, AuthenticationFlow, IssuerUrl, Nonce, }; use serde::{Deserialize, Serialize}; use crat...
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[cfg(feature = "Win32_UI_Shell_Common")] pub mod Common; #[cfg(feature = "Win32_UI_Shell_PropertiesSystem")] pub mod PropertiesSystem; #[derive(:: core :: clone :: Clone, :: core :: marker :...
use chrono::prelude::*; use chrono::Duration; use serde::{Deserialize, Serialize}; /// An university department #[derive(Debug, Deserialize, Serialize)] pub enum Department { /// 공과대학 기계공학과 MEG, /// 공과대학 항공우주공학과 ASE, /// 공과대학 조선해양공학과 NOE, /// 공과대학 산업경영공학과 IEN, /// 공과대학 화학공학과 ...
use crate::config::Config; use console::Emoji; use serde::{Deserialize, Serialize}; use solana_account_decoder::parse_token::{UiMint, UiTokenAmount}; use solana_cli_output::{display::writeln_name_value, OutputFormat, QuietDisplay, VerboseDisplay}; use metaplex_token_metadata::state::{Creator, Data, Key, Metadata}; use ...
pub use macroquad::prelude::Rect as Rectangle; pub use macroquad::prelude::{DVec2, IVec2, Vec2}; use macroquad::prelude::{const_dvec2, const_ivec2, const_vec2}; pub const fn dvec2(x: f64, y: f64) -> DVec2 { const_dvec2!([x, y]) } pub const fn ivec2(x: i32, y: i32) -> IVec2 { const_ivec2!([x, y]) } pub cons...
fn main() { proconio::input!{a:u64,mut s:[String;a]}; s.sort(); s.dedup(); println!("{}", s.iter().count()) }
use crate::riscv32_core::Riscv32Core; use crate::riscv32_core::Riscv32Env; use crate::riscv64_core::Riscv64Core; use crate::riscv_csr::CsrAddr; use crate::riscv32_core::PrivMode; use crate::riscv32_core::MemResult; use crate::riscv_exception::ExceptCode; use crate::riscv_exception::RiscvException; use crate::risc...
//! Endpoints for account registration and management. pub mod bind_3pid; pub mod change_password; pub mod deactivate; pub mod delete_3pid; pub mod get_username_availability; pub mod register; pub mod request_3pid_management_token_via_email; pub mod request_3pid_management_token_via_msisdn; pub mod request_openid_toke...
use std::convert::{TryFrom, TryInto}; use std::fmt; use itertools::Itertools; use crate::codegen::llir::IntLiteral as _; use crate::codegen::*; use crate::ir::{self, op, Type}; use crate::search_space::*; pub trait IdentDisplay { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result; fn ident(&self) ->...
use crate::algo::population::population::Population; pub trait CrossOver<Mod> { fn cross(&self, m1: &mut Mod, m2: &mut Mod); fn cross_pop(&self, population: &mut Population<Mod>) { let size = population.population.len(); for i in 1..(size / 2) { let (m1, m2) = &mut population.popula...
// Copyright 2017 Dasein Phaos aka. Luxko // // 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>, at your // option. This file may not be copied, modified, or distributed // except a...
pub mod database; pub mod email; pub mod handler;
#[macro_use] extern crate glium; use glium::Surface; use glium::{glutin, index, Display, Program}; use glutin::event::{Event, StartCause, WindowEvent}; use glutin::event_loop::{ControlFlow, EventLoop}; use glutin::window::WindowBuilder; use glutin::ContextBuilder; fn main() { let mut event_loop = EventLoop::new()...
#[macro_use] extern crate rental; pub struct Foo { i: i32, } pub struct Bar<'a> { foo: &'a Foo, } pub struct Baz<'a: 'b, 'b> { bar: &'b Bar<'a> } pub struct Qux<'a: 'b, 'b: 'c, 'c> { baz: &'c Baz<'a, 'b> } pub struct Xyzzy<'a: 'b, 'b: 'c, 'c: 'd, 'd> { qux: &'d Qux<'a, 'b, 'c> } impl Foo { pub fn borrow<'...
#[tokio::main] async fn main() { warp::serve(warp::fs::dir("publico")) .run(([0,0,0,0],8080)) .await; }
use fnv::FnvBuildHasher; use rahashmap::HashMap as RaHashMap; use std::rc::Rc; use rand::prelude::{ThreadRng,Rng}; use super::mk_key::MakeKey; use common::SizeOf; use prelude::*; type FnvHashMap<K, V> = RaHashMap<K, V, FnvBuildHasher>; #[derive(Debug)] #[allow(clippy::type_complexity)] pub(super) enum KeyedState<T> ...
use aoc2019::aoc_input::get_input; fn required_fuel(module_mass: u64) -> u64 { (module_mass / 3).saturating_sub(2) } fn total_required_fuel(module_mass: u64) -> u64 { let mut prev_fuel = module_mass; let mut total_fuel = 0u64; while prev_fuel != 0 { prev_fuel = required_fuel(prev_fuel); ...
extern crate backtrace; pub mod error; pub mod types; use std::collections::HashMap; use crate::token::token::{Token, TokenType, TokenData}; use crate::token::stream::TokenStream; use error::ParseError; use types::{Object, Array, Value}; pub fn parse(tokens: Vec<Token>) -> Result<Value, ParseError> { let mut stre...
use crate::{ domain, interface::{StakeTokenValue, YoctoNear, YoctoStake}, }; use near_sdk::serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(crate = "near_sdk::serde")] pub struct RedeemStakeBatchReceipt { /// tracks amount of STAKE that has been claimed on the receip...
fn func_patterns(x: i32) -> &'static str { match x { 1 => "one", 2 => "two", 3 => "three", _ => "anything", } } #[test] fn test_patterns() { let r = func_patterns(1); assert_eq!("one", r); } #[test] fn test_shadown() { let x = 1; let c = 'c'; match c { ...
/// Required functionality for underlying [`std::io::Write`] for adaptation #[cfg(not(any(feature = "auto", all(windows, feature = "wincon"))))] pub trait RawStream: std::io::Write + private::Sealed {} /// Required functionality for underlying [`std::io::Write`] for adaptation #[cfg(all(feature = "auto", not(all(windo...
// Copyright 2019 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. use std::path::PathBuf; use compiletest_rs::{common::Mode, Config}; #[test] fn ui() { let mut config = Config { mode: Mode::Ui, src_b...
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct APP_MEMORY_INFORMATION { pub AvailableCommit: u64, pub PrivateCommitUsage: u64, pub PeakPriva...
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtWidgets/qgraphicsproxywidget.h // dst-file: /src/widgets/qgraphicsproxywidget.rs // // header block begin => #![feature(libc)] #![feature(core)] #![feature(collections)] extern crate libc; use self::libc::*; // <= header block end...
use input_i_scanner::{scan_with, InputIScanner}; fn main() { let stdin = std::io::stdin(); let mut _i_i = InputIScanner::from(stdin.lock()); let n = scan_with!(_i_i, usize); let a = scan_with!(_i_i, u64; n); let x = scan_with!(_i_i, u64); let s = a.iter().copied().sum::<u64>(); let c = x ...
use hyper::{Chunk, Error}; use futures::{future::{self, FutureResult}}; use serde::Deserialize; use crate::consts::ErrorCode; pub fn parse_form<'de, T>(form_chunk: &'de Chunk) -> FutureResult<Result<T, ErrorCode>, Error> where T: Deserialize<'de> + std::fmt::Debug, { let parsedData = if let Ok(data) = serde_jso...
use std::io; use std::io::Read; struct Tile { enabled: bool, enabled_neighbors: u8, enabled_check_cycle: usize, } fn main() { let mut input = String::new(); io::stdin().read_to_string(&mut input).unwrap(); const CYCLES: usize = 6; let lines = input.lines().count(); let columns = input...
#![allow(non_snake_case)] #![doc(include = "../docs/range-proof-protocol.md")] use rand::{CryptoRng, Rng}; use std::iter; use curve25519_dalek::ristretto::RistrettoPoint; use curve25519_dalek::scalar::Scalar; use curve25519_dalek::traits::{IsIdentity, VartimeMultiscalarMul}; use generators::Generators; use inner_pr...
use output::OutputCollection; use sensor::SensorCollection; use std::thread; use std::time::Duration; use app::Config; pub struct App { sensors : SensorCollection, outputs : OutputCollection, } impl App { pub fn from_config(config: Config) -> App { App { sensors : config.sensors, outputs : ...
#[derive(Debug)] enum Shape { Circle(i32), Square(i32), Rectangle(i32, i32), } use Shape::*; fn main() { let s = Rectangle(10, 20); println!("{:?}", s); }
use aoc; use std::collections::HashMap; use std::error::Error; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; #[derive(Debug, Clone)] struct GameInfo { players: usize, last_marble_points: usize, } fn main() -> Result<(), Box<dyn Error>> { let arg = aoc::get_cmdline_arg()?; let ga...
use std::fmt; use crate::calculation::{Frequency, RedundancyExt}; mod calculation; mod filter; fn print_info<T: fmt::Display>(frequency: Frequency<T>, n_gram: f32, letters_num: f32) { println!( "Frequency:\n\ {}", frequency ); let entropy = frequency.calc_entropy(n_gram); prin...
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)]...
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" { #[cfg(feature = "Win32_Foundation")] pub fn AdjustWindowRect(lprect: *mut super::super::Foundation::RECT, dwstyle: WINDOW_STYLE, bmenu: super::super::Fou...
#[cfg(target_arch = "wasm32")] pub mod near_blockchain { use super::sys; use near_bindgen::BlockchainInterface; /// Implementation of the blockchain interface that contracts actually use during the execution /// of the contract. pub struct NearBlockchain {} impl BlockchainInterface for NearBloc...
use structopt::StructOpt; use super::{CliCommand, GlobalFlags}; pub const AFTER_HELP: &str = r#"EXAMPLES: To search all repositories for a package containing a substring: $ deck search firefox To search a specific repository for a package: $ deck search --only-in stable firefox To search for a s...
fn main() { let stdin = std::io::stdin(); let mut rd = ProconReader::new(stdin.lock()); let n: usize = rd.get(); let m: usize = rd.get(); let edges: Vec<(usize, usize, usize)> = (0..m) .map(|_| { let u: usize = rd.get(); let v: usize = rd.get(); let c: us...
use super::streaming::{ file_streamers, frame_stream, FileReceiver, FileSender, FrameMessage, FrameReader, FrameWriter, }; use crate::{ config::Config, fs::FileInfo, sync::file_events_buffer::FileEventsBuffer, sync::FileAction, IronCarrierError, }; use std::{collections::HashMap}; use tokio::{ fs::File,...
use std::collections::BTreeMap; use proconio::input; fn main() { input! { n: usize, k: usize, p: [usize; n], }; let mut map = BTreeMap::<usize, usize>::new(); let mut next = vec![0; n + 1]; let mut ans = vec![-1; n + 1]; for i in 0..n { if let Some((&top, &coun...
extern crate libc; extern crate arrayfire as af; extern crate time; // use std::marker::PhantomData; use self::af::*; use std::rc::Rc; use std::cell::RefCell; use std::collections::HashMap; use std::fmt; use std::ops; // a simple Array can be made a variable // let d = Array::new(&d_input, d_dims); // var!(x = arra...
use projecteuler::helper; fn main() { helper::check_bench(|| { solve(2_000_000); }); assert_eq!(solve(2_000_000), 2772); dbg!(solve(2_000_000)); } //solved using a boundary walk //for the given problem the cursor is moved a total of 2210 times. fn solve(goal: usize) -> usize { let mut curs...
use crate::pointer_trait::{AsPtr, CanTransmuteElement, GetPointerKind, PK_Reference}; use std::{ fmt::{self, Display}, ops::Deref, ptr::NonNull, }; /// A wrapper type for vtable static references, /// and other constants that have `non-'static` generic parameters /// but are safe to reference for the life...
use std::collections::HashMap; #[allow(dead_code)] fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> { let mut num_indices: HashMap<i32, usize> = HashMap::new(); for (i, &x) in nums.iter().enumerate() { let result = num_indices.get(&(target - x)).filter(|&&j| i != j); if let Some(&j) = resu...
#[doc = "Reader of register BITBANG"] pub type R = crate::R<u8, super::BITBANG>; #[doc = "Writer for register BITBANG"] pub type W = crate::W<u8, super::BITBANG>; #[doc = "Register BITBANG `reset()`'s with value 0"] impl crate::ResetValue for super::BITBANG { type Type = u8; #[inline(always)] fn reset_value...
use failure::{format_err, Fallible}; use std::path::Path; use std::process::ExitStatus; use super::{cmd, util}; pub fn run(files: Vec<&str>, stdin: &str) -> Fallible<ExitStatus> { let work_dir = util::dirname(files[0])?; let obj_name = "a.o"; let bin_name = "a.out"; let status = cmd::run( wor...
#[macro_use(assert_approx_eq)] extern crate assert_approx_eq; /// library that calculates averages and percentiles mod lib { use std::f32; /// Returns the nth percentile of the given array /// /// Args: /// /// * `array`: mutable reference to the array to modify /// * `percentile`: the ex...
// Copyright 2019 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. use { crate::model::*, clonable_error::ClonableError, cm_rust::CapabilityPath, failure::{Error, Fail}, fidl::endpoints, fidl_fuchsi...
pub mod error; pub mod key; // /// Load helper. // /// // /// Call this function whenever you need to load a resource and that you want logged information, // /// such as failures, timing, etc. // pub fn load_with<T, A, E, F>( // path: &Path, // loader: F // ) -> Result<A, E> // where F: FnOnce() -> Result<A, E>, ...
use serde::Deserialize; #[derive(Deserialize)] #[serde(rename_all = "PascalCase")] pub struct Data { pub id: usize, pub material_id: usize, pub sort_order: usize, pub name_text_map_hash: usize, pub desc_text_map_hash: usize, pub icon: String, }
extern crate oxygengine_core as core; pub mod component; pub mod nav_mesh_asset_protocol; pub mod resource; pub mod system; pub mod prelude { pub use crate::{component::*, nav_mesh_asset_protocol::*, resource::*, system::*}; } use crate::{ component::NavAgent, resource::NavMeshesRes, system::{NavAgen...
use std::collections::HashMap; struct X { roots: HashMap<i32, i32> } fn read(x: &X, key: i32) -> Option<&i32> { x.roots.get(&key) } fn write(x: &mut X, key: i32, newval: i32) { x.roots.insert(key, newval); } fn main() { let mut x = X{roots: HashMap::new()}; let _y = { read(&x, 42) ...
extern crate peg_syntax_ext; use peg_syntax_ext::peg; peg!{memo r#" #[cache] r -> &'input str = s:$([a-z]+) { s } pub parse = r '+' r { () } / r ' ' r { () } "#} #[test] fn main() { assert_eq!(memo::parse("abc zzz"), Ok(())); }
use std::heap::{Heap, Alloc, Layout}; use core::mem; use core::ptr; use Fail; use backtrace::Backtrace; pub(crate) struct ErrorImpl { inner: &'static mut Inner, } // Dynamically sized inner value struct Inner { backtrace: Backtrace, vtable: *const VTable, failure: FailData, } unsafe impl Send for I...
type Point = (i32, i32); fn distance(a: Point, b: Point) -> i32 { (a.0 - b.0).abs() + (a.1 - b.1).abs() } fn input_points(input: String) -> Vec<Point> { input .split("\n") .map(|x| { let parts: Vec<_> = x.split(", ").collect(); ( parts.get(0).unwrap().pa...
/* Original Author: FoxBoxPDX <foxboxpdx@gmail.com> License Copyright 2021 Melondog Software. All rights reserved. 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.ap...
pub mod sx1250_eu868; pub mod sx1250_us915;
use actix_files as fs; use actix_web::{http::StatusCode, web, HttpResponse, Responder}; use deadpool_postgres::{Client, Pool}; use slog::{crit, error, o, Logger}; use std::{io, process::Command}; use validator::Validate; use crate::{constants, db, errors::CustomError, models, utils}; pub async fn get_client(pool: Poo...
use std::collections::HashMap; use std::fs; mod player; use player::Player; mod card_deck; mod game_rules; use game_rules::GameRules; mod game_state; use game_state::GameState; mod user_input; fn main() { let yams = fs::read_to_string("poo_head_rules.yaml").expect("Something went wrong reading the fil...
use ipfs_embed::{Config, Ipfs}; use libipld::cbor::DagCborCodec; use libipld::multihash::Code; use libipld::{alias, Cid, DagCbor, DefaultParams, Result}; use std::convert::TryFrom; use std::path::Path; const ROOT: &str = alias!(root); #[derive(Debug, Default, DagCbor)] pub struct Block { prev: Option<Cid>, id...
#![warn(rust_2018_idioms)] use linkerd_channel::{channel, error::TrySendError, Receiver, Sender}; use std::sync::Arc; use tokio_test::task; use tokio_test::{assert_err, assert_ok, assert_pending, assert_ready, assert_ready_ok}; trait AssertSend: Send {} impl AssertSend for Sender<i32> {} impl AssertSend for Receiver<...
use super::{common::ListenerId, listener::Listener}; use std::collections::HashMap; #[derive(Default)] pub struct Listeners { listeners: HashMap<ListenerId, Box<dyn Listener>>, } impl Listeners { pub fn add(&mut self, listener: Box<dyn Listener>) { self.listeners.insert(listener.get_id(), listener); ...
use std::fmt::Debug; #[derive(PartialEq)] struct School([u64; 10]); impl Debug for School { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { for i in 0..=8 { write!(f, "{}:{}, ", i, self.0[i])?; } Ok(()) } } impl School { fn from_fishes_iter(fishes:...
use std::process::{ Child, Command, Stdio, ExitStatus }; use std::io::{ BufWriter, Read, Write }; use std::path::{ Path, PathBuf }; use std::net::{ TcpListener, TcpStream }; use std::thread; use std::fs::File; extern crate argparse; extern crate rand; use argparse::{ ArgumentParser }; use rand::distributions::{Indep...
pub mod batch; pub mod buffer; pub mod encoding; pub mod http; pub mod retries; pub mod retries2; #[cfg(feature = "rusoto_core")] pub mod rusoto; pub mod service; pub mod service2; pub mod sink; pub mod tcp; #[cfg(test)] pub mod test; pub mod udp; #[cfg(all(feature = "sinks-socket", unix))] pub mod unix; pub mod uri; ...
use std::sync::atomic::{AtomicU32, Ordering}; pub struct Counter(AtomicU32); impl Counter { pub fn increment(&self) -> u32 { self.0.fetch_add(1, Ordering::Relaxed); self.0.load(Ordering::Relaxed) } } pub fn create_counter() -> Counter { Counter(AtomicU32::new(0)) }
fn main() { let s = "hello world".to_string(); println!("{}", s); let mut s1 = String::new(); s1.push_str("hello world"); println!("{}", s1); println!("Hello, world!"); }
#[test] fn it_adds_two() { assert_eq!(4, 2 + 2); }
mod render; pub use render::Render;
use std::collections::VecDeque; use std::marker::PhantomData; use std::net::IpAddr; use actix_service::Service; use futures::{Async, Future, Poll}; use trust_dns_resolver::config::{ResolverConfig, ResolverOpts}; pub use trust_dns_resolver::error::ResolveError; use trust_dns_resolver::lookup_ip::LookupIpFuture; use tru...
extern crate hmac; #[macro_use] extern crate hyper; extern crate reqwest; extern crate rustc_serialize; extern crate serde_json; extern crate sha2; extern crate time; use hmac::{Hmac, Mac}; use hyper::header::{Headers, ContentType}; use rustc_serialize::hex::ToHex; use serde_json::{Value, Map}; use sha2::Sha256; use s...
use bevy::prelude::*; use bevy_egui::{ egui::{self, Ui}, EguiContext, }; use bevy_prototype_lyon::{ prelude::{FillOptions, GeometryBuilder, TessellationMode}, shapes::{self, RegularPolygonFeature}, }; use crate::{demo_camera_plugin::Page, MultishapeTag, WINDOW_WIDTH}; #[allow(clippy::suboptimal_flops)...
use std::path::Path; use crate::jvm::maven_module::MavenModuleAnalyzer; use crate::{files, ModuleAnalyzer, ProjectStructureAnalyzer}; pub struct MavenProjectStructureAnalyzer {} impl Default for MavenProjectStructureAnalyzer { fn default() -> Self { MavenProjectStructureAnalyzer {} } } impl ProjectS...
use ::amethyst::controls::HideCursor; use ::amethyst::controls::WindowFocus; use ::amethyst::core::math::UnitQuaternion; use ::amethyst::shrev::EventChannel; use ::amethyst::winit::{DeviceEvent, Event}; use ::amethyst::core::*; use ::amethyst::ecs::*; use serde::Serialize; use std::hash::Hash; use std::marker::Phan...
#[macro_use] extern crate log; #[macro_use] extern crate failure; use std::env; use std::thread; use std::path::PathBuf; use std::time::Duration; use telebot::{Bot, functions::ParseMode, error::ErrorKind as ErrorTelegram}; use futures::{Future, Stream, IntoFuture, future::Either}; use hex_database::{Instance, GossipCo...
use crate::any::AnyConnection; use crate::connection::ConnectOptions; use crate::error::Error; use futures_core::future::BoxFuture; use log::LevelFilter; use std::str::FromStr; use std::time::Duration; #[cfg(feature = "postgres")] use crate::postgres::PgConnectOptions; #[cfg(feature = "mysql")] use crate::mysql::MySq...
use crate::lib::{ default_sub_command, file_to_lines, parse_isize, parse_lines, Command, SumChecker, }; use anyhow::Error; use clap::{value_t_or_exit, App, Arg, ArgMatches, SubCommand}; use simple_error::SimpleError; pub const ENCODING_ERROR: Command = Command::new(sub_command, "encoding-error", run); #[derive(De...
#![allow(dead_code)] pub mod utils; mod multiplexer; use std::sync::Arc; use types::*; use protocol::types::*; use super::RedisClient; use self::multiplexer::Multiplexer; use error::{ RedisError, RedisErrorKind }; use super::utils as client_utils; use futures::future::{ loop_fn, Loop, lazy }; use futu...
macro_rules! ffi_wrap { ($fname:ident, $target:ident) => {{ let result: SigarResult<$target> = unsafe { let sigar_ptr = SigarPtr::new()?; let mut info: $target = Default::default(); let res = $fname(sigar_ptr.ptr, &mut info); if res != SIGAR_CODE_OK { ...
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless ...
extern crate bytebeat; use std::io::{Read, Write}; fn main() { let mut code = String::new(); std::io::stdin().read_to_string(&mut code).unwrap(); let code = bytebeat::parse_beat(&code).unwrap(); let code = bytebeat::compile(code).unwrap(); for i in 0..60 { let buf: Vec<_> = (i * 8000..(i +...
//! Mutators that can handle recursive types. //! //! There are two main mutators: //! 1. [`RecursiveMutator`] is the top-level mutator for the recursive type //! 2. [`RecurToMutator`] is the mutator used at points of recursion. It is essentially a weak reference to [`RecursiveMutator`] //! //! In practice, you will wa...
use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use std::time::Duration; use libp2p::autonat; use libp2p::dcutr; use libp2p::gossipsub::{self, IdentTopic, MessageAuthenticity, MessageId}; use libp2p::identify; use libp2p::kad::{record::store::MemoryStore, Kademlia, KademliaConfig, Kademli...
pub static TILE_SIZE: i16 = 24; pub static UPS: u64 = 60; pub static MAX_FPS: u64 = 240; pub static TARGET_ASPECT: (u32, u32) = (1120, 800); pub static BOARD_SIZE_Y: i16 = 800; pub static BOARD_SIZE_X: i16 = 1120; pub static WALK_SPEED: f64 = 200.0; pub static ACCELERATION: f64 = 1000.0; pub static FRICTION: f64 = 0.7;...
use crate::{ encryption::ElGamal, types::{Cipher, PublicKey}, }; use alloc::vec::Vec; use core::ops::{AddAssign, Sub}; use num_bigint::{BigUint, RandBigInt}; use num_traits::{One, Zero}; use rand::Rng; use std::boxed::Box; use std::panic; #[derive(Clone, Eq, PartialEq, Debug, Hash)] pub struct Random; impl Ra...
use proconio::input; #[allow(unused_imports)] use proconio::marker::*; #[allow(unused_imports)] use std::cmp::*; #[allow(unused_imports)] use std::collections::*; #[allow(unused_imports)] use std::f64::consts::*; #[allow(unused)] const INF: usize = std::usize::MAX / 4; #[allow(unused)] const M: usize = 1000000007; fn...
use ic_cdk_macros::*; use ic_cdk::export::candid; #[import(canister = "counter_mo")] struct CounterCanister; #[update] async fn read() -> candid::Nat { CounterCanister::read().await.0 } #[update] async fn inc() -> () { CounterCanister::inc().await } #[update] async fn write(input: candid::Nat) -> () { C...
pub mod home; pub mod create_sso;
extern crate clap; extern crate crossbeam_channel; #[macro_use] extern crate cursive; #[cfg(feature = "share_clipboard")] extern crate clipboard; extern crate directories; extern crate failure; extern crate futures; #[macro_use] extern crate lazy_static; extern crate librespot_core; extern crate librespot_playback; ext...
#![feature(collections)] use std::io::BufRead; use std::collections::BitVec; fn sort(mut input: BitVec, blueprint: &Vec<Vec<u32>>) -> (BitVec, u32) { for comparator in blueprint.iter().skip(1) { if input.get(comparator[0] as usize).unwrap() == false && input.get(comparator[1] as usize).unwrap() == true { inp...
use sfml::system::*; use sfml::window::*; use sfml::graphics::*; use std::error; use crate::population::Population; use crate::pawn::Pawn; use crate::world::World; use crate::tile::Tile; use crate::tile::TileType; const TILE_WIDTH: usize = 25; const TILE_HEIGHT: usize = 25; pub struct Game { window: RenderWindo...
use tokio::sync::Semaphore; // Note: semaphore.add_permits requires this to be less than usize::MAX >> 3 const MAX_SEMAPHORE_PERMITS: usize = 1000; /// A shutdown mechanism that supports three use-cases: /// - sending a shutdown signal, /// - polling if the shutdown signal has been sent and /// - blocking to await...
use std::cell::RefCell; use std::fmt; use std::rc::Rc; use crate::function::Function; use crate::object::*; #[derive(PartialEq)] pub enum Value { Bool(bool), Nil, Number(f64), Obj(Rc<Obj>), } impl Value { pub fn new_with_object(obj: Obj) -> Value { let obj = Rc::new(obj); Value::O...
//! Conversions between AnyLuaValue and structures. //! Also see macros. pub mod serialize; pub mod deserialize; pub mod json; pub use self::serialize::ToTable; pub use self::deserialize:: {FromTable, LuaDecoder, ConverterError, ConvertResult}; // Tests for serialize <-> deserialize compatability #[cfg(test)] mod t...
// This file is part of linux-epoll. 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/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distri...
#![allow(dead_code)] use std::convert::TryInto; pub fn strin(s: &String, n: u32) -> char { let mut x = 0; let mut ret = '\0'; for c in s.chars() { if x == n { ret = c; break; } x+=1; } ret } pub fn strcmp(s1: &String,s2: &String) -> i8{ // Return 0: Strings match // Return 1: Unmatched char found ...
mod events; mod input; mod internal; mod modules; mod time; mod window_context; use ecs::{RunSystemPhase, ECS}; use events::{EventChannel, EventSystem}; use modules::MODULE_LOADER; use renderer::RendererDevice; use window_context::WindowContext; extern crate bulletrs; extern crate cgmath; fn main() { let mut ecs =...