text
stringlengths
8
4.13M
pub mod graphics; pub mod core; pub mod os; pub mod io; mod ffi;
use crate::config::Config; use pemstore::pathfinder::PathFinder; use std::path::PathBuf; #[derive(Debug)] pub struct MixNodePathfinder { pub config_dir: PathBuf, pub private_sphinx_key: PathBuf, pub public_sphinx_key: PathBuf, } impl MixNodePathfinder { pub fn new_from_config(config: &Config) -> Self ...
mod network_type; pub use self::network_type::SdpNetworkType; pub use self::network_type::parse_network_type; mod address_type; pub use self::address_type::SdpAddressType; pub use self::address_type::parse_address_type; mod codec; pub use self::codec::SdpCodecIdentifier; pub use self::codec::parse_codec_identifier; ...
use std::{ io::{self, Read}, process, }; use arboard::Clipboard; use clap::{Parser, Subcommand}; type Result<T, E = Error> = std::result::Result<T, E>; #[derive(Clone, Debug, Parser)] struct Args { #[clap(subcommand)] command: Command, } #[derive(Clone, Copy, Debug, Subcommand)] enum Command { #...
use super::event_dispatcher::*; use super::event_dispatcher::event::*; pub const KERNEL_EVENT_REQUEST: &'static str = "kernel.request"; pub const KERNEL_EVENT_EXCEPTION: &'static str = "kernel.exception"; pub const KERNEL_EVENT_VIEW: &'static str = "kernel.view"; pub const KERNEL_EVENT_CONTROLLER: &'static str = "kern...
#[doc = "Register `TR` reader"] pub type R = crate::R<TR_SPEC>; #[doc = "Register `TR` writer"] pub type W = crate::W<TR_SPEC>; #[doc = "Field `LT` reader - Analog watchdog lower threshold"] pub type LT_R = crate::FieldReader<u16>; #[doc = "Field `LT` writer - Analog watchdog lower threshold"] pub type LT_W<'a, REG, co...
//extern crate rand; use Event::NewRelease; //use rand::{thread_rng, Rng}; enum Event { NewRelease, } fn probability(_: &Event) -> i32 { // let mut random = rand::thread_rng(); // random.gen_range(0, 101) 80 } fn descriptive_probability(event: Event) -> &'static str { match probability(&event) { ...
use async_std::sync::Arc; use crate::file::FileProvider; use crate::mongo::models::document::Document; use crate::mongo::wrapper::MongoWrapper; use crate::mongo::Error; pub type DataResult<T> = Result<T, Error>; #[derive(Clone)] pub struct Data { pub file: Arc<Box<dyn FileProvider>>, mongo: MongoWrapper, } ...
use super::{BrowserOptions, Error, ErrorKind, Result}; use log::debug; use std::process::{Command, Stdio}; /// Parses `line` to find tokens (including quoted strings), and invokes `op` /// on each token pub(crate) fn for_each_token<F>(line: &str, mut op: F) where F: FnMut(&str), { let mut start: Option<usize> ...
use core::fmt; use std::borrow::Borrow; use std::fmt::{Display, Formatter}; use std::hash::{Hash, Hasher}; use std::ops::Deref; use crate::BooToOwned; /// A borrowed-or-owned type (boo). /// /// Similar to `std::borrow::Cow` but without the requirement of /// `TBorrowed : ToOwned<Owned=TOwned>`. #[derive(Debug)] pub ...
use crate::{ common::{Conditionals, Projection, StandardQueryParameters}, error::Error, response::ApiResponse, types::ObjectIdentifier, }; #[derive(Default, Serialize)] #[serde(rename_all = "camelCase")] pub struct RewriteObjectOptional<'a> { #[serde(flatten)] pub standard_params: StandardQuery...
use webrender::api::*; use render::RenderBuilder; use widget::draw::Draw; use resources::resources; use resources::image::ImageInfo; use geometry::{Rect, RectExt, Size}; use style::Component; #[derive(Clone, Debug)] pub struct GLCanvasState { data: ExternalImageData, image_info: ImageInfo, } impl Component f...
use iced_graphics::{Backend, Defaults, Primitive, Renderer}; use iced_native::{layout, mouse, Element, Hasher, Layout, Length, Point, Rectangle, Size, Widget}; pub struct Wrapper { pub items: Vec<Primitive>, size: Size, } impl Wrapper { pub fn new(height: f32, width: f32) -> Wrapper { Wrapper { ...
use sdl2::pixels::Color; use sdl2::rect::Rect; use sdl2::render::WindowCanvas; use sdl2::Sdl; pub struct Display { gfx: [[u8; 64]; 32], draw_flag: bool, canvas: WindowCanvas, } static SCALE: u32 = 20; impl Display { pub fn new(sdl_context: Sdl) -> Display { let video_subsystem = sdl_context.v...
use tokio::net::{TcpListener, TcpStream}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use std::env; #[tokio::main] async fn main() { let addr = env::args() .nth(1) .unwrap_or_else(|| "127.0.0.1:6123".to_string()); let listener = TcpListener::bind(&addr).await.unwrap(); println!("listen on...
use crate::{ database::{Database, DatabaseKind, NoWriteMap, TxnManagerMessage, TxnPtr}, error::{mdbx_result, Result}, flags::{TableFlags, WriteFlags}, table::Table, Cursor, Decodable, Error, Stat, }; use ffi::{MDBX_txn_flags_t, MDBX_TXN_RDONLY, MDBX_TXN_READWRITE}; use indexmap::IndexSet; use libc::...
use itertools::Itertools; pub fn verse(n: i32) -> String { match n { 0 => "No more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.\n".to_string(), 1 => format!("{} bottle of beer on the wall, {} bottle of beer.\nTake it down and ...
use alloc::vec::Vec; use util::Hash; use super::{Sha2, H512_TRUNC256}; pub struct Sha512Trunc256(Sha2<u64>); impl Sha512Trunc256 { pub fn new() -> Self { Self::default() } } impl Default for Sha512Trunc256 { #[rustfmt::skip] fn default() -> Self { Self(Sha2::<u64>::new(H512_TRUNC256...
/// slog formatter for MessagePack using the rmp-serde library. /// /// Implementation translated straight from the JSON formatter. Not /// sure if good. extern crate slog; extern crate slog_stream; extern crate slog_serde; extern crate rmp_serde; use std::io; use slog_serde::SerdeSerializer; use slog::{Record, OwnedK...
use font::{parse}; fn main() { env_logger::init(); let arg = std::env::args().nth(1).unwrap(); let data = std::fs::read(&arg).expect("can't read file"); let font = parse(&data).unwrap(); println!("{} glyphs", font.num_glyphs()); let gid = font.gid_for_unicode_codepoint(205).unwrap(); font.g...
pure fn add(x: int, y: int) -> int { ret x + y; } pure fn sub(x: int, y: int) -> int { ret x - y; } pure fn mul(x: int, y: int) -> int { ret x * y; } pure fn div(x: int, y: int) -> int { ret x / y; } pure fn rem(x: int, y: int) -> int { ret x % y; } pure fn lt(x: int, y: int) -> bool { ret x < y; } pure fn le(x...
//! # Regression models //! //! `regression` provides traits to build and run regression models. //! extern crate ndarray; use std::error::Error; use ndarray::{Array1, ArrayBase, Data, Ix1, Ix2, LinalgScalar}; /// Basic API for a regression model using ndarray types. /// /// The model here takes in a 2-d...
#![macro_use] use crate::gpio::{sealed::Pin, AnyPin}; use crate::pac::spi; use crate::spi::{ByteOrder, Config, Error, Instance, MisoPin, MosiPin, SckPin, WordSize}; use crate::time::Hertz; use core::marker::PhantomData; use core::ptr; use embassy::util::Unborrow; use embassy_extras::unborrow; pub use embedded_hal::spi...
#![allow(non_camel_case_types)] extern crate libc; use self::libc::{int64_t, size_t, ssize_t, time_t, timeval, uint8_t, uint32_t, uint64_t}; pub type Enum_Unnamed1 = ::libc::c_uint; pub const LIBRADOS_OP_FLAG_EXCL: ::libc::c_uint = 1; pub const LIBRADOS_OP_FLAG_FAILOK: ::libc::c_uint = 2; pub const LIBRADOS_OP_FLAG_F...
//! Data for [Swagger UI](https://github.com/swagger-api/swagger-ui). use iron::{Chain, Handler, IronResult, Request, Response, status}; use iron::headers::ContentType; use iron::modifiers::Header; use mount::Mount; use middleware::ResponseHeaders; /// Stub for the Swagger endpoint. Enable with the Cargo feature "sw...
use std::collections::VecDeque; pub struct Node<T> { pub val: T, pub left: Option<Box<Node<T>>>, pub right: Option<Box<Node<T>>>, } impl<T> From<T> for Node<T> { fn from(val: T) -> Self { Self { val, left: None, right: None } } } pub fn rotate_in_place_deq<T>(root: &mut Node<T>) { let...
use crate::member::Member; use crate::poll::{Poll, Vote}; use crate::session::EstimateSession; use crate::util::NotificationLevel; use anyhow::{Context, Result}; use serde::{Deserialize, Serialize}; use uuid::Uuid; /// Sent from server to client, this shared model is used for all client communication #[allow(variant_...
extern crate chai; use chai::stratus; use chai::stratus::*; use crate::state::State; pub struct TestLayer { renderer: chai::graphics::Renderer2D, max: bool, } impl TestLayer { #[profiled] pub fn new() -> TestLayer { TestLayer { renderer: chai::graphics::Renderer2D::new(), ...
use crate::{http_server::pages::blog::md::SyntaxHighlightingContext, *}; pub(crate) async fn serve() -> Result<()> { let app_config = AppConfig::from_env()?; let twitch_config = TwitchConfig::from_env()?; let github_config = GithubConfig::from_env()?; let open_ai_config = OpenAiConfig::from_env()?; ...
use chrono::{DateTime, Utc}; use prometheus::{IntCounter, IntCounterVec, IntGauge, IntGaugeVec, Opts, Registry}; use crate::util::constants::common_literals::NAME; pub struct EventStats { pub channel_create: IntCounter, pub channel_delete: IntCounter, pub channel_update: IntCounter, pub gateway_invali...
use bigdecimal::BigDecimal; use facade::Control; use failure::Error; use futures::compat::{Future01CompatExt, Sink01CompatExt, Stream01CompatExt}; use futures::StreamExt; use futures_legacy::Stream as _; use serde::{Deserialize, Serialize}; use tokio_tungstenite::connect_async; use tungstenite::Message; use url::Url; ...
use std::convert::TryFrom; use std::fmt::Debug; use protobuf::Message; use crate::{ image::TranscodedPictures, request::{MercuryRequest, RequestResult}, Metadata, }; use librespot_core::{Error, Session, SpotifyId}; use librespot_protocol as protocol; pub use protocol::playlist_annotate3::AbuseReportStat...
#[doc = "Register `C5LLR` reader"] pub type R = crate::R<C5LLR_SPEC>; #[doc = "Register `C5LLR` writer"] pub type W = crate::W<C5LLR_SPEC>; #[doc = "Field `LA` reader - pointer (16-bit low-significant address) to the next linked-list data structure If UT1 = UT2 = UB1 = USA = UDA = ULL = 0 and if LA\\[15:20\\] = 0, the ...
//! Python module written in Rust to resolve via surgery an intersection of curves #![feature(map_first_last)] use gcd::Gcd; use pyo3::create_exception; use pyo3::exceptions::PyException; use pyo3::prelude::*; use pyo3::PyObjectProtocol; use rayon::prelude::*; use std::collections::{BTreeSet, HashSet}; create_except...
use codec::{Decode, Encode}; use rstd::cmp::Ord; use rstd::collections::btree_map::BTreeMap; use rstd::prelude::Vec; use sp_arithmetic::traits::SimpleArithmetic; use crate::external_value::{get_median, ExternalValue, Median}; use crate::period_handler::{Part, PeriodHandler}; type RawString = Vec<u8>; #[derive(Clone,...
#[macro_use] extern crate shrinkwraprs; #[macro_use] extern crate derive_new; use digest::DynDigest; use hmac_sha512::sha384::Hash; use rand::Rng; use rsa::algorithms::mgf1_xor; use rsa::internals as rsa_internals; use rsa::{BigUint, PaddingScheme, PublicKey as _, PublicKeyParts, RSAPrivateKey, RSAPublicKey}; use std:...
use room::Room; use std::rc::Rc; pub struct Map { start_room: Rc<Room>, } impl Map { pub fn new(start_room: Room) -> Map { Map{start_room: Rc::new(start_room)} } pub fn get_start_room(&mut self) -> Rc<Room> { self.start_room.clone() } }
use std::collections::HashMap; #[aoc_generator(day14)] pub fn input_generator(input: &str) -> (Vec<char>, HashMap<(char, char), char>) { let mut input = input.split("\n\n"); let template = input.next().unwrap().chars().collect(); let mut rules: HashMap<(char, char), char> = HashMap::new(); let rule_list = inpu...
//! # General methods for aligned access to a byte buffer use crate::{ common::Latin1Str, file::{ FDBHeader, FDBRowHeader, FDBRowHeaderListEntry, FDBTableDataHeader, FDBTableDefHeader, FDBTableHeader, }, }; use assembly_core::buffer::{CastError, MinimallyAligned}; use bytemuck::from_bytes; ...
/// An enum to represent all characters in the CombiningDiacriticalMarks block. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum CombiningDiacriticalMarks { /// \u{300}: '̀' CombiningGraveAccent, /// \u{301}: '́' CombiningAcuteAccent, /// \u{302}: '̂' CombiningCircumflexAccent, /...
pub mod camera_cache; pub mod map; pub mod mesh; pub mod mesh_animation; pub mod renderer; pub mod sprite_animation; pub mod sprite_sheet; pub mod surface_cache; pub mod tilemap; pub mod tilemap_animation; pub mod transform;
use serde::{Deserialize, Serialize}; use super::GameState; #[derive(Debug, Serialize, Deserialize)] pub enum Auth { Failed, Success(GameState), SignIn(String, String), } #[derive(Debug, Serialize, Deserialize)] pub enum Message { Auth(Auth), } impl Message { pub fn to_bytes(&self) -> Vec<u8> { ...
use crate::{error::TtsError, TtsEngine}; use async_trait::async_trait; use core::str; use std::path::{Path, PathBuf}; use tokio::{ fs, io::{AsyncWriteExt, BufWriter}, process::Command, }; pub struct OpenJTalk { pub config: OpenJTalkConfig, } #[async_trait] impl TtsEngine for OpenJTalk { type Conf...
use types::*; /// A request to send a text message. #[derive(Debug,Serialize)] pub struct SendMessage { /// The unique identifier for the target chat or username of the target /// channel. pub chat_id: ChatId, /// The text of the message to be sent. pub text: String, /// Optional method of form...
pub mod render; pub mod route; pub mod router; use crate::agent::RouterState; /// Any state that can be managed by the `Router` must meet the criteria of this trait. pub trait YewRouterState<'de>: RouterState<'de> + PartialEq {} impl<'de, T> YewRouterState<'de> for T where T: RouterState<'de> + PartialEq {}
mod base64; mod request; mod sha1; use std::io::prelude::*; use std::env; use std::collections::HashMap; use std::net::{TcpListener, TcpStream}; use std::str; use std::fs::File; const DEFAULT_PORT: u16 = 4485; fn write_response(request: request::Request, mut stream: TcpStream, routes: &HashMap<&str, String>) { p...
use super::*; use circular_buffer::CircularBuffer; use log::trace; #[cfg(unix)] use nix::{errno, fcntl, libc, sys::socket, unistd}; use std::{mem, net, time}; pub struct Listener { fd: Fd, is_socket_forwarder: bool, } impl Listener { pub fn new_ephemeral(host: &net::IpAddr, executor: &impl Notifier) -> (Self, u16) ...
use std::collections::HashSet; static FILENAME: &str = "input/data"; type Deck = Vec<usize>; fn main() { let data = std::fs::read_to_string(FILENAME).expect("could not read file"); println!("part one: {}", part_one(&data)); println!("part two: {}", part_two(&data)); } fn part_one(data: &str) -> usize { ...
pub struct SavingParameters {} impl SavingParameters { pub fn new() -> SavingParameters { SavingParameters {} } } impl Default for SavingParameters { fn default() -> Self { SavingParameters::new() } }
use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::sync::RwLock; #[derive(Deserialize, Serialize)] pub(crate) struct Todo { pub(crate) id: u32, pub(crate) title: String, pub(crate) completed: bool, } #[derive(Default)] pub(crate) struct Database { pub(crate) store: RwLock<Has...
#[macro_use] mod macros; #[macro_use] pub mod error; mod ast; mod eval; mod scope; mod value; use crate::eval::Evaluate; pub use crate::error::*; pub use crate::scope::Scope; pub use crate::value::Value; pub fn run_script(source: impl AsRef<str>) -> ScriptResult<Value> { let scope = Scope::new_default(); r...
use std::env; use std::process::exit; use std::io::{Write, stderr}; extern crate regex; use regex::Regex; fn main() { let args: Vec<String> = env::args().collect(); if args.len() == 1 { println!("USAGE: regexer REGEX"); exit(1); } let regexp = match Regex::new(args.get(1).expect("Regexp...
#[doc = "Register `CFG2` reader"] pub type R = crate::R<CFG2_SPEC>; #[doc = "Register `CFG2` writer"] pub type W = crate::W<CFG2_SPEC>; #[doc = "Field `MSSI` reader - Master SS Idleness"] pub type MSSI_R = crate::FieldReader; #[doc = "Field `MSSI` writer - Master SS Idleness"] pub type MSSI_W<'a, REG, const O: u8> = cr...
//! Adds [`try_map`](ArrayExt::try_map) and [`map2`](ArrayExt::try_map) methods to arrays. //! //! This crate requires nightly. #![doc(html_root_url = "https://docs.rs/array_try_map/0.1.0")] #![no_std] #![feature( min_const_generics, maybe_uninit_uninit_array, maybe_uninit_extra, maybe_uninit_slice, ...
#[doc = "Register `MACA2LR` reader"] pub type R = crate::R<MACA2LR_SPEC>; #[doc = "Register `MACA2LR` writer"] pub type W = crate::W<MACA2LR_SPEC>; #[doc = "Field `MACA2L` reader - MACA2L"] pub type MACA2L_R = crate::FieldReader<u32>; #[doc = "Field `MACA2L` writer - MACA2L"] pub type MACA2L_W<'a, REG, const O: u8> = c...
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SubscriptionCreationResult { #[serde(rename = "subscriptionLink", default, skip_serializing_if = "Option::is_no...
#[macro_use] extern crate cpython; use std::thread; use std::time::Duration; // use std::io::{self, BufRead}; // use std::sync::mpsc::{self, TryRecvError}; use cpython::{Python, PyResult}; use rppal::system::DeviceInfo; use rppal::gpio::Gpio; const GPIO_ONBOARD_LED: u8 = 23; fn get_device_info(_py: Python) -> PyRes...
use aoc_lib::AocImplementation; fn main() { let day1 = Day1 {}; day1.start(1) } struct Day1 {} impl AocImplementation<i32> for Day1 { fn process_input(&self, input: &str) -> Vec<i32> { input.split('\n').map(|line| line.parse().unwrap()).collect() } fn execute(&self, input: Vec<i32>) -> ...
use serde::Deserialize; use crate::non_empty::NonEmpty; use crate::error::Error; use crate::sources::Source; use crate::Result; use crate::data::{Response, Ticker, Currency, BuildRequest, PreparedRequest, Pair}; pub struct Wasabi { endpoint: String } #[derive(Deserialize)] pub struct WasabiTicker { pub tick...
use std::io::{ stdin, Read, Result as IoResult }; use structopt::StructOpt; use serde::Serialize; use serde_json::{ json, Value }; use sqlparser::{ tokenizer::{ Tokenizer, Token, TokenizerError }, parser::{ Parser, ParserError }, ast::Statement, }; use error::SqlError; use dialect::SqlDialect; mod error; m...
/*! Thinkers are the "brain" of an entity. You attach Scorers to it, and the Thinker picks the right Action to run based on the resulting Scores. */ use std::{ sync::Arc, time::{Duration, Instant}, }; use bevy::prelude::*; use crate::{ actions::{self, ActionBuilder, ActionBuilderWrapper, ActionState}, ...
use std::fs::*; use std::io; use std::path::*; /// Iterator that walks over a directory recursively. /// /// Entries are yielded in a depth-first order. pub struct RecursiveDirIterator { readers: Vec<ReadDir>, } impl RecursiveDirIterator { pub fn new<P: AsRef<Path>>(path: P) -> io::Result<RecursiveDirIterato...
use crate::propagator::{Propagator}; use crate::cell; use crate::cell::{Merge}; use crate::network::{Network}; use std::ops::{ Add, Sub, Mul, Div }; use std::fmt::Debug; impl<A> Network<A> where A: Merge + Debug + Clone + PartialEq + Add<Output=A> { pub fn propagator_add(&mut self, a: cell::ID, b: cell::ID, c: c...
use pinetime_common::display; use pinetime_common::embedded_graphics::{ geometry::Size, image::ImageRaw, mono_font::{ mapping::ASCII, DecorationDimensions, MonoFont, MonoTextStyle, MonoTextStyleBuilder, }, pixelcolor::RgbColor, }; /// 44x85 pixel 54 point size extra bold monospace font pub ...
// Copyright (c) 2018, ilammy // // Licensed under the Apache License, Version 2.0 (see LICENSE in the // root directory). This file may be copied, distributed, and modified // only in accordance with the terms specified by the license. use exonum::{ api::{self, ServiceApiBuilder, ServiceApiState}, blockchain::Tra...
use dotenv::dotenv; use saoirse::{api::Api, Context}; #[tokio::main] async fn main() -> Result<(), saoirse::error::Error> { dotenv().ok(); let ctx = Context::new().await?; let addr = ([127, 0, 0, 1], 8080); Api::serve(ctx, addr).await; Ok(()) }
#[doc = "Register `TAFCR` reader"] pub type R = crate::R<TAFCR_SPEC>; #[doc = "Register `TAFCR` writer"] pub type W = crate::W<TAFCR_SPEC>; #[doc = "Field `TAMP1E` reader - Tamper 1 detection enable"] pub type TAMP1E_R = crate::BitReader; #[doc = "Field `TAMP1E` writer - Tamper 1 detection enable"] pub type TAMP1E_W<'a...
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use fidl_mlme; use Ssid; pub fn fake_bss_description(ssid: Ssid) -> fidl_mlme::BssDescription { fidl_mlme::BssDescription { bssid: [0, 0, 0, 0...
// Copyright 2015 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 ...
#[doc = "Register `MAC1USTCR` reader"] pub type R = crate::R<MAC1USTCR_SPEC>; #[doc = "Register `MAC1USTCR` writer"] pub type W = crate::W<MAC1USTCR_SPEC>; #[doc = "Field `TIC_1US_CNTR` reader - 1 µs tick Counter"] pub type TIC_1US_CNTR_R = crate::FieldReader<u16>; #[doc = "Field `TIC_1US_CNTR` writer - 1 µs tick Count...
use crate::traits::Command; use core::marker::PhantomData; use embedded_hal::{ blocking::{delay::*, spi::Write}, digital::v2::*, }; /// The Connection Interface of all (?) Waveshare EPD-Devices /// pub(crate) struct DisplayInterface<SPI, CS, BUSY, DC, RST, DELAY> { /// SPI _spi: PhantomData<SPI>, /...
// Copyright 2013 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 rand::Rng; #[derive(Debug, Clone, Hash, Eq, PartialEq)] pub struct Universe { n: usize, cell: Vec<u8>, } impl Universe { pub fn new(n: usize) -> Universe { assert!(n >= 3); Universe { n, cell: vec![0; n * n], } } pub fn from_rng<R: Rng>(n: usize...
use super::super::domain::{ designer::DomainDesigner, user::DomainUser, }; pub struct RepositoryDesigner {} impl RepositoryDesigner { pub fn new() -> RepositoryDesigner { RepositoryDesigner {} } pub fn find_designers_total(&self, page_size: i32) -> i32 { page_size * 2 } /...
fn is_leap_year(n: i32) -> bool { if n % 400 == 0 { true } else if n % 100 == 0 { false } else if n % 4 == 0 { true } else { false } } fn leap_year_msg(n: i32) -> String { format!("{} is {}leap year.", n, if is_leap_year(n) { "a " } else { "not a " }) } fn main(...
// Copyright (c) 2016 Anatoly Ikorsky // // 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. All files in the project carrying such notice may not be copied, // m...
pub trait Runnable { fn run(self: Box<Self>); } impl<F: FnOnce()> Runnable for F { fn run(self: Box<F>) { (*self)() } } pub type Job = Box<Runnable + Send + 'static>;
// Problem 27 - Quadratic primes // // Euler discovered the remarkable quadratic formula: // // n² + n + 41 // // It turns out that the formula will produce 40 primes for the consecutive values // n = 0 to 39. However, when n = 40, 40² + 40 + 41 = 40(40 + 1) + 41 is divisible // by 41, and certainly when n = 41...
use crate::config::PhotoConfig; use serde::{Deserialize, Serialize}; /// Suffixes added to resized photo files pub mod suffix { pub static ORIGINAL: &str = "o"; pub static LARGE: &str = "l"; pub static MEDIUM: &str = "m"; pub static SMALL: &str = "s"; pub static THUMB: &str = "t"; } /// Photo disp...
//Git Command use std::process::Command; use std::str; use std::io::Stdout; use crossterm::terminal::disable_raw_mode; use tui::{Terminal, backend::CrosstermBackend}; pub fn git_clone(proj_name: &str, url: String,terminal : &mut Terminal<CrosstermBackend<Stdout>>){ let output = Command::new("git") .arg("cl...
extern crate actix_web; extern crate actix; extern crate reqwest; extern crate serde_json; extern crate serde; extern crate core; extern crate env_logger; extern crate log; mod models; mod routes; mod service_actor; use actix::Actor; use actix_web::server::HttpServer; use actix_web::{http, middleware, App, Http...
use specs::prelude::*; use cgmath::{Matrix4, SquareMatrix}; use std::ops::Deref; #[derive(Component, Clone)] pub struct Transform { pub matrix: Matrix4<f64>, pub inverse: Matrix4<f64>, } impl Transform { pub fn new(matrix: Matrix4<f64>) -> Self { let inverse = matrix.invert().expect("Failed to inv...
use clap::clap_app; use milliseriesdb::buffering::BufferingBuilder; use milliseriesdb::storage::{ env, error::Error, file_system, series_table, Entry, SeriesWriter, }; use std::sync::Arc; use std::{fs, time}; use chrono::{TimeZone, Utc}; fn utc_millis(ts: &str) -> i64 { Utc.datetime_from_str(ts, "%F %H:%M") ...
use std::collections::{HashMap, VecDeque}; use days::day10::part2::parse as knot_hash; #[derive(Debug, Clone)] enum Cell { Unknown, Empty, Region(usize), } fn to_bits(byte: u32) -> Vec<bool> { let byte = byte.to_le(); (0..4) .map(|n| byte & (1 << n) != 0) .rev() // TODO: Not fai...
use std::env; fn main() { if let Ok(file) = dotenv::dotenv() { println!("cargo:rerun-if-changed={}", file.display()); } if env::var("GCS_BUCKET_NAME").is_ok() && env::var("SERVICE_ACCOUNT").is_ok() { println!("cargo:rustc-cfg=test_gcs"); } if env::var("AWS_DEFAULT_REGION").is_ok()...
/*===============================================================================================*/ // Copyright 2016 Kyle Finlay // // 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 // // ...
#![deny(warnings, rust_2018_idioms)] use linkerd_identity as identity; pub use rustls::TLSError as Error; use std::fmt; pub mod accept; pub mod client; mod conditional_accept; pub use self::accept::NewDetectTls; pub use self::client::Client; /// Describes whether or not a connection was secured with TLS and, if it ...
use fyrox::{ core::{ algebra::Vector3, color::Color, color_gradient::{ColorGradient, GradientPoint}, pool::Handle, }, engine::resource_manager::ResourceManager, scene::{ base::BaseBuilder, graph::Graph, node::Node, particle_system::{ ...
use core::marker::PhantomData; use typenum::uint::Unsigned; pub struct Port<Id: Unsigned> { _marker: PhantomData<Id> } impl<Id: Unsigned> Port<Id> { pub unsafe fn get() -> Port<Id> { Port { _marker: PhantomData } } #[inline(always)] pub unsafe fn read_u8(&mut self) -> u8 { let va...
fn main() { let data: Vec<u8> = vec![5, 10, 15, 20]; read_u8_slice(data.as_ptr(), data.len()); } fn read_u8_slice(slice_p: *const u8, length: usize) { for index in 0..length { unsafe { println!("slice[{}] = {}", index, *slice_p.offset(index as isize)); } } }
//! This module contains [`Wrap`] structure, used to decrease width of a [`Table`]s or a cell on a [`Table`] by wrapping it's content //! to a new line. //! //! [`Table`]: crate::Table use std::marker::PhantomData; use crate::{ grid::config::ColoredConfig, grid::dimension::CompleteDimensionVecRecords, gri...
pub mod math; pub mod poker;
//! Rendering Cells use crate::POLY_SUBPIXEL_SCALE; use crate::POLY_SUBPIXEL_SHIFT; use crate::POLY_SUBPIXEL_MASK; use std::cmp::min; use std::cmp::max; /// Rendering Cell /// /// Effectively Represents a Pixel #[derive(Debug,Copy,Clone,PartialEq, Default)] pub(crate) struct Cell { // cell_aa /// Cell x positio...
// Copyright 2017 rust-ipfs-api 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 distributed except accord...
extern crate clap; pub mod coin; use clap::{App, Arg}; use coin::Coin; //use itertools::Itertools; use std::error::Error; use std::str::FromStr; type MyResult<T> = Result<T, Box<dyn Error>>; #[derive(Debug)] pub struct Config { amount: u32, } // -------------------------------------------------- pub fn get_arg...
use crate::domain::interaction::Base; pub type Reading = Base;
extern crate mavlink; mod test_shared; #[cfg(test)] #[cfg(all(feature = "std", feature = "tcp", feature = "common"))] mod test_tcp_connections { use std::thread; /// Test whether we can send a message via TCP and receive it OK #[test] pub fn test_tcp_loopback() { const RECEIVE_CHECK_COUNT: i3...
#![feature(core, libc)] #![deny(missing_docs)] #![cfg_attr(test, deny(warnings))] //! # pico //! //! Nonblocking parsing support using picohttpparser. //! extern crate pico_sys as sys; extern crate libc; /// A recursive reader which can read a single chunk into a buffer. pub trait ChunkReader<C> { /// Retrieve t...
/// An enum to represent all characters in the Siddham block. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum Siddham { /// \u{11580}: '𑖀' LetterA, /// \u{11581}: '𑖁' LetterAa, /// \u{11582}: '𑖂' LetterI, /// \u{11583}: '𑖃' LetterIi, /// \u{11584}: '𑖄' LetterU, ...
use std::cmp; fn act1_6_1(n: i32, a: Vec<u32>) -> u32 { for x in &a { for y in &a { for z in &a { if (x.pow(2) + y.pow(2)) == z.pow(2) { return x + y + z } } } } return 0 } fn act1_6_2(l: i32, n: i32, x: Vec<i32>) -> (i32, i32) { let mut min = 0; for i in &x { min = cmp::max(min, cmp::min...