text
stringlengths
8
4.13M
// https://leetcode.com/problems/min-cost-climbing-stairs use std::cmp::min; impl Solution { pub fn min_cost_climbing_stairs(cost: Vec<i32>) -> i32 { let mut dp = vec![0; cost.len()]; dp[0] = cost[0]; dp[1] = cost[1]; for (i, val) in cost.iter().enumerate(){ if i < 2{ ...
#![feature(phase)] #[phase(plugin)] extern crate megalonyx; extern crate megalonyx; fn main() {} #[cfg(test)] mod test { #[test] fn test_char() { mega!( grammar achar { start = 'z' } ) assert_eq!(achar::parse("zog"), Ok("og")); assert!(...
use crate::ringbuffer::RingBuffer; use crate::{Rect,Time}; use retro_rs::{Buttons, Emulator}; use std::collections::HashSet; #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] pub struct SpriteData { pub index: u8, pub x: u8, pub y: u8, height: u8, pub pattern_id: u8, pub table: u8, pub a...
//! Experimental replacement for `Box<dyn Error>` that implements `Error`. //! //! This module introduces the `DynError` type, which owns an inner `Box<dyn Error>`. Most //! importantly, `DynError` _does_ implement the `Error` trait, unlike `Box<dyn Error>`. As a //! result, `DynError` is more conveniently compatible w...
#[macro_use] extern crate serde; #[macro_use] extern crate log; pub mod client; mod error; pub mod server; pub mod web; pub use crate::client::{TikaBuilder, TikaClient}; pub use crate::error::Result; use reqwest::{IntoUrl, Url}; use std::net; /// Indicates whether a tika server instance should spawned or is already...
//! Shapes for easily constructing basic meshes with [`LyonMeshBuilder`]. //! //! # Overview //! //! This module provides a set of shapes consumable by the [`LyonMeshBuilder`] which draws some simple basic shapes. //! The shapes provided here match with the shapes that have simple tesselators provided by `lyon`. //! ...
pub struct Solution {} impl Solution { pub fn solve_sudoku(board: &mut Vec<Vec<char>>) { Solution::solve(board); } fn solve(board: &mut Vec<Vec<char>>) -> bool { if let Some((x, y)) = Solution::find_first_dot(board) { for num in 1..10 { let c = std::char::from_d...
//! Test Tide endpoints // Turn on warnings for some lints #![warn( // missing_debug_implementations, missing_docs, trivial_casts, trivial_numeric_casts, unreachable_pub, unused_import_braces, unused_qualifications )] use std::collections::{BTreeMap, HashMap}; use tide::{convert::Serialize...
pub mod forty_two; pub mod fifty_six; pub mod five_four_seven; pub mod two_zero_six; pub mod fifteen;
pub mod user; pub mod settings; pub mod tissue; pub mod dive;
#![feature(unchecked_math)] fn main() { // MIN overflow let _val = unsafe { 1_000_000_000i32.unchecked_mul(-4) }; //~ ERROR: overflow executing `unchecked_mul` }
use crate::proto::ProtoMessage; use crate::transport::protocol::{Link, Protocol, ProtocolV1}; use crate::transport::{Transport, TrezorDevice, TREZOR_DEVICES}; use crate::{TrezorError, TrezorResult}; use async_trait::async_trait; use common::log::warn; use hw_common::transport::webusb_driver::{DeviceFilter, WebUsbDevice...
extern crate lalrpop; extern crate peg; fn main() { lalrpop::process_root().unwrap(); peg::cargo_build("src/computor_v1/parser.rustpeg"); }
// 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 ...
mod user; fn main() { let user = user::User { email: "john_snow@example.com".to_string(), family_name: "John".to_string(), given_name: "Snow".to_string(), }; println!("Email: {}", user.email); println!("Family Name: {}", user.family_name); println!("Given Name: {}", user.giv...
use std::process::Command; use rand::{thread_rng, Rng}; use serde::{Deserialize, Serialize}; use crate::{ error::NotifyError, scraping::{ amazon::AmazonScraper, bestbuy::BestBuyScraper, bnh::BnHScraper, evga::EvgaScraper, newegg::NeweggScraper, ScrapingProvider, }, }; #[derive(Serialize, ...
use crate::{ ext::FloatExt, util::{ BLUE, GREEN, RED, angle_to_vec, angle_from_vec, ver, hor, Vector2, Point2 }, io::tex::{Assets, PosText}, obj::{Object, pickup::Pickup, player::Player, enemy::{Enemy, Chaser}, health::Health, weapon::WeaponInstance, grenade::Explosio...
use crate::{id, proof, Level, Result}; use chrono::{self, prelude::*}; use crev_common::{ self, serde::{as_rfc3339_fixed, from_rfc3339_fixed}, }; use crev_common::{is_equal_default, is_vec_empty}; use derive_builder::Builder; use failure::bail; use semver::Version; use serde::{Deserialize, Serialize}; use serde...
#[doc = "Reader of register SOPT7"] pub type R = crate::R<u32, super::SOPT7>; #[doc = "Writer for register SOPT7"] pub type W = crate::W<u32, super::SOPT7>; #[doc = "Register SOPT7 `reset()`'s with value 0"] impl crate::ResetValue for super::SOPT7 { type Type = u32; #[inline(always)] fn reset_value() -> Sel...
use ::vec3::Vec3; pub struct Ray { pub origin: Vec3, pub direction: Vec3, pub inverse_dir: Vec3, // This is used to optimise ray-bbox intersection checks pub signs: [bool; 3] // Handle degenerate case in bbox intersection } impl Ray { pub fn new(origin: Vec3, direction: Vec3) -> Ray { let i...
#![feature(ptr_sub_ptr)] fn main() { let arr = [0u8; 8]; let ptr1 = arr.as_ptr(); let ptr2 = ptr1.wrapping_add(4); let _val = unsafe { ptr1.sub_ptr(ptr2) }; //~ERROR: first pointer has smaller offset than second: 0 < 4 }
use std::collections::HashMap; #[derive(Default)] struct Logger { messages: HashMap<String, i32>, } impl Logger { fn new() -> Self { Logger { messages: HashMap::new(), } } fn should_print_message(&mut self, timestamp: i32, message: String) -> bool { if let Some(&t)...
#![no_std] #![cfg_attr(docsrs, feature(doc_cfg))] use bit_field::BitField; #[allow(unused_imports)] use chrono::{DateTime, FixedOffset, Utc}; #[allow(clippy::clippy::redundant_static_lifetimes)] #[allow(non_camel_case_types)] #[allow(non_upper_case_globals)] #[allow(unused)] mod bootboot_bindings; mod mmap; #[cfg(f...
use crate::instructions::base::bytecode_reader::BytecodeReader; use crate::instructions::base::instruction::{Instruction, NoOperandsInstruction}; use crate::runtime::frame::Frame; pub struct F2d(NoOperandsInstruction); impl F2d { #[inline] pub const fn new() -> F2d { return F2d(NoOperandsInstruction::...
use packed_struct::derive::PackedStruct; #[derive(PackedStruct, Debug, PartialEq)] #[packed_struct(bit_numbering = "msb0", endian = "msb")] pub struct SetScrollStart { pub source_line: u16, } #[cfg(test)] mod test { use super::*; use packed_struct::PackedStruct; #[test] fn set_scroll_start() { ...
use std::boxed::Box; use std::cmp; const MIN_SIZE:usize=10; type Node=Option<u64>; pub struct DynamicArr{ buf:Box<[Node]>, cap:usize, pub length:usize, } impl DynamicArr{ pub fn new()->DynamicArr{ DynamicArr{ buf:Box::new([None;MIN_SIZE]), length:0, cap:MIN_S...
mod generated; mod language; mod syntax_tree; mod token_text; pub(crate) mod grammar; pub(crate) mod utils; use std::{cell::RefCell, rc::Rc}; use crate::{lexer::Lexer, Error, Token, TokenKind}; pub use generated::syntax_kind::SyntaxKind; pub use language::{SyntaxElement, SyntaxElementChildren, SyntaxNodeChildren, S...
use crate::prelude::{TryFromCoinProtocol, TryPlatformCoinFromMmCoinEnum}; use crate::token::{EnableTokenError, TokenActivationOps, TokenProtocolParams}; use async_trait::async_trait; use coins::coin_errors::MyAddressError; use coins::solana::spl::{SplProtocolConf, SplTokenCreationError}; use coins::{BalanceError, CoinB...
use crate::TagType; use syn::{Attribute, DataEnum, Error, Field, Fields, Lit, Meta, NestedMeta, Result, Variant}; pub(crate) fn tag_type(attrs: &[Attribute], enumeration: &DataEnum) -> Result<TagType> { let mut tag_type = None; let mut tag = None; let mut content = None; for attr in attrs { if...
#![feature(used)] #![feature(const_fn)] #![no_std] extern crate cortex_m; #[macro_use(interrupt)] extern crate stm32f042; use stm32f042::*; use stm32f042::peripherals::usart; use core::fmt::Write; use stm32f042::Interrupt; fn main() { cortex_m::interrupt::free(|cs| { let rcc = RCC.borrow(cs); ...
pub use self::mithril::core::*; pub use self::mithril::render::*; mod mithril;
extern crate svm_sdk_mock as svm_sdk; use svm_codec::Codec; use svm_layout::FixedLayout; use svm_runtime_ffi as api; use svm_runtime_testing as testing; use svm_sdk::traits::Encoder; use svm_sdk::ReturnData; use svm_types::{Address, BytesPrimitive, Context, Envelope, Receipt, TemplateAddr}; use api::{svm_account, svm...
// Copyright 2013 The Servo 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>, at ...
use advent_of_code_2021::{parse, read}; use nom::bytes::complete::tag; use nom::character::complete::i64; use nom::multi::many0; use nom::sequence::tuple; use nom::IResult; use std::cmp::max; use std::cmp::min; fn bloc_parser(input: &str) -> IResult<&str, Bloc> { let (input, _) = tag("inp w\n")(input)?; let (i...
#[doc = "Register `CLKCTL` reader"] pub struct R(crate::R<CLKCTL_SPEC>); impl core::ops::Deref for R { type Target = crate::R<CLKCTL_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<CLKCTL_SPEC>> for R { #[inline(always)] fn from(reader: crate::R...
extern crate num_traits; extern crate serde; #[macro_use] extern crate serde_derive; use std::f64; use std::ops::{Add,Mul,Div,Sub,Neg}; use std::ops::{AddAssign,MulAssign,DivAssign,SubAssign}; use std::cmp::Ordering; use std::fmt; use std::hash::{Hash, Hasher}; use num_traits::{Zero,Float,Num,Signed,zero,NumCast}; us...
use crate::models::{COL_ITEM_NAME, COL_ITEM_URI}; use glib::{ bitflags::_core::{future::Future, time::Duration}, MainContext, }; use gtk::TreeModelExt; use rspotify::client::ClientError; use std::sync::Arc; use thiserror::Error; use tokio::{runtime::Handle, sync::RwLock, task::JoinError}; pub type AsyncCell<T>...
//! //! Merge Two Sorted Lists //! //! https://leetcode.com/problems/merge-two-sorted-lists/ //! //! Merge two sorted linked lists and return it as a new list. //! //! The new list should be made by splicing together the nodes of the first two lists. //! //! **Example:** //! ```text //! Input: 1->2->4, 1->3->4 //! Outp...
#[derive(Copy, Clone, PartialEq, Debug)] pub struct GenData{ pub pos: usize, pub gen: u64, } #[derive(Debug)] pub struct EntityActive{ active: bool, gen: u64, } // where we get new GeneratiIDs from #[derive(Debug)] pub struct GenManager{ items: Vec<EntityActive>, drops: Vec<usize>, // List of dropped e...
use std::str::FromStr; use std::{collections::HashMap, iter::IntoIterator}; use crate::{config::Config, error, path::Expression, source::Source, value::Value}; /// A configuration builder /// /// It registers ordered sources of configuration to later build consistent [`Config`] from them. /// Configuration sources it...
use std::{borrow::Cow, str::FromStr}; use log::error; use nimiq_hash::{ sha512::{Sha512Hash, Sha512Hasher}, Blake2bHash, Blake2bHasher, Hasher, Sha256Hash, Sha256Hasher, }; use nimiq_keys::Address; use nimiq_macros::{add_hex_io_fns_typed_arr, add_serialization_fns_typed_arr, create_typed_array}; use nimiq_prim...
use crate::{Tile,SCREEN_HEIGHT,SCREEN_WIDTH}; use rand::Rng; const MAX_ROOMS: usize = 2; const MIN_ROOM_WIDTH: usize = 2; const MAX_ROOM_WIDTH: usize = 7; const MIN_ROOM_HEIGHT: usize = 2; const MAX_ROOM_HEIGHT: usize = 7; const TILE_SIZE: f32 = 10.0; const MAP_WIDTH: f32 = SCREEN_WIDTH / TILE_SIZE; const MAP_HEIGHT:...
use proc_macro2::Ident; use syn::Attribute; #[derive(Debug, Clone)] pub struct NapiFn { pub name: Ident, pub js_name: String, pub attrs: Vec<Attribute>, pub args: Vec<NapiFnArgKind>, pub ret: Option<syn::Type>, pub is_async: bool, pub fn_self: Option<FnSelf>, pub kind: FnKind, pub vis: syn::Visibilit...
use itertools::Itertools; use aocinput::request; fn main() { let resp = request::get_input(2020, 13); let (time, buses) = resp.trim().split("\n").collect_tuple().unwrap(); let time: u32 = time.parse().unwrap(); let buses: Vec<u32> = buses .split(",") .filter(|bus| *bus != "x") ...
use std::cmp::max; use std::collections::VecDeque; use std::default::Default; use std::num::Wrapping; use emulator::device::{self, Device}; use emulator::Ram; use emulator::Registers; use types::*; use types::Value::*; use types::BasicOp::*; use types::SpecialOp::*; error_chain!( links { InterruptError(de...
/*! # Simple usage ## Creating the server The easiest way to create a server is to call `Server::new()`. The `new()` function returns an `IoResult<Server>` which will return an error in the case where the server creation fails (for example if the listening port is already occupied). ```no_run let server = tiny_http...
// 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 ...
pub trait DFA { type State; // some automata work only with ASCII characters todo why? type Input; fn advance(&mut self, input : Self::Input); fn in_final_state(&self) -> bool; fn in_fail_state(&self) -> bool; } #[derive(Debug, PartialEq)] pub enum Error { IsInFailState, }
use crate::job::StackJob; use crate::latch::SpinLatch; use crate::registry::{self, WorkerThread}; use crate::unwind; use std::any::Any; use crate::FnContext; #[cfg(test)] mod test; /// Takes two closures and *potentially* runs them in parallel. It /// returns a pair of the results from those closures. /// /// Concep...
#[macro_use] extern crate glium; use std::fs::File; use std::io::Read; //mod support; mod shaders; use self::shaders::packed_fragment::PACKED_FRAGMENT_SHADER; use self::shaders::planar_fragment::PLANAR_FRAGMENT_SHADER; use self::shaders::video_vertex::VIDEO_VERTEX_SHADER; const YUV: u32 = 0; use glium::index::Primitiv...
use nphysics3d::force_generator::ForceGenerator; use nphysics3d::object::{BodyHandle, BodySet}; pub mod collision; const G: f64 = 6.67408e-11; #[derive(Debug, Clone)] pub struct PlanetGravity { factor: f64, position: na::Point3<f64>, } impl PlanetGravity { pub fn new(mass: f64, position: na::Point3<f64>...
extern crate readline; use readline::{readline, add_history}; use grammar::*; use std::result::Result; mod grammar; fn main() { loop { let result = readline("Kiss! "); match result { Some(input) => { add_history(input.as_slice()); ...
use serum_common::pack::Pack; use serum_registry_rewards::accounts::{vault, Instance}; use serum_registry_rewards::error::{RewardsError, RewardsErrorCode}; use solana_sdk::account_info::AccountInfo; use solana_sdk::program_pack::Pack as TokenPack; use solana_sdk::pubkey::Pubkey; use solana_sdk::sysvar::rent::Rent; use ...
use lazy_static::lazy_static; use serde_json::{self, value as json}; use std::{collections::VecDeque, sync::Mutex, time::SystemTime}; pub struct JsonLogEntry { pub name: &'static str, pub timestamp: u128, pub json: json::Value, } const MAX_EVENTS_IN_QUEUE: usize = 1_000; /// Writes event to event stream ...
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::access_path::{AccessPath, DataPath}; use crate::event::EventHandle; use crate::genesis_config::ConsensusStrategy; use crate::move_resource::MoveResource; use move_core_types::language_storage::{StructTag, CORE_CODE_ADDRESS}; u...
mod context; mod expression; mod main; mod parser_util; mod statement; pub use main::*;
fn main() { // NUMBERS // Rust can use numbers without needing the type specified let a = 10; let b = 1; let c = a + b; println!("c is {}", c); // But if you want to specify a type in Rust this is the syntax let d: i8 = 100; let e: f32 = 0.42; // and so on... // This value...
#![cfg_attr(feature = "sgx", no_std)] #[cfg(feature = "sgx")] extern crate sgx_types; #[cfg(feature = "sgx")] #[macro_use] extern crate sgx_tstd as std; pub mod file; pub mod fs; pub mod poll; pub mod prelude; pub mod util;
fn main() { let mut i; 'a: for i in 0..10 { println!("{}", i); } 'a: for i in (0..10).step_by(2) { println!("{}", i); } }
/* * @lc app=leetcode.cn id=1108 lang=rust * * [1108] IP 地址无效化 */ // @lc code=start impl Solution { pub fn defang_i_paddr(address: String) -> String { return address.replace(".", "[.]"); } } // @lc code=end
//! Settings methods for the [`Engine`]. //! //! Methods for reading and setting various engine configuration values. //! //! Provided types: //! //! - [`DrawMode`]: Determines how `(x, y)` coordinates are used for rendering. //! - [`RectMode`]: Alias for `DrawMode`. //! - [`EllipseMode`]: Alias for `DrawMode`. //! - [...
fn main() { let result :Vec<i32> = (100..1000) // .map(split_to_abc) // .filter(|s| s.is_some()) .filter_map(split_to_abc) // .flat_map(|o| o) .collect(); for i in 0.. result.len() { print!("{} ", result[i]); if i == 10 { println!(""); } } println!(""); } fn split_to_abc(num :i32) -> Option<i32...
use datafusion::error::DataFusionError; use datafusion::execution::context::ExecutionProps; use datafusion::logical_plan::{DFSchema, LogicalPlan}; use datafusion::optimizer::optimizer::OptimizerRule; use datafusion::optimizer::utils; use std::sync::Arc; pub struct FlattenUnion; impl OptimizerRule for FlattenUnion { ...
use crate::rust_book::reference_cycle::List::{Cons, Nil}; use std::cell::RefCell; use std::rc::{Rc,Weak}; #[derive(Debug)] enum List { Cons(i32, RefCell<Rc<List>>), Nil, } impl List { fn tail (&self)->Option<&RefCell<Rc<List>>> { match self { Cons(_,item)=> Some(item), Nil=...
use anyhow::Result; use config::{ConfigError, Config, File}; use std::result; use std::env; use std::path::PathBuf; use redis::Client as RedisClient; use meilisearch_sdk::client::Client; use substrate_subxt::{Runtime, ClientBuilder, Client as SubClient}; use std::time::Duration; pub const REDIS_TIMEOUT: Duration = Dur...
use std::collections::HashMap; use std::time::{SystemTime, UNIX_EPOCH}; use super::{ find_method, ArithmeticOperation, Environment, Expr, Logical, LoxCallable, LoxClass, LoxInstance, Object, Result, RloxError, Stmt, Token, TokenType, INIT_METHOD, }; const THIS: &str = "this"; const SUPER: &str = "super"; #[d...
use std::default::Default; use std::hash::Hash; use std::option; #[cfg(feature = "with-serde")] use serde; use crate::Message; /// Wrapper around `Option<Box<T>>`, convenient newtype. /// /// # Examples /// /// ```no_run /// # use protobuf::MessageField; /// # use std::ops::Add; /// # struct Address { /// # } /// # ...
extern crate rand; use rand::*; use std::thread; const WIDTH: usize = 50; const HEIGHT: usize = 50; struct Universe { matrix: [[bool; WIDTH]; HEIGHT], epoch: u32 } #[inline] fn empty_matrix() -> [[bool; WIDTH]; HEIGHT] { [[false; WIDTH]; HEIGHT] } impl Universe { fn new_empty() -> Universe { ...
struct Solution; impl Solution { fn digits(mut n: i32) -> i32 { let mut res = 0; while n != 0 { n /= 10; res += 1; } res } fn find_numbers(nums: Vec<i32>) -> i32 { let mut res = 0; for n in nums { if Self::digits(n) % 2 == ...
pub fn convert_camel_case(characters: &[char]) -> String { match characters { [] => String::new(), [first_char, rest @ ..] => { rest.iter() .fold( (first_char.to_lowercase().to_string(), false), // first letter is always lower-case ...
// 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 ...
mod game; extern crate ncurses; use ncurses::*; static BOARD_SIZE : usize = 16; fn main() { let mut game = game::Game::new(load_board()); initscr(); noecho(); loop { printw(&(game.draw())); refresh(); game.advance(); std::thread::sleep_ms(500); clear(); }...
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ cargo::{CargoArgs, CargoCommand}, context::XContext, utils, Result, }; use structopt::StructOpt; #[derive(Debug, StructOpt)] pub struct Args { #[structopt(long, short, number_of_values = 1)] /// Run ch...
use multitap_core::input::*; use multitap_core::config::adapter::Mapper; use crate::device::Device; use crate::port::Port; use crate::config::port::Axis; use crate::config::adapter::Adapter; #[derive(Debug)] pub enum Error { InvalidTransformCreateCalled, UnsupportedAutoRepeatForReverseKey(KeyId), Find(Stri...
use readers::prelude::{Index, Value, RAReader, IndexIterator}; use crate::lang::{Attribute}; use fnv::FnvHashMap; use crate::alignments::MAlignmentFunc; use crate::alignments::funcs::iters::array_iter::ArrayIndexRefIterator; #[derive(Debug)] pub struct MulValueAlignFunc<'a> { unbounded_dims: Vec<usize>, index: Fnv...
// 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 crate::math::RawVector; #[cfg(feature = "dim3")] use na::DMatrix; #[cfg(feature = "dim2")] use na::DVector; use rapier::geometry::SharedShape; use rapier::math::{Point, Vector, DIM}; use wasm_bindgen::prelude::*; #[wasm_bindgen] #[cfg(feature = "dim2")] pub enum RawShapeType { Ball = 0, Cuboid = 1, Cap...
extern crate syscall; //add "redox_syscall": "*" to your cargo dependencies use syscall::scheme::SchemeMut; use syscall::error::*; use std::rc::{Rc, Weak}; use std::thread::JoinHandle; use std::sync::mpsc::TryRecvError; use std::cell::RefCell; use std::sync::{RwLock, Arc, Mutex}; use std::collections::btree_map::BTre...
use std::{ collections::{hash_set::Iter, HashMap, HashSet}, fs::read_to_string, }; use itertools::Itertools; fn main() { let p1 = part1("./input"); let p2 = part2("./input"); println!("Part 1: {}", p1); println!("Part 2: {}", p2); } fn part1(path: &str) -> i32 { let input = read_to_strin...
#[doc = "Register `STATUS` reader"] pub struct R(crate::R<STATUS_SPEC>); impl core::ops::Deref for R { type Target = crate::R<STATUS_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<STATUS_SPEC>> for R { #[inline(always)] fn from(reader: crate::R...
#[macro_use] extern crate serde_derive; extern crate serde; extern crate serde_json; extern crate r2d2; extern crate r2d2_diesel; #[macro_use] extern crate diesel; extern crate dotenv; #[macro_use] extern crate diesel_codegen; pub mod schema; pub mod model; pub mod dbmodel; pub mod persist; pub mod sync;
#[cfg(windows)] extern crate winapi; #[cfg(windows)] pub fn set_cursor_pos(x: i32, y: i32) { use winapi::um::winuser::SetCursorPos; unsafe { SetCursorPos(x,y); } }
use futures::Future; use crate::election::{Ballot, Role}; use crate::log::{Log, LogIndex, LogPrefix, LogSuffix}; use crate::message::Message; use crate::{Error, Result}; /// Raftの実行に必要なI/O機能を提供するためのトレイト. /// /// 機能としてはおおまかに以下の三つに区分される: /// /// - **ストレージ** /// - ローカルノードの状態やログを保存するための永続ストレージ /// - Raftが完全に正しく動作するため...
#![warn(clippy::all)] mod cmdline; mod err; mod file; mod gen; use cmdline::{Cmd, Pw}; use err::Error; use file::get_passfile; use gen::generate; use std::fmt::Debug; use std::fs; use std::path::Path; use std::path::PathBuf; use structopt::StructOpt; use zeroize::Zeroize; fn fmt_entry(fmt: &str, entry: EntryData) ->...
//! Vector with dimensions unknown at compile-time. #![allow(missing_docs)] // we hide doc to not have to document the $trhs double dispatch trait. use std::slice::{Iter, IterMut}; use std::iter::{FromIterator, IntoIterator}; use std::iter::repeat; use std::ops::{Add, Sub, Mul, Div, Neg, Index, IndexMut}; use rand::{...
use entry::{EntryState, Entry, ParseError}; use std::boxed::Box; use std::io::BufReader; use std::io::prelude::*; use std::fs::File; use chrono::{NaiveDate, Duration}; use cursive::Cursive; use cursive::view::View; use cursive::align::Align; use cursive::traits::*; use cursive::event::EventResult; use cursive::event:...
//! crates.io Source //! //! Crates.io source first download current crates.io-index zip from GitHub, //! and then extract downloadable crates from crates.io-index in memory. use crate::common::{Mission, SnapshotConfig, TransferURL}; use crate::error::Result; use crate::traits::{SnapshotStorage, SourceStorage}; use c...
use crate::common::*; #[derive(Copy, Clone, Debug, PartialEq, EnumVariantNames, EnumString, IntoStaticStr)] #[strum(serialize_all = "kebab-case")] pub(crate) enum UseColor { Auto, Always, Never, } #[cfg(test)] mod tests { use super::*; #[test] fn variants() { assert_eq!(UseColor::VARIANTS, &["auto", ...
use crate::imp::json_to_rust::validation::validate_root::validate_root; use crate::imp::version_adjuster::adjust_mut_list::adjust_mut_list; use crate::{HashM, HashMt}; use crate::error::Result; use crate::imp::json_to_rust::names::Names; use crate::imp::structs::root_obj::RootObject; use crate::imp::structs::root_value...
pub mod logger; pub mod string; pub mod toml; pub mod util;
use rspotify::{ model::{AdditionalType, Country, Market}, prelude::*, scopes, AuthCodeSpotify, Credentials, OAuth, }; #[tokio::main] async fn main() { // You can use any logger for debugging. env_logger::init(); // Set RSPOTIFY_CLIENT_ID, RSPOTIFY_CLIENT_SECRET and // RSPOTIFY_REDIRECT_URI...
use crate::lib_surface::*; use crate::lib_3d::*; use std::cmp::min; use std::cmp::max; use std::convert::TryFrom; use sdl2::pixels::Color; pub struct Point2D(pub i32, pub i32); pub struct Triangle2D(pub Point2D, pub Point2D, pub Point2D); fn update_min_max(s: &Screen, x: i32, y: i32, xmin: &mut [usize], xmax: &mut [u...
type TreeNode<K, V> = Option<Box<Node<K, V>>>; struct Node<K, V> { key: K, value: V, left: TreeNode<K, V>, right: TreeNode<K, V>, } trait BinaryTree<K, V> { fn pre_order(&self); fn in_order(&self); fn post_order(&self); } trait BinarySearchTree<K: PartialOrd, V>: BinaryTree<K, V> { fn...
error_chain! { foreign_links { Reqwest(::reqwest::Error); Url(::url::ParseError); } }
//! Peripheral Reset and Enable Control (REC) //! //! This module contains safe accessors to the RCC functionality for each //! periperal. //! //! At a minimum each peripheral implements //! [ResetEnable](trait.ResetEnable.html). Additionally those peripherals //! that have a multiplexer in the PKSU may also have metho...
pub mod interpolation; pub mod types; pub mod actions; use std::collections::HashMap; use std::sync::{Arc, Mutex}; use crate::bot::types::*; use crate::bot::actions::*; fn process_event<'slots, 'responses>( responses: &HashMap<&'responses str, &'responses str>, slots: &Mutex<HashMap<&'slots str, SlotVal>>, ...
use actix_files as fs; use actix_web::{web, HttpRequest}; // use std::io; use std::path::{Path, PathBuf}; pub async fn index(_req: HttpRequest) -> actix_web::Result<fs::NamedFile> { Ok(fs::NamedFile::open("../client/dist/index.html")?) } // http://stackoverflow.com/questions/2208933/how-do-i-force-a-favicon-refr...
use super::*; #[derive(Debug, PartialEq)] pub struct Pipeline<'a> { pub commands: Vec<Command<'a>>, pub negated: bool, } impl<'a> Pipeline<'a> { pub fn new(cmd: Command<'a>) -> Pipeline<'a> { Pipeline { commands: vec![cmd], negated: false, } } pub fn negate...
use crate::store; #[derive(Debug, thiserror::Error)] pub enum Error { #[error("nothing to insert")] NothingToInsert, #[error("failed to acquire store")] FailedToAcquireStore, #[error("content length missing")] ContentLengthMissing, #[error("payload too large")] PayloadTooLarge, #[er...
use rusqlite::Connection; mod migrations; fn main() { let mut conn = Connection::open_in_memory().unwrap(); migrations::runner().run(&mut conn).unwrap(); }