text
stringlengths
8
4.13M
use eosio::*; use std::collections::VecDeque; /// <https://github.com/EOSIO/eosio.contracts/blob/c046863a65d7e98424312ee8009f0acb493e6231/contracts/eosio.system/include/eosio.system/eosio.system.hpp#L216-L227> #[derive(Read, Write, NumBytes, Debug, Clone)] pub struct RexPool { pub version: u8, /// total amount...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use anyhow::Result; use crypto::HashValue; use starcoin_config::ChainConfig; use starcoin_state_api::ChainState; use types::{ account_address::AccountAddress, state_set::ChainStateSet, transaction::{RawUserTransaction, S...
use advent::helpers; use anyhow::{Context, Result}; use derive_more::Display; use itertools::Itertools; use lazy_static::lazy_static; use regex::Regex; use std::str::FromStr; #[derive(Debug, Display, Clone)] enum BitOp { #[display(fmt = "{}", _0)] Override(char), #[display(fmt = "X")] Pass, } type BitO...
#[cfg(test)] mod tests { struct Context<'a>(&'a str); // 'b >= 'a struct Parser<'a, 'b: 'a> { context: &'a Context<'b>, } impl<'a, 'b> Parser<'a, 'b> { fn parse(&self) -> Result<(), &'b str> { Err(&self.context.0[1..]) } } //获得了所有权 f...
extern crate reqwest; extern crate serde_json; extern crate ws; extern crate stellar_client; extern crate futures; extern crate futures_timer; pub mod meetup;
use super::interfaces::block::BlockState; use super::interfaces::messenger::{Messenger, SubscriberType}; use super::interfaces::patchwork::PatchworkState; use super::interfaces::player::{Angle, Player, PlayerState, Position}; use super::packet; use super::packet::Packet; use super::translation::TranslationUpdates; use ...
#![feature(unchecked_math)] mod basic; mod cache; mod combinatorics; mod digits; mod error; mod gamma; mod linear; mod prime; pub use basic::*; pub use cache::{Cache, GlobalCache}; pub use error::{Error, Result}; pub use gamma::*; pub use linear::*; pub use prime::*;
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] pub const Catalog: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6eb22881_8a19_11d0_81b6_00a0c9231c29); pub const CatalogCollection: ::windows::core::GUID = ::windows::core::GUID...
use std::io::prelude::*; use std::fs::OpenOptions; use chrono::prelude::*; use std::sync::{Mutex, Arc}; pub fn crear_log() -> std::sync::Arc<std::sync::Mutex<std::fs::File>> { let file = Arc::new(Mutex::new( match OpenOptions::new() .read(true) .write(true) .append...
use game_metrics::{scope, instrument, Metrics}; use std::time::Duration; #[instrument] fn long() { std::thread::sleep(Duration::from_millis(500)); } #[instrument] fn short() { std::thread::sleep(Duration::from_millis(50)); } fn long_scoped() { scope!("long_scoped"); std::thread::sleep(Duration::from...
#![allow(dead_code)] use arrow::record_batch::RecordBatch; use data_types::{sequence_number_set::SequenceNumberSet, SequenceNumber, TimestampMinMax}; use mutable_batch::MutableBatch; mod buffering; mod persisting; mod snapshot; pub(in crate::buffer_tree::partition::buffer) use buffering::*; pub(crate) use persisting:...
use wasm_bindgen::JsCast; use web_sys::WebGlRenderingContext as GL; use web_sys::*; use js_sys::WebAssembly; use super::super::common_funcs as cf; pub struct Color2D { program: WebGlProgram, vertex_buffer_length: usize, gl_buffer: WebGlBuffer, u_color: WebGlUniformLocation, u_transform: WebGlUniformLocation ...
use std::path::{PathBuf, Path}; use std::fs::{Metadata, read_link}; use std::os::unix::fs::MetadataExt; use std::os::unix::fs::PermissionsExt; use users::{get_user_by_uid, get_group_by_gid}; use size::{Size, Base, Style}; use crate::core::MaxInfo; use std::time::UNIX_EPOCH; use time::Timespec; use std::panic::resume_...
use embedded_graphics::{ draw_target::DrawTarget, mono_font::{MonoFont, MonoTextStyle, MonoTextStyleBuilder}, pixelcolor::{PixelColor, Rgb888}, prelude::{Dimensions, Point, Size}, primitives::Rectangle, text::renderer::{CharacterStyle, TextRenderer}, Drawable, }; use embedded_gui::{ geom...
// Definitions of all the different data structures needed for rendering // This defines vectors and vector arithmetic, (more to come) use std::ops::{Add, Sub, Mul}; #[derive(Debug, Clone)] pub struct Vector { pub x: f64, pub y: f64, pub z: f64, pub w: f64, } #[derive(Debug, Clone)] pub struct Matrix...
//map.rs // // use rand::random as rand; use quicksilver::{ geom::Vector, graphics::Color, }; //derive for comp, vecs... #[derive(Clone, Debug, PartialEq, Default)] pub struct Tile { pub pos: Vector, pub id: i32, // tile type code pub ch: char, //for display during development pub...
#![allow(dead_code)] extern crate image; use image::GenericImageView; fn get_path(path: &str) -> String { format!( "/home/xypnox/Projects/learn/rustSick/experiments/pxsort_v1/src/{}", path, ) } fn main() { // Use the open function to load an image from a Path. // `open` returns a `Dy...
use super::{ sppm::{Counter, KDTree, Pixel, Point}, Camera, }; use crate::{ geo::Material, geo::{Geo, HitResult}, linalg::{Ray, Vct}, utils::{clamp, Image, Rng}, Deserialize, Flt, Serialize, EPS, PI, }; use pbr::ProgressBar; use rand::prelude::*; use rayon::prelude::*; use std::sync::Mutex;...
#![warn(clippy::all)] #![warn(clippy::pedantic)] use std::fs; fn main() { run(); } #[allow(clippy::cast_lossless)] #[allow(clippy::cast_possible_truncation)] fn run() { let start = std::time::Instant::now(); // code goes here let mut names: Vec<String> = fs::read_to_string("./names.txt") .expect("could ...
mod args; use args::{Address, OneRegister, RegisterAndValue, TwoRegisters}; #[derive(Debug)] pub enum Opcode { // 0x0 ClearScreen, Return, Call(Address), // 0x01 Jump(Address), // 0x02 CallSubroutine(Address), // 0x03 SkipIfEqual(RegisterAndValue), // 0x04 SkipIfNotEqual...
// // line2.rs // Copyright (C) 2019 Malcolm Ramsay <malramsay64@gmail.com> // Distributed under terms of the MIT license. // use std::fmt; #[cfg(test)] use approx::AbsDiffEq; use nalgebra::Point2; use serde::{Deserialize, Serialize}; use crate::traits::Intersect; #[derive(Clone, Copy, PartialEq, Debug, Serialize, ...
use num_bigint::{BigUint, RandBigInt}; use rand::Rng; uint::construct_uint! { struct U256(4); } pub fn factorization(n: u128) -> Vec<u128> { if is_prime(&n.into()) { return vec![n]; } let mut ret = vec![]; let mut n = n; while !is_prime(&n.into()) { let factor = pollard_rho(n...
use crate::algebra::linear::scalar::Scalar; use fructose::operators::{ClosedAdd, ClosedDiv, ClosedMul, ClosedSub}; use std::fmt::{Debug, Display, Formatter}; use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign}; use std::str::FromStr; #[derive(Debug, Clone)] pub struct DVector<T> { pub da...
import std::str; import std::ivec; import std::option; import option::some; import option::none; import std::map::hashmap; import lib::llvm::llvm; import lib::llvm::llvm::ValueRef; import lib::llvm::llvm::TypeRef; import lib::llvm::llvm::BasicBlockRef; import trans::new_sub_block_ctxt; import trans::new_scope_block_ct...
#[path = "float_to_binary_2/with_float.rs"] pub mod with_float; // `without_float_errors_badarg` in unit tests
use crate::dynamics::{acceleration::Acceleration, velocity::Velocity}; #[derive(Copy, Clone, Debug, PartialEq)] pub struct Circle { x: f64, y: f64, radius: f64, angle: f64, velocity: Velocity, acceleration: Acceleration, } impl Circle { pub fn new( x: f64, y: f64, ra...
use super::helpers::{reverse_add_assign, reverse_add_c_long, reverse_add_c_long_assign}; use crate::integer::Integer; use core::ops::Add; // Add The addition operator +. // ['Integer', 'Integer', 'Integer', 'Integer::add_assign', 'lhs', ['ref_mut'], // ['ref']] impl Add<Integer> for Integer { type Output...
use crate::Result; use std::{fs::File, io::Read, path::Path}; pub fn create_pipeline( vert_file: &Path, frag_file: &Path, vertex_buffer_descriptor: wgpu::VertexBufferDescriptor, format: wgpu::TextureFormat, device: &wgpu::Device, ) -> Result<wgpu::RenderPipeline> { let mut vs_src = String::new(...
pub fn solve(input: Vec<&str>) { part1(); part2(); } fn part1() { println!("Not implemented"); } fn part2() { println!("Not implemented"); }
mod test_utils; use test_utils::ServerTestingExt; use tide::{Request, StatusCode}; async fn add_one(req: Request<()>) -> Result<String, tide::Error> { match req.param::<i64>("num") { Ok(num) => Ok((num + 1).to_string()), Err(err) => Err(tide::Error::new(StatusCode::BadRequest, err)), } } async ...
// Copyright 2019 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 {bitfield::bitfield, bitflags::bitflags, failure::Fail}; /// The error types for packet parsing. #[derive(Fail, Debug, PartialEq)] pub enum Error { ...
use { crate::{ descriptor, escape::{Escape, KeepAlive, Terminal}, }, gfx_hal::Backend, std::ops::{Deref, DerefMut}, }; /// Descriptor set object wrapper. #[derive(Debug)] pub struct DescriptorSet<B: Backend> { escape: Escape<(descriptor::DescriptorSet<B>, KeepAlive)>, } impl<B> Des...
//! Instruction types #![allow(dead_code)] use crate::state::ImpermenantLossStopLossConfig; use borsh::{BorshDeserialize, BorshSchema, BorshSerialize}; /// Instructions supported by the program #[derive(Clone, Debug, BorshSerialize, BorshDeserialize, BorshSchema, PartialEq)] pub enum Instruction { Initialize { ...
use std::path::Path; pub mod compiler; pub mod constants; pub mod deploy; pub use deploy::{deploy_contract, make_web3, make_web3_ganache}; pub fn get_artifact(contract_name: &str) -> deploy::ContractArtifact { deploy::get_artifact(Path::new(constants::BUILD_PATH), contract_name) }
use yew::prelude::*; pub struct EmailApp {} pub enum Msg {} impl Component for EmailApp { type Message = Msg; type Properties = (); fn create(_: Self::Properties, _: ComponentLink<Self>) -> Self { EmailApp {} } fn update(&mut self, _msg: Self::Message) -> ShouldRender { true ...
#![feature(core_intrinsics)] #![feature(const_fn)] use crate::geometry::Vector2; use crate::geometry::Vector3; use crate::types::Float; use crate::types::Int; use std::f32; use std::f64; pub mod bounds; pub mod bssrdf; pub mod efloat; pub mod geometry; pub mod interaction; pub mod intersect; pub mod light; pub mod li...
// auto generated, do not modify. // created: Wed Jan 20 00:44:03 2016 // src-file: /QtNetwork/qhostaddress.h // dst-file: /src/network/qhostaddress.rs // // header block begin => #![feature(libc)] #![feature(core)] #![feature(collections)] extern crate libc; use self::libc::*; // <= header block end // main block ...
// Copyright 2020 - 2021 Alex Dukhno // // 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...
use super::{Chain, Day, Link, Streak}; use chrono::{Datelike, Local, NaiveDate, Duration}; use super::FORMAT; pub fn calculate_streak(chain: &Chain, links: &Vec<Link>) -> Streak { let name = chain.name.to_string(); let mut date: Option<NaiveDate> = None; let mut prev_date: Option<NaiveDate>; let mut ...
use std::error; use std::fs; use std::path::PathBuf; use std::str::FromStr; use structopt::StructOpt; type Error = Box<dyn error::Error>; #[derive(StructOpt)] #[structopt( name = "solve", about = "solve the puzzles from the Advent of Code 2020, day 5" )] struct Opt { /// path to input file; should contain...
//! The various tmux operations commands. use super::project::TMUX_BIN; use super::TmuxError; use clap::crate_name; use shlex::Shlex; use std::env::set_current_dir; use std::process::Command; use std::{env, fmt}; /// The commands. Implemented as an enum instead of traits/structs /// to prevent dynamic dispatch. /// /...
use icell::{ typeid::{self, ICell}, write_all, }; #[test] fn create() { typeid::make!(type TestCreate); let owner = TestCreate::owner(); assert_eq!(std::mem::size_of_val(&owner), 0); } #[test] #[cfg(feature = "std")] // on `no_std` reentrant acquires block #[cfg_attr(miri, ignore)] #[should_panic...
use nalgebra; pub type Pose<F> = nalgebra::geometry::Isometry2<F>; pub type PoseCovariance<F> = nalgebra::base::Matrix3<F>; pub type Point<F> = nalgebra::geometry::Point2<F>; pub type PointCovariance<F> = nalgebra::base::Matrix2<F>; const GRID_OCCU: i8 = 1; const GRID_FREE: i8 = -1; const GRID_NONE: i8 = 0; #[inline(...
#![allow(non_camel_case_types)] #![allow(dead_code)] #![allow(missing_copy_implementations)] use std::ffi::CString; use cql_ffi::batch::CassBatch; use cql_ffi::future::CassFuture; use cql_ffi::future::ResultFuture; use cql_ffi::future::PreparedFuture; use cql_ffi::error::CassError; use cql_ffi::statement::CassStateme...
// `error_chain!` can recurse deeply #![recursion_limit = "1024"] #[macro_use] extern crate error_chain; extern crate log; use clap::App; use clap::Arg; use clap::ArgMatches; use hackscanner_lib::*; use simplelog::TerminalMode; use std::env; use std::path::Path; mod ui; fn main() { if let Err(ref e) = run() { ...
use std::collections::HashMap; use crossterm::event::Event; use irust_api::{Command, GlobalVariables}; use super::Script; const SCRIPT_CONFIG_NAME: &str = "script.toml"; pub struct ScriptManager { sm: rscript::ScriptManager, startup_cmds: Vec<Result<Option<Command>, rscript::Error>>, } macro_rules! mtry { ...
//! Группа унификации плит или фундаментных плит use crate::sig::rab_e::*; use crate::sig::HasWrite; use nom::{bytes::complete::take, multi::count, number::complete::le_u16, IResult}; use std::fmt; #[derive(Debug)] pub struct UnificationSlab { unification_group: u16, //Номер группы унификаций amount: u16, ...
//= { //= "output": { //= "2": [ //= "thread 'main' panicked at 'qwertyuiop', tests/a\\.rs:[0-9]+:[0-9]+\n", //= true //= ], //= "1": [ //= "", //= true //= ] //= }, //= "children": [], //= "exit": { //= "Error": { //= "Unix": { //= "Signal": "SIGABRT" /...
use oxygengine_composite_renderer::{ component::{ CompositeCamera, CompositeCameraAlignment, CompositeRenderAlpha, CompositeRenderLayer, CompositeRenderable, CompositeScalingMode, CompositeScalingTarget, CompositeTransform, CompositeUiElement, CompositeVisibility, UiElementType, UiImage, UiM...
use std::fmt::{Debug, Display}; use std::sync::Arc; use async_trait::async_trait; use parquet_file::ParquetFilePath; use uuid::Uuid; pub mod noop; pub mod prod; mod util; #[cfg(test)] mod test_util; /// Create a [`Scratchpad`] for use as intermediate storage pub trait ScratchpadGen: Debug + Display + Send + Sync { ...
use ted_interface::*; use id_types::*; pub struct Drawn{ pub id: u32, pub mover_id: MoverID, pub sprite: EntitySprite, pub invisible: bool } pub struct BasicDrawn{ pub drawn_id: DrawnID, pub sprite: u32 } pub struct HealthDrawn{ pub drawn_id: DrawnID, pub damageable_id: DamageableID, pub sprite: u32 }
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Instruction and Data Tightly-Coupled Memory Control Registers"] pub itcmcr: ITCMCR, #[doc = "0x04 - Instruction and Data Tightly-Coupled Memory Control Registers"] pub dtcmcr: DTCMCR, #[doc = "0x08 - AHBP Control regist...
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[cfg(feature = "Devices_Spi_Provider")] pub mod Provider; #[link(name = "windows")] extern "system" {} pub type ISpiDeviceStatics = *mut ::core::ffi::c_void; pub type SpiBusInfo = *mut ::core::ffi::c_void...
fn testpalindrome(x: i32) -> bool{ let xstr=x.to_string(); let leng:usize = xstr.len(); let mut v=vec![]; for i in xstr.chars(){ v.push(i); } let mut test: bool =true; for i in 0..v.len()-1{ if v[i as usize]==v[leng-1-i as usize]{ test=true; } els...
use rocket::*; use rocket::http::Status; use rocket::response::NamedFile; use rocket_contrib::json::*; use std::collections::HashMap; use reqwest::header::AUTHORIZATION; use super::BASE_URL; use super::receiver::*; use super::guards::*; use super::super::database::Database; use log::{error, warn, info, debug}; lazy_s...
use crate::shared::cleos; use std::io; use std::process::ExitStatus; fn deploy_example_contract(account: &str, bin: &str) -> io::Result<ExitStatus> { cleos() .arg("set") .arg("abi") .arg(account) .arg(format!("mnt/dev/examples/{}/{}.abi.json", bin, bin)) .status()?; cleo...
use hyper::{Body, Response}; // use std::convert::Infallible; // std::fs::read_to_string(path: P); use std::io::Error; pub fn get_static_content(file: &str) -> Result<String, Error> { let path = format!("./static/{}", file); std::fs::read_to_string(&path) } pub fn get_static_image(file: &str) -> Result<Vec<u8>, E...
use std::ops::Range; use allocator::*; use smallvec::SmallVec; use block::Block; use device::Device; use error::*; use mapping::*; use memory::*; use usage::{Usage, UsageValue}; use util::*; /// Config for `Heaps` allocator. #[derive(Clone, Copy, Debug)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]...
use serenity::prelude::*; use serenity::model::prelude::*; use serenity::framework::standard::{ Args, CommandResult, macros::command, }; use serenity::utils::Colour; use requests::ToJson; use std::collections::HashMap; use std::time::Instant; use std::sync::mpsc; use std::thread; use std::sync::mpsc::Sender;...
use std::process::Command; fn main() { run_with_cd(); } fn run() { let output = Command::new("sh") .arg("-c") .arg("/home/susilo/var/www/ecc4/protected/yii-dev") .output() .expect("Tidak dapat menjalankan command!."); let ls = output.stdout; println!("{:#?}", ls.iter()...
pub trait LocalApic { fn is_supported() -> bool; }
use crate::common::{BuildingColorer, BuildingColorerBuilder, CommonState, Warping}; use crate::game::{State, Transition, WizardState}; use crate::helpers::ID; use crate::mission::pick_time_range; use crate::sandbox::SandboxMode; use crate::ui::UI; use abstutil::{prettyprint_usize, MultiMap, WeightedUsizeChoice}; use ez...
//! Error types used in this driver. use core::str::Utf8Error; /// A collection of errors that can occur. #[derive(Debug, PartialEq, Eq)] pub enum Error<S> { /// Could not read from serial port. SerialRead(S), /// Could not write to serial port. SerialWrite(S), /// Read buffer is too small. //...
use core::cmp::Ordering::{self, *}; use core::fmt::{self, Debug}; use core::ops::{Add, AddAssign, Div, Index, IndexMut, Mul, RangeBounds, Rem}; use core::ptr::NonNull; use std::sync::{Arc, Weak}; use std::vec::Drain; use hashbrown::HashMap; use liblumen_core::locks::Mutex; use liblumen_alloc::borrow::CloneToProcess...
use crate::sig::*; use nom::{ bytes::complete::{tag, take}, IResult, }; use std::fmt; #[derive(Debug)] pub struct BarpbresFe { source: Vec<u8>, } impl HasWrite for BarpbresFe { fn write(&self) -> Vec<u8> { let mut out = self.name().as_bytes().to_vec(); out.extend(&self.source); ...
use matches::matches; use super::*; use crate::key::Key; use crate::{Batching, Datastore}; pub fn test_basic_put_get<D: Datastore>(ds: &D) { let k = Key::new("foo"); let v = b"Hello Datastore!"; ds.put(k.clone(), v.to_vec()).unwrap(); let have = ds.has(&k).unwrap(); assert!(have); let size =...
// Copyright 2020-2021, The Tremor Team // // 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 agr...
use std::fmt; use firefly_diagnostics::SourceIndex; use firefly_intern::Symbol; use firefly_number::{Float, Integer}; use firefly_syntax_erl::LexicalError; #[derive(Debug, Clone, PartialEq, Eq)] pub struct LexicalToken(pub SourceIndex, pub Token, pub SourceIndex); impl LexicalToken { #[inline] pub fn token(&s...
use glob::glob; use std::process::Command; fn main() -> anyhow::Result<()> { let dir_out = std::env::var("OUT_DIR")?; let dir_ocaml = "../../ocaml"; let dir_dune = "../../_build/default"; // Install OCaml dependencies. let mut cmd = Command::new("opam"); cmd.args(&["pin", "add", "-y", "rust-oc...
/* Project Euler Problem 9: A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. */ fn main() { for a in 1..1000 { for b i...
#[macro_use] pub mod utils; mod core; pub use self::core::{ default_filter, AllRulesValidator, Filter, SourceCode, ValidationError, Validator, }; mod iter; pub use self::iter::NodeIterator; mod grammar; mod hint; mod rule; pub use self::rule::{Rule, RuleCode, RULES}; pub mod filters; pub mod validators;
// Copyright 2019 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 { breakpoints_capability::*, component_manager_lib::{ model::{ self, hooks::*, testing::breakpoints::*, testing::test_helpe...
mod mem_regions; use gba_mem::mem_regions::{SystemRom, ExternRam, InternRam, PalettRam, VisualRam, OAM, PakRom, MemRead, MemWrite, MemoryRegion}; use std::io; pub type Address = usize; #[derive(Debug)] pub struct Memory { sys_rom: SystemRom, ext_ram: Exte...
mod jwt; use std::cmp::{Eq, PartialEq}; pub mod pwd; pub mod service; use serde::{Deserialize, Serialize}; #[derive(juniper::GraphQLObject)] pub struct Session { jwt: String, } #[derive(juniper::GraphQLInputObject)] pub struct AuthenticationData { email: String, password: String, } #[derive(Debug, Seria...
// Copyright 2022 Datafuse Labs. // // 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 ...
//------------------------------------------------ // command line syntax: // dnaabox -flag < data_file_test_path /* possible flags are: -pc => pattern_count() ......CHALLENGE 1A -fw => most_frequent_words() ......CHALLENGE 1B -rc => reverse_complement() .........
use async_channel::Sender; use std::collections::HashMap; use std::io::Result; use std::net::SocketAddr; use tdn_types::group::{GroupId, Peer}; use tdn_types::message::{GroupSendMessage, SendMessage}; use tdn_types::primitive::PeerAddr; #[derive(Default, Debug)] pub struct CAPermissionedGroup<P: Peer> { id: GroupI...
mod anti_replay; mod constants; mod device; mod inbound; mod ip; mod messages; mod outbound; mod peer; mod pool; mod route; mod runq; mod types; #[cfg(test)] mod tests; use messages::TransportHeader; use std::mem; use super::constants::REJECT_AFTER_MESSAGES; use super::queue::ParallelQueue; use super::types::*; use ...
use conrod; use conrod::Color; use conrod::render::Text; use conrod::text::rt; use conrod::text; use gfx; use gfx::texture; use gfx::traits::FactoryExt; pub type ColorFormat = gfx::format::Srgba8; type SurfaceFormat = gfx::format::R8_G8_B8_A8; type FullFormat = (SurfaceFormat, gfx::format::Unorm); const FRAGMENT_SH...
use yew::prelude::*; use yew_router::components::RouterAnchor; use crate::app::AppRoute; use super::tab_setting::TabSettings; use super::tab_permission::TabPermissions; use super::tab_users::TabUsers; pub enum Content{ Settings, Permissions, Users } pub struct ViewDetail { content: Content, link...
use crate::{ event::{self, Event}, shutdown::ShutdownSignal, stream::StreamExt01, topology::config::{DataType, GlobalOptions, SourceConfig, SourceDescription}, }; use bytes::Bytes; use futures::compat::Compat; use futures01::{sync::mpsc, Future, Sink, Stream}; use lazy_static::lazy_static; use serde::{D...
fn main() { let a = 3.1f32; let b = 3.9f32; let c = -3.1f32; let d = -3.9f32; assert_eq!(a.trunc(), 3.0); assert_eq!(b.trunc(), 3.0); assert_eq!(c.trunc(), -3.0); assert_eq!(d.trunc(), -3.0); }
#[doc = "Reader of register CR1"] pub type R = crate::R<u32, super::CR1>; #[doc = "Writer for register CR1"] pub type W = crate::W<u32, super::CR1>; #[doc = "Register CR1 `reset()`'s with value 0"] impl crate::ResetValue for super::CR1 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { ...
use super::check; #[test] fn t01_inline() { check( ".result {\n output: 'squoted';\n output: #{'squoted'};\n \ output: \"[#{'squoted'}]\";\n output: \"#{'squoted'}\";\n \ output: '#{'squoted'}';\n output: \"['#{'squoted'}']\";\n}\n", ".result {\n output: 'squoted';\n outpu...
use Command; use hex; use std::io; use std::io::prelude::*; use std::net::TcpStream; use std::io::BufReader; use atoi::atoi; pub struct Request<'a> { pub reader: BufReader<&'a TcpStream>, } impl<'a> Request<'a> { // add code here pub fn decode(&mut self) -> io::Result<Option<Command>> { if let So...
extern crate structopt; #[macro_use] extern crate structopt_derive; use structopt::StructOpt; use std::net::UdpSocket; const PIN_LED1: i32 = 0; const PIN_LED2: i32 = 2; const PIN_INPUT: i32 = 3; fn set_led_state(buf: &mut [u8], pin: usize, val: &str) { match val { "on" => buf[pin] = 1, "off" =...
use std::str::FromStr; use solana_program::pubkey::Pubkey; pub fn susy_wrapped_gton_mint() -> Pubkey { Pubkey::from_str("nVZnRKdr3pmcgnJvYDE8iafgiMiBqxiffQMcyv5ETdA").unwrap() }
test_stdout!(without_value_returns_empty_list, "[]\n"); test_stdout!( with_value_returns_keys_with_value_in_list, "true\ntrue\nfalse\n" ); // From https://github.com/erlang/otp/blob/a62aed81c56c724f7dd7040adecaa28a78e5d37f/erts/doc/src/erlang.xml#L2104-L2112 test_stdout!(doc_test, "true\ntrue\ntrue\ntrue\ntrue\...
// Copyright 2014 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 ...
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[repr(transparent)] #[doc(hidden)] pub struct IVibrationDevice(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IVibrationDevice { type Vtable = IVibrationD...
mod grid; mod space; mod value; pub use grid::Grid;
use super::{Action, Content, History, Session, Subject, Topic}; use crate::state::SpentTime; use std::error::Error; mod sqlite; pub use sqlite::Sqlite; pub trait Backend { fn transfer_content(&mut self, content: &Content) -> Result<(), Box<dyn Error>>; fn transfer_history(&mut self, history: &History) -> Resu...
pub mod utilities; use crate::utilities::Verify; use proffer::*; #[test] fn impl_basic_gen_with_trait() { let mut ipl = Impl::new("That") .set_impl_trait(Some(Trait::new("This"))) .to_owned(); let expected = r#" impl This for That { } "#; let src_code = ipl.gen...
use std::convert::Into; use std::iter::*; use std::fmt; use std::default::Default; use std::ops::Add; use protobuf_iter::*; #[derive(Clone)] pub struct DeltaEncodedIter<'a, P: Packed<'a>, T: Clone + Add<T, Output=T> + From<<P as Packed<'a>>::Item> + Default> { inner: PackedIter<'a, P, T>, last: T, } impl<'a...
use cube::corners::Corner; use cube::edges::Edge; #[derive(Clone, Copy)] pub enum Move { Up, Right, Front, Down, Left, Back, } impl Move { pub fn from_u(u :usize) -> Move { match u { 0 => Move::Up, 1 => Move::Right, 2 => Move::Front, ...
use crate::parser::{Command, Source}; use anyhow::Result; pub fn parse(cmd: &str, _current_function: &str, source: &Source, _arg1: Option<&str>, _arg2: Option<&str>) -> Option<Result<Command>> { match cmd { "add" => Some(Ok(Command::Add(source.clone()))), "sub" => Some(Ok(Command::Sub(source.clone(...
use P55::*; pub fn main() { let trees = cbal_trees(4, 'x'); for tree in trees { println!("{}", tree); } }
//! A proportional-integral-derivative (PID) controller. #![no_std] extern crate num_traits; use num_traits::float::FloatCore; #[derive(Debug)] pub struct Pid<T: FloatCore> { /// Proportional gain. pub kp: T, /// Integral gain. pub ki: T, /// Derivative gain. pub kd: T, /// Limit of contrib...
#[macro_use] extern crate allegro; extern crate allegro_font; extern crate allegro_image; extern crate libloading; extern crate game; use allegro_font::FontAddon; use allegro_image::ImageAddon; use libloading::Library; use game::{State, Platform}; use std::fs; const FPS: f64 = 60.0; const SCREEN_WIDTH: i32...
use std::borrow::{Borrow, BorrowMut}; use std::cell::RefCell; use std::fmt; use std::fmt::{Display, Formatter}; use std::iter::{FromIterator, Once}; use std::ops::{Deref, DerefMut, Range}; use std::rc::Rc; use std::time::Duration; use rand::Rng; use rust_tools::bench::Bench; use crate::mcts_tree::mcts::{BRANCH_FACTO...