text
stringlengths
8
4.13M
//! This module contains various synchronization primitives. use std::borrow::Borrow; use std::error; use std::fmt; use std::sync::Arc; use std::sync::atomic::Ordering; use std::thread::{self, Thread}; use std::time::{Duration, Instant}; pub use self::any::Any; pub use self::all::All; pub mod atomic; mod any; mod all...
pub mod config; pub mod state; pub mod theme_setting;
use ndarray::{Array, IxDyn}; use std::ops::{Deref, DerefMut}; // use super::super::super::{Device, Memory, TransferDirection}; // use super::super::super::error::Result; use super::NativeDevice; use super::super::super::compute_device::ComputeDevice; use super::super::super::memory::Memory; /// A newtype (with an in...
extern crate unrar; use unrar::Archive; use std::path::Path; use std::env; fn main() { let _args: Vec<String> = env::args().collect(); if _args.len()<2 { println!("USAGE: {} [input_rar_name*]",&_args[0]); println!(" * means required"); std::process::exit(1); } let fi...
/* * Simple number guessing game I made using the tutorial at * https://doc.rust-lang.org/stable/book/ch02-00-guessing-game-tutorial.html */ use std::io; use std::cmp::Ordering; use rand::Rng; fn main() { // Generates random number between 0 and 100, thread_rng is the generator we're using let number = r...
use std::path::Path; #[derive(Debug)] enum Error { Fuck, } fn spawn_plugin(path: impl AsRef<Path>) { } fn main() -> Result<(), Error> { Err(Error::Fuck) }
use std::{fs::{self, File}, collections::{HashMap}, hash::{Hash, Hasher}, io::{BufReader, BufRead}, cmp::max}; use block::{Block, CodeLocation, Branch}; use draw::Color; use fps::FpsCounter; use graph::{make_method_graph, call_graphviz_command_line, call_graphviz_in_new_thread, Promise}; use itertools::Itertools; us...
use std::collections::HashSet; // Remove the listed packages and their dependencies pub fn remove_packages<'a>(packages_to_remove: HashSet<&'a str>) -> Vec<i32> { vec![0] }
extern crate advent_of_code_2017_day_5; use advent_of_code_2017_day_5::*; static EXAMPLE_INPUT: &'static str = "0\n3\n0\n1\n-3\n"; #[test] fn part_1_example() { assert_eq!(solve_puzzle_part_1(EXAMPLE_INPUT), "5"); } #[test] fn part_2_example() { assert_eq!(solve_puzzle_part_2(EXAMPLE_INPUT), "10"); }
use std::marker::PhantomData; use super::Pusherator; variadics::variadic_trait! { /// A variadic list of Pusherators. pub variadic<T> PusheratorList where T: Pusherator {} } pub struct Demux<Func, Nexts, Item> { func: Func, nexts: Nexts, _phantom: PhantomData<fn(Item)>, } impl<Func, Nexts, Item> ...
use crate::types::{draft_version::DraftVersion, schema::Schema, schema_error::SchemaError, scope::Scope}; use json_trait_rs::JsonType; #[cfg(test)] use json_trait_rs::RustType; use loader_rs::{LoaderError, LoaderTrait}; use std::{collections::HashMap, sync::Arc}; use url::Url; use uuid::Uuid; #[derive(Debug)] pub(in c...
fn bouncing_ball(h: f64, bounce: f64, window: f64) -> i32 { // h must be greater than 0 if !(h > 0.0) { return -1; } // bounce must be between 0 and 1 if !(0.0 < bounce && bounce < 1.0) { return -1; } // window must be between 0 and h if !(0.0 < window && window < h) { return -1; } let mut count = 1; ...
use rand::{prelude::*}; use rand_xorshift::XorShiftRng; use approx::*; use crate::{prelude::*, transform::*, Complex, Quaternion, random::Unit}; const SAMPLE_ATTEMPTS: usize = 256; #[test] fn chaining() { let mut rng = XorShiftRng::seed_from_u64(0xBEEF0); for _ in 0..SAMPLE_ATTEMPTS { let a: Moebius...
use std::borrow::Cow; use std::sync::Arc; use std::time::Instant; use discorsd::{async_trait, BotState}; use discorsd::commands::*; use discorsd::errors::BotError; use discorsd::http::channel::embed; use crate::Bot; #[derive(Copy, Clone, Debug)] pub struct PingCommand; #[async_trait] impl SlashCommand for PingComma...
use std::fmt::{Debug, Formatter}; use ndarray::{Array1, Array2}; pub type TransferFn = fn(&Array2<f32>, &Array1<f32>, &Array1<f32>) -> Array1<f32>; #[derive(Copy, Clone)] pub struct Transfer { transfer_fn: TransferFn, } impl Debug for Transfer { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { ...
use predicates::prelude::Predicate; use predicates::str::contains; use short::BIN_NAME; use test_utils::init; use test_utils::{HOME_CFG_FILE, PRIVATE_ENV_DIR, PROJECT_CFG_FILE}; mod test_utils; #[test] fn cmd_pdir() { let mut e = init("cmd_env_pdir"); e.add_file( PROJECT_CFG_FILE, r#" setups:...
use std::cell::RefCell; use std::future::Future; use std::rc::Rc; use bytes::BytesMut; use futures_channel::{mpsc, oneshot}; use futures_util::StreamExt; use js_sys::{ArrayBuffer, Uint8Array}; use rsocket_rust::frame::Frame; use rsocket_rust::transport::Transport; use rsocket_rust::utils::Writeable; use rsocket_rust::...
use log::debug; use log::{error, info}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::fs::File; use std::io::{Read, Write}; #[derive(Debug)] pub struct RecoverEntry { pub hash: String, pub last_checked: chrono::DateTime<chrono::Utc>, } impl RecoverEntry { pub fn waited_enoug...
#![doc = "generated by AutoRust 0.1.0"] #![allow(unused_mut)] #![allow(unused_variables)] #![allow(unused_imports)] use crate::models::*; use reqwest::StatusCode; use snafu::{ResultExt, Snafu}; pub mod capacities { use crate::models::*; use reqwest::StatusCode; use snafu::{ResultExt, Snafu}; pub async f...
fn main() { println!("Hello, world!"); another_func(); func_param(8); func_param_type(9, 7.8); func_contain_statements_expressions(); func_return(); } fn another_func() { println!("Another function!"); } fn func_param(x: i32) { println!("The value of x is: {}", x); } fn func_param_typ...
// 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 device layer. pub mod arp; pub mod ethernet; use std::collections::HashMap; use std::fmt::{self, Debug, Display, Formatter}; use device::etherne...
use color_eyre::{eyre::Context, Report}; use log::LevelFilter; use simplelog::{ConfigBuilder, TermLogger, TerminalMode, WriteLogger}; use std::fs::OpenOptions; use std::path::PathBuf; use tracing::instrument; #[derive(Clap, Debug)] pub struct Logging { /// Log file (stdout if not present) #[clap(long, short, p...
pub struct BinGen { seed: u8, len: usize, } impl BinGen { pub fn new(seed: u8, len: usize) -> Self { Self { seed, len } } pub fn generate(&self) -> impl Iterator<Item = u8> { let mut state = self.seed; (0..self.len).map(move |index| { state = state.wrapping_mul(...
///// chapter 4 "structuring data and matching patterns" ///// program section: // fn main() { struct Score(i32, u8); let score = Score(73, 2); ///// destructure the tuple // let Score(h, l) = score; println!("health {} - level {}", h, l); } ///// output should be: /* */// end of output
use std::io; use std::str::FromStr; use std::time::Duration; use crate::message::CommMessage; use std::collections::{HashMap, HashSet}; use std::net::{SocketAddr, TcpStream, AddrParseError}; use serde::{Serialize, de::DeserializeOwned}; use crate::message; use derive_more::{From, Error, Display}; #[derive(From, Error...
// 给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。 // 如果不存在最后一个单词,请返回 0 。 // 说明:一个单词是指由字母组成,但不包含任何空格的字符串。 // 示例: // 输入: "Hello World" // 输出: 5 // struct Solution{} impl Solution { pub fn length_of_last_word(s: String) -> i32 { let list: Vec<&str> = s.split_whitespace().collect(); let length: usize = l...
extern crate num; extern crate rand; extern crate rustc_serialize; use std::error::Error; use std::io::Write; use std::ops::{BitOrAssign, Shl}; use rand::SeedableRng; pub type MyRng = rand::isaac::Isaac64Rng; #[macro_export] #[cfg(debug_assertions)] macro_rules! ix { ( $v:expr , $i:expr ) => ($v[$i]) } #[macro_...
use alloc::rc::Rc; use alloc::string::String; use alloc::vec::Vec; use core::cell::RefCell; use serde::Deserialize; use serde_json::Value as Json; #[derive(Clone, Debug, PartialEq, Eq, Deserialize)] #[serde(rename_all = "lowercase")] pub enum PluginType { #[serde(skip)] Unknown, Library, #[cfg(featu...
use std::result; use base64::{engine::general_purpose::STANDARD, Engine}; use serde::{Deserialize, Serialize}; use crate::algorithms::Algorithm; use crate::errors::Result; use crate::jwk::Jwk; use crate::serialization::b64_decode; /// A basic JWT header, the alg defaults to HS256 and typ is automatically /// set to ...
#[doc = "Reader of register GEOMETRY_SUPERVISORY"] pub type R = crate::R<u32, super::GEOMETRY_SUPERVISORY>; #[doc = "Reader of field `WORD_SIZE_LOG2`"] pub type WORD_SIZE_LOG2_R = crate::R<u8, u8>; #[doc = "Reader of field `PAGE_SIZE_LOG2`"] pub type PAGE_SIZE_LOG2_R = crate::R<u8, u8>; #[doc = "Reader of field `ROW_CO...
pub use super::amazon_aws::AmazonAws; pub use super::http_bin::HttpBin; pub use super::if_config::IfConfig; pub use super::IpAddrClient;
//! ## Usage //! //! ```rust //! use std::sync::Arc; //! use cita_trie::MemoryDB; //! use cita_trie::{PatriciaTrie, Trie}; //! use cita_trie::Keccak256Hash; //! fn main() { //! let memdb = Arc::new(MemoryDB::new(true)); //! //! let key = "test-key".as_bytes(); //! let value = "test-value".as_bytes(); //! ...
// Copyright (c) 2017 The Noise-rs Developers. // // 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 http://opensource.org/licenses/MIT>, at your option. All files in the // project carrying such notice may not be cop...
// q0101_symmetric_tree struct Solution; use crate::util::TreeNode; use std::cell::RefCell; use std::rc::Rc; impl Solution { pub fn is_symmetric(root: Option<Rc<RefCell<TreeNode>>>) -> bool { if let Some(t) = root { return Solution::symmetric(&t.borrow().left, &t.borrow().right); } el...
extern crate arrayfire; use arrayfire::*; /** * Layer struct. * * Makes sure that the datastructure can be treated as a Layer in a Neural Network. * This means that it needs to implement a training strategy. * * In this case, it will be training using backpropagation and the adam optimizer. */ pub trait Layer...
//! # Iron CMS //! CMS based on Iron Framework for **Rust**. #[macro_use] extern crate iron; #[macro_use] extern crate router; #[macro_use] extern crate maplit; #[macro_use] extern crate diesel; extern crate handlebars_iron as hbs; extern crate handlebars; extern crate rustc_serialize; extern crate staticfile; extern c...
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. //! Contains common error types for prover and verifier. use core::fmt; // PROVER ERROR // =============================================...
use hyper::{Response, Request, Client, Body}; use std::result::Result; use crate::proxy::proxy_handler::tunnel; type HttpClient = Client<hyper::client::HttpConnector>; mod host_addr; use host_addr::host_addr; pub async fn https_request(_client: HttpClient, acceptor: tokio_rustls::TlsAcceptor, req: Request<Body>) -> R...
use diesel::mysql::MysqlConnection; use diesel::Connection; use dotenv::dotenv; use std::env; pub fn establish_connection() -> MysqlConnection { dotenv().ok(); let database_host = env::var("DATABASE_HOST"); let database_name = env::var("DATABASE_NAME"); let database_user = env::var("DATABASE_USER"); ...
mod dto; pub use self::dto::*; use actix_files as fs; use actix_web::{http, web, App, HttpMessage, HttpRequest, HttpResponse, Responder, Scope}; use crate::auth::roles::*; use crate::auth::{assert_roles, Claims, KeycloakCache}; use crate::business as bus; use crate::database::*; //use futures::future::Future; /...
#[doc = "Reader of register HOST_CTL1"] pub type R = crate::R<u32, super::HOST_CTL1>; #[doc = "Writer for register HOST_CTL1"] pub type W = crate::W<u32, super::HOST_CTL1>; #[doc = "Register HOST_CTL1 `reset()`'s with value 0x83"] impl crate::ResetValue for super::HOST_CTL1 { type Type = u32; #[inline(always)] ...
use std::env; use std::fs::File; use std::io; use std::io::prelude::*; use std::io::BufWriter; use std::io::{stdout, BufReader}; use std::os::unix::ffi::OsStrExt; use std::path::{Path, PathBuf}; use structopt::StructOpt; fn main() { let config: Config = Config::from_args(); concatenate_and_print_image(config)...
use crate::vpn::util::ConnectionProtocol; use structopt::StructOpt; mod configure; mod connect; mod initialize; pub use configure::configure; pub use connect::connect; pub use initialize::initialize; /// An enum for all the cli's subcommands /// /// The enum options correspond one to one with ALL features of the cli...
pub mod built_info; pub mod client; pub mod config; pub mod sockets;
//! The types described by the GTP specification. //! They have an ever growing collection //! of useful methods to manipulate them. //! The most interesting should currently be the conversions //! to more usual data types of Rust. use super::data::*; /// An unsigned integer of 31 bits. /// /// The spec says: /// > A...
use logpack_derive::Logpack; use serde_derive::Deserialize; use hexdump::HexReader; use ansi_term::{ANSIString, ANSIStrings}; use ron::ser::{to_string}; use ron::de::{from_str}; use std::fmt::Debug; use std::io::BufRead; #[derive(Logpack, Debug, Eq, PartialEq, Deserialize)] pub struct GenericType<T> { test: T, ...
// TODO(mingwei): fix line numbers in tests // https://github.com/hydro-project/hydroflow/issues/729 // https://github.com/rust-lang/rust/pull/111571 use std::cell::RefCell; use std::rc::Rc; use hydroflow::scheduled::graph::Hydroflow; use hydroflow::util::collect_ready; macro_rules! test_warnings { ( $hf...
use std::{ cmp::Reverse, collections::{BinaryHeap, HashMap, HashSet}, sync::Arc, }; use itertools::Itertools; use maplit::hashset; use ruma_common::MilliSecondsSinceUnixEpoch; use ruma_events::{ room::{ member::{MemberEventContent, MembershipState}, power_levels::PowerLevelsEventContent...
use indicatif::{ProgressBar, ProgressStyle}; use serde::Deserialize; use std::collections::HashMap; use std::env; use std::error::Error; use std::fmt; use std::fs::{create_dir, File}; use std::io::copy; use std::path::Path; #[derive(Deserialize, Debug)] struct Emoji { ok: bool, emoji: HashMap<String, String>, ...
use serde::{Deserialize, Serialize}; use sqlx::FromRow; #[derive(FromRow, Deserialize, Serialize)] pub struct Data { pub county_id: i16, pub state_id: i16, pub value: f64, }
//! This is a simple chat program (server and client). use std::sync::mpsc::channel; use std::thread; mod input; mod protocol; mod state; /// Print the welcome banner, spawn the input thread, and start the state machine. fn main() { println!(" Example Chat v{}", env!("CARGO_PKG_VERSION")); println!(" Try /c...
#![no_std] // don't link the Rust standard Library #![no_main] // disable all Rust-level entry points #![feature(custom_test_frameworks)] #![test_runner(rust_os::test_runner)] #![reexport_test_harness_main = "test_main"] use core::panic::PanicInfo; use rust_os::println; #[no_mangle] //don't mangle the name of this fu...
use rex_regex as rex; fn bench_complicated() { let re_s = "^[hH][eE]l+o +[Ww]orld!?$"; let re = rex::compile(re_s).unwrap(); let inputs = vec![ "Hello World", "hEllo world!", "HEllllllo world", "Helllllllllo world!", ]; let size = inputs.len(); println!("{...
// This file is part of Substrate. // Copyright (C) 2017-2020 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 // 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 F...
use crate::{ hir::Var, ty::{FnType, PrimitiveType, Type}, }; use std::fmt::Display; #[derive(Debug, Clone, PartialEq, Eq)] pub enum Builtin { Type { name: &'static str, ty: PrimitiveType, }, Fn { name: &'static str, ty: FnType, }, } impl Builtin { pub fn loo...
use actix_web::{HttpResponse, web}; use crate::DB::DB; use std::sync::Mutex; #[path = "img_utls.rs"] mod img_utls; pub async fn save_file(data: web::Data<Mutex<DB>>,mut parts: awmp::Parts) -> HttpResponse { let file_data = parts.files.take("file").pop().unwrap(); let title = String::from(*parts.texts.as_hash_...
pub mod binary_resource_file;
mod opcodes; #[cfg(test)] mod cpu_tests; pub struct CPU<'a> { pub accumulator: u8, pub status: Status, pub program_counter: u16, pub stack_pointer: u16, pub register_x: u8, pub register_y: u8, memory: [u8; 0xFFFF], opcode_table: [opcodes::Opcode<'a>; 0xFF], } #[derive(Debug, Clone, Co...
pub mod classification; pub mod regression; pub mod miscelanous; mod tests;
//! A collection of line-drawing algorithms for use in graphics and video games. //! //! Currently implemented: //! //! * [`Bresenham`] - An implementation of [Bresenham's line algorithm]. //! * [`Bresenham3d`] - A 3-Dimensional implementation of bresenham. //! * [`BresenhamCircle`] - Bresenham's circle algorithm. //! ...
//! A simple RPC library to be used together with `prost` for defining type-safe RPC services. //! //! This library lets you generate traits for implementing a generic RPC mechanism using Protobuf as //! the schema language. You have to supply your own underlying transport mechanism, for example //! WebSockets, UNIX p...
pub trait Solve<T> { type Output; fn solve(input: T) -> Self::Output; }
#[doc = "Reader of register PWR_MPUCR"] pub type R = crate::R<u32, super::PWR_MPUCR>; #[doc = "Writer for register PWR_MPUCR"] pub type W = crate::W<u32, super::PWR_MPUCR>; #[doc = "Register PWR_MPUCR `reset()`'s with value 0"] impl crate::ResetValue for super::PWR_MPUCR { type Type = u32; #[inline(always)] ...
use solve::infer::InferenceTable; use solve::infer::ucanonicalize::UniverseMap; use std::fmt::{Debug, Error, Formatter}; use solve::slg::{ExClause, TableIndex}; use solve::slg::on_demand::table::AnswerIndex; crate struct Strand { crate infer: InferenceTable, pub(super) ex_clause: ExClause, /// Index into...
use crate::{ errors::{ConfigError, Error}, PeerId, DEFAULT_SEND_BUFFER, }; use ckb_logger::info; use p2p::{ multiaddr::{Multiaddr, Protocol}, secio, }; use rand; use rand::Rng; use serde::{Deserialize, Serialize}; use std::fs; use std::io::Read; use std::io::Write; use std::path::PathBuf; #[derive(Clon...
use kagura::prelude::*; pub fn span(text: impl Into<String>) -> Html { Html::span(Attributes::new(), Events::new(), vec![Html::text(text)]) } pub fn div(text: impl Into<String>) -> Html { Html::div(Attributes::new(), Events::new(), vec![Html::text(text)]) }
use std::fs::File; use std::io::{self, prelude::*, BufReader}; fn calc(operation: usize, cursor: usize, program: &mut Vec<usize>) { // Determine first, second and third values let op1 = program[program[cursor + 1]]; let op2 = program[program[cursor + 2]]; let pos = program[cursor + 3]; let res = m...
#![no_std] #![allow(non_camel_case_types, non_snake_case, non_upper_case_globals)] #![crate_type = "rlib"] #[macro_use] extern crate bitflags; extern crate block; extern crate cocoa; extern crate core_foundation; extern crate core_graphics; extern crate libc; #[macro_use] extern crate objc; mod classes; mod constants...
use crate::admin::*; use actix_web::{get, post, web, HttpResponse, HttpRequest, Responder, Error as ActixError}; use sqlx::{Postgres, Pool}; use serde::{Serialize, Deserialize}; use futures::future::{ready, Ready}; use crate::utils::validate_credentials; use crate::middlewares::auth::create_jwt; // ADMIN apps in the...
// gui pub trait Draw { fn draw(&self); } pub struct Screen { pub components: Vec<Box<dyn Draw>>, } impl Screen { pub fn run(&self) { for component in self.components.iter() { component.draw(); } } } // 上面的实现可以是不同的只要实现了Deaw Trait就行 // 下面的实现方式只能是一种实现了Draw的类型 pub struct Scr...
use glium::{Frame, Program}; use std::time::Instant; use std::collections::{BTreeMap}; use crate::player::PlayerControlMessage; use crate::animation::ObjAnimation; use crate::draw::{basic_render, ObjDef, ObjDrawInfo, EnvDrawInfo}; use crate::interpolation::{InterpolationHelper, Interpolate}; pub struct PeerPlayer { p...
// 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::model::*, cm_rust::{self, ChildDecl, ComponentDecl, UseDecl, UseStorageDecl}, fidl::endpoints::Proxy, fidl_fuchsia_io::{Direct...
// error-pattern:assigning to upvar // Make sure that nesting a block within a lambda doesn't let us // mutate upvars from a lambda. fn main() { let i = 0; let ctr = lambda () -> int { block () { i = i + 1; }(); ret i; }; log_err ctr(); log_err ctr(); log_err ctr(); log_err ctr(); log_err ct...
#[doc = "Register `HSICFGR` reader"] pub type R = crate::R<HSICFGR_SPEC>; #[doc = "Register `HSICFGR` writer"] pub type W = crate::W<HSICFGR_SPEC>; #[doc = "Field `HSICAL` reader - HSI clock calibration Set by hardware by option byte loading during system reset nreset. Adjusted by software through trimming bits HSITRIM...
//! Wrappers around `HashMap` and `Vec` mapping to a respective type within tycho. //! //! //! These functions come in handy when creating objects/elements manually or want a specific //! serialisation target when using serde. pub use array::Array; pub use list::List; pub use map::Map; pub use struct_::Struct; pub use...
fn main() { let mut vv1: Vec<i32> = Vec::new(); vv1.push(11); vv1.push(22); vv1.push(33); // println!("{:?}", &vv1[100]); // panic 崩溃, 越界了 println!("{:?}", vv1.get(101)); // 越界取得 None }
/* [Running] cd "/home/hsuhau/GitHub/hsuhau/rust/src/15_rust_ownership/" && rustc 15_rust_ownership.rs && "/home/hsuhau/GitHub/hsuhau/rust/src/15_rust_ownership/"15_rust_ownership warning: unused variable: `v2` --> 15_rust_ownership.rs:6:8 | 6 | let v2 = v; | ^^ help: if this is intentional, prefix it w...
use bigint::U256; use errors::{Error, Result}; /// Size of a word in bytes const WORD_SIZE: usize = 32; pub struct Memory { bytes: Vec<u8>, } #[allow(dead_code)] /// Memory model used for the EVM impl Memory { pub fn new() -> Memory { Memory { bytes: Vec::new() } } pub fn size(&self) -> usiz...
fn main() { let mut big_bad_num: u64 = 600851475143; let mut i = 3; while big_bad_num % 2 == 0 { big_bad_num /= 2; } while big_bad_num > 1 { if big_bad_num % i == 0 { big_bad_num /= i; } else { i += 2; } } println!("{}", i) }
use chrono::{DateTime, Utc}; use common::result::Result; use crate::domain::publication::PublicationId; #[derive(Debug, Clone)] pub struct Item { publication_id: PublicationId, date: DateTime<Utc>, } impl Item { pub fn new(publication_id: PublicationId) -> Result<Self> { Ok(Item { pu...
extern crate colored; extern crate backtrace; extern crate rustyline; mod smew; use self::smew::source::*; use self::smew::lexer::*; use self::smew::parser::*; use self::smew::interpreter::*; use std::collections::HashMap; use rustyline::Editor; fn print(args: &Vec<Object>) -> Object { for arg in args { if le...
pub fn create_motionless_w(pos: ::na::Vector3<f32>, eraser: bool, world: &::specs::World) { create_motionless( pos, eraser, &mut world.write(), &mut world.write(), &mut world.write(), &mut world.write(), &mut world.write(), &mut world.write(), ...
#![allow(unused)] use std::fs::File; use std::io::Read; use scan_fmt::*; use std::{thread, time}; fn main() { let mut file = File::open("input").unwrap(); let mut buf = String::new(); file.read_to_string(&mut buf).unwrap(); let input = buf.lines(); let mut points: Vec<(i32,i32,i32,i32)> = input ...
use ipfs::{Ipfs, IpfsOptions, Ipld, Types}; use futures::join; use futures::{FutureExt, TryFutureExt}; fn main() { let options = IpfsOptions::<Types>::default(); env_logger::Builder::new().parse_filters(&options.ipfs_log).init(); tokio::runtime::current_thread::block_on_all(async move { // Start d...
use blake3::{hash, Hash}; use std::io::{stdin, BufRead, Result}; use std::time::Instant; const TOTAL_LINE_COUNT: usize = 46366321; fn main() -> Result<()> { let mut f = stdin().lock(); let mut buf = Vec::new(); let begin = Instant::now(); let mut i = 1; let mut accum = (0u128, 0u128); while l...
#![feature(associated_consts)] #![allow(non_camel_case_types)] use math::{vec2, Additive}; mod math; use std::cell::RefCell; use std::collections::{HashMap, HashSet}; use std::io; use std::ops::Deref; use std::rc::Rc; extern crate rayon; use rayon::prelude::*; extern crate sfml; use sfml::system::{Clock, Time, Ve...
mod base; pub use base::*; #[cfg(feature = "random")] mod random; #[cfg(feature = "random")] pub use random::*; #[cfg(all(test, feature = "random", feature = "approx"))] mod tests;
#![allow(non_snake_case)] #[allow(unused_imports)] use std::io::{self, Write}; #[allow(unused_imports)] use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque}; #[allow(unused_imports)] use std::cmp::{max, min, Ordering}; macro_rules! input { (source = $s:expr, $($r:tt)*) => { let...
use crate::{ datastructures::lua_set_native, eval::{LuaAllocator, LuaResult, LuaRunState, LV}, natives::LuaArgs, }; pub fn lua_string_format(_s: &LuaRunState, args: &LuaArgs) -> LuaResult { let base_string = args.get_string_arg(0)?; // TODO implement string format actually print!("CALLED FORMAT...
#[doc = "Register `I2C_ISR` reader"] pub type R = crate::R<I2C_ISR_SPEC>; #[doc = "Register `I2C_ISR` writer"] pub type W = crate::W<I2C_ISR_SPEC>; #[doc = "Field `TXE` reader - TXE"] pub type TXE_R = crate::BitReader; #[doc = "Field `TXE` writer - TXE"] pub type TXE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, ...
#[macro_use] extern crate serde_derive; extern crate docopt; use docopt::Docopt; #[macro_use] extern crate error_chain; extern crate bflib; use bflib::*; use std::fs::File; use std::path::Path; use std::io::{self, Read}; const USAGE: &'static str = " Usage: brainfuck [options] INPUT brainfuck (--help | --ve...
//! # Linux文件I/O //! //! //! use super::error::Error; use std::ffi::CString; use std::ffi::c_void; /// 定义文件描述符 pub type FileDescription = libc::c_int; /// 定义文件访问标志 pub type FileFlag = libc::c_int; /// 定义文件访问权限 pub type Mode = libc::mode_t; /// 偏移量 pub type Offset = libc::off_t; /// 以只读方式打开 pub const O_RDONLY : F...
use std::str::FromStr; pub fn a(input: &str) -> String { let res = find(input, 12, 2); res[0].to_string() } pub fn b(input: &str) -> String { let mut sol = 0; for i in 0..99 { for j in i..99 { let res = find(input, i, j); if res[0] == 19690720 { sol = 100 * res[1] + res[2]; } ...
pub mod catalog; pub mod file;
#[cfg(test)] use barneshut::{QuadTree, find_bounding_box, bh_force, pcl_pointers, bh_stepsim}; use physics::{Particle, PhysVec, force}; mod barneshut; mod physics; fn dummy_particles(n: int) -> Vec<Particle> { let mut v : Vec<Particle> = Vec::new(); for x in range(0,n) { v.push( Particle { pos: PhysV...
/// Used to perform a cheap conversion to a [`Face`](struct.Face.html) reference. pub trait AsFaceRef { /// Convert to a [`Face`](struct.Face.html) reference. fn as_face_ref(&self) -> &ttf_parser::Face<'_>; } impl AsFaceRef for ttf_parser::Face<'_> { #[inline] fn as_face_ref(&self) -> &ttf_parser::Face...
// #![cfg_attr(feature = "cargo-clippy", deny(warnings))] extern crate rand; extern crate rand_chacha; extern crate sha2; pub mod keypair; pub mod lbvrf; pub mod ntt; pub mod param; pub mod poly; pub mod poly256; pub mod poly32; pub mod serde; #[cfg(test)] mod test; pub trait VRF { type PubParam; type PublicK...
// (Full example with detailed comments in examples/01a_quick_example.rs) // // This example demonstrates clap's "usage strings" method of creating arguments // which is less verbose extern crate clap; use clap::{App, Arg, SubCommand}; fn main() { let matches = App::new("myapp") .version("1.0") .au...
#[macro_use] extern crate futures; use jsonrpc_core as rpc; // it needs to be before other modules // otherwise the macro for tests is not available. #[macro_use] pub mod helpers; pub mod client; pub mod error; pub mod transports; pub mod types; pub use error::Error; pub use error::Result; pub type RequestId = usiz...
#![deny( anonymous_parameters, bad_style, missing_copy_implementations, missing_debug_implementations, unused_extern_crates, unused_import_braces, unused_results, unused_qualifications, )] #![cfg_attr( feature = "cargo-clippy", // Allow lints that will fail due to PyO3 allow(clip...