text
stringlengths
8
4.13M
use std::io; fn main() { let vector1 = vec![1, 2, 3, 4, 5]; loop { let mut index = String::new(); println!("Type the vector index that you want to display:"); io::stdin() .read_line(&mut index) .expect("failed to read line"); let index: u32 = match index.t...
#[macro_use] extern crate serde_derive; #[macro_use] extern crate clap; use clap::{Arg, App, SubCommand}; use std::process; use std::env; use std::fs::{self, File}; use std::io::{Error, ErrorKind}; use std::io::prelude::*; use std::path::{Path, PathBuf}; use std::time::SystemTime; use chrono::{DateTime, TimeZone,...
use super::builder::{Build, Builder}; use super::{BoxedConstructor, ItemHandle, Pool}; /// A [`Pool`] that uses round-robin logic to retrieve items /// in the pool. Can be converted into the items with the `into_items()` function. pub struct RoundRobinPool<T, TCError> { items: Vec<ItemHandle<T>>, constructor: ...
// 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 proc_macro2::{Ident, Span, TokenStream}; use quote::quote; use syn::{ punctuated::Punctuated, spanned::Spanned, token::Comma, Attribute, DeriveInput, Field, Lit, Meta, MetaNameValue, NestedMeta, Type, Variant, }; macro_rules! assert_attribute { ($e:expr, $err:expr, $input:expr) => { if !$e { ...
fn insert(word: &str) -> bool { let previous_word = "hello"; // if previous_word < word { // return false; // } let prefix_length = common_prefix_length(word, previous_word); return true; } fn main() { let the_string: &str = "hi"; if insert(the_string) == true { println!("Th...
pub static RPC_LOCAL: &str = "http://localhost:8545";
use serde::{Deserializer, Serializer}; use serde_derive::{Deserialize, Serialize}; use std::marker::PhantomData; /// Serde support for deserializing quoted integers. /// /// Configurable so that quotes are either required or optional. pub struct QuotedIntVisitor<T> { require_quotes: bool, _phantom: PhantomData...
#![feature(raw_ref_op)] #![feature(core_intrinsics)] #![feature(custom_mir)] use std::intrinsics::mir::*; // Make sure calls with the return place "on the heap" work. #[custom_mir(dialect = "runtime", phase = "optimized")] pub fn main() { mir! { { let x = 0; let ptr = &raw mut x; ...
use gambit::grammar::{Grammar, Formula}; //------------------------------------------------------------------------------------------------- // TYPE /// represents a state #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pub enum State { Expr, Factor, One, Add, Mul } //------------------------------...
use crate::error::Error; #[derive(Clone)] pub struct BitArray { pub bits: Vec<i32>, pub size: isize, } impl BitArray { pub fn new() -> BitArray { return BitArray { bits: vec!(), size: 0, } } pub fn new_with_size(size: isize) -> BitArray { return Bit...
use std::marker; use std::ops::{Add, Sub}; use amethyst_core::{ECSBundle, Result}; use amethyst_core::cgmath::{BaseFloat, Basis2, Point2, Point3, Quaternion}; use collision::{Aabb2, Aabb3, Bound, ComputeBound, Contains, Discrete, HasBound, Primitive, SurfaceArea, Union}; use collision::algorithm::broad...
use std::time::{SystemTime, UNIX_EPOCH}; use uuid::Uuid; #[allow(dead_code)] pub fn get_time() -> u64 { SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() } #[allow(dead_code)] pub fn get_time_in_msec() -> u128 { SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() } #[allow(dead_code)]...
// Claxon -- A FLAC decoding library in Rust // Copyright 2014 Ruud van Asseldonk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // A copy of the License has been included in the root of the repository. #![feature(test)] extern...
#![feature(lang_items)] #![feature(const_fn, unique)] #![no_std] #![allow(dead_code)] extern crate rlibc; extern crate spin; #[macro_use] mod console; #[no_mangle] pub extern fn kmain(multiboot_information_address: usize) { console::clear_screen(); kprint!("Hello, world{}", "!"); kprintln!("multiboot inf...
use std::fmt::Display; use merkle_tree::ProofNode; use hash_utils::{create_leaf_hash, create_node_hash}; #[derive(Debug)] pub struct Proof<T: Display> { root_hash: String, value: T, path: Vec<ProofNode>, } impl<T> Proof<T> where T: Display { pub fn new(root_hash: String, value: T, path: Vec<Proof...
#![feature(test)] extern crate rex; extern crate json; extern crate test; use json::JsonValue; use rex::render::*; use rex::dimensions::{Pixels, Float}; fn profile_svg() { println!("SVG Renderer"); if let JsonValue::Array(examples) = json::parse(include_str!("../examples.json")) .expect("fail...
// Copyright 2020 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 ...
// 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 ...
// 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...
// Copyright 2020 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 surf::Client; pub struct ApplicationService { client: Client, } impl ApplicationService { pub fn new(client: &Client) -> Self { Self { client: client.clone(), } } pub fn get_properties(&self) {} pub fn quit(&self) {} pub fn set_mute(&self) {} pub fn set_volume(&self) {} }
#![no_std] #![no_main] use core::sync::atomic::{AtomicBool, Ordering}; #[panic_handler] fn panic(_panic_info: &core::panic::PanicInfo) -> ! { loop {} } // BSS example #[no_mangle] pub static BSSTHING: AtomicBool = AtomicBool::new(false); #[no_mangle] pub extern fn _start() -> *const u8 { BSSTHING.store(true...
#![warn(missing_docs)] // Copyright 2020 sacn Developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://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 distribute...
fn main () {} #[cfg(test)] mod tests { extern crate qutonium; use qutonium::prelude::*; #[derive(Clone, Display, PartialEq)] struct Can { flavor: &'static str, ounces: u8, } impl Can { pub fn new (flavor: &'static str, ounces: u8) -> Self { Can { flavor, ounces, ...
use crate::contract_status::app::App; use crate::contract_status::app::Node; use tui::style::Color; use tui::style::Modifier; use tui::style::Style; pub mod async_keys; pub mod rich_status; // row selection enum MoveSelection { Up, Down, } // tab selection enum SwitchTab { Next, Previous, } // render ...
// 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 math_lib::add; #[test] fn add_five_and_six() { assert_eq!(add(5, 6), 11); }
use rusimeta::*; use std::path::Path; use std::fs; use serial_test::serial; use chrono; use chrono::Utc; #[derive(Debug)] struct TestFile<'a> { path: &'a str, expected_json_path: &'a str, pub expected_metadata: rusimeta::MetadataOfInterest, } impl<'a> TestFile<'a> { pub fn path(&self) -> &str { ...
#[macro_use] extern crate enum_as_inner; #[derive(EnumAsInner)] enum ManyVariants { One{ one: u32 }, Two{ one: u32, two: i32 }, Three{ one: bool, two: u32, three: i64 }, } #[test] fn test_one_named() { let many = ManyVariants::One{ one: 1 }; assert!(many.as_one().is_some()); assert!(many.as_t...
use super::EccPoint; use group::ff::PrimeField; use halo2_proofs::{ circuit::Region, plonk::{Advice, Assigned, Column, ConstraintSystem, Constraints, Error, Expression, Selector}, poly::Rotation, }; use pasta_curves::pallas; use std::collections::HashSet; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub ...
use crate::error::*; use std::io::{Read as _, Write as _}; use std::os::unix::io::{AsRawFd as _, FromRawFd as _}; // ideally i would just be able to use tokio::fs::File::from_std on the // std::fs::File i create from the pty fd, but it appears that tokio::fs::File // doesn't actually support having both a read and a ...
use serialize::base64::{self, ToBase64}; use serialize::hex::FromHex; #[test] fn run() { let hex = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f697 \ 36f6e6f7573206d757368726f6f6d"; let b64_exp = "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t"; let b64_a...
use std::iter::{Product, Sum}; use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign}; #[allow(clippy::wildcard_imports)] use graphite::*; use image::Rgba; use serde::{Deserialize, Serialize}; pub type Color = Rgb; #[derive(Clone, Copy, Debug, Default, PartialEq, Deseriali...
// Copyright 2017 Mozilla Foundation // // 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...
#[allow(clippy::unreadable_literal)] // integer type fn test1() { let i8_max: i8 = std::i8::MAX; let i8_min: i8 = std::i8::MIN; assert_eq!(i8_max, 127); assert_eq!(i8_min, -128); let u8_max: u8 = std::u8::MAX; let u8_min: u8 = std::u8::MIN; assert_eq!(u8_max, 255); assert_eq!(u8_min, 0...
use crate::io::Encode; // The Flush message does not cause any specific output to be generated, // but forces the backend to deliver any data pending in its output buffers. // A Flush must be sent after any extended-query command except Sync, if the // frontend wishes to examine the results of that command before iss...
//! Verify that the user has a secure browser installed. #[macro_use] extern crate log; extern crate pnet; use colored::*; use pnet::datalink; /// Check if a vpn is running. Uses this trick: /// https://apple.stackexchange.com/questions/310220/who-creates-utun0-adapter pub fn is_vpn_running() -> bool { let result =...
#![feature(box_syntax)] use rustyline::{Editor}; use rustyline::error::{ReadlineError}; use std::env; use parserlib::{generate_ast_with_err_handling, generate_ast}; use parserlib::Formatter; fn main() { let mut rl = Editor::<()>::new(); if env::args().len() > 2 { println!("[usage] <file>"); st...
extern crate time; use std::option::Option; use std::collections::{HashMap, HashSet}; use time::now; #[derive(Debug, Clone)] struct Program { name: String, weight: u32, aggregated_weight: u32, programs: Vec<String>, } impl Program { fn aggregated_sum(&mut self, programs: Programs) -> u32 { ...
/// Sorts a slice in-place using /// [K-sort](https://arxiv.org/abs/1107.3622) /// /// This sorting algorithm is in fact a modification of quick sort which should /// be faster than quicksort for arrays with less than 7 million elements /// This algorithm is generally compared to heapsort and quicksort, it doesn't ///...
use clap::Parser; /// Creates a new group using the login credentials provided or prompted for #[derive(Parser)] pub struct CreateGroup { /// Name of the group to be created #[clap(index = 1)] pub group: String, }
use core::fmt; /// Error indicating that a radix was not in the supported range of values for FF1. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct InvalidRadix(pub(super) u32); impl fmt::Display for InvalidRadix { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "The radix {} i...
use std::marker::PhantomData; use std::mem::{self, MaybeUninit}; use std::cell::UnsafeCell; use crate::{Ledger, LedgerError}; // /// A double-ended stack allocator // pub struct Hold<T> { // ledger: Ledger, // buffer: *mut Slot<T>, // _marker: PhantomData<T>, // } // struct Slot<T> { // value: Unsafe...
use crate::ui::{MyWindow}; use crate::core::Espaco; use std::cell::{RefMut, RefCell}; use std::rc::Rc; #[derive(Clone)] pub struct MyApp<'a>{ my_window : MyWindow, space : Espaco<'a> } impl<'a> MyApp<'a>{ pub fn new(space :Espaco) -> MyApp{ let mut my_window = MyWindow::new(); MyApp...
//! # LaPoL parse //! //! `lapol-parse-rs` implements the parsing of LaPoL code into an AST, //! which can then be serialized and sent to JavaScript. mod ast; mod error; mod parse; pub use ast::AstNode; pub use error::ParserError; pub use parse::parse;
mod heap; mod pool; mod sort; mod stack;
pub mod window_controls; pub mod window_log; pub mod window_metronome; pub mod window_settings; pub mod window_stats; pub mod window_tapes; pub mod windows; pub use crate::core::Modul; pub use window_controls::*; pub use window_log::*; pub use window_metronome::*; pub use window_settings::*; pub use window_stats::*; p...
use std::slice; use coord::IntoCoord; use cgmath::Vector2; use limits::LimitsRect; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct StaticGrid<T> { items: Vec<T>, width: usize, height: usize, size: usize, } pub trait StaticGridIdx: Copy { fn wrap_to_index(self, width: usize) -> usize; ...
use super::noop::*; use super::plumbing::*; use super::ParallelIterator; pub(super) fn for_each<I, F, T>(pi: I, op: &F) where I: ParallelIterator<Item = T>, F: Fn(T) + Sync, T: Send, { let consumer = ForEachConsumer { op }; pi.drive_unindexed(consumer) } struct ForEachConsumer<'f, F> { op: &'f...
mod io; use std::sync::{ Arc, Mutex, atomic::{AtomicBool, Ordering::Relaxed} }; use std::thread::{self, JoinHandle}; use std::time::Duration; use termios::*; use termion::event::Key; use termion::input::TermRead; use crate::error::*; use crate::util::*; // constants const STDIN_FD: std::os::unix::io::RawFd = 0;...
struct Cat { name: String, } fn test<T>(t: T) where T: Copy, { } fn main() { println!("test!"); let cat = Cat { name: String::from("some cat"), }; test(&cat); test(&cat) }
//! # The controlling player //! //! The player is used to process all input from the actual player, and translate it into commands //! in the game, that a character can execute. use graphics::RenderWindow; use sdl2::keyboard::Keycode; use sdl2::event::Event; use character::Character; use std::fmt::{Display, Error, Fo...
#[doc = "Register `MSC_TINTMSK` reader"] pub struct R(crate::R<MSC_TINTMSK_SPEC>); impl core::ops::Deref for R { type Target = crate::R<MSC_TINTMSK_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<MSC_TINTMSK_SPEC>> for R { #[inline(always)] fn f...
pub mod astar; pub use astar::Astar; pub mod factory;
//! Heap layout management. pub mod layout; pub mod trace; use self::trace::{Packet, Parser}; use eyre::{bail, Result}; use std::collections::BTreeMap; use std::fs::File; /// Processed trace map. pub type TraceMap = BTreeMap<u32, TraceEntry>; /// Processed trace entry. #[derive(Default)] pub struct TraceEntry { ...
/**! * rainfall * * Reads a sequence of rainfall measurements from the standard input and * writes a summary to the standard output. * * INPUT * * The input format is a sequence of measurements represented as * unitless, non-negative numbers, written in ASCII, one per line: * * 12.5 * 18 * 7 *...
uucore_procs::main!(uu_df); // spell-checker:ignore procs uucore
fn main() { assert!(Ok::<i32, String>(42) == Ok(42)); }
use orbtk::prelude::*; use orbtk::theme::DEFAULT_THEME_CSS; static CSS_EXT: &'static str = include_str!("../res/grid.css"); fn get_theme() -> ThemeValue { ThemeValue::create_from_css(DEFAULT_THEME_CSS) .extension_css(CSS_EXT) .build() } widget!(MainView); impl Template for MainView { fn temp...
// use tokio::prelude::*; use futures::executor::ThreadPool; use isahc::prelude::*; use scraper::{element_ref::ElementRef, Html, Selector}; use std::io::{Read, Write}; use std::net::SocketAddrV4; use futures::future::join_all; use std::str::FromStr; use std::sync::{Arc, RwLock}; use std::time::Duration; pub async fn g...
extern crate drawille; use drawille::Canvas; fn main() { let mut canvas = Canvas::new(100, 100); canvas.line(2, 2, 80, 80); canvas.line(2, 80, 80, 80); canvas.line(2, 2, 2, 80); println!("{}", canvas.frame()); }
use serde_json::Value; use chashmap::CHashMap; use log::{trace, error, debug}; use std::sync::Arc; use std::ops::DerefMut; /// Database object per ACI documentation #[derive(Debug, Clone)] pub struct Database { name: String, data: Arc<CHashMap<String, Value>> } impl Database { /// Create a new empty dat...
use bcc_sys::bccapi::*; use std::ffi::CString; use std::ptr; fn main() { #[cfg(any( feature = "v0_4_0", feature = "v0_5_0", feature = "v0_6_0", feature = "v0_6_1", feature = "v0_7_0", feature = "v0_8_0", ))] { let cs = CString::new("".to_string()).unw...
pub mod window; pub mod label; pub mod rect; pub mod color; pub mod button; pub mod slider; pub mod webview; pub mod app; mod responder; pub mod utils; // use self::utils::*;
use std::io::Cursor; use rev_lines::RawRevLines; fn main() -> Result<(), Box<dyn std::error::Error>> { let file = Cursor::new(vec![ b'A', b'B', b'C', b'D', b'E', b'F', b'\n', // some valid UTF-8 in this line b'X', 252, 253, 254, b'Y', b'\n', // invalid UTF-8 in this line b'G', b'H', b'I', ...
use pty_shell::{PtyCallback, PtyShell}; use clap::Parser; use std::io::Write; /// Starts a recording session. /// All input will be recorded to the given file. /// /// The resulting file will consist in a number of lines, each prefixed with /// the time in seconds since the beginning of the session, and a list of //...
//! The NFA we construct for each regex. Since the states are not //! really of interest, we represent this just as a vector of labeled //! edges. use std::fmt::{Debug, Formatter, Error}; use std::usize; use lexer::re::{Regex, Alternative, Elem, RepeatOp, Test}; #[cfg(test)] mod interpret; #[cfg(test)] mod test; #[...
// Copyright 2020 WHTCORPS INC Project Authors. Licensed Under Apache-2.0 use std::borrow::Cow; use std::convert::TryInto; use std::{i64, str, u64}; use milevadb_query_datatype::prelude::*; use milevadb_query_datatype::{self, FieldTypeFlag, FieldTypeTp}; use crate::ScalarFunc; use milevadb_query_datatype::codec::con...
#![allow(dead_code)] use crate::{Error, Result}; use std::{ convert::{TryFrom, TryInto}, fmt, str::{self, FromStr}, }; #[derive(Debug, PartialEq, Eq, Clone)] pub struct ChunkType { bytes: [u8; 4], } impl TryFrom<[u8; 4]> for ChunkType { type Error = Error; fn try_from(bytes: [u8; 4]) -> Resu...
use std::cmp::{min, max}; /// アリが与えられて、アリが落ちるまでの最小と最大の方向 /// アリの初期の位置はわからない pub fn ants (l: i32, ants: &[i32]){ let mut min_t = 0; for &ant_pos in ants{ min_t = max(min_t, min(ant_pos, l - ant_pos)); } let mut max_t = 0; for &ant_pos in ants{ max_t = max(max_t, max(ant_pos, l - ant...
extern crate bmp280; extern crate failure; extern crate i2cdev; use std::thread; use std::time; // Determined from testing your particular chip const OFFSET: f32 = -161.0; fn main() -> Result<(), failure::Error> { let dev = i2cdev::linux::LinuxI2CDevice::new("/dev/i2c-1", 0x77)?; let mut bmp = bmp280::Bmp280...
use crate::shell_parsing::get_arg; use crate::shell_state::ShellState; use std::fs::File; pub fn open_image(shell_state: ShellState, args: Vec<&str>) -> ShellState { let image_filename = get_arg(&args, 1).expect("Couldn't open image file!"); shell_state.open_file(image_filename) } pub fn create_new_i...
struct Solution(); impl Solution { pub fn smaller_numbers_than_current(nums: Vec<i32>) -> Vec<i32> { let mut new_array = Vec::new(); // 统计在当前索引之后的所有小于该值的计数,然后输出在新数组中 let len = nums.len(); for i in 0 .. len { let mut count = 0; for j in 0..len { ...
/// Bubble sort pub fn sort<T: Ord>(arr: &mut [T]) { for i in 1..arr.len() { for j in (i..arr.len()).rev() { if arr[j] < arr[j - 1] { arr.swap(j, j - 1); } } } } #[cfg(test)] mod tests { use super::sort; use crate::sorting::shuffle::shuffle; #[test] fn test_sort() { let mut arr = [10, 9, 8, 7, ...
//! @brief command line setup and parse use { clap::{ crate_description, crate_name, crate_version, App, AppSettings, Arg, ArgMatches, SubCommand, }, solana_clap_utils::input_validators::{is_url_or_moniker, is_valid_pubkey, is_valid_signer}, }; /// Construct the cli input model and parse command l...
extern crate eakio; use std::process; fn main() { eakio::init_logger(); if let Err(e) = eakio::command() { println!("Error: {}", e); process::exit(1) } }
use rocket_contrib::json::Json; use rocket::http::{Status, ContentType}; use crate::datastructures::{Schema, ErrorMessage}; use crate::Conf; use rocket::{State, Response}; use crate::dao::ConnectionRestMapping; use std::io::Cursor; use super::internal::*; #[get("/?<limit>&<offset>")] pub fn get_schemas(state: State<...
// 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 rayon::prelude::*; #[derive(Debug, Clone, Copy)] enum Instruction { Nop(isize), Acc(isize), Jmp(isize) } fn cpu(ops: &[Instruction], swap: Option<usize>) -> Result<isize, isize> { let mut visited = vec![false; ops.len()]; let mut ptr = 0; let mut acc = 0; let swap = swap.unwrap_or(usize::MAX); while ptr <...
use my_algo::linked_list::shll::{utils::dedup_by_abs, LinkedList}; use structopt::StructOpt; #[derive(StructOpt, Debug)] struct Opt { input: Vec<isize>, } fn main() { let opt = Opt::from_args(); println!("inputs: {:?}", opt.input); let n = opt .input .iter() .max_by(|x, y| x.ab...
// This file is part of Substrate. // Copyright (C) 2017-2022 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 // // ht...
use cosmwasm_std::{ log, to_binary, Api, CanonicalAddr, Env, Extern, HandleResponse, HandleResult, HumanAddr, InitResponse, InitResult, Querier, QueryResult, StdError, Storage }; use std::collections::HashSet; //use cosmwasm_storage::{PrefixedStorage}; //use schemars::_serde_json::value; use crate::{msg::{Count...
// Ref: https://leetcode.com/problems/integer-to-english-words/discuss/70625/My-clean-Java-solution-very-easy-to-understand pub struct Solution {} const LESS_THAN_20: [&str; 20] = [ "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Elev...
extern crate core_affinity; #[macro_use] extern crate criterion; use mimalloc::MiMalloc; #[global_allocator] static GLOBAL: MiMalloc = MiMalloc; use criterion::{BatchSize, Criterion, ParameterizedBenchmark, Throughput}; use std::fs::File; use std::io::Read; macro_rules! bench_file { ($name:ident) => { fn...
trait Food { fn is_food(&self) -> bool; } trait Vegetable { fn is_vegetable(&self) -> bool; } trait Fruit: Food + Vegetable { fn eat2(&self); } struct Apple { name: String, price: i64, } impl Fruit for Apple { fn eat2(&self) { println!("eat!"); } } impl Vegetable for Apple { ...
//! pixel indexing use std::fmt::Debug; use num::traits::{cast::NumCast, int::PrimInt}; /// calculate the sqrt of some integer pub fn isqrt<T>(x: T) -> T where T: PrimInt + Debug, { <T as NumCast>::from((<f64 as NumCast>::from(x).unwrap() + 0.5).sqrt()).unwrap() } const CTAB: [i32; 256] = [ 0, 1, 256, 2...
// Infinite loops fn main() { let mut x = 0; loop { x += 1; if x % 2 == 0 { println!("{} is even", x); // Skip the rest of this loop iteration AKA // continue with the NEXT iteration continue; } println!("{} is odd", x); ...
mod topic_detail; mod topic_list; use super::app::App; use super::app::Context::{TopicDetailPage, TopicListPage}; use crate::model::Event; use crossterm::event::KeyCode; use std::borrow::BorrowMut; pub fn handle_event(event: Event<KeyCode>, app: &mut App) { let context = app.context.borrow_mut(); match contex...
use crate::models::user::User; use crate::schema::user; use rocket::request::{self, FromRequest, Request}; use rocket::{http::Status, Outcome}; use serde::Serialize; #[derive(Queryable, Identifiable, Serialize, FromForm, AsChangeset, Insertable)] #[table_name = "user"] pub struct Admin { pub id: i32, pub usern...
use qd_nat::{with_n, Add, Nat}; #[test] #[should_panic] fn add_unknown() { with_n! { let _: Add<N, N> = Add::from_usize(0).unwrap(); } } #[test] #[should_panic] fn add_mismatched() { with_n! { let _ = N::from_usize(1); let _: Add<N, N> = Add::from_usize(0).unwrap(); } } #[test...
use std::fs; use chrono::{DateTime, Local}; use colored::*; use comfy_table::presets::UTF8_HORIZONTAL_BORDERS_ONLY; use comfy_table::{Cell, CellAlignment, ContentArrangement, Table}; use flexi_logger::{FileSpec, LevelFilter}; use log::error; use crate::errors::PaperoniError; pub fn display_summary( initial_artic...
#[derive(Debug)] pub enum AssetLoadError { LoadFileError, FormatError, LoadImageError, UploadImageError, NotFoundLoader, FindDepAssetError }
// Copyright 2017 ETH Zurich. All rights reserved. // // 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 //...
use futures::future::ok; use futures_cpupool::CpuPool; use futures_cpupool::Builder as CpuPoolBuilder; use super::ExecutorService; use super::Task; use server::config::ZeusConfig; use util::errors::*; pub struct CpuPoolScheduler { cpu_pool: CpuPool, } impl CpuPoolScheduler { pub fn new( name: &str, confi...
use sqlx::{Connection, MySql, MySqlConnection, Transaction}; use sqlx_test::new; #[sqlx_macros::test] async fn macro_select_from_cte() -> anyhow::Result<()> { let mut conn = new::<MySql>().await?; let account = sqlx::query!("select * from (select (1) as id, 'Herp Derpinson' as name, cast(null as char) ...
#[derive(Debug)] struct Case { x: u16, y: u16, k: u16, } #[derive(Debug)] struct Input { cases: Vec<Case>, } fn parse_case(line: &&str) -> Case { let cs = line.split_whitespace().collect::<Vec<&str>>(); Case { x: cs[0].parse().unwrap(), y: cs[1].parse().unwrap(), k: cs[...
extern crate web_todo_frontend; extern crate yew; use web_todo_frontend::TodoApp; use yew::prelude::*; fn main() { yew::initialize(); App::<(), TodoApp>::new(()).mount_to_body(); yew::run_loop(); }
mod graph; mod adjacency_list; mod property_map; use graph::*; use adjacency_list::*; use property_map::*; use std::collections::HashMap; use std::hash::Hash; fn relax(u: Vertex, v: Vertex, w: &PMap<Edge, f32>, d: &mut PMap<Vertex, f32>, p: &mut PMap<Vertex, Vertex>) { let d_v: f32 = *...
use std::fmt; use crate::Location; /// An `Error` type for operations performed in this crate. #[derive(PartialEq, Eq, Clone)] pub struct Error { pub(crate) message: String, pub(crate) data: String, pub(crate) loc: Location, } impl Error { /// Create a new instance of `Error`. pub fn new(message:...