text
stringlengths
8
4.13M
use super::*; use fnd::{ containers::{Array, String}, serde::*, }; #[test] fn deserialize() { macro_rules! check_value { ($value:expr, $type:ident, $serialized:expr) => { let mut de = CborDeserializer::new(&$serialized[..]); let value = $type::deserialize(&mut de).unwrap();...
//! tprime binary #![feature(rust_2018_preview, try_from)] #![warn(missing_docs)] use env_logger; mod mods; use self::mods::pathfinding; fn main() { env_logger::init(); let mut pathfinder = pathfinding::AStarPathfinder::default(); let path = pathfinder.get_path(); println!("AStarPathfinder::default...
extern crate transportation; fn main() { let interval_token = ::transportation::set_interval(|| eprintln!("Interval"), ::std::time::Duration::from_secs(5)); ::transportation::set_timeout( move || { eprintln!("Timeout 1"); let token = ::transportation::set_timeout(|| eprintln!("Timeout 2"), ::std::time::Durat...
use super::{SimpleProductService, SimpleWishlistService}; use std::sync::Arc; lazy_static! { static ref PRODUCT_SERVICE: Option<Arc<SimpleProductService>> = SimpleProductService::new().map(Arc::new).ok(); static ref WISHLIST_SERVICE: Option<Arc<SimpleWishlistService>> = SimpleWishlistService::n...
use yew::{function_component, html, Html}; use yew_router::{Routable, BrowserRouter, Switch}; use crate::components::{container::Container, home::Home, not_found::NotFound}; #[function_component(App)] pub fn app() -> Html { html! { <BrowserRouter> <Switch<Route> render={switch} /> </Br...
mod errors; pub use errors::Result;
use std::collections::hash_map::Entry::*; use rustc_hash::FxHashMap; use crate::util::clear::Clear; pub struct HalfJoinStateReduce<K, A> { pub table: FxHashMap<K, A>, } impl<K, A> Default for HalfJoinStateReduce<K, A> { fn default() -> Self { Self { table: Default::default(), } ...
extern crate postgres; mod binance_api; mod rates; use std::env; use postgres::{Connection, TlsMode}; use std::{thread, time}; fn main() { let key = env::var("BINANCE_KEY").expect("BINANCE_KEY env is not set"); let secret = env::var("BINANCE_SECRET").expect("BINANCE_SECRET env is not set"); let binance =...
#[derive(Debug, Clone, Copy)] pub struct Orientation { pub rotation: Rotation, pub flipped: bool } impl Orientation { pub fn neutral() -> Orientation { Orientation { rotation: Rotation::RightSideUp, flipped: false } } pub fn index_zero_side(&self) -> u32 { let conv = self.rotation ...
use serde::Serialize; use std::{error, fmt}; #[derive(Serialize, Debug)] /// An authentication error pub struct AuthError { pub kind: &'static str, pub message: &'static str, } const USERNAME_NOT_FOUND: AuthError = AuthError { kind: "UsernameNotFound", message: "User with specified username not found"...
pub struct Repl; impl Repl { pub fn eval_code(_code: String) -> String { String::from("2") } }
pub mod asynt; #[cfg(test)] mod tests; use std::io::{Result, Write}; pub trait Asynt { fn to_asynt(&self, f: &mut dyn Write, indent: usize) -> Result<()>; } impl<T: asynt::Asynt> Asynt for T { fn to_asynt(&self, f: &mut dyn Write, indent: usize) -> Result<()> { self.to_asynt(f, indent) } }
//! Handle `cargo rm` arguments use crate::errors::*; #[derive(Debug, Deserialize)] /// Docopts input args. pub struct Args { /// Crate name (usage 1) pub arg_crate: String, /// Crate names (usage 2) pub arg_crates: Vec<String>, /// dev-dependency pub flag_dev: bool, /// build-dependency ...
//! The virtio module contains a virtualization standard for network and disk device drivers. //! This is the "legacy" virtio interface. //! //! The virtio spec: //! https://docs.oasis-open.org/virtio/virtio/v1.1/virtio-v1.1.pdf use crate::bus::*; use crate::cpu::*; use crate::trap::*; /// The interrupt request of vi...
use syn::parse_quote_spanned; use syn::spanned::Spanned; use super::{ DelayType, FlowProperties, FlowPropertyVal, OpInstGenerics, OperatorCategory, OperatorConstraints, OperatorInstance, WriteContextArgs, RANGE_1, }; /// > 1 input stream, 1 output stream /// /// > Generic parameters: A `Lattice` type, must im...
//! scanner use crate::prelude::{anyhow, ErrorKind, Result}; use unicode_segmentation::{Graphemes, UnicodeSegmentation}; /// Kinds of tokens /// /// Tokens that must require symmetry have both forms as token types, the rest fall under Builtin or literal token types. #[derive(PartialEq, Debug, Copy, Clone)] pub enum ...
use std::collections::HashSet; use std::fs::File; use std::io::Write; use std::path::Path; use std::{env, fs}; fn main() { let root_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); let rdata_dir = format!("{}/src/rdata", root_dir); let entries = fs::read_dir(&rdata_dir).unwrap(); let qtype_only = { ...
extern crate ctrlc; use ctrlc::CtrlC; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; fn main() { CtrlC::set_handler(move || { println!("CtrlC handler 1"); }); let running = Arc::new(AtomicBool::new(true)); let r = running.clone(); CtrlC::set_handler(move || { pri...
use crate::commands; use anyhow::Result; use clap::Clap; /// Run the application using the command line arguments pub fn run() -> Result<()> { let opts: Opts = Opts::parse(); if let Some(name) = opts.context { // shortcut for activate commands::activate(&name)?; return Ok(()); } el...
extern crate redis; use self::redis::{Commands, Connection}; use std::str::FromStr; use std::env; fn connect() -> Connection { let url = env::var("REDIS_URL").unwrap_or("redis://127.0.0.1:6379/".to_string()); let client = redis::Client::open(url.as_str()).unwrap(); client.get_connection().unwrap() } pub...
use std::str::FromStr; use bip32::{Language, Mnemonic}; use conquer_once::Lazy; use elements::{bitcoin::util::amount::Amount, Address, AddressParams, Txid}; use futures::lock::Mutex; use js_sys::Promise; use reqwest::Url; use rust_decimal::{prelude::ToPrimitive, Decimal, RoundingStrategy}; use wasm_bindgen::{prelude::...
use super::Repository; use crate::{Error, ErrorKind}; use std::path::Path; /// A path *relative to the root of the git repository* that is guaranteed to be tracked by Git. /// /// This type is immutable. #[cfg_attr(docsrs, doc(cfg(feature = "osv-export")))] pub struct GitPath<'a> { repo: &'a Repository, path: ...
/// 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。 /// /// example 1: /// 输入: 123 /// 输出: 321 /// /// example 2: /// 输入: -123 /// 输出: -321 /// /// example 3: /// 输入: 120 /// 输出: 21 /// /// /// 思路: /// 利用x%10 和 x/10 对末尾数进行弹出 /// 但是需要注意反转后是否会超过i32的最大值或最小值 /// i32_max_value:2147483647 /// i32_min_value:-2147483648 fn reverse(x: i3...
mod octant; pub mod testmap; pub use octant::Octant; pub use testmap::TestMap;
use std::collections::BTreeMap; use std::error::Error; use prettytable; #[derive(Copy, Clone, Debug, PartialEq, Eq)] crate enum ColumnType { Key, Integer, String, } // TODO: `Option`-ize to represent NULL? #[derive(Clone, Debug, PartialEq, Eq)] pub enum Chamber { Key(usize), Integer(isize), S...
struct Point { a: u32, b: u32, } impl Point { fn diff(&self) -> u32 { 2 * self.a + self.b } } fn main() { let n: usize = { let mut line = String::new(); std::io::stdin().read_line(&mut line).unwrap(); line.trim_end().parse().unwrap() }; let mut points: Vec<P...
/* * 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 */ use reqwest; use crate::apis::ResponseContent; use super::{Error, configuration}; /// struct for typ...
// Allow uppercase names to match Windows API: #![allow(clippy::upper_case_acronyms)] #[cfg(windows)] mod os_defs { pub use winapi::shared::{ ntdef::{HRESULT, LPCSTR, LPCWSTR, LPSTR, LPWSTR, WCHAR}, wtypes::BSTR, }; pub use winapi::um::combaseapi::CoTaskMemFree; pub use winapi::um::ole...
#![macro_use] // Evolve to log error and exits // with specified status code!! #[macro_export] macro_rules! errorln( ($($arg:tt)*) => ( { use std::io::Write; match writeln!(&mut ::std::io::stderr(), $($arg)* ) { Ok(_) => {}, Err(x) => panic!("Unable to write to stderr: {}", x), }...
pub use self::container::Container; pub use self::docker::{Docker, Logs, Ports}; pub use self::image::Image; pub use self::wait_for_message::{WaitError, WaitForMessage}; mod container; mod docker; mod image; mod wait_for_message;
/* * 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. */ #[cfg(target_arch = "aarch64")] mod aarch64; #[cfg(target_arch = "x86_64")] mod x86_64; #[cfg(targ...
pub fn factors(mut n: u64) -> Vec<u64> { let mut vec = Vec::new(); let mut div = 2; while n > 1 { if n % div == 0 { vec.push(div); n /= div; continue; } div += 1; } vec }
#[ link(name = "simplespawn", vers = "0.1.2", author = "smadhueagle") ]; #[pkg(id = "simplespawn", vers = "0.1.2")]; // Additional metadata attributes #[ desc = "A simple thread spawn example in rust"]; #[ license = "MIT" ]; #[crate_type = "bin"]; extern mod rustils; use rustils::randutils; use std::t...
use crate::alpaca::tick_data::TickData; use crate::kafkautil::producer::KafkaMsg; use std::sync::mpsc::{Receiver, RecvError, SendError, Sender}; pub(crate) struct MapRecv<T, U, F: Fn(T) -> U> { pub(crate) recv: Receiver<T>, pub(crate) f: F, } pub(crate) struct MapSender<T, U, F: Fn(T) -> U> { pub(crate) s...
use log::trace; use std::path::Path; use clap::clap_app; use c_utils::{ fs::{read_from_file, write_to_file}, nv, }; use failure::format_err; use toml; use failure::Error; use serde::Deserialize; #[derive(Debug, Deserialize)] struct Config { kwd: Option<String>, repl: Option<String>, } pub fn entry(...
mod commands; mod config; mod util; use commands::*; fn main() { let action = if util::args_len() > 1 { util::get_argument(1) } else { String::from("help") }; match action.as_str() { "f" | "find" => find::run(), "g" | "grep" => grep::run(), "l" | "list" => list...
use crate::errors::Errcode; use crate::ipc::generate_socketpair; use crate::hostname::generate_hostname; use std::ffi::CString; use std::path::PathBuf; use std::os::unix::io::RawFd; #[derive(Clone)] pub struct ContainerOpts { pub path: CString, pub argv: Vec<CString>, pub uid: u32, pub mount_dir: Path...
use crate::{ component::UserInterfaceView, resource::{ApplicationData, UserInterface}, ui_theme_asset_protocol::UiThemeAsset, }; use core::{ app::AppLifeCycle, assets::{asset::AssetId, database::AssetsDatabase}, ecs::{Comp, ResRead, ResWrite, Universe, UnsafeRef, UnsafeScope, WorldMut, WorldRef}...
use std::fs::{create_dir_all, read_dir, remove_file, File, OpenOptions}; use std::io::{Read, Write}; use std::str::FromStr; use chrono::prelude::Utc; use crossbeam::queue::SegQueue; use uuid::Uuid; use crate::types::body::{IngestBody, IngestBodyBuffer, IntoIngestBodyBuffer}; use crate::Offset; use metrics::Metrics; u...
use maud::{html, Markup, PreEscaped, Render}; use crate::http_server::templates::LOGO_SVG; pub fn head() -> Markup { let temporary_remove_service_worker_script = r#" navigator.serviceWorker.getRegistrations().then(function(registrations) { for(let registration of registrations) { registr...
/* * 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. */ use std::borrow::Borrow; use std::fmt::Debug; use std::hash::Hash; use std::marker::PhantomData; use smallvec::SmallVec; pub co...
use std::{ env::{args, Args}, io::{stdin, stdout, BufRead, Lines, Stdin, StdinLock, Stdout, Write}, process::exit, }; fn main() { let mut find_mode: bool = true; let mut case_insensitive: bool = false; let string: String = { let mut string: Option<String> = None; { ...
#[doc = "Reader of register RTC_TIME"] pub type R = crate::R<u32, super::RTC_TIME>; #[doc = "Writer for register RTC_TIME"] pub type W = crate::W<u32, super::RTC_TIME>; #[doc = "Register RTC_TIME `reset()`'s with value 0x0100_0000"] impl crate::ResetValue for super::RTC_TIME { type Type = u32; #[inline(always)]...
use multiversion::multiversion; #[multiversion(targets("x86_64+avx", "x86+avx", "x86+sse", "aarch64+neon",))] pub fn pub_add(a: &mut [f32], b: &[f32]) { a.iter_mut().zip(b.iter()).for_each(|(a, b)| *a += b); } #[multiversion(targets("x86_64+avx", "x86+avx", "x86+sse", "aarch64+neon",))] fn priv_add(a: &mut [f32],...
/* * 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 */ /// HttpLogError : Invalid query performed. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)...
// Copyright 2014-2015 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-MI...
use std::io; use std::net; use crate::model::{Error, ErrorKind}; pub trait PktStream { fn pkt_size(&self) -> usize; fn recv_pkt(&mut self) -> Result<&[u8], Error>; fn send_pkt(&self, pkt: &[u8]) -> Result<(), Error>; } pub struct UdpPktStream { pkt_size: usize, socket: net::UdpSocket, buf: Ve...
use std::io; use std::io::prelude::*; use std::fs::File; use std::collections::HashMap; fn main() -> io::Result<()> { let mut f = File::open("input")?; let mut input = String::new(); f.read_to_string(&mut input)?; part1(&input); part2(&input); Ok(()) } fn part1(input: &str) { let mut cou...
//! Helper for incoming pieces requests. //! //! Handle (i.e. answer) incoming pieces requests from a remote peer received via //! `RequestResponsesBehaviour` with generic [`GenericRequestHandler`]. use crate::request_handlers::generic_request_handler::{GenericRequest, GenericRequestHandler}; use parity_scale_codec::{...
#![feature(proc_macro_hygiene, decl_macro)] #[macro_use] extern crate rocket; pub mod libs;
pub trait RunMain{ fn run(); }
use std::str::CharIndices; use std::iter::Peekable; #[derive(PartialEq, Debug)] pub enum Token<'a> { Eof, Punctuator(Punctuator, usize, usize), Name(&'a str, usize, usize), IntValue(&'a str, usize, usize), FloatValue(&'a str, usize, usize), StringValue(&'a str, usize, usize), } #[derive(PartialEq, Debug)...
use specs::{Entities, Join, Read, ReadStorage, System, Write, WriteStorage}; use components::*; use resources::*; pub struct BomberSystem { } impl BomberSystem { pub fn new() -> Self { BomberSystem { } } } impl<'a> System<'a> for BomberSystem { type SystemData = ( Read<'a, DeltaT...
#[macro_export] macro_rules! dot_product { ($x:expr, $y:expr) => ( $x.0 * $y.0 + $x.1 * $y.1 ); } #[cfg(test)] mod tests { #[test] fn happy_path() { assert_eq!(dot_product!((-1, 2), (3, -4)), -11) } }
// Utility functions for rot module to do its stuff. use std::ffi::OsStr; use std::path::Path; /// Gives back the output directory path to the new transformed file. /// `instance_path` signifies the original path to the file that was encrypted / decrypted. pub fn parse_to_path(outdir: &str, filename: &str, instance_pa...
/* * Copyright (C) 2019-2021 TON Labs. All Rights Reserved. * * Licensed under the SOFTWARE EVALUATION License (the "License"); you may not use * this file except in compliance with the License. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed...
// q0111_minimum_depth_of_binary_tree struct Solution; use crate::util::TreeNode; use std::cell::RefCell; use std::rc::Rc; impl Solution { pub fn min_depth(root: Option<Rc<RefCell<TreeNode>>>) -> i32 { if let Some(rrc) = root { match (&rrc.borrow().left, &rrc.borrow().right) { ...
use maxminddb::Reader; use simple_irc::Prefix; use crate::config::Server; use crate::geoip_response; use crate::irc_state::IrcState; pub struct PrivMsgRequest<'a> { pub server: &'a Server, pub irc_state: &'a IrcState, pub user: &'a Prefix, pub source: &'a String, pub message: &'a String, } pub st...
// Copyright 2018 Steven Bosnick // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE-2.0 or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except accord...
use apllodb_shared_components::SqlType; use serde::{Deserialize, Serialize}; use super::{column_definition::ColumnDefinition, column_name::ColumnName}; /// Column with data type. #[derive(Clone, Eq, PartialEq, Hash, Debug, Serialize, Deserialize, new)] pub struct ColumnDataType { column: ColumnName, sql_type:...
#[macro_use] extern crate serde_default; #[derive(Debug, DefaultFromSerde, PartialEq, Eq)] pub struct MyStruct { // This field is renamed to make sure serde_default is properly ignoring // other serde fields #[serde(rename = "foo", default = "field_1_default")] field1: u16, // This field is using t...
// 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. //! Main Overnet functionality. #![deny(missing_docs)] #[macro_use] extern crate failure; #[cfg(test)] extern crate timebomb; #[macro_use] extern crate l...
use std::convert::TryInto; use num_derive::FromPrimitive; use num_enum::IntoPrimitive; use num_traits::FromPrimitive; use bytes::{ Bytes, Buf, BytesMut, BufMut }; #[derive(FromPrimitive, IntoPrimitive, Debug, PartialEq, Copy, Clone)] #[repr(u8)] pub enum Type { NodeInfoReceived = 0x84, NodeInfoRe...
use std::env; fn main() { let target = env::var("TARGET").unwrap(); let board = target.split('-').nth(1).unwrap(); let cpu = "cortex-m3"; println!("cargo:rustc-cfg=target_board=\"{}\"", board); println!("cargo:rustc-cfg=target_cpu=\"{}\"", cpu); }
use scan_fmt::*; #[derive(Hash,Ord,PartialOrd,Eq,PartialEq)] struct Point(i32,i32,i32,i32); fn manhattan(Point(x0,y0,z0,w0): &Point, Point(x1,y1,z1,w1): &Point) -> i32 { (x0-x1).abs() + (y0-y1).abs() + (z0-z1).abs() + (w0-w1).abs() } fn parse(input: &str) -> Vec<Point> { input .lines() .map(|...
use crate::{ common::{CurrentCell, LazyLoadCellOutput}, cost_model::instruction_cycles, syscalls::{ build_tx, Debugger, LoadCell, LoadCellByField, LoadInputByField, LoadTx, LoadTxHash, }, ScriptError, }; use ckb_core::cell::{CellMeta, ResolvedTransaction}; use ckb_core::script::{Script, ALWA...
/** * cargo new ep1 * cd C:\Users\むずでょ\OneDrive\ドキュメント\practice-rust\concurrency\ep1 * cargo check --example input * cargo build --example input * cargo run --example input */ use std::io; fn main() { let mut line = String::new(); // コマンド プロンプトからの入力があるまで待機します。 io::stdin() .read_line(&mut lin...
//! Program state processor use crate::{error::MoebiusError, instruction::MoebiusInstruction, state::Moebius}; use num_traits::FromPrimitive; use solana_program::{ account_info::{next_account_info, AccountInfo}, decode_error::DecodeError, entrypoint::ProgramResult, info, instruction::{AccountMeta, ...
#![allow(non_snake_case)] #![allow(unused_imports)] #![allow(unused_variables)] #![allow(dead_code)] use std::fs::*; use std::io::Write; use clap::*; use indicatif::{ProgressBar, ProgressStyle}; use string_builder::Builder; mod GCode; use GCode::*; mod Util; use Util::*; mod Translator; use Translator::*; mod Transla...
// This file is part of rdma-core. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/rdma-core/master/COPYRIGHT. No part of rdma-core, including this file, may be copied, modified, propagated, or distributed ...
#[doc = "Register `M4FAR` reader"] pub type R = crate::R<M4FAR_SPEC>; #[doc = "Field `FDATAH` reader - Failing data high (64-bit memory)"] pub type FDATAH_R = crate::FieldReader<u32>; impl R { #[doc = "Bits 0:31 - Failing data high (64-bit memory)"] #[inline(always)] pub fn fdatah(&self) -> FDATAH_R { ...
fn counting_sort( mut data: Vec<usize>, min: usize, max: usize, ) -> Vec<usize> { // create and fill counting bucket with 0 let mut count: Vec<usize> = Vec::with_capacity(data.len()); count.resize(data.len(), 0); for num in &data { count[num - min] = count[num - min] + 1; } ...
use bellman::groth16; use bls12_381::Bls12; use ff::Field; use group::Group; use rand::rngs::OsRng; use std::collections::HashMap; use std::io; use crate::crypto::{ coin::Coin, create_mint_proof, create_spend_proof, load_params, merkle::CommitmentTree, note::{EncryptedNote, Note}, save_params, schn...
use dialoguer::{console::style, theme::ColorfulTheme}; use indicatif::ProgressStyle; use lazy_static::{initialize, lazy_static}; #[cfg(target_os = "windows")] lazy_static! { pub static ref THEME: ColorfulTheme = ColorfulTheme { prompt_suffix: style(">".to_string()).for_stderr().black().bright(), ac...
use byteorder::{BigEndian, ByteOrder, LittleEndian, NativeEndian}; use packed::{Aligned, Packed, Unaligned}; use pod::Pod; use core::cmp::Ordering; use alloc::fmt; use core::hash::{Hash, Hasher}; use core::marker::PhantomData; use uninitialized::uninitialized; /// A type alias for unaligned little endian primitives pu...
mod linked_list; use linked_list::List; fn main() { let mut a: List<i32> = List::new(); a.prepend(45); let ret = a.take_head(); println!("{:?}", ret); }
use actix_web::http::StatusCode; use url::Url; mod support; #[actix_rt::test] async fn redirects_root_url() { // Arrange let address = support::spawn_app(Url::parse("http://example.com/").unwrap()); // Act let response = support::client() .get(&format!("{}/", &address)) .send() ...
//! Defines types and traits related to transposition tables. use std::cmp::min; use moves::{Move, MoveDigest}; use value::*; use depth::*; use search_node::SearchNode; /// `BOUND_EXACT`, `BOUND_LOWER`, `BOUND_UPPER`, or `BOUND_NONE`. /// /// For the majority of chess positions our evaluations will be more /// or le...
// A fource that can be applied. pub enum Force { Probe }
mod error; mod multi; mod value; pub use self::error::{DocumentError, DocumentErrorKind}; pub use self::multi::MultiValue; pub use self::value::Value; use failure::ResultExt; use std::collections::HashMap; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Document { #[serde(flatten)] pub values: HashM...
pub mod body; pub mod cell; pub mod observation; pub mod position; use log::{error, warn}; use rand::Rng; use std::ops::Range; pub use body::*; pub use cell::*; pub use observation::*; pub use position::*; use super::entity::*; use super::entity_type::*; pub use crate::position::{Coord, Dir, Position}; use crate::Me...
#[doc = "Reader of register CH_AL3_CTRL"] pub type R = crate::R<u32, super::CH_AL3_CTRL>; impl R {}
use std::fs::File; use std::io::{self, BufReader, Write}; use std::net::{SocketAddr, TcpStream}; use std::path::PathBuf; use super::protocol::{self, ProtocolConnection}; use anyhow::{anyhow, bail, Context}; trait LoadFile { fn file_state(&mut self) -> &mut Option<File>; fn filename_state(&mut self) -> &mut O...
pub trait AsShellCommand { fn as_shell_command(&self) -> String; } pub trait AsShellArg { fn as_shell_arg(&self) -> String; }
use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion}; pub fn string_width(c: &mut Criterion) { let mut group = c.benchmark_group("string_width"); for size in [1 << 8, 1 << 15, 1 << 22] { group.bench_with_input( BenchmarkId::from_parameter(format!("tabled-{size...
pub struct Mass { fuel: u32, } impl Mass { pub fn new(mass: u32) -> Mass { Mass { fuel: mass } } pub fn burn_baby(&mut self) -> u32 { let mut total = 0; for cur_fuel in self.next() { total += cur_fuel; } return total; } } impl Iterator for Mass { type Item = u32; fn next(&mu...
use mail::email_service::send_email; static SENDER: &str = "pawanbisht62@gmail.com"; static RECEIVER: &str = "pawan.bisht@knoldus.in"; fn main() { println!("{}", send_email(SENDER, RECEIVER)); }
pub mod display; #[derive(Debug)] pub struct ViewPort { pub x1: isize, pub y1: isize, pub width: usize, pub height: usize, }
#[doc = "Reader of register TXOICR"] pub type R = crate::R<u32, super::TXOICR>; #[doc = "Reader of field `TXOICR`"] pub type TXOICR_R = crate::R<bool, bool>; impl R { #[doc = "Bit 0 - Clear-on-read transmit FIFO overflow interrupt"] #[inline(always)] pub fn txoicr(&self) -> TXOICR_R { TXOICR_R::new(...
fn main() { let x: Vec<&str> = vec![ "md", "exe", "txt" ]; let ext = "mdw"; println!("{:?}", x.contains(&ext)); }
use std::fmt::{Show, Formatter, Result}; use std::char; #[deriving(Clone, PartialEq, Show)] pub enum TokenType { Identifier, Period, Bang, Question, Comma, Colon, Semicolon, Bit_And, Bit_Or, Bit_Negate, Add_Op, Min_Op, Mult_Op, Div_Op, Mod_Op, Power_O...
//! Bindings for Unix Domain Sockets and futures //! //! This crate provides bindings between `mio_uds`, the mio crate for Unix //! Domain sockets, and `futures`. The APIs and bindings in this crate are very //! similar to the TCP and UDP bindings in the `futures-mio` crate. This crate //! is also an empty crate on Win...
use std::{any::Any, fmt::Display}; use pasture_core::{ math::AABB, meta::Metadata, nalgebra::{Vector3, Vector4}, }; /// Metadata for .pnts files. Contains the PNTS global semantics #[derive(Clone, Debug)] pub struct PntsMetadata { points_length: usize, rtc_center: Option<Vector3<f32>>, quantiz...
#![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 ServicesProperties { #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] ...
use serde::{Deserialize}; use warp::{ http::{Response}, Filter, }; use std::process::Command; use std::process::Stdio; // use std::env; use std::path::Path; // use std::io::{self, Write}; #[derive(Deserialize)] struct GitRepo{ repo_url: String, repo_name: String, } #[tokio::main] async fn main(){ ...
use super::Scheduler; #[async_trait] pub trait SchedulerRepository { async fn find(&self) -> anyhow::Result<Option<Scheduler>>; async fn save(&self, scheduler: Scheduler) -> anyhow::Result<()>; }
extern crate serde; extern crate serde_json; use std::sync::{Arc, Mutex}; use std::io::Read; use iron::{Handler, status, IronResult, Response, Request, AfterMiddleware}; use iron::headers::ContentType; use database::Database; use router::Router; use model::Post; use std::error::Error; use uuid::Uuid; use model; macr...
pub mod api; pub mod contract; pub mod schema; pub mod transactions; pub mod service; pub mod runner; pub use schema::Schema; pub use service::{Service, ServiceFactory}; pub use crate::proto::lvm as proto;
struct Computer { memory: Vec<isize>, ip: usize, } fn read_stdin() -> isize { let mut buffer = String::new(); std::io::stdin().read_line(&mut buffer).expect("STDIn read failed."); buffer.trim().parse::<isize>().unwrap() } fn write_stdout(number: isize) { println!("{}", number); } impl Comput...
pub mod method; pub mod query_string; pub mod request; pub mod response; pub mod status_code; pub use method::{MethodErr, Methods}; pub use query_string::{QueryString, Values as QueryStringVal}; pub use request::ParseError; pub use request::Request; pub use response::Response; pub use status_code::StatusCode;