text
stringlengths
8
4.13M
use crate::peripherals::{R16, R8}; #[allow(non_camel_case_types)] #[derive(Debug, Copy, Clone)] pub enum Instruction { //8-bit load LD_R_R(R8, R8), LD_R_N(R8, u8), LD_iR_R(R16, R8), LD_iR_N(R16, u8), LD_R_iR(R8, R16), LD_R_iN(R8, u16), LD_iN_R(u16, R8), LDI_iR_R(R16, R8), LDI_R_...
//! This module deals with configuration data including the management of the list of secrets #![allow(clippy::manual_filter_map)] use rand::Rng; use thiserror::Error; //use serde::Deserialize; use serde_derive::Deserialize; /// A tag to enclose parts of the secret to be visible from the start, e.g. /// "guess_-me_" ...
#![allow(dead_code)] use std::sync::Arc; use serde_json::Value; use tokio::sync::mpsc; use tokio::sync::RwLock; use crate::jsonrpc::endpoints::{ Discv5EndpointKind, HistoryEndpointKind, PortalEndpointKind, StateEndpointKind, }; use crate::jsonrpc::types::{HistoryJsonRpcRequest, PortalJsonRpcRequest, StateJsonRpc...
#[macro_use] extern crate unitary; fn main() { units!(m, s); let dist = qty!(1.0; m); let time = qty!(2.0; s); println!("{}", &dist); println!("{}", time); println!("{}", dist.clone() / time); println!("{}", (dist.clone() / dist)); }
/* * Copyright Stalwart Labs Ltd. See the COPYING * file at the top-level directory of this distribution. * * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or * https://www.apache.org/licenses/LICENSE-2.0> or the MIT license * <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your * optio...
#![feature(test)] use dev_util::impl_benchmark; impl_benchmark!(sha0, Sha0);
// The Base64-encoded content in text.txt has been encrypted via AES-128 in ECB mode under the key "YELLOW SUBMARINE" // Symmetric key algorithm // Modern CPUs have AES instructions built into them! (These are much faster and more secure) // If you implement your own - people can look up CPU caches! // a block ciph...
//! Data Processing Instruction Definitions //! //! //! The instructions defined in this module are listed in the ARMv7-m Architecture Reference Manual on page 131: //! //! OpCode Instruction //! 0000 Bitwise AND AND (register) on page A7-201 //! 0001 Exclusive OR EOR (registe...
use super::ExtractedSyntaxGrammar; use crate::generate::grammars::{ Production, ProductionStep, SyntaxGrammar, SyntaxVariable, Variable, }; use crate::generate::rules::{Alias, Associativity, Precedence, Rule, Symbol}; use anyhow::{anyhow, Result}; struct RuleFlattener { production: Production, precedence_s...
//! Structs defining Amazon data sets. use crate::arrow::*; use arrow2_convert::ArrowSerialize; use serde::{Deserialize, Serialize}; /// A rating as described in a source CSV file. #[derive(Serialize, Deserialize)] pub struct SourceRating { pub user: String, pub asin: String, pub rating: f32, pub times...
use crate::{ error::Error, receiver::{ Action, AnyReceiver, AnyWrapperRef, BusPollerCallback, PermitDrop, ReceiverTrait, SendUntypedReceiver, TypeTagAccept, }, stats::Stats, Bus, Event, Message, Permit, ReciveUntypedReceiver, TypeTag, TypeTagAcceptItem, }; use core::sync::atomic::{At...
use diesel::prelude::*; use diesel::r2d2::{ConnectionManager, Pool}; use tonic::Status; use tracing::instrument; use crate::api::permission_membership_request::IdPermissionOrUserid; use crate::api::PermissionMembershipData; use crate::schema::permission_membership; use crate::schema::permission_membership::dsl::*; use...
// 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 fn ensure_empty_iter<'a>( iter: &mut impl Iterator<Item = &'a str>, keyword: &str, ) -> Result<(), String> { iter.next().map_or(Ok(()), |extra_str| { Err(format!( "extra characters in \"{}\" line: {}", keyword, extra_str )) }) } pub fn ensure_empty(value: &str, keyword: &str) -> Result<...
use *; use std::ops::{Index, IndexMut}; impl<T> Index<ptr::Bool> for Reactor<T> { type Output = fns::Bool<T>; fn index(&self, id: ptr::Bool) -> &fns::Bool<T> { &self.bools[usize::from(id)] } } impl<T> Index<ptr::Point1<T>> for Reactor<T> { type Output = fns::Point1<T>; fn index(&self, id:...
extern crate serde_json; use std::fmt; use std::error::Error; use self::serde_json::Map; use self::serde_json::Value; use super::url::ParseError; pub use super::rustache::RustacheError; pub use super::curl::Error as CurlError; pub use super::serde_yaml::Error as YamlError; pub use std::io::Error as IoError; #[derive(...
#![allow(dead_code)] #![allow(unused_variables)] #![allow(unused_assignments)] // constants // --------- const CONSTANT_1: u8 = 123; // immutable always, can be defined in outer scope // const CONSTANT_1: u8 = 321; - ERROR: `CONSTANT_1` redefined here (no shadowing allowed) // const mut CONSTANT_2: u8 = 123; - ERROR...
//! The tokenizer module implements a nock tokenizer. // Copyright (2017) Jeremy A. Wall. // // 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-...
extern crate text_ui; use text_ui::app::App; use text_ui::backend::{ color::{self, Color}, Backend, }; use text_ui::widget::{shared, DbgDump, Line, Linear, Readline, Shared, Text}; use text_ui::{Event, Input, Key}; use std::thread; use std::time::Duration; struct DemoApp { log: Shared<Text>, side: Shared<...
// Copyright (c) Microsoft. All rights reserved. extern crate bytes; extern crate edgelet_core; #[macro_use] extern crate failure; extern crate hsm; mod certificate_properties; mod crypto; mod error; pub mod tpm; pub const IOTEDGED_VALIDITY: u64 = 7_776_000; // 90 days pub const IOTEDGED_COMMONNAME: &str = "iotedged...
#![cfg(feature = "derive")] #[macro_use] extern crate asn1_der; use ::asn1_der::{ IntoDerObject, FromDerObject, DerObject }; #[test] fn test() { // Define inner struct #[derive(Debug, Clone, Eq, PartialEq, Asn1Der)] struct Inner { integer: u128, boolean: bool, octet_string: Vec<u8>, utf8_string: String, ...
/// An enum to represent all characters in the PhoneticExtensionsSupplement block. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum PhoneticExtensionsSupplement { /// \u{1d80}: 'ᶀ' LatinSmallLetterBWithPalatalHook, /// \u{1d81}: 'ᶁ' LatinSmallLetterDWithPalatalHook, /// \u{1d82}: 'ᶂ' ...
#![allow(dead_code)] mod lexer; mod parser; // use lexer; // use parser; // use std; // use parser; use std::collections::VecDeque; use std::collections::HashMap; use parser::AST; use lexer::Token; pub trait Graphics { // Draws a line from p1 to p2 using window center as origin point (0, 0), and // having the x-...
use crate::{browser::Resources, html::Html, platform, render, Cmd, Sub}; use std::cell::RefCell; use std::fmt::Debug; use std::rc::Rc; use wasm_bindgen::{JsCast, JsValue}; pub struct Program<Model, Msg> { pub model: RefCell<Model>, pub view: Box<Fn(&Model) -> Html<Msg>>, pub update: Box<Fn(&Msg, &mut Model...
/* ---Find the First M Multiples of N--- Implement a function, multiples(m, n), which returns an array of the first m multiples of the real number n. Assume that m is a positive integer. Ex. multiples(3, 5.0) should return [5.0, 10.0, 15.0] */ fn main() { println!("{:?}", multiples(3, 5.0)); } fn multiples(m:...
fn main() { stack_scopes(); pvar_vs_fvars(); heap_scopes(); println!("\nOWNERSHIP"); let s1 = gives_ownership(); takes_ownership(s1); // s1 is no longer available here let mut s2 = String::from("hi"); s2 = takes_and_gives_ownership(s2); println!("{}", s2); println!("\nBORRO...
use std::fmt::Display; use std::path::Path; use colored::Colorize; pub fn error(err: impl Display) { eprintln!("{} {}", "error:".red().bold(), err); } pub fn success(msg: impl Display) { println!("{} {}", "success:".green().bold(), msg); } pub fn info(msg: impl Display) { println!("{} {}", "info:".blue(...
#![allow(non_snake_case, non_camel_case_types)] use libc::{c_int, c_short, c_void}; use crate::connector::ssh_connector; use crate::session::ssh_session; use crate::socket_t; #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct ssh_event_struct { _unused: [u8; 0], } pub type ssh_event = *mut ssh_event_struct; p...
use std::env; use std::fs; fn main() { let args: Vec<String> = env::args().collect(); let filename = &args[1]; let contents = fs::read_to_string(filename) .expect("Something went wrong reading the file"); let split_contents = contents.lines(); let answers: Vec<&str> = split_contents.collect(); let ...
use super::constants::*; // A collection of helpers to handle data structures for Cryptonid needs // Concatenate two arrays to a unique vector pub fn concatenate_arrays<T: Clone>(x: &[T], y: &[T]) -> Vec<T> { let mut concat = x.to_vec(); concat.extend_from_slice(y); concat } // KECCAK HELPERS // Get Sp...
use iron::{IronResult, Response, status}; use iron::headers::ContentType; use serde::Serialize; use serde_json; /// Turns any serializable object into a JSON Iron response. pub fn response<S: Serialize>(data: S) -> IronResult<Response> { let mut response = Response::with((status::Ok, itry!(serde_json::to_string(&d...
use std::iter; use std::mem; use crate::*; pub fn solve_line < LineIter: IntoIterator <Item = Cell>, > ( line_iter: LineIter, clues_line: & CluesLine, ) -> Option <LineSolverIter> { LineSolver::new ( line_iter, clues_line, ).ok ().map (LineSolver::into_iter) } #[ derive (Default) ] pub struct LineSolver {...
use std::fmt::Debug; #[derive(Debug)] pub enum CssSelectorAtom { Id(String), Class(String), Tag(String), } #[derive(Debug)] pub struct CssSelectorComposite { pub sels: Vec<CssSelectorAtom> } #[derive(Debug)] pub struct CssSelectorMultiple { pub sels: Vec<CssSelectorComposite> } impl std::fmt::...
mod precise; pub use precise::AymPrecise;
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT license. */ #![warn(missing_debug_implementations, missing_docs)] use std::str::FromStr; /// Distance metric #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum Metric { /// Squared Euclidean (L2-Squared) L2, /// ...
#[doc = "Reader of register SPINLOCK9"] pub type R = crate::R<u32, super::SPINLOCK9>; impl R {}
use crate::{messages::SBPMessage, serialize::SbpSerialize}; #[cfg(feature = "sbp_serde")] use serde::{Deserialize, Serialize}; #[cfg_attr(feature = "sbp_serde", derive(Serialize, Deserialize))] #[derive(Debug, Clone)] pub struct Unknown { pub msg_id: u16, pub sender_id: u16, pub payload: Vec<u8>, } impl ...
use std::time::{Duration, Instant, SystemTime}; use cfg_if::cfg_if; cfg_if! { if #[cfg(test)] { #[cfg(all(feature = "diesel2", feature = "sha-1"))] mod sleep; #[cfg(all(feature = "diesel2", feature = "sha-1"))] pub use self::sleep::*; pub fn instant_now() -> Instant { ...
#![cfg(not(target_arch = "wasm32"))] use std::cell::RefCell; use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::collections::HashMap; use std::net::SocketAddr; use std::pin::pin; use std::rc::Rc; use futures::{SinkExt, StreamExt}; use tokio::net::tcp::{OwnedReadHalf, OwnedWriteHalf}; use tokio::net::...
use std::cmp::max; use std::fs::File; use std::io::prelude::*; use std::io::{self, BufReader}; fn get_row(rows: &str) -> i32 { assert_eq!(rows.len(), 7); let mut lower = 0; let mut upper = 127; for letter in rows.chars().collect::<Vec<char>>() { let current_mod = (upper - lower + 1) / 2; ...
/********************************************** > File Name : AVLTree.rs > Author : lunar > Email : lunar_ubuntu@qq.com > Created Time : Tue 16 Feb 2021 05:02:38 PM CST > Location : Shanghai > Copyright@ https://github.com/xiaoqixian **********************************************/ /* * Imp...
#![cfg(feature = "curly")] use dynfmt::{Format, SimpleCurlyFormat}; macro_rules! test_fmt { ($name:ident, $expected:expr, $format:expr, $($args:expr),* $(,)*) => { #[test] fn $name() { assert_eq!( $expected, SimpleCurlyFormat .format(...
// Licensed: Apache 2.0 /// /// Wrap raw pointers /// This is effectively syntax sugar to avoid; /// `(*var).attr`, allowing `var.attr` on raw pointers. /// /// Other utility functions may be exposed, /// however the intent is to keep this a thin wrapper on raw pointers, /// not to invent a new way of managing pointer...
//! HyperLogLog implementation. use std::cmp; use std::collections::hash_map::DefaultHasher; use std::fmt; use std::hash::{BuildHasher, BuildHasherDefault, Hash, Hasher}; use std::marker::PhantomData; use crate::hyperloglog_data::{ BIAS_DATA_OFFSET, BIAS_DATA_VEC, POW2MINX, RAW_ESTIMATE_DATA_OFFSET, RAW_ESTIMATE_D...
#[doc = "Register `WPCCR` reader"] pub type R = crate::R<WPCCR_SPEC>; #[doc = "Register `WPCCR` writer"] pub type W = crate::W<WPCCR_SPEC>; #[doc = "Field `DCYC` reader - Number of dummy cycles"] pub type DCYC_R = crate::FieldReader; #[doc = "Field `DCYC` writer - Number of dummy cycles"] pub type DCYC_W<'a, REG, const...
use std::fs::File; use std;
use std::fmt; use header::{Header, Headers}; use http::{MessageHead, ResponseHead, Body}; use status::StatusCode; use version::HttpVersion; /// An HTTP Response pub struct Response<B = Body> { version: HttpVersion, headers: Headers, status: StatusCode, #[cfg(feature = "raw_status")] raw_status: ::...
#[doc = "Reader of register SPINLOCK8"] pub type R = crate::R<u32, super::SPINLOCK8>; impl R {}
//! # msfs-rs //! //! These bindings include: //! //! - MSFS Gauge API //! - SimConnect API //! //! ## Building //! //! If your MSFS SDK is not installed to `C:\MSFS SDK` you will need to set the //! `MSFS_SDK` env variable to the correct path. //! //! ## Known Issues //! //! Until https://github.com/rust-lang/rfcs/iss...
// 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::BssDescription; use Ssid; use std::cmp::Ordering; #[derive(Clone, Debug, PartialEq)] pub struct BssInfo { pub bssid: [u8; 6], pub s...
//! A Single-Producer, Multiple-Consumer queue. use std::sync::mpsc::{channel, Receiver, RecvError, Sender, SendError}; use std::sync::{Arc, Mutex, MutexGuard}; use std::fmt; use std::any::Any; use std::error::Error; #[derive(PartialEq, Eq, Clone, Copy, Debug)] /// Error from broadcast module. pub enum BroadcastError...
//! Content processing for POST and PUT. use mime::Mime; /// Processed content from PUT and POST requests. /// /// This will automatically store posted content in its most sensible form based on its MIME type. pub struct Content { mime: Mime, data: Data, } /// The stored form of the data. enum Data { ///...
pub mod ast; pub mod expand_visitor; pub mod expander; pub mod lexer; pub mod parser; pub mod rename_idents; pub mod replace_idents; pub mod span; pub mod span_visitor; pub mod tokens; pub mod tryfrom_visitor; pub mod visitors; #[cfg(test)] mod prop;
use std::cmp::min; use std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::sync::mpsc::SyncSender; use std::time::Duration; use chashmap::CHashMap; use crossbeam::queue::ArrayQueue; use rug::Integer; use rug::ops::Pow; use crate::algebra; use crate::serial_MPQS::{initialize_qs, InitResult}; use crate::to...
#[doc = "Register `CFGR1` reader"] pub type R = crate::R<CFGR1_SPEC>; #[doc = "Register `CFGR1` writer"] pub type W = crate::W<CFGR1_SPEC>; #[doc = "Field `MEM_MODE` reader - Memory mapping selection bits"] pub type MEM_MODE_R = crate::FieldReader<MEM_MODE_A>; #[doc = "Memory mapping selection bits\n\nValue on reset: 0...
use std::ffi::CStr; use std::fmt; use std::marker::PhantomData; use std::mem; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use std::ops::{Deref, DerefMut}; use std::os::raw::{c_char, c_void}; use std::path::Path; use std::ptr; use std::string; use anyhow::Result; use libc; use ffi; use errors::{AsResult, ErrorKind::C...
use crate::parser::Error; use crate::schedule_at; use crate::time_domain::RuleKind::*; #[test] fn basic_range() -> Result<(), Error> { assert_eq!( schedule_at!("Mo-Su", "2020-06-01"), schedule! { 00,00 => Open => 24,00 } ); assert_eq!(schedule_at!("Tu", "2020-06-01"), schedule! {}); a...
use crate::utils::establish_connection; use diesel::deserialize::QueryableByName; use diesel::mysql::MysqlConnection; use diesel::prelude::*; use diesel::sql_query; use chrono::{NaiveDateTime}; mod utils; type DB = diesel::mysql::Mysql; #[derive(Debug)] pub struct Memos { id: i32, name: String, ...
//! Control register #[cfg(cortex_m)] use core::arch::asm; #[cfg(cortex_m)] use core::sync::atomic::{compiler_fence, Ordering}; /// Control register #[derive(Clone, Copy, Debug)] pub struct Control { bits: u32, } impl Control { /// Creates a `Control` value from raw bits. #[inline] pub fn from_bits(b...
use menu::types::PaginationContainer; use serenity::client::Client as SerenityClient; use serenity::http::Http; use serenity::prelude::{GatewayIntents, RwLock, SerenityError}; use std::collections::{HashMap, HashSet}; use std::sync::Arc; use crate::core::event_handler::Zero2EventHandler; use crate::core::framework::Ze...
use alloc::boxed::Box; use collections::vec::Vec; use core::intrinsics::volatile_load; use core::mem::size_of; //use core::slice; use drivers::io::{Io, Mmio}; use drivers::pci::config::PciConfig; use arch::context::context_switch; use fs::KScheme; use super::{Hci, Packet, Pipe, Setup}; #[repr(packed)] #[derive(C...
use std::thread; use fast_spsc_queue::create_spsc_queue; fn main() { let (mut producer, mut consumer) = create_spsc_queue::<String>(2); let child = thread::spawn(move || { while let Some(msg) = consumer.dequeue() { println!("Child received {}", msg); }; }); for i in 0..60 ...
//! Simple Game Protocol use std::io; use crate::state::*; use crate::search::*; use crate::consts::*; use crate::pgn_parser::*; use crate::hashtables::*; pub fn user_input< 'a >( buffer: &'a mut String, stdin: &'a mut io::Stdin ) -> &'a str { buffer.clear(); match stdin.read_line( buffer ) { Ok( _ ) ...
use super::{ChatServer, ClientPacket}; use crate::auth::UserInfo; use crate::chat::{InternalId, SessionState}; use crate::error::*; use log::*; impl ChatServer { pub(super) fn handle_message(&mut self, user_id: InternalId, content: String) { if self.check_ratelimit(user_id, content.clone()) { ...
pub mod channel; pub mod process; pub mod start; pub mod util;
fn main() { let mut source: ::std::path::PathBuf = ::std::env::var("CARGO_MANIFEST_DIR") .expect("No `CARGO_MANIFEST_DIR` env var") .into(); source.push(".windows"); source.push("winmd"); let mut destination: ::std::path::PathBuf = ::std::env::var("OUT_DIR") .expect("No `OUT_DI...
use crate::point::Error; use crate::Result; /// The ASPRS classification table. /// /// Classifications can be created from u8s and converted back into them: /// /// ``` /// use las::point::Classification; /// let classification = Classification::new(2).unwrap(); /// assert_eq!(Classification::Ground, classification);...
use webrtc_sctp::association::*; use webrtc_sctp::chunk::chunk_payload_data::PayloadProtocolIdentifier; use webrtc_sctp::error::*; use webrtc_sctp::stream::*; use bytes::Bytes; use clap::{App, AppSettings, Arg}; //use std::io::Write; use std::sync::Arc; use tokio::net::UdpSocket; use tokio::signal; use tokio::sync::mp...
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. use core::{ convert::TryFrom, fmt::{Debug, Display}, ops::{ Add, AddAssign, BitAnd, Div, DivAssign, Mul, MulAssign, Ne...
use crate::{ bet_database::{BetId, BetState}, bitcoin::{Amount, Script}, change::{BinScript, Change}, party::Party, ValueChoice, }; use anyhow::{anyhow, Context}; use bdk::{bitcoin, bitcoin::Denomination, database::BatchDatabase, FeeRate}; use core::str::FromStr; use olivia_core::{EventId, OracleEve...
use serenity::framework::standard::{macros::command, Args, CommandResult}; use serenity::model::prelude::{Message, MessageId}; use serenity::prelude::Context; use crate::core::checks::ADMIN_CHECK; #[command] #[checks(Admin)] async fn cleanup(context: &Context, message: &Message, args: Args) -> CommandResult { // ...
#[cfg(any(feature = "backend_egl", feature = "renderer_gl"))] extern crate gl_generator; #[cfg(any(feature = "backend_egl", feature = "renderer_gl"))] use gl_generator::{Api, Fallbacks, Profile, Registry}; use std::{env, fs::File, path::PathBuf}; #[cfg(any(feature = "backend_egl", feature = "renderer_gl"))] fn main()...
// inside lib.rs, only the following line should be in here pub mod error; pub mod instruction; pub mod processor; pub mod state; #[cfg(not(feature = "no-entrypoint"))] pub mod entrypoint;
#[cfg(test)] mod tests { extern crate pqcrypto_classicmceliece; use self::pqcrypto_classicmceliece::mceliece8192128::*; #[test] fn basic_classicmceliece_test() { let (pk, sk) = keypair(); let (ss1, ct) = encapsulate(&pk); let ss2 = decapsulate(&ct, &sk); assert...
#![allow(non_upper_case_globals)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(dead_code)] include!(concat!(env!("OUT_DIR"), "/nginx.rs")); #[no_mangle] pub unsafe extern "C" fn ngx_http_calculator_handler( r: *mut ngx_http_request_t, ) -> ngx_int_t { let rc = ngx_http_read_client_request_bod...
use crate::api::*; use crate::data::{get_book, get_order}; fn composer<T1: 'static, T2: 'static, E: 'static>( input: Result<T1, E>, transform: &'static impl Fn(T1) -> Result<T2, E>, ) -> Result<T2, E> { input.and_then(transform) } fn compose_two<T1: 'static, T2: 'static, T3: 'static, E: 'static>( tran...
//! Rust parser for the racr format. //! //! # Examples //! ## Parse Access //! ``` //! assert_eq!( //! racr::Access::ReadOnly, //! racr_parser::AccessParser::new().parse("ro").unwrap() //! ); //! ``` //! ``` //! assert_eq!( //! racr::Access::WriteOnly, //! racr_parser::AccessParser::new().parse("wo").u...
use std::fs::{self, DirEntry}; use std::{io, path::Path}; pub struct VisitDir { root: Box<dyn Iterator<Item = io::Result<DirEntry>>>, children: Box<dyn Iterator<Item = VisitDir>>, } impl VisitDir { pub fn new<P: AsRef<Path>>(path: P) -> io::Result<Self> { let root = Box::new(fs::read_dir(&path)?);...
// TODO: Needs improvement pub fn ladder_length(begin_word: String, end_word: String, word_list: Vec<String>) -> i32 { use std::collections::HashSet; let begin_word: Vec<char> = begin_word.chars().collect(); let end_word: Vec<char> = end_word.chars().collect(); let word_list: Vec<Vec<char>> = word_list...
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ //! Provides a more rustic interface to a minimal set of `perf` functionality. //! //! Explicitly m...
fn read_line() -> String { let mut line = String::new(); std::io::stdin().read_line(&mut line).unwrap(); line.trim_end().to_owned() } fn main() { let stdin = read_line(); let mut iter = stdin.split_whitespace(); let a: isize = iter.next().unwrap().parse().unwrap(); let b: isize = iter.next(...
extern crate futures; extern crate tokio_core; use futures::{Future, Stream}; use tokio_core::io::{copy, Io}; use tokio_core::net::TcpListener; use tokio_core::reactor::Core; fn main() { // Create the event loop that will drive this server let mut core = Core::new().unwrap(); let handle = core.handle(); ...
pub mod tui; mod config; mod source; mod scraper; use async_trait::async_trait; use crate::track::Track; use super::{metasource, websearch}; pub use config::Config; pub use source::{Params as SourceParams, Status, ItemStatus}; #[derive(Debug, Clone)] pub struct Module<WS: websearch::Module> { config: Config<WS::Se...
extern crate proc_macro; use std::io::{Error as IOError}; use byteorder::{ByteOrder, WriteBytesExt, BE, LE}; use failure::Fail; use quote::{ToTokens, quote}; use proc_macro::TokenStream; use proc_macro_hack::proc_macro_hack; use syn::{parse_macro_input, Error as SynError, Expr, IntSuffix, FloatSuffix, Lit, LitInt, Lit...
//! Checks that the declared unsafety is respected by the attributes #![deny(warnings)] #![no_main] #![no_std] extern crate cortex_m_rt; extern crate panic_halt; use cortex_m_rt::{entry, exception, ExceptionFrame}; #[entry] unsafe fn main() -> ! { foo(); loop {} } #[exception] unsafe fn DefaultHandler(_ir...
#![doc = "generated by AutoRust 0.1.0"] #![allow(unused_mut)] #![allow(unused_variables)] #![allow(unused_imports)] use super::{models, API_VERSION}; #[non_exhaustive] #[derive(Debug, thiserror :: Error)] #[allow(non_camel_case_types)] pub enum Error { #[error(transparent)] Skus_List(#[from] skus::list::Error),...
#[doc = "Reader of register LPTIM_SIDR"] pub type R = crate::R<u32, super::LPTIM_SIDR>; #[doc = "Reader of field `S_ID`"] pub type S_ID_R = crate::R<u32, u32>; impl R { #[doc = "Bits 0:31 - S_ID"] #[inline(always)] pub fn s_id(&self) -> S_ID_R { S_ID_R::new((self.bits & 0xffff_ffff) as u32) } }
extern crate libc; extern crate regex; #[macro_use] extern crate lazy_static; use std::env; use std::fs::File; mod keyboard; mod virtual_keyboard; mod key_converter; use keyboard::Keyboard; use virtual_keyboard::*; use key_converter::KeyConverter; fn loop_keymap(kbd: Keyboard, mut vkbd: VirtualKeybo...
mod boid; use ggez::{GameResult, event, Context, graphics}; use ggez::graphics::Color; use ggez::mint::Vector2; use glam::*; use legion::{World, Schedule, Resources, Read, IntoQuery, Entity}; use crate::boid::{update_positions_system, update_velocities_system, Position, Boid, Velocity, update_velocities, Acceleration...
use super::hpu::*; use std::boxed::Box; use std::fs::File; use super::error::*; use std::io::{BufRead, BufReader, BufWriter, Write}; use crate::{hack_report_less}; pub fn create_assembler(path: &std::path::PathBuf) -> Assembler { Assembler { path: path.clone(), hpu: HPU::new(path), } } pub st...
use crate::parser::nom_input; use crate::parser::parse::token_tree::TokenNode; use crate::parser::parse::tokens::RawToken; use crate::parser::{Pipeline, PipelineElement}; use crate::shell::shell_manager::ShellManager; use crate::Tagged; use ansi_term::Color; use rustyline::completion::Completer; use rustyline::error::R...
use crate::distribution::{Discrete, DiscreteCDF}; use crate::function::factorial; use crate::statistics::*; use crate::{Result, StatsError}; use rand::Rng; use std::cmp; use std::f64; /// Implements the /// [Hypergeometric](http://en.wikipedia.org/wiki/Hypergeometric_distribution) /// distribution /// /// # Examples /...
fn main() { let f = print_number; f(); } fn print_number() { println!(666); }
use std::collections::BTreeSet; // TODO: evaluate performance of using btreemap's instead of sets (it's nice to have the sortedness, but performance?) // insertion should (almost always) be a greater value? #[derive(Clone)] pub enum Selection { AlwaysOne(usize), MaybeOne(Option<usize>), Multiple(BTreeSet<...
pub mod mutable_ref; pub mod reference; pub fn references() { mutable_ref::mut_ref(); reference::reference(); }
use proc_macro2::{Span, TokenStream as TokenStream2}; use quote::quote; use syn::{parse::ParseBuffer, Error, Fields, Ident, ItemEnum, Type}; pub struct MoebiusInstruction { ast: ItemEnum, } impl MoebiusInstruction { pub fn expand(&self) -> TokenStream2 { let mut initialize_fields = vec![quote! { moebi...
use futures::future::{Future, FutureResult}; use negotiationresponse::NegotiationResponse; use connection::Connection; use serde_json::{Map, Value}; use std::sync::mpsc::Sender; pub trait ClientTransport { fn name(&self) -> &str; fn negotiate( &mut self, url: &str, connection_data: &str...
#[macro_use] extern crate lazy_static; extern crate wars_8_api; use wars_8_api::*; use std::sync::Mutex; const MSG: &str = "UwU"; lazy_static! { static ref COORDS: Mutex<((i32, i32), (i32, i32), bool)> = Mutex::new(((0, 6), (1, 1), false)); } #[no_mangle] pub fn _init() { } #[no_mangle] pub fn _update() { ...
#![deny(missing_docs, unsafe_code)] use super::{BitMode, DeviceType, FtStatus, FtdiCommon, TimeoutError}; use std::convert::From; use std::time::Duration; #[derive(Debug, Copy, Clone, Eq, PartialEq)] #[repr(u8)] enum MpsseCmd { SetDataBitsLowbyte = 0x80, GetDataBitsLowbyte = 0x81, SetDataBitsHighbyte = 0x...
pub mod networks; pub mod transaction_types; pub use self::networks::Network; pub use self::transaction_types::TransactionType;