text
stringlengths
8
4.13M
pub mod portfolio;
use std::{ io::Read }; use std::fs::File; mod executor; use executor::System; fn main() { let mut args = std::env::args().skip(1); let file = File::open(args.next().unwrap()).unwrap(); let memory_size: usize = args.next().map(|x| x.parse().unwrap()).unwrap_or(1024); let mut memory = Vec::with_cap...
use super::versions; use crate::{models::{ props_action_points_categories::PropsActionPointsCategory, props_boost_categories::PropsBoostCategory, props_builder_recruitment_categories::PropsBuilderRecruitmentCategory, props_fixed_treasure_chest_categories::PropsFixedTreasureChestCategory, props_fixed...
mod routes; pub mod models; pub use models::*; pub use routes::init;
// Copyright 2016 Pierre-Étienne Meunier // // 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 pyo3::prelude::*; use log::debug; use socket2::{Domain, Protocol, Socket, Type}; use std::net::{IpAddr, SocketAddr}; #[pyclass] #[derive(Debug)] pub struct SocketHeld { pub socket: Socket, } #[pymethods] impl SocketHeld { #[new] pub fn new(ip: String, port: u16) -> PyResult<SocketHeld> { let ...
use error_chain::error_chain; use ::ate::prelude::*; use crate::request::*; error_chain! { types { GatherError, GatherErrorKind, ResultExt, Result; } links { AteError(::ate::error::AteError, ::ate::error::AteErrorKind); ChainCreationError(::ate::error::ChainCreationError, ::ate::er...
use rustc_serialize::json; use structures::logic::channel::DmxAddress; #[derive(RustcDecodable, RustcEncodable, Debug, Clone)] pub enum ChannelGroup { Single(DmxAddress), RGB(DmxAddress, DmxAddress, DmxAddress), RGBA(DmxAddress, DmxAddress, DmxAddress, DmxAddress), Moving2D(DmxAddress, DmxAddress) } #...
use std::fmt::Debug; #[allow(dead_code)] pub fn merge_sort<T>(array: &mut Vec<T>) -> Vec<T> where T: Debug + PartialOrd + PartialEq + Clone { if array.len() > 1 { let high = array.len() - 1; let low = 0 as usize; merge_sort_slice(array, low, high); array.clone() } else { ...
struct Solution; impl Solution { pub fn contains_nearby_almost_duplicate(nums: Vec<i32>, k: i32, t: i32) -> bool { let k = k as usize; let len = nums.len(); let mut sorted = vec![]; for i in 0..len { let v = nums[i]; let index; if sorted.len() < k...
use crate::Color; use crate::Buffer; pub struct Canvas { buf: Vec<Color>, width: u32, height: u32, } impl Canvas { pub fn new(width: u32, height: u32) -> Self { let len = (width * height) as usize; let mut buf = Vec::with_capacity(len); buf.resize(len, Color::transparent()); ...
use super::context::Context; pub struct Root; #[juniper::object( Context = Context, )] impl Root {}
extern crate lazy_static; extern crate serialport; pub mod data; mod error; use data::Data; use error::Error; use lazy_static::*; use regex::Regex; use serialport::ErrorKind; use std::boxed::Box; use std::io::BufRead; use std::io::BufReader; use std::sync::mpsc::channel; use std::sync::mpsc::Receiver; use std::thread...
// ----------------------------------------------------------------------------- // Rust SECoP playground // // This program 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 2 of the License, o...
use scoped_threadpool::Pool; use super::Individual; use rand; use rand::Rng; use num_cpus; pub struct Evolution<T: Individual> { generation: u32, generation_size: usize, survival_rate: f32, pub individuals: Vec<T>, thread_pool: Pool, } impl<T: Individual> Evolution<T> { /// Constructs a new `...
use std::fmt::{Debug, Display}; use std::ops::{Deref, Index}; use std::option::Option::Some; //https://rust-unofficial.github.io/too-many-lists/ type Link<T> = Option<Box<Node<T>>>; pub struct List<T> { head: Link<T>, } struct Node<T> { element: T, next: Link<T>, } impl<T> List<T> { pub fn new() -> ...
use serde::{Deserialize, Serialize}; use std::path::Path; use crate::{debugger_catch, textbuffer::cursor::BufferCursor}; use self::{ metadata::{calculate_hash, MetaData}, operations::LineOperation, }; /// Buffer manager module pub mod buffers; /// ContiguousBuffer module - a buffer that keeps a simple String...
#![allow(unused)] extern crate ezflags; extern crate num; extern crate rand; extern crate rand_distr; use crate::num::{One, Zero}; use ezflags::flag::FlagSet; use ray_weekend::{ light::{Light, PointLight}, material::{Dielectric, Lambertian, Mat, Metallic, Checkers}, object::Object, plane::Plane, renderable:...
use crate::species; use species::Species; /// Faction class. #[derive(Clone, Copy, Debug)] pub enum Faction { /// The player faction. Player, /// A species-based faction. Species(Species), } /// Penalties given by the faction when laws are broken. #[derive(Clone, Copy, Debug)] pub enum Penalty { /...
#![feature(integer_atomics)] extern crate bincode; extern crate byteorder; extern crate crc; extern crate failure; extern crate fs2; extern crate futures; extern crate grpcio; extern crate indexmap; extern crate protobuf; extern crate raft; extern crate serde; extern crate tokio; #[macro_use] extern crate lazy_static; ...
use test::Bencher; #[bench] fn rect_tiny_skia(bencher: &mut Bencher) { use tiny_skia::*; let mut paint = Paint::default(); paint.set_color_rgba8(50, 127, 150, 200); paint.anti_alias = false; let rect = Rect::from_xywh(50.7, 20.1, 812.4, 777.3).unwrap(); let mut pixmap = Pixmap::new(1000, 100...
/// Shell sort (improved insertion sort): run time O(n^2) average case, O(n) best case for sorted slices, space - O(1) pub fn shell<T>(list: &mut [T]) where T: std::cmp::PartialOrd { let mut k = list.len()/2; while k > 0 { let mut i = 0; while i < list.len() { let mut j = i; ...
//! Coarsely-synchronized stacks. use super::sequential::Stack; use std::sync::{Mutex, MutexGuard}; /// A coarsely-synchronized stack. /// /// This can be shared between threads by wrapping it in an `Arc`. #[derive(Debug)] pub struct CoarseStack<T>(Mutex<Stack<T>>); impl<T> CoarseStack<T> { /// Returns a new, e...
#![feature(test)] extern crate test; use std::time::{Duration, UNIX_EPOCH}; use test::Bencher; use webe_id::*; #[bench] fn bench_next(b: &mut Bencher) { // set up factory let epoch = UNIX_EPOCH .checked_add(Duration::from_millis(1546300800000)) // 01-01-2019 12:00:00 AM GMT .expect("failed to...
use winapi::shared::dxgi1_5::DXGI_FEATURE_PRESENT_ALLOW_TEARING; use winapi::shared::minwindef::BOOL; use winapi::shared::winerror::SUCCEEDED; #[derive(Copy, Clone)] pub struct AllowTearing; unsafe impl super::Feature for AllowTearing { const FLAG: u32 = DXGI_FEATURE_PRESENT_ALLOW_TEARING; type Structure = B...
// MIT/Apache2 License use super::ffi; use crate::{ config::{ GlConfig, GlSwapMethod, COLOR_INDEX_BIT, CONFIG_NONE, DONT_CARE, NON_CONFORMANT_CONFIG, RGBA_BIT, RGBA_FLOAT_BIT_ARB, RGBA_UNSIGNED_FLOAT_BIT_EXT, SLOW_CONFIG, TEXTURE_1D_BIT_EXT, TEXTURE_2D_BIT_EXT, TEXTURE_RECTANGLE_BIT_EXT, ...
/** * [841] Keys and Rooms * * There are n rooms labeled from 0 to n - 1 and all the rooms are locked except for room 0. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key. When you visit a room, you may find a set of distinct keys in it. Each key has a number on it, ...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::service::NetworkActorService; use crate::worker::RPC_PROTOCOL_PREFIX; use crate::PeerMessage; use anyhow::{format_err, Result}; use futures::channel::oneshot::Receiver; use futures::future::BoxFuture; use futures::FutureE...
use cli::VERSION; use core::credentials::Credentials; use core::entities::AccessToken; use hyper::header::{Accept, Authorization, Basic, Bearer, ContentType, Headers, UserAgent}; use reqwest::{Client, Error, Response}; use serde::Serialize; use serde_json; use std::collections::HashMap; use url::form_urlencoded::byte_s...
use anyhow::Error; use stack_string::StackString; use stdout_channel::StdoutChannel; use movie_collection_lib::make_list::make_list; #[tokio::main] async fn main() -> Result<(), Error> { env_logger::init(); let stdout = StdoutChannel::new(); match make_list(&stdout).await { Ok(_) => {} Er...
use xml::Node; fn main() { let e: Node = r#" <hello a="b" c="d"> <foo>Hello world</foo> </hello>"# .parse() .unwrap(); println!("{:#?}", e); }
use amethyst_assets::{Asset, Error, Handle, ProcessingState, ResultExt, SimpleFormat}; use amethyst_core::specs::prelude::VecStorage; use gfx_glyph::Font; /// A loaded set of fonts from a file. #[derive(Clone)] pub struct FontAsset(pub Font<'static>); /// A handle to font data stored with `amethyst_assets`. pub type ...
use actix_web::{error, web::Path, Responder, web::Data}; use diesel::prelude::*; use puccinia::database::models::{Wallet, Account, Position}; use puccinia::database::schema::{wallets, accounts, positions}; use rust_decimal::Decimal; use std::str::FromStr; use std::sync::Arc; use super::AppState; pub fn wallet(info: (P...
extern crate imagefmt; extern crate rand; extern crate clap; use clap::{Arg, App}; use imagefmt::{ColFmt, ColType}; use maze::maze::{Maze, Coordinate}; use maze::depthfirstsearch::depth_first; use std::str::FromStr; use std::process::exit; mod maze; fn main() { let matches = App::new("maze_generator") .about("The...
use std::fmt::Display; use http::Response; use serde::{de::DeserializeOwned, Serialize}; use tantivy::schema::Schema; use async_trait::async_trait; pub use toshi_types::*; pub use crate::error::ToshiClientError; pub mod error; #[cfg(feature = "isahc_client")] pub use isahc_client::ToshiClient; #[cfg(feature = "is...
fn main() { let x = 2.0; // f32 let y: f32 = 3.0; // f32 // addition let sum = 5 + 10; // subtraction let difference = 95.5 - 4.3; // multiplication let production = 4 * 30; // division let quotient = 56.7 / 32.2; // remainder let remainder = 43 % 5; println!("...
use hyper::{http, Body, Method, Request, Response}; use mongodb::Database; use crate::routes::{login::login, register::register}; // implement Outh google // implement Oauth facebook // implement Oauth Phone // implement 0auth Microsoft // implement 0auth Apple // implement Windows hello ? pub async fn router(req: R...
extern crate pathfinding; #[allow(unused_imports)] use generate::astar::pathfinding::prelude::bfs; use generate::parkinglot::*; impl Pos { #[allow(unused_variables, dead_code)] pub fn successors(&self, lot: &ParkingLot) -> Vec<Pos> { let &Pos(x, y) = self; let mut result: Vec<Pos> = vec![...
pub mod http_sender; pub mod rpc_request; pub mod rpc_sender; pub mod validator_container_initializer; pub mod validator_service;
use std::f64; static TILE_SIZE: i32 = 32; static SCALE: f64 = 1.0; // This is a divider of TILE_SIZE, 1.0 for 32, 2.0 for 16, etc. pub trait AsGame {fn to_game(&self) -> Game;} pub trait AsTile {fn to_tile(&self) -> Tile;} pub trait AsPixel {fn to_pixel(&self) -> Pixel;} /// A `Game` unit represents a density-in...
// use build_info::Version; use build_info::{get_version, Version}; use clap::{App, AppSettings, Arg, ArgMatches, SubCommand}; pub fn get_matches() -> ArgMatches<'static> { let version = get_version!(); App::new("ckb") .author("Nervos Core Dev <dev@nervos.org>") .about("Nervos CKB - The Common...
use reqwest::blocking::{Client, Response}; use snailquote::unescape; use crate::reference::Reference; use crate::version::BibleVersion; const ESV_URL_PREFIX: &str = "https://api.esv.org/v3/passage/text/"; fn fetch_esv(reference: Reference) -> Result<String, &'static str> { let api_key: String = match std::env::v...
use crate::error::*; use crate::format::Format; #[derive(PartialEq, Debug)] /// A representation of a Hearthstone deck pub struct Deck { version: u8, pub format: Format, /// The dbfid of the heroes this deck should use pub heroes: Vec<u32>, /// The dbfid of the cards in the deck that have a single ...
// https://leetcode.com/problems/minimum-time-to-remove-all-cars-containing-illegal-goods/ // You are given a 0-indexed binary string s which represents a sequence of train cars. // s[i] = '0' denotes that the iᵗʰ car does not contain illegal goods and s[i] = '1' denotes // that the iᵗʰ car does contain illegal goods....
use std::os::raw::c_char; use std::slice; use symbolic::unreal::{Unreal4Crash, Unreal4File}; use crate::core::SymbolicStr; use crate::utils::ForeignObject; /// An Unreal Engine 4 crash report. pub struct SymbolicUnreal4Crash; impl ForeignObject for SymbolicUnreal4Crash { type RustObject = Unreal4Crash; } /// A...
pub fn add_one(x: i32) -> i32 { x + 1 } #[cfg(test)] mod add_one_tests { use super::*; #[test] fn it_adds_one_to_positive() { assert_eq!(3, add_one(2)); } #[test] fn it_adds_one_to_negative() { assert_eq!(-3, add_one(-4)); } }
use std::collections::HashMap; //static TESTINFO: &'static str = include_str!("dayseven.txt"); static TESTINFO: &'static str = include_str!("dayseventest.txt"); struct Program { name: String, parent: Option<String> } //named!(take4, take!(4)); pub fn day() -> String { let mut programs: HashMap<String, P...
use std::io::{self, Read}; fn main() -> io::Result<()> { let mut buffer = String::new(); io::stdin().read_to_string(&mut buffer)?; let mem: Vec<usize> = buffer .split(",") .map(|op| op.parse()) .filter_map(Result::ok) .collect(); println!("Pt. 1 {}", solve(mem....
use crate::SH; use crate::utils; use kuchiki::{ElementData, NodeDataRef, NodeRef}; pub const SCRIPT_TAG: SH = ("script[src]", external); pub const LINK_TAG: SH = ("link[type='application/x-javascript'], link[type='application/javascript'], link[type='text/javascript']", external); pub const LINK_JSON_TAG: SH = ("link...
mod config; mod error; mod updater; pub use self::config::Config; pub use self::error::*; pub fn run(config: Config) -> Result<(), Error> { updater::update_ips(config.get_domains(), config.get_token()) }
//! Integration tests for GDLK that expect compile errors. The programs in //! these tests should all fail during compilation. use gdlk::{compile_and_allocate, HardwareSpec, ProgramSpec, Valid}; /// Compiles the program for the given hardware, executes it under the given /// program spec, and expects a runtime error....
mod shader_type; mod shader; mod shader_error; pub use self::shader_type::*; pub use self::shader::*; pub use self::shader_error::*;
#![allow(non_snake_case, unused_variables, unused_imports, unreachable_code, dead_code, unused_must_use, unused_doc_comments)] mod VirtualNetwork; mod Parser; mod TCPConnection; mod queue; use VirtualNetwork::VNC; use Parser::*; use TCPConnection::*; use std::io::{self, Read, Write}; use std::collections::{hash_map:...
fn main() { let a="hello"; if a == "hello" { println("hello world !"); } else if a == "world" { println("world !") } else { println("q") } }
//! # Call of Ferris //! //! Call of Ferris is a thrilling action game where your favorite Ferris the crab and the rust mascot got guns and has taken up the duty to find evildoer languages while managing to keep itself alive. //! Take part in this awesome adventure and help Ferris be the best ever! //! //! For a fuller...
use assert_cmd::Command; use serde::Serialize; #[derive(Serialize)] struct Input { input: String, } #[derive(Serialize)] struct Output { output: String, } #[test] fn test_input_error() { Command::cargo_bin("aks-cluster-suffix") .unwrap() .assert() .code(1); } #[test] fn test_inpu...
//Copyright 2020 EinsteinDB Project Authors & WHTCORPS Inc. Licensed under Apache-2.0. use std::fmt; use std::sync::Arc; use criterion::{Bencher, Criterion}; use engine_lmdb::raw::DB; use engine_lmdb::Compat; use edb::{MuBlock, WriteBatchExt}; use test_violetabftstore::*; use test_util::*; const DEFAULT_DATA_SIZE: u...
use crate::lib; pub fn run(part: u32) { let mut seat_ids: Vec<_> = lib::parse::read_to_vec::<String>("input/05.txt") .iter() .map(|s| { let b = s .replace("F", "0") .replace("B", "1") .replace("L", "0") .replace("R", "1")...
mod vec3; mod ray; mod sphere; mod hittable; mod hittable_list; mod rtweekend; mod camera; mod material; use vec3::Vec3 as Color; use vec3::Vec3 as Point3; use crate::vec3::Vec3; use crate::sphere::Sphere; use crate::hittable_list::HittableList; use crate::hittable::HitRecord; use crate::hittable::Hittable; use crate:...
//! Virtualize a UART bus. //! //! This allows multiple Tock capsules to use the same UART bus. This is likely //! most useful for `printf()` like applications where multiple things want to //! write to the same UART channel. //! //! Clients can choose if they want to receive. Incoming messages will be sent //! to all ...
#[allow(unused_imports)] use serde_json::Value; #[derive(Debug, Serialize, Deserialize)] pub struct AntivirusPolicyExtended { /// A description for the policy. #[serde(rename = "description")] pub description: Option<String>, /// Whether the policy is enabled. #[serde(rename = "enabled")] pub e...
use crate::front_models::server_lists::FrontDisplayServerTime; use crate::{facades::versions, models::server_lists::ServerList, FrontDisplayMetaVersion}; use anyhow::Result; use chrono::Utc; use diesel::PgConnection; pub fn get_server_list(conn: &PgConnection, version: i64) -> Result<FrontDisplayMetaVersion> { ve...
use crate::peer_store::{Behaviour, PeerStore, ReportResult, Score, ScoringSchema, Status}; use crate::PeerId; use fnv::FnvHashMap; use libp2p::core::Multiaddr; use log::{debug, trace}; use std::time::{Duration, Instant}; #[derive(Debug)] struct PeerInfo { addresses: Vec<Multiaddr>, last_updated_at: Instant, ...
#![feature(nll)] extern crate bbcode; extern crate env_logger; extern crate fimfiction_api; extern crate fs_extra; extern crate handlebars; #[macro_use] extern crate log; extern crate pathdiff; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate structopt; extern crate tom...
extern crate nix; use nix::sys::signal; use std::io; fn read_int(msg: &str) -> i32 { loop { let mut s = String::new(); println!("{}",msg); io::stdin().read_line(&mut s).unwrap(); match s.trim_right().parse::<i32>() { Ok(i) => return i, Err(_) => println!("Invalid Number"), } } } f...
#![deny(missing_docs)] #![deny(missing_debug_implementations)] #![cfg_attr(test, deny(warnings))] //! dox extern crate base64; #[macro_use] extern crate bitflags; extern crate bytes; extern crate headers_core; #[macro_use] extern crate headers_derive; extern crate http; extern crate mime; extern crate sha1; extern cr...
//! A simple library for composing the results of future computation results with a minimal //! overhad. //! //! The library does not concern itself with the way that the future result is obtained. //! //! It exports the `Future` trait, which is in essence quite similar to the `Iterator` trait. //! Implementors are req...
use std::{ env, ffi::OsString, fs::File, io::{stdout, Read, Write}, }; use pulldown_cmark::{Options, Parser}; use pulldown_cmark_to_cmark::{cmark, cmark_resume}; fn main() -> Result<(), Box<dyn std::error::Error>> { let path = env::args_os() .nth(1) .expect("First argument is markd...
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. // #[PerformanceCriticalPath] use std::cmp::PartialOrd; use std::collections::VecDeque; use std::ops::{Add, AddAssign, Sub, SubAssign}; use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sy...
//extern crate rustpython_parser; #[macro_use] extern crate clap; extern crate env_logger; #[macro_use] extern crate log; extern crate rustpython_parser; extern crate rustpython_vm; use clap::{App, Arg}; use rustpython_parser::parser; use rustpython_vm::compile; use rustpython_vm::obj::objstr; use rustpython_vm::print...
extern crate nalgebra as na; use na::Vector2; use nphysics2d::algebra::Velocity2; use nphysics2d::material::{MaterialHandle, BasicMaterial}; use ncollide2d::shape::{Cuboid, ShapeHandle}; use nphysics2d::object::{ ColliderHandle, ColliderDesc, }; use sdl2::event::Event; use sdl2::keyboard::{Keycode, KeyboardSta...
// Copyright 2019 Conflux Foundation. All rights reserved. // Conflux is free software and distributed under GNU General Public License. // See http://www.gnu.org/licenses/ use std::{marker::PhantomData, ptr::null_mut, slice}; /// Use FieldsOffsetMaybeInPlaceByteArrayMemoryManager and macro /// make_parallel_field_ma...
// This is a part of Chrono. // See README.md and LICENSE.txt for details. /*! * Various scanning routines for the parser. */ use super::{ParseResult, INVALID, OUT_OF_RANGE, TOO_SHORT}; use crate::Weekday; /// Tries to parse the non-negative number from `min` to `max` digits. /// /// The absence of digits at all i...
#[doc = "Register `DFESTATUS` reader"] pub struct R(crate::R<DFESTATUS_SPEC>); impl core::ops::Deref for R { type Target = crate::R<DFESTATUS_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<DFESTATUS_SPEC>> for R { #[inline(always)] fn from(read...
#[doc = "Register `DATABYTEREV` reader"] pub struct R(crate::R<DATABYTEREV_SPEC>); impl core::ops::Deref for R { type Target = crate::R<DATABYTEREV_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<DATABYTEREV_SPEC>> for R { #[inline(always)] fn f...
use std::env; fn main() { let args: Vec<String> = env::args().collect(); let n = parse_config(&args); let e = (1. + 1. / n as f64).powf(n as f64); println!("{}", e); } fn parse_config(args: &[String]) -> usize { let digits = &args[1]; digits.parse::<usize>().unwrap() }
//! Representation of mesh data with its vertices and all buffer data. use crate::renderer::buffer::Buffer; use crate::renderer::Material; use std::cell::RefCell; use std::rc::Rc; use std::vec::Vec; use web_sys::WebGlRenderingContext; /// Mesh data as the union of its `Buffers` and the number of vertices in the mesh ...
// //mod util; // //mod imp; // //mod lie; // mod vec; // mod mat; // mod lie; // use std::f32; // use lie::{SO3}; // use vec::{Vec3}; // use mat::{Mat3}; // //use crate::util::{todo}; // struct Ang3 { // } // impl From<Vec3> for Ang3 { // fn from(v: Vec3) -> Self { // // todo() // pan...
use std::cmp::{Ord, Ordering, PartialOrd}; use std::fmt; use ctxt::SemContext; use driver::cmd::{Args, CollectorName}; use gc::copy::CopyCollector; use gc::swiper::Swiper; use gc::space::{Space, SpaceConfig}; use gc::zero::ZeroCollector; pub mod arena; pub mod chunk; pub mod copy; pub mod root; pub mod space; pub mod...
// Copyright 2018-2021 Cargill Incorporated // // 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...
extern crate test; use std::convert::TryInto; use bytes::Bytes; use test::Bencher; use crate::codec::ProtocolCodecSync; use crate::types::block::Block; use crate::types::transaction::SignedTransaction; use crate::{codec, types}; use crate::fixed_codec::tests::*; macro_rules! test { ($mod: ident, $r#type: ident...
use crate::actor; use crate::node::stats::NodeStatsStreamFactory; use crate::node::{NodeStatsInfo, NodeStatsObserver}; use act_zero::{call, Actor, ActorError, ActorResult, Addr, AddrLike, Produces, WeakAddr}; use async_trait::async_trait; use tokio::stream::StreamExt; use tracing::{info, trace, warn}; pub struct Stats...
use std::{str, thread}; use std::io::prelude::*; use std::io::{Error, ErrorKind, Result}; use std::net::{TcpListener,TcpStream}; use std::sync::{Arc, Mutex}; use std::collections::HashMap; mod set; mod get; #[derive(Clone)] pub struct Index { inner: Arc<Mutex<HashMap<String, u64>>>, } impl Index { pub fn new...
//! Common error scenarios handled by this crate. use std::fmt::Formatter; /// Represents possible errors that might happen during the Lambda /// function execution. /// /// As observed in a few projects available at GitHub, most of the time /// main function will return a [Result] instance that will handled by /// th...
impl Solution { pub fn find_best_value(mut arr: Vec<i32>, target: i32) -> i32 { arr.sort(); let mut part_sum = 0; let mut right_index = arr.len(); for i in 0..arr.len() { let sum = part_sum + arr[i] * (arr.len() - i) as i32; if sum > target { ...
#![no_main] // cargo +nightly fuzz run fuzz_objects -j 12 -- -max_len=16777216 # 16M libfuzzer_sys::fuzz_target!(|data| { if let Ok(arc) = symbolic_debuginfo::Archive::parse(&data) { let _ = arc.file_format(); let num_objects = arc.object_count(); for idx in 0..num_objects { if...
use std::{ net::{IpAddr, Ipv4Addr}, time::{SystemTime, UNIX_EPOCH}, }; use petgraph::dot::Dot; use pnet::datalink::NetworkInterface; use tokio::io::AsyncWriteExt; use crate::{error::*, topo::TopoGraph, OPT}; pub fn get_interface_ipv4_addr(ni: &NetworkInterface) -> Option<Ipv4Addr> { for ip in ni.ips.iter...
fn main() { let _x = 5; // can't borrow as mutable //let y = &mut x; }
use transitive::transitive_fn; pub fn direct_fn() { transitive_fn(); }
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @generated SignedSource<<085b96473751f6ff499d57fcc5854332>> */ mod parse; use parse::transform_fixture; use fixture_tests::te...
//! A work-stealing based thread pool for executing futures. #![deny(warnings, missing_docs, missing_debug_implementations)] extern crate coco; extern crate futures; extern crate num_cpus; extern crate rand; #[macro_use] extern crate log; mod task; use coco::deque; use task::Task; use futures::{Future, Poll, Asyn...
#[doc = "Register `INTENSET` reader"] pub struct R(crate::R<INTENSET_SPEC>); impl core::ops::Deref for R { type Target = crate::R<INTENSET_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<INTENSET_SPEC>> for R { #[inline(always)] fn from(reader: ...
#[allow(unused_imports)] use serde_json::Value; #[derive(Debug, Serialize, Deserialize)] pub struct ClusterPatchPatches { #[serde(rename = "patches")] pub patches: Option<Vec <crate::models::ClusterPatchPatchesPatch>>, }
use iced::{button, text_input, Element}; use crate::ui::step::Step; use crate::ui::model::{StepMessage, WindSetting, PersonSetting}; pub struct Steps { steps: Vec<Step>, current: usize, } impl Steps { pub fn new() -> Steps { Steps { steps: vec![ Step::Welcome, ...
use anyhow::Result; use indexmap::IndexMap; use quote::{format_ident, quote}; use serde::{Deserialize, Serialize}; use xshell::cmd; #[derive(Deserialize, Serialize, Debug)] pub struct NodeType { pub named: bool, #[serde(rename = "type")] pub kind: String, // IndexMap is used to preserve order for iteration pub fi...
use crate::core::definition; use crate::core::implementation; use crate::core::intermediary; pub struct TryIntoResultImpl; pub struct ParameterStruct<'a> { pub struct_definition_ref: &'a definition::Struct, pub struct_intermediary_ref: &'a intermediary::Struct<'a>, pub data_context_intermediary_ref: &'a...
use std::cell::RefCell; use std::rc::Rc; #[derive(Debug, Eq, Ord, PartialEq, PartialOrd, Clone)] struct Reservation { name: String, min: i32, max: i32, weight: i32, } #[derive(Debug, Eq, Ord, PartialEq, PartialOrd, Clone)] struct Unit { name: String, capacity: i32 } trait Similarable { fn...
use wasm_bindgen::prelude::*; use web_sys::console; use serde::{Serialize, Deserialize}; use rand::prelude::*; // When the `wee_alloc` feature is enabled, this uses `wee_alloc` as the global allocator. #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; #[w...
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Copy, Clone)] pub enum IpProtocol { ICMP = 1, TCP = 6, UDP = 17, Unknown, } impl std::convert::From<u8> for IpProtocol { fn from(p: u8) -> IpProtocol { match p { 1 => IpProtocol::ICMP, 6 => IpProtocol::TCP, ...
// Proof of knowledge of signature for signature defined in 2018 paper, CT-RSA 2018 (eprint 2017/1197). use crate::pok_sig::{PoKOfSignature as PoKOfSignature16, PoKOfSignatureProof}; use amcl_wrapper::field_elem::FieldElement; use crate::signature_2018::Signature; use crate::keys::{Verkey, Params}; use crate::errors::...