text
stringlengths
8
4.13M
// 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 ...
/* This is part of mktcb - which is under the MIT License ********************/ use snafu::ResultExt; use crate::error::Result; use crate::error; use crate::config::Config; use crate::download; use crate::util; use log::*; use std::path::PathBuf; pub struct Toolchain { pub cross_compile: String, url: url::Ur...
/* Crypto.com Chain Multi-sig backend demo in Actix-Web */ #[macro_use] extern crate diesel; use actix_cors::Cors; use actix_web::{http::header, middleware, web, App, Error as AWError, HttpResponse, HttpServer}; use diesel::prelude::*; use diesel::r2d2::{self, ConnectionManager}; use futures::future::Future; use li...
use criterion::{criterion_group, criterion_main, Criterion}; use partial_mixed_markdown::Document; criterion_main!(benches); criterion_group!(benches, functions); fn functions(c: &mut Criterion) { let mixed = include_str!("../tests/mixed.md"); let large = include_str!("../tests/large.md"); let mut group =...
//! This project is used for explaining IIR filtering operation using constant //! coefficient difference equation. //! //! Requires `cargo install probe-run` //! `cargo run --release --example 2_23_direct_iir_filtering` #![no_std] #![no_main] use panic_break as _; use stm32f4xx_hal as hal; use core::f32::consts::{F...
use std::ops::Range; use std::cmp; pub use rand::*; pub fn seeded_rng(seed: u64) -> XorShiftRng { XorShiftRng::from_seed([ (seed ^ 0x4d3a1613c0077157) as u32, (seed ^ 0xaa99ab477fd5d862) as u32, (seed ^ 0xa16d13ad8b5d4420) as u32, (seed ^ 0x82e93fddc8167589) as u32 ]) } pub fn...
use super::service::{NewService, Service}; use crate::codec; use futures::{future, select}; use futures_util::{future::FutureExt, sink::SinkExt, stream::StreamExt}; use log::{error, trace}; use net2; use std::{future::Future, io, net::SocketAddr, sync::Arc}; use tokio::net::{TcpListener, TcpStream}; use tokio_util::co...
#[derive(Debug)] enum MyOption<T> { MyNone, MySome(T) } use MyOption::*; impl<T> MyOption<T> { fn map<U, F>(self, f: F) -> MyOption<U> where F: FnOnce(T) -> U { panic!("implement me") } fn and_then<U, F>(self, f: F) -> MyOption<U> where F: FnOnce(T) -> MyOption<U> { ...
/// GeneralRepoSettings contains global repository settings exposed by API #[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct GeneralRepoSettings { pub http_git_disabled: Option<bool>, pub mirrors_disabled: Option<bool>, } impl GeneralRepoSettings { /// Create a builder for this object. ...
use super::*; /// An export block. /// /// # Semantics /// /// This block will only be exported in the specified backend. /// /// # Syntax /// /// ```text /// #+BEGIN_EXPORT BACKEND /// CONTENTS /// #+END_EXPORT /// ``` /// /// `CONTENTS` can contain anything except a line `#+END_EXAMPLE` on its own. Lines beginning /...
use crate::{Browser, BrowserOptions, Error, ErrorKind, Result, TargetType}; use core_foundation::array::{CFArray, CFArrayRef}; use core_foundation::base::TCFType; use core_foundation::error::{CFError, CFErrorRef}; use core_foundation::url::{CFURLRef, CFURL}; use std::os::raw::c_void; /// Deal with opening of browsers ...
use rand::{thread_rng, Rng, sample}; pub fn shuffler(deck: &mut [&str]) { let mut rng = thread_rng(); rng.shuffle( deck); } pub fn sub_sample(deck: &[String], num: usize) { let mut rng = thread_rng(); let sample = sample(&mut rng, deck, num); } pub fn percentage_sub_sample(deck: &[String], percentag...
use std::sync::{Arc, RwLock}; use bevy::core_pipeline::bloom::BloomSettings; use bevy::prelude::*; use bevy_inspector_egui::plugin::InspectorWindows; use bevy_inspector_egui::{Inspectable, InspectorPlugin}; use palette::{Blend, LinSrgba, Srgba}; use crate::animations::current_config; use crate::backends::null::NullBa...
use piston_window::*; use rand::Rng; use noise::*; const BG:[f32; 4] = [33.0/255.0, 33.0/255.0, 33.0/255.0, 1.0]; struct Particle { x: f64, y: f64, xv: f64, yv: f64, size: f64, color: [f32; 4] } fn main() { let mut rng = rand::thread_rng(); let perlin = Perlin::new(); let mut part...
use std::net::{IpAddr, SocketAddr}; use std::{ error::Error, fmt, io, time::{Duration, Instant}, }; use futures::prelude::*; use futures::select; use log::warn; use tokio::time::interval; use crate::packet::*; use crate::protocol::{handshake::Handshake, TimeStamp}; use crate::util::get_packet; use crate::...
mod datastore; fn main() { match datastore::create_order(String::from("Apple"), 3) { Err(e) => println!("Error: {}",e), Ok(_) => println!("OK") }; match datastore::show_table() { Err(e) => println!("Error: {}",e), Ok(_) => println!("OK") }; match datastore::update_...
use std::collections::BTreeMap; fn main() { let mut map:BTreeMap<u64, u64> = BTreeMap::new(); map.entry(0).or_insert(0); let y = map[&0] + 1; // http://stackoverflow.com/questions/41090572/expected-reference-found-integral-variable-in-accessing-a-value-from-btreemap/41090691#41090691 println!("{}", y); }
pub fn my_lib() {}
use crate::Number; use super::Term; ///A term which multiplies a given term by a constant number. Especially useful for - signs pub struct ScalarTerm<T: Number> { term: Box<dyn Term<T> + Send + Sync>, scale: T } impl<T: Number> ScalarTerm<T> { ///Creates a ScalarTerm using the given subterm and multipl...
use crate::lib::environment::Environment; use crate::lib::error::DfxResult; use crate::lib::identity::identity_manager::IdentityManager; use anyhow::anyhow; use clap::Clap; use ic_agent::identity::Identity; /// Shows the textual representation of the Principal associated with the current identity. #[derive(Clap)] pub...
use std::borrow::Cow; use uuid::Uuid; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug)] pub struct Order<'a> { side: OrderSide, client_oid: Option<Uuid>, product_id: Cow<'a, str>, #[serde(flatten)] _type: OrderType, #[serde(flatten)] stop: Option<OrderStop>, } ...
use crate::shared::tree_node::TreeNode; struct Solution; use std::cell::RefCell; use std::rc::Rc; /// https://leetcode.com/problems/invert-binary-tree/ impl Solution { /// 0 ms 2.2 MB pub fn invert_tree(root: Option<Rc<RefCell<TreeNode>>>) -> Option<Rc<RefCell<TreeNode>>> { fn helper(node: Rc<RefCell<...
#[cfg(feature = "dll")] #[macro_export] macro_rules! native_loader { ($plugin_type:ident) => { struct NativePlugin { id: $crate::uuid::Uuid, plugin: Option<Box<dyn $plugin_type>>, library: $crate::libloading::Library, } impl Drop for NativePlugin { ...
//! Decodes formats for rotations. //! //! Rotations are always stored as a 3x3 matrix (probably for speed; the NDS //! probably wasn't fast enough to convert Euler angles or quaternions to //! matrices on the fly). This also means that a "rotation" matrix might not //! actually be a rotation (ie. orthogonal of determi...
use std::{ collections::hash_map::DefaultHasher, hash::{Hash, Hasher}, }; use glam::{DAffine2, DVec2}; use serde::{Deserialize, Serialize}; use crate::{ layers::{self, Folder, Layer, LayerData, LayerDataType, Shape}, DocumentError, DocumentResponse, LayerId, Operation, Quad, }; #[derive(Debug, Clone, Deserialize...
static NUNINFLECTED: [&'static str; 44] = ["bison", "flounder", "pliers", "bream", "gallows", "proceedings", "breeches", "graffiti", "rabies", "britches", "headquarters", "salmon", "carp", "herpes", "scissors", "chassis", "high-jinks", "sea-bass", "clippers", "homework", "series", "cod", "innings", "shears", "contretem...
use rand::distributions::{IndependentSample, Range}; use rand::thread_rng; #[derive(Clone, Debug)] pub struct Food { pub x: u32, pub y: u32, } fn round_to_tens(num: u32) -> u32 { (num / 10) * 10 } impl Food { pub fn next_rand_food(upper_bound_x: u32, upper_bound_y: u32) -> Food { let between_x = Range...
pub use self::ai::AIBigBrainSystem; pub use self::ball::{BallMoveSystem, BALL_MOVE_SYSTEM}; pub use self::bounce::BounceSystem; pub use self::paddle::{PaddleMoveSystem, PaddleSystem, PADDLE_MOVE_SYSTEM, PADDLE_SYSTEM}; pub use self::score::{ScoreSystem, SCORE_SYSTEM}; mod ai; mod ball; mod bounce; mod paddle; mod scor...
use anyhow::Result; use git2::Repository; use crate::{get_remotes, TrimPlan}; /// Prints all locally to-be-deleted branches. pub fn print_local( plan: &TrimPlan, _repo: &Repository, mut writer: impl std::io::Write, ) -> Result<()> { let mut merged_locals = Vec::new(); for branch in &plan.to_delete...
mod agent; mod agent_debug_info; mod agents; mod apply_velocity_navigator; mod look_where_you_go_navigator; mod navmesh; mod neighborhood; mod orca; mod reach_target_navigator; mod scenarii; mod utils; mod vec2; use agent_debug_info::AgentDebugInfo; use agents::Agents; use navmesh::Navmesh; use scenarii::{load_scenari...
// the boolean condition doesn't need to be surroinded by // parentheses, and each condition is followed by a block. // `if-else` conditionals are expressions, and, all branches // must return the same type fn main() { let n = 5; if n < 0 { print!("{} is negative", n); } else if n > 0 { pri...
use std::fs::File; use std::io::{self, BufRead}; use std::path::Path; // The output is wrapped in a Result to allow matching on errors // Returns an Iterator to the Reader of the lines of the file. fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>> where P: AsRef<Path>, { let file = Fi...
fn main() { println!("get_min(&[5, 4, 3, 2, 1]) = {}", get_min(&[5, 4, 3, 2, 1])); println!( "remove_space(\" No s pa ce any more \") = \"{}\"", remove_space(" No s pa ce any more ") ); println!( "remove_odd(&[1, 2, 3, 4, 5]) = {:?}", remove_odd(&[1, 2, 3, 4, 5]) ...
/* chapter 4 syntax and semantics */ fn main() { let a = vec![1, 2, 3, 4, 5]; // a: Vec<i32> println!("{:?}", a); let b = vec![0; 5]; // ten zeroes println!("{:?}", b); } // output should be: /* */
//! Terminal events defined specific to usage. use crate::util::{Point, Size}; #[derive(Debug)] pub enum MouseButton { Left, Middle, Right, } #[derive(Debug)] pub enum EventKind { ScrollUp, ScrollDown, Move, Drag(MouseButton), Press(MouseButton), Release(MouseButton), } pub struc...
use std::io::{Result, Write}; /// A type which duplicates its writes to the provided writers pub struct BroadcastWriter<A: Write, B: Write> { primary: A, secondary: B, } impl<A: Write, B: Write> BroadcastWriter<A, B> { /// Creates a new BroadcastWriter instance which can be used as a Write. /// All da...
use core::ops::{Deref, DerefMut}; /// A smart pointer to a socket. /// /// Allows the network stack to efficiently determine if the socket state was changed in any way. pub struct Ref<'a, T: 'a> { socket: &'a mut T, consumed: bool, } impl<'a, T: 'a> Ref<'a, T> { /// Wrap a pointer to a socket to make a sm...
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 // // ---------- W A R N I N G: A U T O - G E N E R A T E D C O D E !! ---------- // PLEASE DO NOT HAND-EDIT THIS FILE. IT HAS BEEN AUTO-GENERATED WITH THE // FOLLOWING...
use crate::display::DisplayWith; use crate::grammar::Grammar; use crate::grammar::NonterminalIndex; use crate::grammar::Symbol; use crate::grammar::TerminalIndex; use crate::lr0; use crate::set::FirstSet; use crate::set::FirstSets; use crate::set::FollowSet; use std::cmp::Ordering; use std::collections::BTreeMap; use s...
#![allow(dead_code)] #![allow(unused_variables)] // struct definition struct User { // fields with their data types username: String, email: String, sign_in_count: u64, active: bool, } fn main() { // struct instance creation let user1 = User { email: String::from("someone@example.c...
use crate::circuit::{Circuit, Gate}; use std::collections::HashMap; pub fn print(c: &Circuit) { println!("{} {}", c.nwires() - c.ninputs(), c.nwires()); println!("{} {} {}\n", c.ninputs(), 0, c.noutputs()); let mut map = HashMap::new(); // The inputs are implicitly the first refs in Bristol format ...
use error_chain::error_chain; pub mod peer { use error_chain::error_chain; error_chain! { errors { ConnectFailed {} HasNoPeerAddr {} HasNoLocalAddr {} ReadMessageFailed {} Disconnected {} AlreadyRunning {} ShutdownFail...
//! Exposes an API for creating state-machine-based Kubernetes Operators. #![deny(missing_docs)] mod manifest; mod object; mod operator; mod runtime; mod store; pub mod util; #[cfg(feature = "admission-webhook")] pub mod admission; pub mod state; // TODO: Remove once webhooks are supported. #[cfg(not(feature = "ad...
use float_eq::assert_float_eq; use totsu::prelude::*; use totsu::*; type La = FloatGeneric<f64>; type AMatBuild = MatBuild<La>; type AProbQP = ProbQP<La>; type ASolver = Solver<La>; // #[test] fn test_qp1() { let _ = env_logger::builder().is_test(true).try_init(); let n = 2; // x0, x1 ...
use stomp_parser::error::StompParseError; pub struct StompClientError { message: String, } impl StompClientError { pub fn new<T: Into<String>>(message: T) -> Self { StompClientError { message: message.into(), } } } impl std::fmt::Debug for StompClientError { fn fmt(&self, ...
use ::*; #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum KeyboardEventType { KeyPress, KeyDown, KeyUp, } impl KeyboardEventType { fn from(event: EM_EVENT_TYPE) -> KeyboardEventType { match event { EMSCRIPTEN_EVENT_KEYPRESS => KeyboardEventType::KeyPress, EMS...
use std::collections::HashSet; pub struct Solution {} /** https://leetcode.com/problems/jewels-and-stones/ **/ impl Solution { pub fn num_jewels_in_stones(j: String, s: String) -> i32 { let j_set: HashSet<char> = j.chars().into_iter().collect(); let mut count = 0; for x in s.chars() { ...
// Suppress noisy warnings when a method is not used under a certain feature flag. #![allow(unused)] use reqwest::{IntoUrl, Method, Response}; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use crate::error::{Error, Result}; #[derive(Clone, Debug, Default)] pub(crate) struct HttpClient { inner: reqwe...
#[doc = "Reader of register EVENT_ENABLE"] pub type R = crate::R<u32, super::EVENT_ENABLE>; #[doc = "Writer for register EVENT_ENABLE"] pub type W = crate::W<u32, super::EVENT_ENABLE>; #[doc = "Register EVENT_ENABLE `reset()`'s with value 0"] impl crate::ResetValue for super::EVENT_ENABLE { type Type = u32; #[i...
use std::io::File; use std::path::posix::Path; //use std::option::Option; use std::vec::Vec; // Prints the byte length of every underlying packet in the stream // A bitstream is represented by the stream itself (read to a certain point), // plus any information needed to process the remainder of the stream at that //...
//! Repo branches interface //! //! For more information, visit the official //! [Github docs](https://developer.github.com/v3/repos/branches/) extern crate serde_json; use self::super::{Iter, MediaType, Github, Result}; use std::collections::BTreeMap; fn identity<T>(x: T) -> T { x } /// reference to gists assoc...
#[doc = "Register `BDTR` reader"] pub type R = crate::R<BDTR_SPEC>; #[doc = "Register `BDTR` writer"] pub type W = crate::W<BDTR_SPEC>; #[doc = "Field `DTG` reader - Dead-time generator setup"] pub type DTG_R = crate::FieldReader; #[doc = "Field `DTG` writer - Dead-time generator setup"] pub type DTG_W<'a, REG, const O...
#![feature(test)] extern crate mpsc; extern crate rand; extern crate test; use std::sync::Arc; use std::sync::mpsc as std_mpsc; use std::thread; use rand::{thread_rng, Rng}; use test::Bencher; fn get_data() -> Vec<u8> { thread_rng().gen_iter().take(1000).collect() } fn get_data_sum<I: IntoIterator<Item=u8>>(xs...
use itertools::Itertools; use sample::{signal, Signal}; use image::ImageBuffer; use image::Rgba; use std::sync::Arc; use vulkano::buffer::BufferUsage; use vulkano::buffer::CpuAccessibleBuffer; use vulkano::command_buffer::AutoCommandBufferBuilder; use vulkano::command_buffer::CommandBuffer; use vulkano::command_buffer...
/* linux/samples/rust/rust_chrdev.rs I add two file-operations: read and write - write-operation failed with EFAULT - I checked the comments of read_slice: Returns `EFAULT` if the byte slice is bigger than the remaining size of the user slice - So I must use chunk instead of chunkbuf. - This souce works well. */ #![n...
use std::path::{ Path, PathBuf }; pub mod gen; pub fn module_filename<P: AsRef<Path>, T: chom_ir::Namespace>(namepsace: &T, root: P, module_path: chom_ir::Path<T>) -> PathBuf { let mut file_path = root.as_ref().to_path_buf(); for segment in module_path { match segment { chom_ir::path::Segment::Module(id) =>...
#[doc = "Register `CRYP_IMSCR` reader"] pub type R = crate::R<CRYP_IMSCR_SPEC>; #[doc = "Register `CRYP_IMSCR` writer"] pub type W = crate::W<CRYP_IMSCR_SPEC>; #[doc = "Field `INIM` reader - INIM"] pub type INIM_R = crate::BitReader; #[doc = "Field `INIM` writer - INIM"] pub type INIM_W<'a, REG, const O: u8> = crate::B...
// Copyright 2016 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
#![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 ClusterProperties { #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub nex...
#[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct RepoCommit { pub author: Option<crate::commit_user::CommitUser>, pub committer: Option<crate::commit_user::CommitUser>, pub message: Option<String>, pub tree: Option<crate::commit_meta::CommitMeta>, pub url: Option<String>, } impl ...
use std::io::{BufWriter, Write}; use byteorder::WriteBytesExt; use crate::error::{TychoError, TychoStatus}; use crate::write::length::write_length; pub(crate) fn write_byte<W: Write>(writer: &mut W, byte: &u8) -> TychoStatus { match writer.write_u8(*byte) { Ok(_) => Ok(()), Err(e) => Err(TychoErr...
extern crate libc; use libc::{size_t, malloc}; use std::mem; use std::ptr; fn main() { // How ugly it is to pretend Rust is unsafe C. unsafe { let mut orig: *mut int = malloc(mem::size_of::<int>() as size_t) as *mut int; ptr::write(&mut *orig, 5i); println!("{}", *orig); ...
#![feature(proc_macro)] extern crate meteor_kernel; use meteor_kernel::foo; fn main() { let x = foo!(); }
use *; /// Stores selection state. pub struct Selection<T> { /// Selected scalars. pub selected1: Vec<ptr::Point1<T>>, /// Selected 2D vectors. pub selected2: Vec<ptr::Point2<T>>, /// Selected 3D vectors. pub selected3: Vec<ptr::Point3<T>>, /// Selected 4D vectors. pub selected4: Vec<pt...
use crate::auditwheel::{get_policy_and_libs, patchelf, relpath}; use crate::auditwheel::{PlatformTag, Policy}; use crate::build_options::CargoOptions; use crate::compile::{warn_missing_py_init, CompileTarget}; use crate::module_writer::{ add_data, write_bin, write_bindings_module, write_cffi_module, write_python_pa...
use super::{Definition, Document, Selection, SelectionSet}; use crate::{node_trait, visit, visit_each}; #[allow(unused_variables)] pub trait Visitor { fn enter_query(&mut self, doc: &Document) {} fn enter_query_def(&mut self, def: &Definition) {} fn enter_sel_set(&mut self, sel_set: &SelectionSet) {} f...
use crate::kind::Kind; use crate::class::Class; use crate::opcode::OpCode; use crate::rcode::ResponseCode; use crate::record::Record; use crate::record::ClientSubnet; use crate::record::OPT; use crate::record::OptAttr; use crate::edns::EDNS_V0; use crate::edns::EDNSFlags; use crate::ser::Serializer; use crate::ser::Se...
use super::utils::read_to_le_bytes; use crate::error::DemoError; use crate::error::ErrorType; use crate::reader::Reader; #[derive(Debug)] pub struct Header { header: String, demo_protocol: i32, network_protocol: i32, server_name: String, client_name: String, map_name: String, game_director...
use std::any::TypeId; use crate::Resource; pub struct MyResource {} pub struct AnotherResource {} #[test] fn dyn_has_correct_type_id() { let my_resource = MyResource {}; let my_resource_dyn: &dyn Resource = &my_resource; assert_eq!(my_resource_dyn.type_id(), TypeId::of::<MyResource>()); } #[test] fn do...
// This file is part of Substrate. // Copyright (C) 2019-2020 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // ht...
extern crate enigo; use enigo::*; use std::{thread, time}; fn main() { let wait_time = time::Duration::from_millis(200); let mut enigo = Enigo::new(); thread::sleep(wait_time); enigo.key_sequence("hello world"); }
use std::io::{self, IoSlice}; use std::sync::atomic::Ordering; #[cfg(feature = "io_timeout")] use std::time::Duration; use super::super::{co_io_result, IoData}; use crate::coroutine_impl::{is_coroutine, CoroutineImpl, EventSource}; use crate::io::AsIoData; use crate::yield_now::yield_with_io; pub struct SocketWriteVe...
#![warn(rust_2018_idioms)] pub mod provider; pub(crate) mod rpc; mod service; pub use rpc::DefaultEthConfig; pub use service::EthConfiguration;
use bmp; use minifb::{Key, KeyRepeat, MouseButton, MouseMode, Window, WindowOptions}; use std::{collections::BTreeMap, fmt::Debug, time::Duration}; mod saveread; #[derive(Debug)] struct Img { image: Vec<u32>, width: usize, height: usize, objects: BTreeMap<usize, Vec<((usize, usize), FromImage)>>, ...
extern crate csv; use std::error::Error; use std::collections::{HashMap,HashSet}; pub type Grammar = u16; pub const NUM_PARAMS: usize = 13; #[derive(Debug)] pub struct Domain { pub language: HashMap<Grammar, HashSet<u32>> } type Record = (u16, u32, u32); impl Domain { pub fn new() -> Domain { let la...
use log::*; use std::fs::File; use std::io::{BufRead, BufReader, BufWriter, Write}; use std::path::PathBuf; use structopt::StructOpt; use dfa_optimizer::{Row, Table}; use std::collections::BTreeMap; /// dfa reads in a formatted DFA file and spits /// out an optimized form of given DFA. #[derive(Debug, Clone, StructO...
#[doc = "Register `PLLCFGR` reader"] pub type R = crate::R<PLLCFGR_SPEC>; #[doc = "Register `PLLCFGR` writer"] pub type W = crate::W<PLLCFGR_SPEC>; #[doc = "Field `PLLM` reader - Division factor for the main PLL (PLL) and audio PLL (PLLI2S) input clock"] pub type PLLM_R = crate::FieldReader; #[doc = "Field `PLLM` write...
mod deck; mod game; #[cfg(test)] mod tests { use super::deck::*; #[test] fn test_string() { let c = Card::new(Suit::SPADE, Rank::ACE); assert_eq!(c.to_string(), "Ace of Spades") } #[test] fn test_cards() { let v = cards(&[]); assert!(v.len() == 13 * 4) } ...
use engine::{Input, Output, Event}; use std::sync::mpsc_queue::Queue; use std::sync::Arc; use std::comm::channel; pub struct PipelineBuilder { inputs: Vec<fn<'a>() -> Box<Input+'a>>, outputs: Vec<fn<'a>() -> Box<Output+'a>> } impl PipelineBuilder { pub fn new() -> PipelineBuilder { PipelineBuilder { inputs: V...
use crate::error::Result; use crate::laheader::LazHeader; use crate::lapoint::LazPoint; use crate::lautil::ErrorHandler; /// Reader of laz points pub struct LazReader { data: Vec<u8>, ptr: laszip_sys::laszip_POINTER, is_open: bool, } /// Iterator over points of a reader pub struct LazPointReaderIterator<'...
use super::command::ParameterizedCommand; use super::track::Track; #[cfg(test)] mod tests { use super::super::command::Command; use super::*; fn convert_commands(commands: &[Command]) -> Vec<ParameterizedCommand> { commands .iter() .map(|cmd| ParameterizedCommand::new(None,...
use crate::models::Token; use crate::util::ensure_is_authorized; use actix_multipart::Multipart; use actix_web::{error, web, HttpResponse, Result}; use actix_web_grants::permissions::AuthDetails; use anyhow::anyhow; use crc32c::crc32c; use database::models::{Item as DatabaseItem, LogEntry, Token as DatabaseToken}; use ...
use super::error::{ErrorKind, Result}; use std::path::{Path, PathBuf}; pub fn join<T: AsRef<Path>, S: AsRef<str>>(base: T, cmp: S) -> Result<PathBuf> { let mut path: String = cmp.as_ref().to_owned(); let mut base: PathBuf = base.as_ref().to_path_buf(); if path.starts_with("./") { path = path.trim_l...
#![allow(unused_imports)] #![allow(unused_variables)] #![allow(unused_mut)] #![allow(dead_code)] use std::rc::{Rc, Weak}; use std::sync::Arc; use std::collections::HashMap; use std::collections::hash_map::Entry::{Occupied, Vacant}; #[derive(Debug,Clone,Hash,PartialEq,Eq,PartialOrd,Ord)] pub enum Atom { Symbol(Arc...
use std::result::Result; use std::option::Option; use parse::{digit_char, letter_char, no_spec_char}; pub struct LexerMsg<'a> { pub prefix: Option<&'a [u8]>, pub command: &'a [u8], pub params: Vec<&'a [u8]> } pub enum POption<T> { Prefix(T), NoPrefix, ErrPrefix } impl<T> POption<T> { fn unwrap<'a>( &'a...
//! Simple wheel timer with bounded interval. //! //! Relevant: //! http://www.cs.columbia.edu/~nahum/w6998/papers/sosp87-timing-wheels.pdf #![no_std] extern crate heapless; use heapless::Vec; use heapless::ArrayLength; /// Fixed ring size pub struct TimerWheel<T, RINGLEN, TICKLEN> where TICKLEN: ArrayLength<T>,...
#[macro_use] extern crate log; extern crate env_logger; extern crate getopts; extern crate docker; extern crate imagecleanup; use std::env; use getopts::Options; use docker::Docker; use imagecleanup::*; const DEFAULT_DOCKER_UNIX: &'static str = "/var/run/docker.sock"; fn version(){ println!("{}", env!("CARGO_PKG_VE...
/// LeetCode Monthly Challenge problem for March 30th, 2021. Not my own work. /// Required looking solutions with explanations. pub struct Solution {} impl Solution { /// Returns the maximum number of envelopes that can be put inside one /// another. Envelopes cannot be rotated. /// /// # Examples ...
use SafeWrapper; use ir::{GlobalObject, GlobalValue, Value, Type, Linkage, ThreadLocalMode, Constant, User}; use sys; use std::ptr; /// A global variable. pub struct GlobalVariable<'ctx>(GlobalObject<'ctx>); impl<'ctx> GlobalVariable<'ctx> { /// Creates a new global constant. pub fn new_constant(value: &Valu...
// https://adventofcode.com/2017/day/5 use std::io::{BufRead, BufReader}; use std::fs::File; fn main() { // Read input to a vector let f = BufReader::new(File::open("input.txt").expect("Opening input.txt failed")); let mut jumps: Vec<i32> = Vec::new(); for line in f.lines() { let jump: i32 = l...
// q0098_validate_binary_search_tree struct Solution; use crate::util::TreeNode; use std::cell::RefCell; use std::rc::Rc; impl Solution { pub fn is_valid_bst(root: Option<Rc<RefCell<TreeNode>>>) -> bool { if let Some(root_tree) = root { let mut check_list = vec![(i64::min_value(), i64::max_va...
use crate::{BoxFuture, Entity, Result}; pub trait Delete<E: Entity>: Send + Sync { fn delete<'a>(&'a self, k: &'a E::Key) -> BoxFuture<'a, Result<()>>; } impl<E, T> Delete<E> for &T where E: Entity, E::Key: Sync, T: Delete<E>, { fn delete<'a>(&'a self, k: &'a E::Key) -> BoxFuture<'a, Result<()>> {...
mod data; mod utils; use wasm_bindgen::prelude::*; // When the `wee_alloc` feature is enabled, use `wee_alloc` as the global // allocator. #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; #[wasm_bindgen] #[repr(u8)] #[derive(Copy, Clone, PartialEq, Eq, ...
#[macro_use] extern crate criterion; extern crate heliometer; use criterion::Criterion; use std::io::Read; fn bubble_sort(crit: &mut Criterion) { crit.bench_function("bubble sort", |b| { b.iter(|| { let mut file = std::fs::File::open("examples/bsort.bf").unwrap(); let mut input = S...
#[doc = "Register `RTSR3` reader"] pub type R = crate::R<RTSR3_SPEC>; #[doc = "Register `RTSR3` writer"] pub type W = crate::W<RTSR3_SPEC>; #[doc = "Field `TR82` reader - Rising trigger event configuration bit of Configurable Event input x+64"] pub type TR82_R = crate::BitReader<TR82_A>; #[doc = "Rising trigger event c...
use std::borrow::Borrow; use std::fs::File; use std::io; #[cfg(unix)] use std::os::unix::fs::FileExt; #[cfg(windows)] use std::os::windows::fs::FileExt; /// Trait offering a uniform `pread` for positioned reads, with platform /// dependent side-effects. /// /// For `File` (and any `Borrow<File>`), this is implemente...
mod kvraft; mod persister; mod raft; mod read_only; pub use kvraft::KvRaftNode; pub use persister::{FilePersister, Persister}; pub use raft::RaftNode;
#![allow(non_snake_case, non_camel_case_types)] use libc::c_int; use crate::channel::ssh_channel; use crate::session::ssh_session; #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct ssh_message_struct { _unused: [u8; 0], } pub type ssh_message = *mut ssh_message_struct; extern "C" { pub fn ssh_message_get...
use pyo3::prelude::*; use pyo3::wrap_pyfunction; use primal::is_prime; /// sum_primes(n: int) -> int /// -- /// Calculates the sum of primes from 0 to n and returns it as an integer #[pyfunction] fn sum_primes(n: i64) -> u64 { let mut sum: u64 = 0; let n = n as u64; for i in 0..n { // check if number exists...
use crate::hittable::{aabb::Aabb, HitRecord, Hittable, Hittables}; use crate::ray::Ray; use rand::rngs::SmallRng; #[derive(Debug, Clone)] pub struct FlipFace { pub object: Box<Hittables>, } impl FlipFace { pub fn new(object: Hittables) -> Hittables { Hittables::from(FlipFace { object: Box:...