text
stringlengths
8
4.13M
use log::{debug, error, info}; use c_markdown; use c_replace; use std::collections::hash_map::HashMap; use std::env; type UtilityMap = HashMap<&'static str, fn(Vec<std::ffi::OsString>) -> i32>; fn util_map() -> UtilityMap { let mut map: UtilityMap = HashMap::new(); map.insert("render", c_markdown::entry); ...
use crate::prelude::*; pub struct VhdxImage { } impl Drop for VhdxImage { fn drop(&mut self) { let res = self.flush(); debug_assert!(res.is_ok()); } } impl ReadAt for VhdxImage { fn read_at(&self, _offset: u64, _data: &mut [u8]) -> Result<usize> { todo!() } } ...
use std::mem; #[derive(Debug)] pub struct BST { root: Link, } #[derive(Debug)] enum Link { Empty, More(Box<Node>), } #[derive(Debug)] struct Node { elem: i32, left: Link, right: Link, } impl BST { pub fn new() -> Self { BST {root: Link::Empty} } pub fn insert(&mut self,...
pub mod db; pub mod tally; use serenity::async_trait; use serenity::framework::StandardFramework; use serenity::Client; use serenity::model::channel::Message; use serenity::framework::standard::{CommandResult, Args}; use serenity::client::{Context, EventHandler}; use serenity::framework::standard::macros::{command, gr...
use itertools::Itertools; use std::collections::BTreeMap; pub fn lowest_price(books: &[u32]) -> u32 { let mut hm: BTreeMap<u32, u32> = BTreeMap::new(); let mut output_sum = 0; let mut output: Vec<Vec<u32>> = Vec::new(); for book in books { match hm.contains_key(book) { true => { ...
/*! Primitive Mark'n'Sweep garbage collection runtime. Please note * this is not a GC for Rust, but GC in Rust. * * Each object on stack or heap has an usize tag at offset zero; by * this tag, the runtime will know object type and thus pointer * offsets. The tag also designates a moved object if it is odd (thus ...
use randomize::PCG32; use std::time::{Duration, Instant}; use tiled::PropertyValue; pub(crate) trait Animated { fn animate(&mut self) -> usize; } struct Frame { index: usize, duration: Duration, } struct Animation { frames: Vec<Frame>, current_index: usize, start_time: Instant, } impl Animat...
mod gen_network; use actix::Actor; use actix_rt::System; use bus::{Broadcast, BusActor}; use chain::{ChainActor, ChainActorRef}; use config::{get_available_port, NodeConfig}; use consensus::dev::DevConsensus; use futures_timer::Delay; use gen_network::gen_network; use libp2p::multiaddr::Multiaddr; use logger::prelude:...
#[doc = "Register `CR2` reader"] pub type R = crate::R<CR2_SPEC>; #[doc = "Register `CR2` writer"] pub type W = crate::W<CR2_SPEC>; #[doc = "Field `ADON` reader - A/D converter ON / OFF"] pub type ADON_R = crate::BitReader<ADON_A>; #[doc = "A/D converter ON / OFF\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, Part...
//! Extract recognized container files from ROMs or other packed files. use cli::Args; use decompress; use errors::Result; use nitro::Container; use nitro::container::read_container; use std::collections::HashSet; use std::fs; use std::io::Write; use std::path::PathBuf; use util::cur::Cur; use util::OutDir; pub fn ma...
fn part_1(presents_limit: usize) -> usize { let presents_limit = presents_limit / 10; let mut houses = vec![0; presents_limit]; for elf in 0..presents_limit { (elf..presents_limit) .step_by(elf + 1) .for_each(|v| houses[v] += elf + 1); } houses.iter().position(|&p| ...
#![cfg(nightly)] #![feature(test)] #[macro_use] extern crate may; extern crate test; use may::coroutine::*; use test::Bencher; #[bench] fn yield_bench(b: &mut Bencher) { b.iter(|| { scope(|s| { for _ in 0..1000 { go!(s, || for _i in 0..10000 { yield_now(); ...
#[doc = "Register `RCC_MP_AHB6ENCLRR` reader"] pub type R = crate::R<RCC_MP_AHB6ENCLRR_SPEC>; #[doc = "Register `RCC_MP_AHB6ENCLRR` writer"] pub type W = crate::W<RCC_MP_AHB6ENCLRR_SPEC>; #[doc = "Field `MDMAEN` reader - MDMAEN"] pub type MDMAEN_R = crate::BitReader; #[doc = "Field `MDMAEN` writer - MDMAEN"] pub type M...
use crate::token::*; use crate::Error; use TokenType::*; use std::error; use std::vec::Vec; use std::format; pub fn scan(code: Vec<char>) -> Result<Vec<Token>, Box<dyn error::Error>> { let mut index = 0; let mut tokens: Vec<Token> = Vec::new(); while let Some(res) = parse_token(&code, index) { /...
#[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; /// A vec ensured to have at least 1 element. #[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct NonEmptyVec<T>(Vec<T>); impl<T> NonEmptyVec<T> { pub(crate) fn new(v:...
//! //! Persistant side storage for failed inserts "after the fact" as important distinction to a "write ahead log" //! thus aiming to be more flash friendly on embedded devices where you want to keep writes to a minimum. This //! will cause data loss if after failed insert also the writing to flash fails!. For that pr...
//! This crate offers Rust bindings to [KaTeX](https://katex.org). //! This allows you to render LaTeX equations to HTML. //! //! # Usage //! //! Add this to your `Cargo.toml`: //! ```toml //! [dependencies] //! katex = "0.4.0-alpha.1" //! ``` //! //! # Examples //! //! ``` //! let html = katex::render("E = mc^2").unwr...
use std::path::{Path, PathBuf}; use std::process::{Command, Output}; use super::parsing; use super::{NixQueryEntry, NixQueryPathMap, NixQueryTree}; use crate::tree; #[derive(Clone, Debug, Eq, PartialEq)] pub enum NixStoreErr { CommandErr(String), Utf8Err(String), NixStoreErr(String), ParseErr(String),...
pub mod api; pub mod auth; pub mod models; use chrono::{DateTime, Utc}; use orgize::Org; pub async fn sync() {} fn filter_headlines_by_scheduled( org: &Org, time_min: DateTime<Utc>, time_max: DateTime<Utc>, updated_min: Option<DateTime<Utc>>, ) { }
// Copyright 2017 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...
mod connection_string; mod document; mod operation; use crate::{ bson::{Bson, Document}, error::Result, options::WriteConcern, }; fn write_concern_to_document(write_concern: &WriteConcern) -> Result<Document> { match bson::to_bson(&write_concern)? { Bson::Document(doc) => Ok(doc), _ =>...
//! Symbols used to denote deprecated usages of PyO3's proc macros. #[deprecated( since = "0.14.0", note = "use `#[pyo3(name = \"...\")]` instead of `#[name = \"...\"]`" )] pub const NAME_ATTRIBUTE: () = (); #[deprecated( since = "0.14.0", note = "use `#[pyfn(m)] #[pyo3(name = \"...\")]` instead of `#...
use crate::chiapos::{Tables, TablesCache}; use std::mem; const K: u8 = 17; #[test] fn self_verification() { let seed = [1; 32]; let tables = Tables::<K>::create_simple(seed); let tables_parallel = Tables::<K>::create_parallel(seed, &mut TablesCache::default()); for challenge_index in 0..1000_u32 { ...
//! Implementation of a websocket transport. use super::super::{ConnectionError, Credentials, Request, Subscribe}; use tungstenite::handshake::client::Request as TungsteniteRequest; /// Wraps a websocket connection pub struct WebSocket { address: String, credentials: Option<Credentials>, websocket: tungst...
pub mod always_success; pub mod next_epoch_ext; pub mod overall; pub mod secp_2in2out; pub mod util;
use std::collections::VecDeque; use std::rc::Rc; use std::cell::RefCell; use crate::ast::expressions; use crate::ast::lexer::tokens::{self, Keyword}; use crate::ast::parser; use crate::ast::rules; use crate::ast::stack; use crate::interpreter::{types, environment, cache}; /// Id contains cached value for an environm...
#[macro_use] extern crate num_derive; extern crate num_traits; mod calculator; mod card; mod cards_iterator; mod hand; mod table; mod types; pub use self::card::Card; pub use self::hand::Hand; pub use self::table::Table; pub use calculator::Calculator; fn main() { let card1 = Card { rank: types::Rank::Th...
use { crate::Error, heck::{KebabCase, SnakeCase}, rewryte_parser::models::{Enum, Item, Schema, Table, Types}, std::io, }; #[derive(Default, Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)] pub struct Options { pub juniper: bool, pub serde: bool, pub sqlx: bool, } pub fn write_sch...
//////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2018, the Perspective Authors. // // This file is part of the Perspective library, distributed under the terms // of the Apache License 2.0. The full license can be found in the LICENSE // file. use async_std::sync::M...
use utils; pub fn problem_003() -> u64 { let n: u64 = 600851475143; *utils::prime_factors(n).iter().max().unwrap() } #[cfg(test)] mod test { use super::*; use test::Bencher; #[test] fn test_problem_003() { let ans: u64 = problem_003(); println!("Answer to Problem 3: {}", ans);...
mod codec; mod tcp; mod uds; pub use tcp::TcpConnection; pub use uds::UnixConnection; cfg_if! { if #[cfg(feature = "tls")] { mod tls; pub use tls::TlsConnection; } }
//! The representation of a single client. Holds information like name, role //! (e.g. villager, mafia), alive or not, etc. Also contains a `ws::Sender`, so //! that whenever this client does something, has something happen to them, or //! is affected by some action, we can notify the actual client in the browser. use...
// This declaration will look for a file named `app.rs` or `app/mod.rs` and will // insert its contents inside a module named `my` under this scope mod app; use app::models::user::User; use app::models::profile::Profile; fn main() { let user: User = User::new( 1, "frankemeks77@yahoo.com" ); ...
use crate::pool::TxPool; use crate::FeeRate; use futures::future::Future; use tokio::prelude::{Async, Poll}; use tokio::sync::lock::Lock; pub struct EstimateFeeRateProcess { pub tx_pool: Lock<TxPool>, pub expect_confirm_blocks: usize, } impl EstimateFeeRateProcess { pub fn new(tx_pool: Lock<TxPool>, expec...
use async_executor::Executor; use async_native_tls::TlsAcceptor; use async_std::sync::Mutex; use easy_parallel::Parallel; use ff::Field; use http_types::{Request, Response, StatusCode}; use log::*; use rand::rngs::OsRng; use serde_json::json; use smol::Async; use std::fs::File; use std::io::prelude::*; use std::io::Buf...
//! Note: This entire module is an exercise //! in bashing the trait system over the //! head until it lets us do what we want //! safely. use shred::{ResourceId, SystemData}; use specs::*; use types::*; use std::any::Any; use std::marker::PhantomData; use std::ops::{Deref, DerefMut}; use protocol::GameType; pub t...
use crate::iv::Iv; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize)] pub struct EncryptedFile { pub iv: Iv, pub buffer: Vec<u8>, pub mac: [u8; 32], }
use super::uniq; use super::Opts; use indoc::indoc; use std::str; static NDJSON: &str = indoc! {r#" {"id":1,"sub_id":11,"val":"abc"} {"id":2,"sub_id":21,"val":"ghi"} {"id":2,"sub_id":22,"val":"ghi"} {"id":3,"sub_id":31,"val":"jkl"} {"id":4,"sub_id":41,"val":"mno"} {"id":5,"sub_id":51,"val":"pqr...
use crate::sector::{ sector_record_chunks_size, sector_size, RecordMetadata, SectorContentsMap, SectorContentsMapFromBytesError, SectorMetadataChecksummed, }; use parity_scale_codec::Decode; use rayon::prelude::*; use std::mem::ManuallyDrop; use std::simd::Simd; use subspace_core_primitives::crypto::{blake3_has...
use std::collections::HashMap; use std::time::Duration; use async_trait::async_trait; use hyper::{Body, StatusCode}; use hyper::client::Client; use json; use log::debug; use url::Url; use crate::conn::{self, ApicCommError}; /// Data returned from the APIC authenticator to the APIC connection. #[derive(Clone, Debug,...
use crate::allpass::DelayAPF; use crate::comb_filter::CombFilter; use crate::delay::Delay; use crate::lowpass::OnePoleLPF; use crate::lowpass_comb_filter::LPFCombFilter; fn samples_from_ms(ms: f64, sample_rate: f64) -> usize { time_calc::samples_from_ms(ms, sample_rate) as usize } pub struct Reverb { pre_dela...
mod molecule; mod molecule_building; use molecule::*; use molecule_building::*; use std::iter::Peekable; const BOND_TYPES: [(char, molecule::Order); 4] = [ ('-', Order::Single), ('=', Order::Double), ('#', Order::Triple), ('$', Order::Quadruple), ]; const BRACKET_ATOM_START: char = '['; const BRACKET...
/* chapter 4 syntax and semantics */ fn main() { let tuple: (u32, String) = (5, String::from("five")); println!("{:?}", tuple); // here, tuple is moved, // because the String is moved let (a, _b) = tuple; println!("{} and {}", a, _b); // the next line will give // "error: use of parti...
use crypto_markets::{fetch_symbols, get_market_types, MarketType}; #[macro_use] mod utils; const EXCHANGE_NAME: &str = "bitmex"; fn get_market_type_from_symbol(symbol: &str) -> MarketType { let date = &symbol[(symbol.len() - 2)..]; if date.parse::<i64>().is_ok() { // future if symbol.starts_w...
use std::collections::VecDeque; use crate::ast::expressions::*; use crate::ast::stack; use std::boxed::Box; #[test] fn test_stack_unpack() { let mut stack = stack::Stack::default(); stack.push_single(Box::new(primitives::Nil)); stack.push_repetition( vec![ Box::new(primitives::Nil) as...
extern crate iron; extern crate time; use time::precise_time_ns; use iron::{BeforeMiddleware, AfterMiddleware, typemap}; use iron::prelude::*; use iron::request::Request; pub struct ResponseTime; impl typemap::Key for ResponseTime { type Value = u64; } impl BeforeMiddleware for ResponseTime { fn before(&s...
use aoc::*; fn main() -> Result<()> { println!("Day 2 part 1 result is {}", part1()); println!("Day 2 part 2 result is {}", part2()); Ok(()) } fn part1() -> usize { count_valid_passwords(valid_1) } fn part2() -> usize { count_valid_passwords(valid_2) } fn count_valid_passwords(valid: fn((usize, ...
use crate::List::{Cons, Nil}; use std::rc::{Rc}; use std::cell::{RefCell, RefMut}; fn main () { list_count(); } enum List { Cons(i32, Rc<List>), Nil, } fn litsts() { let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil))))); let _b = Cons(3, Rc::clone(&a)); let _c = Cons(4, Rc::clone(&a)); }...
// 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 { crate::{ constants::{GRAPH_KEY, TITLE_KEY}, models::AddModInfo, story_graph::{ModuleData, StoryGraph}, story_stor...
fn main() { let a=[1,2,3]; assert!(a.iter().any(|&x| x>1)); }
use crate::*; pub fn init(globals: &mut Globals) -> Value { let id = globals.get_ident_id("Float"); let class = ClassRef::from(id, globals.builtins.object); globals.add_builtin_instance_method(class, "<=>", cmp); globals.add_builtin_instance_method(class, "floor", floor); Value::class(globals, clas...
use crate::transports::http::{GraphQLRequest, GraphQLResponse, RequestContext}; use crate::Result; use async_trait::async_trait; use reqwest::Client; use serde_json::{Map, Value}; use std::collections::HashMap; use std::iter::FromIterator; #[derive(Debug)] pub struct ServiceDefinition { pub url: String, pub cl...
#![feature(test)] extern crate test; extern crate pest; extern crate pest_grammars; use test::Bencher; use pest::Parser; use pest_grammars::json; const CANADA : &str = include_str!("../assets/canada.json"); #[bench] fn pest(b: &mut Bencher) { b.iter(||{ json::JsonParser::parse_str(json::Rule::json, CANADA).u...
#[doc = "Prunes branches of the tree that are not exported"]; import rustc::syntax::ast; import rustc::syntax::ast_util; import rustc::middle::ast_map; export mk_pass; fn mk_pass() -> pass { run } fn run(srv: astsrv::srv, doc: doc::cratedoc) -> doc::cratedoc { let fold = fold::fold({ fold_mod: fold_...
use std::{ marker::PhantomData, pin::Pin, task::{Context, Poll}, }; use bson::RawDocument; use futures_core::{future::BoxFuture, Stream}; use futures_util::StreamExt; use serde::{de::DeserializeOwned, Deserialize}; #[cfg(test)] use tokio::sync::oneshot; use super::{ common::{ kill_cursor, ...
//! Generic api response types use serde::Deserialize; /// A Kubernetes status object /// /// Equivalent to Status in k8s-openapi except we have have simplified options #[derive(Deserialize, Debug)] pub struct Status { /// Suggested HTTP return code (0 if unset) #[serde(default, skip_serializing_if = "num::Zer...
use job::Job; pub enum Message { RunJob(Job), Terminate, }
extern crate iota; extern crate libc; extern crate tokio; use std::ffi::{CStr, CString}; use iota::{Client as IotaClient, MessageId, Result}; use libc::c_char; use tokio::runtime::Runtime; pub struct NodeClient { _runtime: Runtime, client: IotaClient, } impl NodeClient { fn new(node_uri: &str) -> Self {...
/// An input event. /// /// An `Event` represents a single event from the underying terminal. At the moment no further /// processing is done on events and raw escape sequences will also be passed as `Key`s.:wq #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum Event { Key(char), }
use super::args::{ Access, parse_z0, parse_i, parse_mi, parse_mr, parse_rm, parse_rr, parse_rrvv, parse_rvm, parse_rvmvv, Disp, Register, Mem, RegSize, }; use super::platform::{ Encode, Ext, }; mod a; /// Details how the Opcode is encoded pub trait Opcode { /// How many uOPs is th...
use crate::components::Token; use crate::root::{AppAnchor, AppRoute}; use crate::services::{Error, RecipeService}; use oikos_api::components::schemas::RecipeModel; use uuid::Uuid; use yew::{prelude::*, services::fetch::FetchTask}; use yew_router::{ agent::RouteRequest, prelude::{Route, RouteAgentDispatcher}, ...
use comet::api::Collectable; use comet::api::Finalize; use comet::api::Gc; use comet::api::Trace; use comet::api::Visitor; use comet::gc_base::AllocationSpace; use comet::immix::instantiate_immix; use comet::immix::Immix; use comet::immix::ImmixOptions; pub enum List<T: Collectable> { Nil, Cons(T, Gc<List<T>, ...
use webrtc_audio_processing::*; fn main() { let config = InitializationConfig { num_capture_channels: 2, // Stereo mic input num_render_channels: 2, // Stereo speaker output ..InitializationConfig::default() }; let mut ap = Processor::new(&config).unwrap(); let config = Confi...
use crate::candidate::*; use crate::network_type::*; use tokio::time::Instant; // CandidatePairStats contains ICE candidate pair statistics #[derive(Debug, Clone)] pub struct CandidatePairStats { // timestamp is the timestamp associated with this object. pub timestamp: Instant, // local_candidate_id is t...
use common::AgentSettings; use std::fs::File; use std::io::BufReader; use tempfile::tempdir; mod common; // workaround for unused functions in different features: https://github.com/rust-lang/rust/issues/46379 pub use common::*; #[tokio::test] #[cfg_attr(not(feature = "k8s_tests"), ignore)] async fn test_k8s_enrichm...
use std::collections::HashMap; /* Copyright (c) 2023 Uber Technologies, Inc. <p>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 <p>http://www.apache.org/licenses/LICENSE-2.0 <p>Unless required...
use std::net::{UdpSocket, SocketAddr}; use std::time; use tracker::{Announce, Result, ResultExt, Response, TrackerResponse, Event, Error, ErrorKind, dns}; use std::collections::HashMap; use {CONFIG, PEER_ID, amy}; use util::bytes_to_addr; use std::io::{self, Write, Read, Cursor}; use byteorder::{ReadBytesExt, WriteByte...
use neon::vm:: { Call, JsResult }; use neon::mem::Handle; use neon::js:: { JsInteger, JsArray, Object }; pub fn return_js_array(call: Call) -> JsResult<JsArray> { let scope = call.scope; let array: Handle<JsArray> = JsArray::new(scope, 3); try!(array.set(0, JsInteger::new(scope, 9000))); try!(array.se...
// Generated by `scripts/generate.js` use std::os::raw::c_char; use std::ops::Deref; use std::ptr; use std::cmp; use std::mem; use utils::c_bindings::*; use utils::vk_convert::*; use utils::vk_null::*; use utils::vk_ptr::*; use utils::vk_traits::*; use vulkan::vk::*; use vulkan::vk::{VkStructureType,RawVkStructureType...
use std::slice::Iter; pub struct Allergies { score: u32, } use Allergen::*; #[derive(Debug, PartialEq, Copy, Clone)] pub enum Allergen { Eggs = 1, Peanuts = 2, Shellfish = 4, Strawberries = 8, Tomatoes = 16, Chocolate = 32, Pollen = 64, Cats = 128, } impl Allergen { pub fn iter...
//! Single-threaded pool of (non-`Send`) futures #![doc(html_root_url = "https://docs.rs/fumio-pool/0.1.0")] #![warn( missing_debug_implementations, missing_docs, nonstandard_style, rust_2018_idioms, clippy::pedantic, clippy::nursery, clippy::cargo, )] #![allow( clippy::module_name_repetitions, // often hidden...
use fourthrail::*; pub const MAP_WIDTH: i32 = 120; pub const MAP_HEIGHT: i32 = 120; // The map of a level pub struct Map<T: Copy> { tiles : [T ; (MAP_WIDTH * MAP_HEIGHT) as usize] } impl<T: Copy> Map<T> { pub fn new(t: T) -> Map<T> { Map {tiles: [t ; (MAP_WIDTH * MAP_HEIGHT) as usize]} } pu...
use std::ops::RangeInclusive; fn main() { let input = String::from_utf8(std::fs::read("input/day16").unwrap()).unwrap(); let mut input = input.split("\n\n"); let fields: Vec<RangeInclusive<u16>> = input .next() .unwrap() .split_terminator('\n') .flat_map(|field| { ...
use crate::{ cmd::*, keypair::{Keypair, Network}, result::{bail, Result}, traits::{ToJson, TxnSign, B64}, }; use serde::{Deserialize, Serialize}; use std::{ fs::File, path::{Path, PathBuf}, }; #[derive(Debug, StructOpt)] /// Commands multi signature transactions pub enum Cmd { Inspect(Inspe...
use crate::ast_transform::Transformer; use crate::source::SourceLocation; #[derive(Debug, Clone)] pub struct NoOp; impl crate::utils::Sourced for NoOp { fn source(&self) -> &SourceLocation { &SourceLocation::NoSource } } impl NoOp { pub fn default_transform(self, _visitor: &mut impl Transformer) ...
use std::sync::Arc; // ==== Tuple/HList ==== pub trait Tuple: Sized { type HList: HList<Tuple = Self>; fn into_hlist(self) -> Self::HList; } impl Tuple for () { type HList = HNil; fn into_hlist(self) -> Self::HList { HNil(()) } } pub trait HList: Sized { type Tuple: Tuple<HList = S...
// vim: shiftwidth=2 use crate::dev_input_rw::{DevInputReader, Exclusion}; use std::path::Path; use nix::Error::Sys; use nix::errno::Errno::ENODEV; pub fn run_monitor(dev_file: &str) { match run_monitor_err(dev_file) { Err(msg) => println!("{}", msg), Ok(()) => () } } fn run_monitor_err(dev_file: &str)...
// 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. //! The Internet Protocol, versions 4 and 6. mod forwarding; mod types; pub use self::types::*; use std::fmt::Debug; use std::mem; use std::ops::Range; ...
use std::env; use diesel::prelude::*; use dotenv::dotenv; pub fn establish_connection() -> MysqlConnection { // 加载.env文件 dotenv().ok(); let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set in env"); MysqlConnection::establish(&database_url).expect(&format!("Can not connec...
use std::process; use std::thread; use std::time::{Duration, SystemTime}; use systemstat::{Platform, System}; use clap::ArgMatches; use num_cpus; mod args; fn main() { let mut treshold: f32 = 0.0; let mut reverse: bool = false; let mut sleep_millis: u64 = 1000; let mut max_time: u64 = u64::MAX; l...
#[deriving(ToStr,Eq,Rand)] pub enum Attack { Main, Power } pub trait Position { fn x(&self)-> int; fn y(&self)-> int; fn set_x(&mut self, int); fn set_y(&mut self, int); } pub trait Move { fn translate(&mut self, dx: int, dy: int); } pub trait Character: ToStr + Move + Position { ...
/* * 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. */ use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; use std::sync::Arc; use reveri...
use std::{any::Any, sync::mpsc::Sender}; pub enum StateError { CouldNotReadData, CouldNotWriteData, } pub type StateData = Box<dyn Any>; #[derive(Clone)] pub struct StateUpdate(Sender<StateData>); impl StateUpdate { pub fn new(sender: Sender<StateData>) -> Self { Self(sender) } pub fn w...
/* * Datadog API V1 Collection * * Collection of all Datadog Public endpoints. * * The version of the OpenAPI document: 1.0 * Contact: support@datadoghq.com * Generated by: https://openapi-generator.tech */ /// WidgetRequestStyle : Define request widget style. #[derive(Clone, Debug, PartialEq, Serialize, De...
use std::net::{SocketAddr}; #[derive(Debug, Serialize, Deserialize)] pub struct Message { pub from: SocketAddr, pub content: String, }
// Copyright (C) 2021 Subspace Labs, Inc. // 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 // // http://www.apache.org/licenses/LICENSE-2.0 // // Unle...
use std::error::Error; use std::fmt; #[derive(Debug, PartialEq)] pub enum FormatError { InvalidEscapeCharacter(usize, char), UnclosedPlaceholder, UnopenedPlaceholder, InvalidIndex(String), InvalidPadding(String), EmptyFormatter, } impl fmt::Display for FormatError { fn fmt(&self, f: &mut f...
//! //! Interpolation method for computation of cubic spline points within //! the range of a discrete set of known points. //! //! [**Demo**](https://emgyrz.github.io/cubic_spline/) //! //! # Example //! ``` //! use cubic_spline::{Points, Point, SplineOpts, TryFrom}; //! //! let source = vec![(10.0, 200.0), (256.0, 39...
use super::types::*; use eos::types::*; use serde::Serialize; use serde_json; use stdweb::Value; use yew::prelude::*; js_serializable!(ScatterRequiredFields); js_serializable!(ScatterNetwork); js_serializable!(EosJsConfig); js_serializable!(Authorization); js_deserializable!(Authorization); js_serializable!(ScatterTra...
//! Host I/O use crate::nr; use core::{fmt, slice}; /// A byte stream to the host (e.g., host's stdout or stderr). #[derive(Clone, Copy)] pub struct HostStream { fd: usize, } impl HostStream { /// Attempts to write an entire `buffer` into this sink pub fn write_all(&mut self, buffer: &[u8]) -> Result<(),...
use crate::parser::Error; use crate::time_domain::RuleKind::*; use crate::{datetime, parse, schedule_at}; #[test] fn s000_idunn_interval_stops_next_day() -> Result<(), Error> { use crate::time_domain::DateTimeRange; use chrono::Duration; let oh = parse("Tu-Su 09:30-18:00; Th 09:30-21:45")?; let start ...
extern crate stellar_multi_sig_orchestrator; use stellar_multi_sig_orchestrator::multi_sig_orchestrator; fn main() { multi_sig_orchestrator::start(); }
extern crate common; extern crate day3; use std::env::args; use std::fs::File; use std::io::BufReader; use std::process::exit; fn main() { let ar: Vec<String> = args().collect(); if ar.len() != 2 { eprintln!("Usage: {} <INPUT>", &ar[0]); exit(-1); } let input_file = File::open(&ar[1])...
use std::{env, error::Error, fs, path::{Path, PathBuf}, process}; use classifiles::{Config, Params}; use slog::{o, Drain}; mod yaml_conf { use serde::{Serialize, Deserialize}; #[derive(Debug, PartialEq, Serialize, Deserialize)] pub struct Config { pub mime_info_db: InfoDbConfig, pub libma...
use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; /// Represents a (possibly ongoing) period of time tracking, with its associated metadata. #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] pub struct Event { /// The start of a time-tracking period. pub start: Dat...
use super::{DataClass, DataIdDefinition}; use ::std::marker::PhantomData; pub type DataIdSimpleType = u8; pub(crate) static DATAID_DEFINITION : DataIdDefinition<DataIdSimpleType, DataIdType> = DataIdDefinition { data_id: 12, class: DataClass::FaultHistoryInformation, read: true, wr...
mod sorted_string_table; use std::fs::File; use std::io; use std::collections::HashMap; use std::fmt; #[derive(Copy, Clone, Debug)] pub struct Point { lat: f64, long: f64 } impl fmt::Display for Point { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "({}, {})", self.long, sel...
mod repository; pub use repository::*; use common::event::Event; use common::model::{AggregateRoot, StringId}; use common::result::Result; pub type ReaderId = StringId; #[derive(Debug, Clone)] pub struct Reader { base: AggregateRoot<ReaderId, Event>, username: String, name: String, lastname: String, ...
use serde::{Serialize, Deserialize}; #[derive(Debug, Serialize, Deserialize)] pub struct User { // #[serde(rename = "_id")] // Use MongoDB's special primary key field name when serializing #[serde(rename(serialize = "id", deserialize = "_id"))] pub id: bson::oid::ObjectId, pub given_name: String, ...
use ferris_base; pub fn seeded_assert_evolution_with_pauses( start: Vec<&str>, inputs: Vec<Option<ferris_base::core::direction::Direction>>, end: Vec<&str>, seed: Option<[u8; 32]>, ) -> bool { let start_one_line = start.join("\n"); let start_as_lines = start_one_line.lines(); let mut level ...