text
stringlengths
8
4.13M
#![allow(clippy::implicit_hasher)] use crate::{alloc_generators::CollectionGenerator, Driver, TypeGenerator, ValueGenerator}; use core::{hash::Hash, ops::RangeInclusive}; use std::{ collections::{HashMap, HashSet}, sync::Mutex, }; const DEFAULT_LEN_RANGE: RangeInclusive<usize> = 0..=32; // TODO support Build...
use lib::day4::passport::Passport; use lib::day4::runner; use std::error::Error; /* See https://adventofcode.com/2020/day/4 for details. */ fn main() -> Result<(), Box<dyn Error>> { // All we care about are required fields being present, which is checked at parse time. // If the type system says it's valid, it's v...
//! Random code uses in protobuf test crates. pub mod build; pub mod hex; mod serialize_deserialize_generated; pub use serialize_deserialize_generated::*; mod serialize_deserialize_dynamic; pub use serialize_deserialize_dynamic::*; mod serialize_deserialize_both; pub use serialize_deserialize_both::*; mod text_for...
use std::ops::RangeInclusive; use anyhow::{anyhow, bail, Context, Result}; use lazy_static::lazy_static; use regex::Regex; lazy_static! { pub static ref PROBLEM1_RE: Regex = Regex::new(r"(?:byr:(\S+)|iyr:(\S+)|eyr:(\S+)|hgt:(\S+)|hcl:(\S+)|ecl:(\S+)|pid:(\S+)|cid:(\S+)|\s)+?(?:\n\n|\n$)").unwrap(); pub static...
// Copyright 2020 WHTCORPS INC Project Authors. Licensed Under Apache-2.0 use std::fs; use std::io::{Error, ErrorKind, Result}; use std::sync::Mutex; use std::time::{Duration, Instant}; use crate::collections::HashMap; use libc::{self, pid_t}; use prometheus::core::{Collector, Desc}; use prometheus::{self, proto, Cou...
/// MAX deposits in the mem block pub const MAX_MEM_BLOCK_DEPOSITS: usize = 50; /// MAX withdrawals in the mem block pub const MAX_MEM_BLOCK_WITHDRAWALS: usize = 50; /// MAX withdrawals in the mem block pub const MAX_MEM_BLOCK_TXS: usize = 500; /// MAX tx size 50 KB pub const MAX_TX_SIZE: usize = 50_000; /// MAX withdr...
pub fn is_anagram (word:string) ->
{{#ifeq visibility "Full"}}{{else~}} let incr = {{>choice.getter incr use_old=true}}.is({{incr_condition}}); let incr_value = {{>counter_value value use_old=true}}; if incr.is_true() { actions.push(Action::{{to_type_name counter.name}}({{>choice.arg_ids counter}} {{~#ifeq visibility "NoM...
#[macro_use] extern crate bitflags; pub mod menu_service; pub mod read_write; pub mod backend; pub mod plugin_handler; pub mod id_register; pub mod service; pub mod message_service; pub mod capstone_service; pub mod dialogs; pub mod ui_ffi; pub mod ui; pub mod view; pub mod cfixed_string; pub mod docking; pub mod io; ...
use std::convert::From; use movingai::Coords2D; ///Describes a route between two points. ///Giving the total distance needed to travel and a vector of each step needed. pub struct Route { distance: f64, steps: Vec<Coords2D>, } impl From<(f64, Vec<Coords2D>)> for Route { fn from(item: (f64, Vec<Coords2D>)...
use std::fmt::Debug; use std::any::Any; use crate::callback::CallbackType; use crate::id::Identifier as IIdentifier; use crate::utils::{Utils, CreateInfo}; use crate::proc::Info; use crate::error::{Error, Result}; /// The option style type. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Style { /// Boolean styl...
// This file is part of Substrate. // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Softwa...
//! JSON export use crate::eval::emit::{Emitter, Event, RenderMetadata}; use crate::eval::primitive::Primitive; use std::io::Write; use super::table::{AsKey, FromPairs, FromPrimitive, FromVec, TableAccumulator}; impl AsKey<String> for serde_json::Value { fn as_key(&self) -> String { self.as_str().unwrap(...
// This file is part of Substrate. // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Softwa...
use std::collections::HashMap; use std::convert::TryInto; use std::fs::DirEntry; use std::fs::File; use std::fs::{self}; use std::io::prelude::*; use std::io::SeekFrom; use std::path::Path; use std::time::Duration; use rusb::{Context, Device, DeviceDescriptor, DeviceHandle, Direction, UsbContext}; static VID: u16 = 0...
use jinya_ui::widgets::form::input::*; use jinya_ui::layout::button_row::*; use jinya_ui::layout::page::*; use jinya_ui::widgets::button::*; use jinya_ui::widgets::dialog::content::*; use yew::prelude::*; use yew::services::ConsoleService; pub struct ContentDialogs { link: ComponentLink<Self>, dialog_open: boo...
#![cfg_attr(rustfmt, rustfmt::skip)] use { ::syn::{ visit_mut::VisitMut, }, super::{ *, }, }; pub(in super) fn export ( Args { executor, js, rename }: Args, fun: &'_ ItemFn, ) -> Result<TokenStream2> { let block_on = match (executor, fun.sig.asyncness) { | (Some(Exe...
use cgmath::prelude::One; use cgmath::{Matrix3, Matrix4}; use gfx; use gfx::gfx_pipeline_inner; use gfx::traits::*; use piston_window::*; use shader_version::glsl::GLSL; use shader_version::Shaders; use super::vertex::Vertex; gfx::gfx_pipeline!( object_pipe { vbuf: gfx::VertexBuffer<Vertex> = (), u_model_view...
#[doc = "Register `ADDR` reader"] pub struct R(crate::R<ADDR_SPEC>); impl core::ops::Deref for R { type Target = crate::R<ADDR_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<ADDR_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<ADDR_SP...
use std::fs; fn calculate(input: &Vec<Vec<&str>>) -> (i32, i32, i32) { let mut horiz:i32 = 0; let mut depth: i32 = 0; let mut aim: i32 = 0; for x in input { let dist: i32 = x[1].parse().expect("Bug"); match x[0] { "forward" => { horiz += dist; ...
#![cfg_attr(rustfmt, rustfmt::skip)] //! See [the dedicated section of the guide](https://getditto.github.io/safer_ffi/dyn_traits/_.html). use_prelude!(); #[path = "futures/_mod.rs"] #[cfg(feature = "futures")] #[cfg_attr(all(docs, feature = "nightly"), doc(cfg(feature = "futures")) )] pub mod futures; #[doc(no...
// OpenAOE: An open source reimplementation of Age of Empires (1997) // Copyright (c) 2016 Kevin Fuller // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including wi...
use clickhouse_rs::Pool; use clickhouse_rs::types::{Options, Simple, Complex, Block}; use failure::{Error, format_err}; use futures::{future, Future, Stream}; use log::*; use std::time::{Duration, Instant}; use tesseract_core::{Backend, DataFrame, QueryIr}; mod df; mod sql; use self::df::{block_to_df}; use self::sql:...
#[doc = "Register `MTACTL` reader"] pub struct R(crate::R<MTACTL_SPEC>); impl core::ops::Deref for R { type Target = crate::R<MTACTL_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<MTACTL_SPEC>> for R { #[inline(always)] fn from(reader: crate::R...
pub struct Pokemon { pub id: u32, pub name: String, pub element: String, pub in_pokeball: bool, } impl Pokemon { pub fn new(id: u32, name: String, element: String, in_pokeball: bool) -> Pokemon { Pokemon { id: id, name: name, element: element, ...
use std::ops::Index; #[derive(Debug)] struct Policy { min: i32, max: i32, chr: char } impl Policy { fn from_string(str: &str) -> Result<Policy, &'static str> { let mut parts: Vec<&str> = str.trim().split(' ').collect(); if parts.len() != 2 { return Err("malformed data"); ...
#[allow(unused_imports)] use serde_json::Value; #[derive(Debug, Serialize, Deserialize)] pub struct StoragepoolTiers { #[serde(rename = "tiers")] pub tiers: Option<Vec <crate::models::StoragepoolTierExtended>>, }
use nom::IResult; use std::str; use std::vec::Vec; use packfile; struct Tree { sha: String, entries: Vec<TreeEntry> } struct TreeEntry { mode: EntryMode, path: String, sha: String } enum EntryMode { Normal, Executable, Symlink, Gitlink, SubDirectory } impl Tree { fn fro...
//! PADRE Debugger //! //! This program creates a socket interface that enables debuggers to communicate //! in a standard manner with multiple different debuggers and programming languages. //! Options supported: //! -p/--port Port to run socket interface on //! -h/--host Hostname to run on //! -t/--type T...
use crate::component::Component; use crate::entity_id::EntityId; use crate::views::ViewMut; /// Removes component from entities. pub trait Remove { /// Type of the removed component. type Out; /// Removes component in `entity`, if the entity had a component, they will be returned. /// Multiple compon...
//! `goat-cli` is a command line interface to query the //! [Genomes on a Tree Open API](https://goat.genomehubs.org/api-docs/) using //! an asynchronous [`tokio`](<https://docs.rs/tokio/latest/tokio/>) runtime. //! //! I'm documenting the code here for others, and for future me. use lazy_static::lazy_static; use std:...
// OpenAOE: An open source reimplementation of Age of Empires (1997) // Copyright (c) 2016 Kevin Fuller // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including wi...
use byteorder::{ByteOrder, BigEndian}; const SCONV: f64 = 60.0 / (1u64 <<32) as f64; type Tid = [u8; 8]; pub fn make_tid(year: u32, month: u32, day: u32, hour: u32, minute: u32, second: f64) -> Tid { let days = ((year - 1900) * 12 + month - 1) * 31 + day - 1; let minutes = ((...
#![allow(unused)] // FIXME: #[macro_use] extern crate log; #[macro_use] extern crate noa_common; use std::{path::PathBuf, process::Stdio, time::Duration}; use clap::Parser; use editor::Editor; use noa_common::logger::install_logger; use noa_compositor::{ compositor::Compositor, terminal::{Event, InputEvent,...
mod block_client; mod es_sinker; pub use block_client::BlockClient; pub use es_sinker::{EsSinker, IndexConfig, LocalTipInfo}; use serde::{Deserialize, Serialize}; use starcoin_crypto::HashValue; use starcoin_rpc_api::types::{ BlockHeaderView, BlockMetadataView, BlockView, SignedUserTransactionView, StrView, Tr...
#![no_std] #![no_main] mod defmt_impls; use cortex_m::asm::nop; use stm32wlxx_hal as hal; use hal::pac; use hal::prelude::*; use cortex_m_rt::entry; #[entry] fn main() -> ! { let dp = pac::Peripherals::take().unwrap(); let mut rcc = dp.RCC.constrain(); let mut gpioa = dp.GPIOA.split(&mut rcc.ahb2); ...
struct Amazon{ wallet: u32, pin: u8 } struct Google{ wallet: u32, pin: u8 } struct Facebook{ id: u32 } impl Pay for Amazon { fn pay_with(&self, id: u32) -> bool{ if() } } trait Pay { fn pay_with(&self, id: u32) -> bool; } fn main() { // Statements here are executed when th...
use std::env; // accept command line arguments among other things use std::io; use std::io::prelude::*; use std::fs::File; fn main() -> io::Result<()> { let args: Vec<String> = env::args().collect(); let filename = &args[1]; println!("Opening {}...", filename); let mut f = File::open(filename)?; let mut buf...
extern crate rand; extern crate ropey; use std::io::Cursor; use ropey::Rope; const TEXT: &str = include_str!("test_text.txt"); #[test] #[cfg_attr(miri, ignore)] fn from_reader_01() { // Make a reader from our in-memory text let text_reader = Cursor::new(TEXT); let rope = Rope::from_reader(text_reader)....
// mod disk; use super::disk::Disk; use super::utility; pub const MAGIC_NUMBER: usize = 0xf0f03410; pub const INODES_PER_BLOCK: usize = 128; pub const POINTERS_PER_INODE: usize = 5; pub const POINTERS_PER_BLOCK: usize = 1024; #[derive(Copy, Clone, Debug)] #[allow(dead_code)] pub struct Superblock { pub MagicNum...
use std::sync::Arc; use std::collections::HashMap; use std::vec::Vec; use rpc::zeus_meta::ZeusDBSchema; use super::table_schema::TableSchema; pub struct DBSchema { inner: Arc<ZeusDBSchema>, tables: HashMap<i32, Arc<TableSchema>> } impl DBSchema { pub fn new(zeus_db_schema: ZeusDBSchema) -> DBSchema { let m...
use rapier::dynamics::CCDSolver; use wasm_bindgen::prelude::*; #[wasm_bindgen] pub struct RawCCDSolver(pub(crate) CCDSolver); #[wasm_bindgen] impl RawCCDSolver { #[wasm_bindgen(constructor)] pub fn new() -> Self { RawCCDSolver(CCDSolver::new()) } }
use ds323x::TempConvRate; use embedded_hal_mock::{i2c::Transaction as I2cTrans, spi::Transaction as SpiTrans}; #[allow(unused)] mod common; use self::common::{ destroy_ds3232, destroy_ds3234, new_ds3232, new_ds3234, BitFlags as BF, Register, DEVICE_ADDRESS as DEV_ADDR, DS323X_POR_STATUS, }; macro_rules! call_...
use super::*; use nom; use std::ops::RangeInclusive; use std::str; fn is_word(c: char) -> bool { matches!(c, 'a'..='z' | 'A'..='Z' | '0'..='9' | '_' | '.') } named!(word(Span) -> Word, do_parse!( word: take_while!(is_word) >> (Word { word, }) )); named!(hex_integer(Span) -> I...
use serde::{Deserialize, Serialize}; #[derive(Default, Deserialize, Serialize)] /// Struct representing a [Mastodon field](https://docs.joinmastodon.org/entities/field/) pub struct Field { pub name: String, pub value: String, pub verified_at: Option<String>, }
//! TCP and UDP Echo Servers. //! //! Implementation of [RFC 862](https://tools.ietf.org/html/rfc862) extern crate clap; use std::process; mod tcp; /// An EchoServer instance must be able to handle clients. pub trait EchoServer { fn start(&self, host: &str, port: u16) -> Result<(), String>; } fn main() { ...
use anyhow::Result; use super::Context; use crate::{ command::Ed25519, types::{ External, HashSig, Mac, NBytes, U64, }, }; use iota_streams_core_edsig::signature::ed25519; /// Signature size depends on Merkle tree height. impl<F> Ed25519<&ed25519::Keypair, &External...
// should find the bug even without these //@compile-flags: -Zmiri-disable-validation -Zmiri-disable-stacked-borrows struct SliceWithHead(u8, [u8]); fn main() { let buf = [0u32; 1]; // We craft a wide pointer `*const SliceWithHead` such that the unsized tail is only partially allocated. // That should be ...
extern crate int_enum; use int_enum::IntEnum; #[repr(usize)] #[derive(PartialEq, Eq, Debug, Clone, Copy, IntEnum)] pub enum Direction { North = 0, East = 1, South = 2, West = 3, } pub struct Robot { x: i32, y: i32, direction: Direction, } impl Robot { pub fn new(x: i32, y: i32, direc...
//! A simple example of a chat app with SOCKS5 support. use std::fs; use std::io::Result; use std::net::TcpStream; use std::sync::{Arc, Mutex}; use std::thread; use std::time; use std::io::stdin; use std::net::{SocketAddr, TcpListener}; use socks::Socks5Stream; type Chat = Arc<Mutex<talkers::Talker>>; type Chats = A...
#![feature(test)] #![feature(str_split_once)] #[allow(unused_imports)] use shared::prelude::*; extern crate test; const INPUT: &'static str = include_str!("./input.txt"); type Data<'a> = Vec<Instruction>; type Solution = i32; #[derive(Debug, Clone, PartialEq, Copy)] enum OpCode { Acc, Jmp, Nop, } #[der...
use super::TypeInfo; use crate::all_storages::AllStorages; use crate::error; use crate::info::DedupedLabels; use crate::scheduler::label::Label; use crate::scheduler::workload::Workload; use crate::type_id::TypeId; use crate::world::World; use alloc::boxed::Box; use alloc::vec::Vec; /// Self contained system that may ...
mod state_machine; use crate::cloud_provider::{CloudNodeInfo, CloudProvider}; use crate::dns_provider::DnsProvider; use crate::node::discovery::{NodeDiscoveryData, NodeDiscoveryObserver, NodeDiscoveryProvider}; use crate::node::exploration::NodeExplorationObserver; use crate::node::stats::NodeStatsStreamFactory; use c...
use serde::{Deserialize, Serialize}; use std::error::Error; use std::net::Ipv4Addr; use warp::{http, Filter}; mod db; use db::{Book, BookScoresMgr, Score}; const LISTEN_ADDRESS: Ipv4Addr = Ipv4Addr::new(127, 0, 0, 1); const LISTEN_PORT: u16 = 8282; const RSC_VERSION: &str = "v1"; const RSC_NAME: &str = "books"; con...
use crate::metadata_detector::MetadataDetector; use crate::{Meta, Type}; #[test] fn detect_file_mime_type() { let path = "foo.txt"; let mut meta = Meta::new("test", Type::File); let meta_detector = MetadataDetector::new().unwrap(); assert_eq!(meta.metadata.keys().count(), 0); meta_detector.popul...
use crate::physics::Position; use bevy::prelude::*; fn position_sprites_system(mut query: Query<(&mut Transform, &Position)>) { for (mut transform, position) in query.iter_mut() { transform.translation.x = position.0.x; transform.translation.y = position.0.y; } } pub struct SantaRenderPlugin; ...
//! Wasm plugin system implementation details. mod error; mod manager; mod plugin; pub use error::{Handler as HandlerError, Runtime as RuntimeError}; pub use manager::Manager; pub use plugin::Plugin;
use super::*; struct Factory {} impl HttpServiceFactory for Factory { fn register(self, config: &mut AppService) { get_nexuses.register(config); get_nexus.register(config); get_node_nexuses.register(config); get_node_nexus.register(config); put_node_nexus.register(config); ...
extern crate rustbox; use std::default::Default; use rustbox::{InitOptions, Key, RustBox}; mod lib; use lib::text_box::TextBox; fn main() { let rustbox = match RustBox::init(InitOptions { buffer_stderr: true, ..Default::default() }) { Result::Ok(v) => v, Result::Err(e) => pa...
use asexp::Sexp; use expression::{Expression, ExpressionError}; use num_traits::{One, Zero}; use std::fmt::Debug; use std::ops::{Add, Div, Mul, Sub}; pub trait NumType: Debug + Copy + Clone + PartialEq + PartialOrd + Default + Zero + One + Add<Output = Self> + Sub<Output = Self>...
extern crate number_place_lib; use rand::seq::SliceRandom; use clap::{App, Arg}; //use chrono::prelude::*; use std::path::Path; use std::fs::File; use std::io::{BufWriter, Write}; #[derive(Debug, Clone)] struct SelectableColValues { col_index: usize, values: Vec<i32>, } fn generate_line(lines: &Vec<Vec<i32>>...
/* * Ory APIs * * Documentation for all public and administrative Ory APIs. Administrative APIs can only be accessed with a valid Personal Access Token. Public APIs are mostly used in browsers. * * The version of the OpenAPI document: v0.0.1-alpha.21 * Contact: support@ory.sh * Generated by: https://openapi-gen...
// Copyright 2018-2021 Cargill Incorporated // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or...
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use crate::{tl_types::TLType, utils::MyResult}; impl TLType for u32 { fn tl_read(input: &mut std::io::Read) -> MyResult<Self> { Ok(input.read_u32::<LittleEndian>()?) } fn tl_write(&self, output: &mut std::io::Write) -> MyResult<usize> { ...
use core::convert::{AsMut, AsRef}; use core::ops::{Deref, DerefMut}; /// Type used to access `!Sync` storages. #[cfg_attr(docsrs, doc(cfg(feature = "thread_local")))] pub struct NonSync<T: ?Sized>(pub(crate) T); impl<T: ?Sized> AsRef<T> for NonSync<T> { fn as_ref(&self) -> &T { &self.0 } } impl<T: ?S...
use super::{ Convert, ConvertDetails, IdempotentData, IdempotentStore, Quantity, SettlementAccount, SettlementStore, SE_ILP_ADDRESS, }; use bytes::Bytes; use futures::{ future::{err, ok, result, Either}, Future, }; use hyper::{Response, StatusCode}; use interledger_ildcp::IldcpAccount; use interledger_p...
//! Utilities for discovering devices on the LAN. //! //! Examples //! //! ```rust,no_run //! use futures_util::{pin_mut, stream::StreamExt}; //! use mdns::{Error, Record, RecordKind}; //! use std::time::Duration; //! //! const SERVICE_NAME: &'static str = "_googlecast._tcp.local"; //! //! #[async_std::main] //! async ...
use crate::mesh::Mesh; use std::fs::OpenOptions; use stl_io::{Normal, Vertex}; pub struct Exporter { } impl Exporter { pub fn new() -> Self { Self {} } pub fn export(&self, mesh: &Mesh, path: &str) { let mut stl_mesh: Vec<stl_io::Triangle> = Vec::new(); let positions: Vec<f32> = ...
use serde_derive::Deserialize; use std::path::PathBuf; mod parse; mod utils; use parse::parse_yaml_config; use utils::default_config_xdg_dir; #[derive(Deserialize, Debug)] pub struct Configuration { pub actions: Option<Vec<ActionSpec>>, } #[derive(Deserialize, Debug)] pub struct ActionSpec { pub action: Opt...
#[macro_use] extern crate serde_derive; #[macro_use] extern crate slog; #[macro_use] extern crate trackable; pub use self::error::{Error, ErrorKind}; pub mod contact; pub mod distribution; pub mod global; pub mod http; pub mod study; pub mod time; pub mod trial; mod error; mod message; pub type Result<T> = std::res...
// Cadence - An extensible Statsd client for Rust! // // This file is dual-licensed to the public domain and under the following // license: you are granted a perpetual, irrevocable license to copy, modify, // publish, and distribute this file as you see fit. // This example shows using a very simple UDP sink. This si...
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use std::{ io::{Error, Read, Write}, ops::Deref, }; use hemtt_io::{ReadExt, WriteExt}; #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub struct Timestamp(u32); impl Deref for Timestamp { type Target = u32; fn deref(&self) ->...
#![allow(warnings)] use argparse::{ArgumentParser, Store, StoreTrue}; #[macro_use] extern crate autograph; use autograph::nn::{ Conv2d, Dense, Forward, Layer, Pool2dArgs, autograd::{Graph, ParameterD, Variable, Variable2, Variable4}, optimizer::{Optimizer, Sgd}, saved::{SavedModel, SavedCheckpoint}, }; ...
use crate::map::{Degree, MapCoord}; use ahash::RandomState; use csv::Reader; use indexmap::IndexMap; use std::{ collections::{HashMap, HashSet}, fmt::Display, }; #[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)] pub struct StationId(pub u32); // Corresponds to entries in stations.csv #[derive(Debug, Clone)] ...
#[doc = r"Register block"] #[repr(C)] pub struct PSEL { #[doc = "0x00 - Pin number configuration for PDM CLK signal"] pub clk: CLK, #[doc = "0x04 - Pin number configuration for PDM DIN signal"] pub din: DIN, } #[doc = "CLK (rw) register accessor: an alias for `Reg<CLK_SPEC>`"] pub type CLK = crate::Reg<...
mod inp; use inp::Inp; use std::io::Result; use std::collections::LinkedList; fn main() -> Result<()> { let mut inp = Inp::new(); let s: LinkedList<char> = inp.next_line().trim().chars().collect(); let mut p: LinkedList<char> = inp.next_line().trim().chars().collect(); if s.len() == p.len() { ...
use std::io::Error; use std::collections::HashMap; pub use rustc_serialize::json::Json; use rustc_serialize::json::ParserError; use math::{Point3, Vector3}; /// An error that occured while reading from a JSON object #[derive(Debug)] pub enum JsonError { InvalidInput, UnsupportedType(String), NoKey(String)...
extern crate calculator; use calculator::Expr::*; use calculator::*; fn main() { let x = Value(10.0); let y = Value(20.0); let sum = Expr::sum(&x, &y); let div = Expr::div(&sum, &y); let mult = Expr::pro(&div, &sum); println!("{:?}", mult); println!("{}", mult.to_float()); }
extern crate itertools; extern crate pest; #[macro_use] extern crate pest_derive; use std::collections::hash_map::Entry; use std::collections::HashMap; use itertools::Itertools; use pest::Parser; #[derive(Parser)] #[grammar = "claim.pest"] pub struct ClaimParser; const PUZZLE: &str = include_str!("../input"); stru...
pub use realm::base::*; pub fn increment(in_: &In0) -> Result<()> { use crate::schema::hello_counter; use diesel::prelude::*; diesel::update(hello_counter::table) .set(hello_counter::count.eq(hello_counter::count + 1)) .execute(in_.conn) .map(|_| ()) .map_err(Into::into) } ...
use blake2b_simd::blake2b; use parking_lot::RwLock; use rand::{thread_rng, Rng}; use std::sync::Arc; use std::thread; use std::time::Duration; #[derive(Clone)] pub struct POS { target: usize, delay: u64, is_interrupt: Arc<RwLock<bool>>, } impl POS { pub fn new(target: usize, delay: u64) -> POS { ...
#![no_std] #![no_main] extern crate panic_semihosting; extern crate cortex_m_rt; use core::sync::atomic::Ordering; use core::sync::atomic::compiler_fence; use core::cell::RefCell; use core::fmt::Write; use core::ops::DerefMut; use cortex_m::interrupt::Mutex; use cortex_m_rt::entry; use nrf51::interrupt; use ubit:...
#[derive(Debug)] enum Currency { Pkr, usDollar, Yen, Aed, } fn main() { let num = "hello"; match num { num => println!("value exist is : {}", num), } // let amount = Currency::Yen; // match amount { // Currency::Pkr => println!("$1 in pkr is Rs.156"), // Cur...
// Claxon -- A FLAC decoding library in Rust // Copyright 2017 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. #![no_main] extern crate...
//! Types to support arrays of [ASCII][ascii] and [UCS4][ucs4] strings //! //! [ascii]: https://numpy.org/doc/stable/reference/c-api/dtype.html#c.NPY_STRING //! [ucs4]: https://numpy.org/doc/stable/reference/c-api/dtype.html#c.NPY_UNICODE use std::cell::RefCell; use std::collections::hash_map::Entry; use std::convert:...
use core::controller::{Controller, RequestController}; use http::request::Request; use http::response::Response; use http::Method::GET; pub struct HomeController; impl Controller for HomeController { #[core_macros::route("/", GET)] fn handle(&self, request: &Request, request_controller: &RequestController) ->...
use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader}; fn traverse_firewall(layers: &HashMap<u32, u32>, delay: u32) -> (u32, u32) { let mut penalty = 0; let mut caught = 0; for (ticks, range) in layers { // [0 1 2, ..., r-2, r-1, r-2, ..., 2, 1] if (ticks + de...
use super::{deserialize_binary, deserialize_from_string, serialize_binary, serialize_to_string}; use serde::{Deserialize, Serialize}; #[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)] struct TestStruct { #[serde( deserialize_with = "deserialize_binary", serialize_with = "serialize_binar...
use crate::applic_folder::fsm_folder::fsm::Fsm; use crate::applic_folder::fsm_folder::gen_folder::genc_folder::c_gen_gi_h::vtable_pattern; use crate::applic_folder::fsm_folder::gen_folder::genrust_folder::genall::build_cnd_id; use crate::applic_folder::fsm_folder::gen_folder::genrust_folder::genall::build_msg_id; use c...
use opengl_graphics::Texture; use specs::prelude::*; use crate::isometric::Isometric; use crate::pigeon::PigeonholeSort; use crate::position::Position; use crate::settings::flatten_pos; use crate::sprite::Sprite; use crate::view::components::IsometricCamera; use crate::view::ViewCutMode; /// Sorts objects according t...
use message_types::ips_bs::{ToBackground, ToPage}; use wasm_bindgen::{prelude::*, JsCast}; use wasm_bindgen_extension::browser; use web_sys::MessageEvent; #[wasm_bindgen(start)] pub async fn main() -> Result<(), JsValue> { console_error_panic_hook::set_once(); wasm_logger::init(wasm_logger::Config::new(log::L...
extern crate rand; use std::io; use std::cmp::Ordering; use rand::Rng; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1, 101);//exclusive on the upper bound //println!("The secret number is: {}", secret_number); loop{ println!("Please input your ...
use crate::event::{self, Event}; use regex::Regex; use scraper::{Html, Selector}; use std::error::Error; const PUSH_EVENT: &str = r"^Created \d{1,} commits in \d{1,} repositor(y|ies)$"; const PULL_REQUEST_REVIEW_EVENT: &str = r"^Reviewed \d{1,} pull request(s)? in \d{1,} repositor(y|ies)$"; const PULL_REQUEST_EVEN...
#![cfg(not(target_arch = "wasm32"))] extern crate wasm_bindgen_test_project_builder as project_builder; use project_builder::{project, run}; mod comments; mod dependencies; mod import_class; mod imports; mod js_objects; mod node; mod non_debug; mod non_wasm; mod simple; mod typescript;
mod display; mod git; mod github; mod repository; mod subcommand; use anyhow::Result; use env_logger::Target; pub fn check() -> Result<()> { init_logger(); subcommand::checker::check()?; Ok(()) } pub fn check_output_json() -> Result<()> { init_logger(); let j = subcommand::checker::output_json()?...
use std::fmt; use aes::{Aes128, cipher::{generic_array::GenericArray, {BlockCipher, NewBlockCipher}}}; use serde::{Deserializer, Deserialize}; use FormatError::*; #[derive(Debug)] pub enum FormatError { UnexpectedEof, BadMagic, BadAes, BadBase64, BadLength, BadMetadata } type Result<T> = std::result::Result<T, Format...
// 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 ...
#[allow(unused_imports)] use serde_json::Value; #[derive(Debug, Serialize, Deserialize)] pub struct SubnetsSubnetPoolRange { /// High IP #[serde(rename = "high")] pub high: String, /// Low IP #[serde(rename = "low")] pub low: String, }
use crate::config; use crate::eth; use crate::exchange; use crate::geth; use crate::http; use crate::log; use crate::time; use crate::types; use secp256k1::SecretKey; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::fmt::Display; use std::fs; #[derive(Debug, Serialize, Deserialize)] pub str...
use core::fmt; use std::{fmt::Display, ops::Deref}; #[derive(PartialEq, Debug)] pub enum Tree<T: Display> { Leaf(T), Fork(Box<Tree<T>>, Box<Tree<T>>) } impl<T: Display> Tree<T> { pub fn left(&mut self) -> &mut Box<Tree<T>> { match self { Self::Leaf(ref mut _leaf) => panic!("left - Shou...