text
stringlengths
8
4.13M
use db; use diesel::pg::PgConnection; use diesel::prelude::*; use errors::*; use models; use models::PullRequestParams; use request::{GitHubEvent, SignedPayload}; use rocket::State; use serde_json as json; #[post("/webhook", data = "<payload>")] pub fn receive(event: Option<GitHubEvent>, payload: SignedPayload, db_con...
extern crate rust_ssg; use std::path::PathBuf; fn main() { rust_ssg::run(PathBuf::from("../programs/main.site")); }
extern crate rustc_serialize; extern crate bincode; use std::io::Write; use std::io::Error as IoError; use std::io::ErrorKind as IoErrorKind; use rustc_serialize::Encoder; pub use bincode::rustc_serialize::EncodingError; use byteorder::{ BigEndian, WriteBytesExt }; use byteorder::Error as ByteOrderError; use super::u...
extern crate lib; use std::io; use std::io::Read; fn main() { let stdin = io::stdin(); let mut line = String::new(); // Read the lines from stdin. if let Err(err) = stdin.lock().read_to_string(&mut line) { println!("Error reading input: {}", err); std::process::exit(2); }; let b...
use crate::progress::Progress; pub fn qpow(x: i64, mut y: i64, p: i64) -> i64 { //快速幂及模数,x^y%p let mut ans = 1i128; let mut m: i128 = x as i128; while y != 0 { if (y & 1) != 0 { ans *= m; ans %= p as i128; } m *= m; m %= p as i128; y >>= 1...
pub mod x25519;
use super::*; /// Helper for paging implementation /// /// Currently not exposed/used. Requires some more thoughts on how to use this to implement a `Stream` of messages /// /// TODO actually it would be awesome if this could be parsed back to `ListParameters` #[derive(Debug, Serialize, Deserialize, Eq, PartialEq)] pu...
use std::io::*; use util::{Scanner, Joinable}; fn main() { std::thread::Builder::new() .stack_size(1048576) .spawn(solve) .unwrap() .join() .unwrap(); } fn solve() { let cin = stdin(); let cin = cin.lock(); let mut sc = Scanner::new(cin); let n = sc.read(); ...
use std::fs; // Pythonでいう // import std.fs as fs // use std::fs::*; // こうすると // from std.fs import * // って感じ。 use std::fs::File; use std::io::Read; use std::io::{BufRead, BufReader}; fn main() { let path = "sample.txt"; println!("read all lines."); /* if let Ok(data) = std::fs::read_to_string(path) {...
use super::{action, Filter}; use good_mitm::utils::SingleOrMulti; use serde::{Deserialize, Serialize}; use std::{error::Error, fs, io::BufReader, path::Path}; #[derive(Debug, Clone, Deserialize, Serialize)] pub struct Rule { pub name: String, #[serde(alias = "mitm")] pub mitm_list: Option<SingleOrMulti<Str...
pub mod hwtypes;
pub mod difference; #[cfg(test)] mod tests { #[test] fn it_works() { assert_eq!(2 + 2, 4); } } #[test] #[ignore] fn another() { panic!("Make this test fail") } #[test] fn another2() { assert_ne!(2 + 2, 3); } pub fn add_two_integers(x: i32, y: i32) -> i32 { x + y }
use crate::hitable::HitRecord; use crate::ray::Ray; use crate::util::{random_in_unit_sphere, Color, Vec3f}; use rand::prelude::*; pub type Albedo = Color; pub type Fuzz = f64; pub type RefractiveIndex = f64; #[derive(Copy, Clone, Debug)] pub enum Material { NoMaterial, Diffuse(Albedo), Metal(Albedo, Fuzz...
#[macro_use] extern crate glium; use glium::{glutin, Surface}; use arrayfire as af; fn main() { let event_loop = glutin::event_loop::EventLoop::new(); let wb = glutin::window::WindowBuilder::new(); let cb = glutin::ContextBuilder::new(); let display = glium::Display::new(wb, cb, &event_loop).unwrap(); ...
#![feature(advanced_slice_patterns, slice_patterns, convert)] extern crate argparse; extern crate yaml; extern crate term; extern crate chrono; use std::io::prelude::*; use std::io::BufReader; use std::fs::File; use std::fmt; use yaml::constructor::*; use yaml::constructor::YamlStandardData::{YamlMapping, YamlString...
use std::io::Error; use std::mem; use std::os::unix::io::RawFd; use std::ptr::copy_nonoverlapping; use ebpf_core::{ffi, Map}; cfg_if! { if #[cfg(target_arch = "x86")] { pub const BPF_SYSCALL: libc::c_long = 357; } else if #[cfg(target_arch = "x86_64")] { pub const BPF_SYSCALL: libc::c_long = 3...
#[doc = "Register `ERR` reader"] pub struct R(crate::R<ERR_SPEC>); impl core::ops::Deref for R { type Target = crate::R<ERR_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<ERR_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<ERR_SPEC>) ...
#![feature(associated_type_bounds)] use pallet_balances::AccountData; use pallet_ibc::Event; use sp_core::H256; use sp_runtime::generic::Header; use sp_runtime::traits::{BlakeTwo256, IdentifyAccount, Verify}; use sp_runtime::{MultiSignature, OpaqueExtrinsic}; use substrate_subxt::{ balances::{Balances, BalancesEve...
use advent_of_code_2022::{read, parse}; use nom::branch::alt; use nom::bytes::complete::tag; use nom::combinator::value; use nom::IResult; use nom::multi:: many0; use nom::sequence::terminated; use std::cmp::max; #[derive(Copy, Clone, Debug, PartialEq)] enum Direction { Left, Right, } type Input = Vec<Directi...
use crate::{ core::{ components::maths::{ camera::{Camera, DefaultCamera}, transform::Transform, }, resources::window::WindowDimensions, }, legion::{systems::CommandBuffer, *}, }; #[system(for_each)] pub(crate) fn default_camera( cmd: &mut CommandBuffer, ...
mod eventkit; use crate::{opt::Opt, taskwarrior::Task}; use anyhow::Result; use eventkit::{EventStore, Reminder}; pub(crate) fn execute(opt: &Opt) -> Result<()> { let mut taskwarrior_args = opt.args.clone(); taskwarrior_args.push("+remindme".to_string()); taskwarrior_args.push("(status:pending or status:w...
pub fn build_proverb(list: &[&str]) -> String { let mut answer: String = String::new(); let mut i:usize = 0; if list.len() > 0 { while i < list.len()-1 { answer.push_str(&format!("For want of a {} the {} was lost.\n",list[i],list[i+1]).to_string()); i += 1; } ...
use super::*; use super::puzzles::Data; #[derive(Clone)] pub struct Input{ data: Vec<Vec<char>> } impl puzzles::Data<Vec<Vec<char>>> for Input{ fn new(input:&str) -> Input{ Input{ data : parser::one_char_vec_per_line(input)} } fn get_data(&self) -> &Vec<Vec<char>>{ &self.data } } ...
#[macro_export] macro_rules! field { ($opt_field:expr, $type:expr, $field:expr) => { $opt_field.ok_or_else(|| crate::codec::CodecError::MissingField { r#type: $type, field: $field, }) }; } #[macro_export] macro_rules! impl_default_bytes_codec_for { ($category:ident,...
fn use_slice(slice: &mut[i32]) // borrowing a slice of i32 data { println!("first elem = {}, len = {}", slice[0], slice.len()); slice[0] = 4321; } fn slices() { let mut data = [1, 2, 3, 4, 5]; // use_slice(&mut data); //full slice so index[0] of 'data' is changed to 4321 us...
use rustyline::error::ReadlineError; use rustyline::Editor; use crate::cli::commands::{parse_command, apply_command}; pub fn runner() { let mut repl = Editor::<()>::new(); println!("storagenv - type 'help' to see a list of available commands"); if repl.load_history("history.txt").is_err() { println...
#[allow(unused_imports)] use serde_json::Value; #[derive(Debug, Serialize, Deserialize)] pub struct ClusterEmail { /// Cluster email notification settings. #[serde(rename = "settings")] pub settings: Option <crate::models::ClusterEmailSettings>, }
extern crate clap; extern crate flate2; extern crate colored; use colored::Colorize; #[macro_use] extern crate nom; use std::fs::File; use std::io::{BufReader, Read}; use flate2::bufread::GzDecoder; mod enums; use enums::*; struct Eat {} #[cfg(feature = "put")] struct Put {} //////////////////////////////////////...
// Copyright (c) 2020, Jason Fritcher <jkf@wolfnet.org> // All rights reserved. use std::{ str, sync::{ atomic::{AtomicBool, Ordering}, Arc, }, time::SystemTime, }; use tokio::net::TcpStream; use tokio::sync::mpsc; use tokio::time::{delay_for, Duration}; use tokio_tungstenite::{ co...
use crate::{define_universal_commands, Command, SceneCommand, SceneContext}; use fyrox::core::reflect::ResolvePath; define_universal_commands!( make_set_scene_property_command, Command, SceneCommand, SceneContext, (), ctx, handle, self, { ctx.scene }, );
//! Hatter is a small, whitespace sensitive templating language with //! HTML support built right in. Its HTML features and syntax are a //! cheap knock off of Imba, except Hatter produces raw, static HTML - //! no JavaScript in sight. //! Hatter can be used to generate static web sites or to render //! server side co...
// Copyright 2012-2017 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-MI...
fn main() { let passwords = get_input("../day2.txt"); println!("part one:{}", part_one(&passwords)); println!("part two:{}", part_two(&passwords)); } fn part_one(passwords: &Vec<Password>) -> u32 { let mut total: u32 = 0; for p in passwords { let count = p .password ...
mod builder; mod conf; mod auth; mod keys; mod misc; pub use builder::*; pub use conf::*; pub use auth::*; pub use keys::*; pub use misc::*;
//! This module is auto populated by the build script using the vergen crate. //! It is used to print version information at start. #![allow(dead_code)] include!(concat!(env!("OUT_DIR"), "/version.rs"));
use std::fs::{create_dir_all, remove_dir_all}; use std::io::Cursor; use heed::EnvOpenOptions; use milli::update::{IndexDocumentsMethod, UpdateBuilder, UpdateFormat}; use milli::Index; fn create_index() { let db_name = "bug.mmdb"; match remove_dir_all(db_name) { Ok(_) => eprintln!("The previous db has ...
#[derive(Debug)] pub struct OpCode { pub op: u8, // Technically a u4 but u8 makes for easier comparisons pub x: u8, // Technically a u4 but u8 makes for easier comparisons pub y: u8, // Technically a u4 but u8 makes for easier comparisons pub n: u8, // Technically a u4 but u8 makes for easier comparison...
//! Compress a pruned tree to remove all eliminated bindings use crate::core::error::CoreError; use crate::core::expr::*; use moniker::{BoundVar, ScopeOffset, Var}; /// Occasionally we need to push an expression with bound vars /// inside an extra scope, this increments de bruijn indices to /// compensate. pub fn succ...
mod config; mod text_generation; mod twitter; use crate::text_generation::actor::{choose_actor, generate_dialogue}; use crate::text_generation::elaine::ELAINE; use crate::text_generation::frank::FRANK; use crate::text_generation::george::GEORGE; use crate::text_generation::jerry::JERRY; use crate::text_generation::kra...
use std::collections::VecDeque; use std::str::CharIndices; #[derive(Debug)] pub struct CharIter<'a> { start: usize, end: usize, iter: CharIndices<'a>, input: &'a str, buffer: VecDeque<(usize, char)>, } impl<'a> CharIter<'a> { pub fn new(input: &str) -> CharIter<'_> { let mut iter = inp...
// macros4.rs // Make me compile! Execute `rustlings hint macros4` for hints :) /* If you create an overloaded macro (one that can take different types of arguments * which all share the same name), then you must have a separator between the * alternative macro bodies. */ macro_rules! my_macro { () => { ...
use std::marker::PhantomData; use std::ops::{Deref, DerefMut}; use std::sync::{Arc, RwLock}; use amethyst_assets::{Asset, AssetLoaderSystemData, Format}; use amethyst_core::{ ecs::{ Read, ReaderId, System, SystemData, Write, World }, shrev::EventChannel, SystemDesc, }; use derivative::Derivativ...
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::IER { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W...
use rand::Rng; use std::cmp::Ordering; use std::io; fn main() { println!("Guess the number!"); // Takes a range expression as an argument and generates a random number in the range let secret_number = rand::thread_rng().gen_range(1..=100); // Comment out: No fun telling what the number is //p...
use Data; use Func; use FuncArc; use FuncUnsafe; use Lib; use LibArc; use LibUnsafe; use std::mem; use std::cell::RefCell; use std::ops::DerefMut; use Symbol; use test::examplelib::EXAMPLELIB; #[test] fn load_examplelib() { unsafe { Lib::new(EXAMPLELIB).unwrap(); } } #[test] fn add_2_numbers() { u...
use crate::theory_primitive::interval::Interval; #[derive(PartialEq, Debug, Clone)] pub struct Scale { pub name: String, pub aliases: Vec<String>, pub intervals: Vec<Interval>, }
use actix::prelude::*; use log::info; pub struct Cache {} impl Actor for Cache { type Context = Context<Self>; fn started(&mut self, _: &mut Self::Context) { info!("Cache actor started"); } }
#[doc = "Register `PCFC` reader"] pub struct R(crate::R<PCFC_SPEC>); impl core::ops::Deref for R { type Target = crate::R<PCFC_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<PCFC_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<PCFC_SP...
use std::collections::HashMap; use serde::{Deserialize, Serialize}; use std::fmt::Formatter; use tantivy::schema::Schema; /// In a delete query, this is returned indicating the number of documents that were removed /// by the delete. #[derive(Debug, Serialize, Deserialize, Clone)] pub struct DocsAffected { /// Th...
fn chessboard_cell_color(cell1: &str, cell2: &str) -> bool { let mut sum1 = 0; let mut sum2 = 0; for c in cell1.chars(){ sum1 += c as u32; } for c in cell2.chars(){ sum2 += c as u32; } return sum1 % 2 == sum2 % 2; } fn main() { } #[test] fn basic_tests() { assert_eq...
#[derive(Debug, Clone)] pub enum Conds_awaitconfirm_no { Cnd_awaitconfirm_no_1, } #[derive(Debug, Clone)] pub enum Conds_awaitconfirm_other { Cnd_awaitconfirm_other_1, } #[derive(Debug, Clone)] pub enum Conds_awaitconfirm_yes { Cnd_awaitconfirm_yes_1, } #[derive(Debug, Clone)] pub enum Conds_init_hello_a...
use std::cell::RefCell; use std::rc::Rc; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use web_sys::WebGlRenderingContext as GL; #[wasm_bindgen] pub fn chasm(canvas_id: &str) -> Result<(), JsValue> { let window = window(); let document = document(); let chasm = document.get_element_by_id(canvas_i...
use std::process::Command; /// Pass git-describe through CARGO_GIT_VERSION env variable /// /// NOTE: Cargo.toml still needs to be updated on releases fn set_version_from_git() { let cmd = Command::new("git") .arg("describe") .arg("--always") .arg("--dirty") .output(); match cm...
/// Блок лог файла pub mod block; /// Лог файл - сумма блоков /// /// Структура лог файла см [LogFile](logfile::LogFile) pub mod logfile;
//! Modal group 0, non-modal use crate::Span; use crate::{value::Value, word::parse_word}; use nom::{ branch::alt, bytes::complete::tag_no_case, character::complete::digit1, character::complete::space0, combinator::map, combinator::not, sequence::{separated_pair, terminated}, IResult, }...
use clap::Shell; use std::env; include!("src/bin/clap_app/mod.rs"); fn main() { let outdir = match env::var_os("OUT_DIR") { None => return, Some(outdir) => outdir, }; let mut app = build_cli(); app.gen_completions("gsc", Shell::Fish, outdir); }
// Turn on all warnings #![warn(clippy::all)] // Used for the faster hash algorithm extern crate fnv; // Used for arbitrary-precision numbers extern crate num; // Used to pool identifiers and operators (making identifier comparison faster) extern crate string_interner; // Explicitly expose just the interfaces we want...
use std::mem; pub struct List<T> { head: Link<T>, } enum Link<T> { Empty, More(Box<Node<T>>), } struct Node<T> { elem: T, next: Link<T>, } impl<T> List<T> { pub fn new() -> Self { List { head: Link::Empty } } pub fn push(&mut self, elem: T) { self.head = Link::More(B...
use diesel::sql_types::Integer; #[derive(QueryableByName)] pub struct ProductId { #[sql_type = "Integer"] product_id: i32, } impl ProductId { pub fn get_id(&self) -> i32 { self.product_id } }
use super::*; use yansi::Paint; pub struct Characters { pub hbar: char, pub vbar: char, pub xbar: char, pub vbar_break: char, pub uarrow: char, pub rarrow: char, pub ltop: char, pub mtop: char, pub rtop: char, pub lbot: char, pub rbot: char, pub mbot: char, pub lb...
pub fn part2(input: &Vec<(bool, (isize, isize), (isize, isize), (isize, isize))>) { let mut cubes = Vec::new(); for (active, x, y, z) in input { if *active { add_cube(&mut cubes, (*active, *x, *y, *z)) } else { } } println!("{:?}", cubes); } fn add_cube( cubes: ...
extern crate kv_server; // --- std --- use std::{ fs::{read_dir, remove_dir_all}, io, sync::Arc, }; // --- external --- use futures::{Future, Stream}; use hashbrown::HashMap; // --- custom --- use kv_server::{ hash::{MergePolicy, Options}, protos::{ kv_server::{Operation, Request, ScanReque...
#[cfg(feature = "zkp-prover")] #[allow(dead_code)] mod prover; #[allow(dead_code)] mod verify; fn main() {}
use crate::ffi; use crate::{Result, Status}; use std::ffi::CString; use std::thread::sleep; use std::time::{Duration, Instant}; /// wrapper of tag model based on `libplctag` #[derive(Debug)] pub struct RawTag { tag_id: i32, } impl RawTag { /// create new RawTag /// # Note /// if you p...
#[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::BRR { #[doc = r" Writes to the register"] #[inline] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w.b...
#![feature(globs, macro_rules, unsafe_destructor)] pub mod c; pub mod thincrust;
// Copyright 2021 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 //! Implementation of [`MnemonicSecretManager`]. use std::ops::Range; use async_trait::async_trait; use crypto::{ hashes::{blake2b::Blake2b256, Digest}, keys::slip10::{Chain, Curve, Seed}, }; use iota_types::block::{ address::{Address...
use fmod_studio::system::{StudioInitialization, System}; use std::io::{stdin, Read}; extern crate pancurses; use pancurses::{endwin, initscr, Input}; fn main() { let window = initscr(); let system = System::initialized(StudioInitialization { spawn_update_thread: true, ..Default::default() }...
use nse; use nse::core::{Entity, Exit, Message, System}; use nse::NSE; #[derive(Debug)] struct NoopSystem { counter: u64, // how often noop should be executed } impl NoopSystem { fn new(count: u64) -> Self { NoopSystem { counter: count } } } impl System for NoopSystem { fn...
use super::connection::{Floating, Idle, Live}; use crate::connection::ConnectOptions; use crate::connection::Connection; use crate::database::Database; use crate::error::Error; use crate::pool::{deadline_as_timeout, CloseEvent, Pool, PoolOptions}; use crossbeam_queue::ArrayQueue; use crate::sync::{AsyncSemaphore, Asyn...
use std::fmt::Debug; use rcore_fs::vfs::INode; use crate::file::{AccessMode, SeekFrom, StatusFlags}; use crate::poll::Events; use crate::prelude::*; pub trait SyncFile: Debug + Sync + Send { fn read(&self, _buf: &mut [u8]) -> Result<usize> { return_errno!(EBADF, "not support read"); } fn readv(&...
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files // DO NOT EDIT use crate::{VpnPluginFailure, VpnServiceState}; use glib::{ prelude::*, signal::{connect_raw, SignalHandlerId}, translate::*, }; use std::{boxed::Box as Box_, fmt, mem::transmute, ptr}; glib::wrapper! { ...
// Copyright 2019 WHTCORPS INC Project Authors. Licensed under Apache-2.0. use crate::errors::Result; use crate::properties::DecodeProperties; use crate::cone::Cone; use crate::CausetHandleExt; use std::ops::Deref; pub trait BlockPropertiesExt: CausetHandleExt { type BlockPropertiesCollection: BlockPropertiesColl...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ get_available_port_from, get_random_available_ports, parse_key_val, ApiQuotaConfig, ApiSet, BaseConfig, ConfigModule, QuotaDuration, StarcoinOpt, }; use anyhow::Result; use clap::Parser; use serde::{Deserialize,...
pub struct Solution; impl Solution { pub fn roman_to_int(s: String) -> i32 { let mut iter = s.chars().peekable(); let mut ans: i32 = 0; while let Some(c) = iter.next() { ans += match c { 'M' => 1000, 'D' => 500, 'L' => 50, ...
pub mod restoration; pub mod skirmish; pub mod communication; pub use restoration::Restoration; pub use skirmish::Skirmish; pub use communication::Communication;
#[allow(unused_imports)] use tracing::{info, warn, debug, error, trace, instrument, span, Level}; use serde::*; use ate::crypto::*; #[derive(Debug, Serialize, Deserialize, Clone)] pub struct SmsVerification { pub salt: String, pub hash: AteHash, }
extern crate url; pub mod serializer; pub mod utils; pub mod structs;
use rust_fsm::*; use crate::utils::*; use log::info; #[cfg(target_arch = "x86_64")] use core::arch::x86_64::*; use std::io::BufWriter; use std::fs::File; use std::io::Write; state_machine! { derive(Debug) FSM(initial) initial => { outputstreaminit => outputstreamcreated }, outputstreamcreated => { ...
pub mod flann { //! # Clustering and Search in Multi-Dimensional Spaces //! //! This section documents OpenCV's interface to the FLANN library. FLANN (Fast Library for Approximate //! Nearest Neighbors) is a library that contains a collection of algorithms optimized for fast nearest //! neighbor search in large d...
// //! Copyright 2020 Alibaba Group Holding Limited. //! //! 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 a...
mod key; pub use key::*; mod macos; pub use macos::*;
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 pub use crate::console::G_DEFAULT_CONSOLE_CONFIG; use crate::console::{init_helper, CommandName, RLHelper}; use crate::error::CmdError; use crate::{ print_action_result, result_to_json, CommandAction, CommandExec, CustomCommand,...
use crate::completion::{self, Suggestion}; use crate::context; pub(crate) struct NuCompleter {} impl NuCompleter {} impl NuCompleter { pub fn complete( &self, line: &str, pos: usize, context: &completion::Context, ) -> (usize, Vec<Suggestion>) { use crate::completion::...
//! --- Part Two --- //! //! Once you give them the coordinates, the Elves quickly deploy an Instant Monitoring Station to //! the location and discover the worst: there are simply too many asteroids. //! //! The only solution is complete vaporization by giant laser. //! //! Fortunately, in addition to an asteroid scan...
#[derive(Debug, PartialEq, Copy, Clone)] pub enum Token { MoveLeft, MoveRight, Add, Subtract, Output, Input, LoopStart, LoopEnd, } impl Token { pub fn from_byte(token: u8) -> Option<Token> { use self::Token::*; match token as char { '<' => Some(MoveLeft), '>' => Some(MoveRight), ...
use std::path::PathBuf; use anyhow::Result; use async_trait::async_trait; use clap::{App, Arg}; use tokio::runtime; use tracing::instrument; use crate::logging; const VERSION: &str = env!("CARGO_PKG_VERSION"); const MINIMUM_WORKER_THREAD_COUNT: usize = 6; #[async_trait] pub trait Daemon { type Config; fn l...
use crate::marker::{GcDeref, GcDrop, GcSafe}; /// A secret little function to check if a field is `GcDeref` #[doc(hidden)] #[inline(always)] pub fn check_gc_deref<T: GcDeref>(_: &T) {} /// A secret little function to check if a field is `GcDrop` #[doc(hidden)] #[inline(always)] pub fn check_gc_drop<T: GcDrop>(_: &T) ...
// This is a file to examine different control flow methods for rust fn main() { // Rust allows for if else statements seen below let number = 4; if( number % 2 == 0){ println!("The number is even"); } else{ println!("The number is even"); } let mut i = 0; // loo...
use std::fmt; use std::time::{self, Duration, SystemTime, UNIX_EPOCH}; use byteorder::{BigEndian, WriteBytesExt}; use rand::{thread_rng, Rng}; /// K-Sortable Unique ID. /// - 00-03: unsigned int32 BE UTC timestamp with custom epoch /// - 04-19: random payload #[derive(Clone, Hash, Eq, PartialEq, Ord, PartialOrd)...
mod config; pub use config::*; pub mod device; pub mod schedule; pub mod sensor; pub mod server;
use ggez::graphics::{DrawMode, Mesh, MeshBuilder, WHITE}; use ggez::nalgebra::{Point2, Vector2}; use ggez::{Context, GameResult}; pub struct MapState { pub origin: Point2<f32>, // The screen coordinate of the map's upper left corner pub width: f32, pub height: f32, pub start_point: Point2<f32>, // The ...
//this files goes over arrays //arrays are fixed length, same data type use std::mem; pub fn run(){ let mut nums: Vec<i32> = vec![1,2,3,4]; //now this is a vector definition //main difference is that we can edit the vector length // println!("{:?}", nums); //reassign a value, which is a va...
// Copyright (c) 2019, Facebook, Inc. // All rights reserved. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use bumpalo::Bump; use decl_rust::direct_decl_parser::parse_decls; use ocamlrep::ptr::UnsafeOcamlPtr; use ocamlrep_ocamlpool:...
use phf; use namepart::NamePart; static GENERATION_BY_SUFFIX: phf::Map<&'static str, usize> = phf_map! { "1" => 1, "2" => 2, "3" => 3, "4" => 4, "5" => 5, "1st" => 1, "2nd" => 2, "3rd" => 3, "4th" => 4, "5th" => 5, "I" => 1, "Ii" => 2, "Iii" => 3, "Iv" => 4, ...
use crate::{ util::triangulate, vec::{Ray, Vec3, Vector}, vis::{Visibility, Visible}, }; use num::Float; use serde::{ de::{self, Deserialize, Deserializer, MapAccess, SeqAccess, Visitor}, ser::{Serialize, SerializeStruct, Serializer}, }; use std::{ffi::OsString, io, path::Path}; #[derive(Debug, Clone, Partia...
use std::collections::{HashMap, HashSet}; use std::hash::Hash; #[derive(Debug)] pub struct Borrow<'a, K: 'a + Hash + Eq, V: 'a> { _original: &'a mut HashMap<K, V>, borrows: Vec<&'a mut V>, } impl<'a, K: 'a + Eq + Hash, V> Borrow<'a, K, V> { pub fn with_hashset(original: &'a mut HashMap<K, V>, keys: &HashSet<K>) ->...
use bytes::buf::Chain; use bytes::Bytes; use digest::{Digest, OutputSizeUser}; use generic_array::GenericArray; use rand::thread_rng; use rsa::{pkcs8::DecodePublicKey, Oaep, RsaPublicKey}; use sha1::Sha1; use sha2::Sha256; use crate::connection::stream::MySqlStream; use crate::error::Error; use crate::protocol::auth::...
use syn::{bracketed, token}; use syn::parse::{ Parse, ParseStream }; use quote::ToTokens; use proc_macro2::TokenStream; pub trait ParseOptional: Sized { fn parse_optional(input: ParseStream) -> syn::Result<Option<Self>>; } pub trait ParseStreamExt { fn parse_optional<T>(self) -> syn::Result<Option<T>> where ...
// Copyright 2015-2018 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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 Software Foundation, either version 3 of the License, or // (at your option) any lat...