text
stringlengths
8
4.13M
fn main() { //e6 //The sum of the squares of the first ten natural numbers is, //1**2 + 2**2 + ... + 10**2 = 385 //The square of the sum of the first ten natural numbers is, //(1 + 2 + ... + 10)**2 = 55**2 = 3025 //Hence the difference between the sum of the squares of the first ten natural numbers and the square of...
// list of kernel submodules pub mod activation_functions; pub mod apply_kernel; pub mod kernel; pub mod morphology; pub mod optimization;
use crate::test_utils::TestRandom; use crate::{Hash256, TreeHashVector}; use rand::RngCore; use serde_derive::{Deserialize, Serialize}; use ssz_derive::{Decode, Encode}; use test_random_derive::TestRandom; use tree_hash_derive::TreeHash; /// Historical block and state roots. /// /// Spec v0.5.1 #[derive(Debug, Clone, ...
use serde::Deserialize; #[derive(Deserialize)] pub struct Config { pub global: Global, } #[derive(Deserialize)] pub struct Global { pub address: String, pub db_url: String, pub pool_size: usize, }
#![feature(lang_items)] fn main() { println!("--output--"); println!("`#![feature]` *may* be used!"); }
#[derive(Debug)] #[allow(non_camel_case_types)] pub enum Opcode { NOP = 0x00, LD_BC_d16 = 0x01, LD_rBC_A = 0x02, INC_BC = 0x03, INC_B = 0x04, DEC_B = 0x05, LD_B_d8 = 0x06, RLCA = 0x07, LD_ra16_SP = 0x08, ADD_HL_BC = 0x09, LD_A_rBC = 0x0A, DEC_BC = 0x0B, INC_C = 0x0C, ...
struct Dice { bottom: i32, top: i32, north: i32, south: i32, west: i32, east: i32, } fn rotate(dice: Dice, direction: char) -> Dice { match direction { 'S' => Dice { bottom: dice.south, top: dice.north, north: dice.bottom, south: dice....
use std::collections::HashMap; use std::fmt::Write; use std::result::Result as StdResult; use failure::Error; use nom; pub type Result<T> = StdResult<T, Error>; /// The error type for this crate. #[derive(Debug, Fail)] pub enum PcapError { /// `Incomplete` indicates that more data is needed to decide. #[fail...
use crate::{ArgMatchesExt, Result, ResultExt}; use clap::{App, Arg, ArgGroup, ArgMatches}; use ronor::Sonos; use scraper::{Html, Selector}; use std::collections::HashMap; use std::io::Write; use std::process::{Command, Stdio}; use url::Url; pub const NAME: &str = "speak"; pub fn build() -> App<'static, 'static> { A...
use std::env; use std::fs; use std::process; fn main() { let args: Vec<String> = env::args().collect(); if args.len() != 2 { eprintln!("{:?}: wrong arguments", &args[0]); process::exit(1); } let st = match fs::metadata(&args[1]) { Ok(st) => st, Err(why) => { ...
//! The module contains a [`Grid`] structure. use std::{ borrow::{Borrow, Cow}, cmp, collections::BTreeMap, fmt::{self, Write}, }; use crate::{ color::{AnsiColor, Color}, colors::Colors, config::{AlignmentHorizontal, AlignmentVertical, Indent, Position, Sides}, dimension::Dimension, ...
use proconio::input; use proconio::marker::*; use std::cmp::*; fn main() { input! { n: u128 } if n % 2 == 1{ println!("0"); exit(); } let ten: f64 = 10.0; let max_times = (ten.log(5.0) * 18.0).ceil() as u32; let mut res = 0u128; for i in 1..max_times{ r...
pub trait Named { fn name(&self) -> &str; fn has_name_with(&self, string: &str) -> bool { self.name().to_lowercase().contains(&string.to_lowercase()) } } #[cfg(test)] mod tests { use super::*; struct NamedStruct { name: String, } impl Named for NamedStruct { fn nam...
/// Inbound connections session. Manages the creation of inbound sessions. Used /// to create an inbound session and start and stop the session. /// /// Class consists of 3 pointers: a weak pointer to the peer-to-peer class, an /// acceptor pointer, and a stoppable task pointer. Using a weak pointer to P2P /// allows u...
fn main() { let rect1 = Rectangle::from(30, 50); let rect2 = Rectangle::from(40, 40); let rect3 = Rectangle::from(20, 20); let square = Rectangle::square(40); rect1.print_area(); rect2.print_area(); rect3.print_area(); square.print_area(); println!("Can rect1 hold rect2? {}", rect1...
macro_rules! implement_binary_assign_operator { ($operator_trait:ident<$type_rhs:ty> for $type:ty, fn $function:ident($lhs:ident, $rhs:ident) { $body:expr } ) => { // val impl<T> $operator_trait<$type_rhs> for $type where T: Base { fn $function(&mut self,...
table! { blocks (hash) { id -> Int8, height -> Int8, hash -> Bytea, prev_hash -> Bytea, } } table! { inputs (utxo_tx_hash, utxo_tx_idx) { id -> Int8, height -> Int8, utxo_tx_hash -> Bytea, utxo_tx_idx -> Int4, } } table! { outputs (tx...
extern crate clap; use clap::{App, Arg}; use ignore::Walk; use std::fs::File; use std::io::BufRead; use std::io::BufReader; use std::path::Path; struct TodoSearcher<'a> { trigger_words: Vec<&'a str>, } const VERSION: &str = env!("CARGO_PKG_VERSION"); fn main() { let matches = App::new("DoThis") .ver...
// // Define generics in structs // #[derive(Debug)] // struct Point<T> { // x: T, // y: T // } // when making this struct vars x,y must be of the same type // #[derive(Debug)] // struct Pointt<T, U> { // x:T, // y:U // } // this struct can mix types // // generics in method definitions // imp...
// q0087_scramble_string struct Solution; impl Solution { pub fn is_scramble(s1: String, s2: String) -> bool { let t: Vec<u8> = s2.as_bytes().iter().cloned().rev().collect(); let s3 = String::from_utf8(t).unwrap(); Solution::is_scramble1(&s1, &s2) || Solution::is_scramble1(&s1, &s3) } ...
mod class; mod prop; pub use class::*; pub use prop::*;
pub mod common; pub mod person;
use std::fs; use std::collections::VecDeque; use std::collections::BTreeMap; use std::collections::HashMap; struct Computer{ ip: usize, program: BTreeMap<usize, i64>, relbase: i64, } impl Computer { fn new(program: BTreeMap<usize, i64>) -> Computer { Computer { ip: 0, program: program, relbase...
// Copyright (c) 2018 Alexander Færøy. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. use std::fmt; use expression::{Evaluate, Generator}; use math::{sin, PI}; pub struct SinPi { expression: Box<dyn Evaluate>, } impl SinPi { pub f...
use criterion::{black_box, criterion_group, criterion_main, Criterion}; use iterators::{ filter_map_filter_callback, filter_map_filter_inline, fold_callback, fold_inline, for_loop_callback, for_loop_inline, }; pub fn criterion_benchmark(c: &mut Criterion) { let nums = black_box((0..100_000).collect::<Vec<u...
#![no_std] #![no_main] #![feature(abi_efiapi)] use mikan::{FrameBufferConfig}; extern crate rlibc; use core::fmt::Write; use byteorder::{ByteOrder, LittleEndian}; use uefi::{ prelude::*, proto::media::file::{File, FileAttribute, FileInfo, FileMode, FileType}, proto::media::fs::SimpleFileSystem, prot...
use std::fs::File; use std::io::BufRead; use std::io::BufReader; use std::process::Command; pub fn get_section(filename: &str, section: &str) -> Result<String, String> { if let Ok(lesson_file) = File::open(filename) { let mut reader = BufReader::new(lesson_file); let mut text = String::new(); ...
/*! ```rudra-poc [target] crate = "slice" version = "0.0.4" [report] issue_url = "https://github.com/hinaria/slice/issues/2" issue_date = 2021-02-17 [[bugs]] analyzer = "UnsafeDataflow" bug_class = "UninitExposure" rudra_report_locations = ["src/lib.rs:186:5: 207:6"] ``` !*/ #![forbid(unsafe_code)] fn main() { p...
/* * 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::ffi::CStr; use std::ffi::OsStr; use std::mem::MaybeUninit; use std::os::unix::io::AsRawFd;...
use super::Parameter; use ethane_types::Address; use std::convert::TryFrom; use std::fmt; use std::str; impl fmt::Display for Parameter { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { match self { // data is stored in a H256 type on 32 bytes, so right padded 20 ...
#[test] fn pdb_info() { let file = std::fs::File::open("fixtures/self/foo.pdb").expect("opening file"); let mut pdb = pdb::PDB::open(file).expect("opening pdb"); let pdb_info = pdb.pdb_information().expect("pdb information"); assert_eq!(pdb_info.age, 2); assert_eq!( pdb_info.guid, ...
extern crate ncurses; extern crate num; mod metronome; mod clock; mod interface; fn main () { let control = metronome::Metronome::new(); control.run(); }
use ::mantle; pub struct IOPort { port: u16 } pub struct IOPortSet { first: u16, count: u16 } pub fn request(first_port: u16, count: u16) -> IOPortSet { // TODO: make exclusive! IOPortSet { first: first_port, count } } pub fn request_one(port: u16) -> IOPort { // TODO: make exclusive! IO...
//this is the implementatation of poly1305 in rust using as a base //this implementation https://github.com/floodyberry/poly1305-donna using 64 bit * 64 bit = 128 bit multiplication abd 64 bit addition //there is already an implementatation on rust using this method but on 32 bits //you can find that here //https://git...
pub fn build_proverb(list: &[&str]) -> String { if list.len() == 0 { return String::new(); } let mut result: Vec<String> = vec![]; for i in 0..(list.len() - 1) { result.push(format!( "For want of a {} the {} was lost.", list[i], list[i + 1] ))...
use crate::geometry::{Point, Rect}; use crate::graph_query::GraphQuery; use crate::overlays::OverlayKind; use crate::reactor::Reactor; use crate::vulkan::texture::Texture; use crate::vulkan::GpuTask; use ash::version::DeviceV1_0; use ash::{vk, Device}; use anyhow::Result; use crossbeam::atomic::AtomicCell; use futur...
use crate::{ alloc::{Allocator, GlobalAllocator}, containers::Array, }; use core::{ borrow::Borrow, cmp::{Eq, PartialEq}, fmt, hash, ops::{Deref, DerefMut}, ptr::copy_nonoverlapping, str, }; pub struct String<A: Allocator = GlobalAllocator> { buf: Array<u8, A>, } impl<A: Allocator...
use util; #[test] fn test_lcamel_to_lsnake() { let base = "customRootSupport"; // lower camel case String let target = "custom_root_support"; // lower snake case String let result = util::lcamel_to_lsnake(base); assert_eq!(result, target); } #[test] fn test_ucamel_to_lsnake() { let base = "CustomRootSu...
use crate::resource::Resource; use crate::model::SessionToken; use crate::xml::AuthXmlParser; use std::io::Read; pub struct AuthenticationResource { pub username: String, pub password: String } impl Resource<SessionToken> for AuthenticationResource { fn parse(&self, bytes: impl Read) -> Result<SessionTo...
use crate::grammar::ast::eq::ast_eq; use crate::grammar::ast::{eq::AstEq, NumLit}; use crate::grammar::testing::TestingContext; #[test] fn test_ast_eq() { fn test_aeq<T: AstEq>(v: &Vec<T>) { assert!(ast_eq(&v[0], &v[1])); assert!(!ast_eq(&v[1], &v[2])); } let tcx = TestingContext::with(&["...
#[macro_use] extern crate quickcheck; extern crate byte; extern crate byteorder; use byte::ctx::*; use byte::*; use byteorder::*; #[test] fn test_str() { let bytes: &[u8] = b"abcd\0efg"; let mut offset = 0; assert_eq!( bytes .read_with::<&str>(&mut offset, Str::Delimiter(NULL)) ...
use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug)] pub struct MojangVersionManifest { pub latest: MojangVersionManifestLatest, pub versions: Vec<MojangReleaseProfile>, } impl MojangVersionManifest { pub fn look_up_version(&self, version: String) -> Option<&MojangReleaseProfile> ...
use std::{borrow::Cow, cmp::Ordering, fmt}; use crate::util::{matcher::QUERY_SYNTAX_REGEX, CowUtils}; #[derive(Debug, Default)] pub struct FilterCriteria<'q> { pub stars: OptionalRange<f32>, pub ar: OptionalRange<f32>, pub cs: OptionalRange<f32>, pub hp: OptionalRange<f32>, pub od: OptionalRange<f...
use std::env::current_dir; use std::error; use std::fs::File; use std::io::{Read, Write}; use chrono; use chrono::Datelike; use handlebars::Handlebars; use reqwest; use reqwest::Error; use serde_json::json; use toml; use toml::Value; pub fn main() { println!("Bootstrapping current day puzzle ..."); let now =...
//! Utilities to parse the prefix and command out of a message. //! //! Refer to the [`content`] function for the definition of a prefix. use std::sync::Arc; use serenity::client::Context as SerenityContext; use serenity::model::channel::Message; use crate::command::Command; use crate::configuration::Configuration; ...
use mmu::Mmu; use std::vec::Vec; use rand::random; pub struct Cpu { mmu: Mmu, registers: Vec<u8>, stack: Vec<u16>, video: Vec<u8>, input: Vec<u8>, delay_timer: u8, sound_timer: u8, sp: u16, pc: u16, i: u16 } impl Cpu { pub fn new(mmu: Mmu) -> Cpu { Cpu { ...
// Copyright 2019 Google LLC // // 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 in ...
use crate::obj::*; #[repr(C)] pub(crate) union ObjOrWord { obj: *mut std::ffi::c_void, word: *const std::sync::atomic::AtomicU64, } #[repr(C)] pub(crate) struct QueueMultiSpec { pub(crate) obj_or_word: ObjOrWord, pub(crate) result: *mut std::ffi::c_void, pub(crate) cmp: u64, pub(crate) sq: i32, pub(crate) ret:...
pub fn filter_map_filter_inline(nums: &[u64]) -> Vec<u64> { nums.iter() .filter(|&&n| n % 3 == 0) .map(|&n| n & (255 << 8)) .filter(|&n| n % 3 == 0) .collect() } pub fn fold_inline(nums: &[u64]) -> Vec<u64> { nums.iter().fold(Vec::new(), |mut result, &n| { if n % 3 == 0 ...
mod capability; mod into_uuid; pub use self::capability::Capability; pub use self::into_uuid::IntoUuid; pub(crate) use self::capability::CapabilityMeta;
use std::sync::{Arc, Mutex}; use chrono::Local; use crate::notifications::types::logged_notification::{ BytesThresholdExceeded, FavoriteTransmitted, LoggedNotification, PacketsThresholdExceeded, }; use crate::notifications::types::notifications::Notifications; use crate::notifications::types::sound::{play, Sound}...
//! client is the actual API for this library use tokio_io::{io, AsyncRead, AsyncWrite}; use tokio_io::codec::length_delimited; use tokio_proto::pipeline::ServerProto; // Transport is handling the delimited Header in every Vert.x messages struct Transport {} impl<T: AsyncRead + AsyncWrite + 'static> ServerProto<T> ...
#![feature(decl_macro, proc_macro_hygiene)] use rocket::routes; use librainbowapi::{ db::PrimaryDb, graphql::{mutation_root::MutationRoot, query_root::QueryRoot}, routes::{self, Schema}, }; fn main() { // let allowed_origins = AllowedOrigins::some_exact(&["http://localhost:8080"]); // You can also deserialize ...
fn main() { let f1 = 'A'; println!("{:?}", f1); let f2: char = 'b'; println!("{:?}", f2); }
#[doc = "Register `ITLINE17` reader"] pub type R = crate::R<ITLINE17_SPEC>; #[doc = "Field `LPTIM1` reader - LPTIM1"] pub type LPTIM1_R = crate::BitReader; impl R { #[doc = "Bit 2 - LPTIM1"] #[inline(always)] pub fn lptim1(&self) -> LPTIM1_R { LPTIM1_R::new(((self.bits >> 2) & 1) != 0) } } #[doc...
use crate::{ components::{ collision_box, player, Ball, CollisionBox, MovementState, Net, Player, PlayerType, }, resources::Score, utils::Side, }; use amethyst::{ core::Transform, derive::SystemDesc, ecs::{Join, ReadStorage, System, SystemData, Write, WriteStorage}, ui::{UiFinder...
use crate::{resolve, ResponseBuilder}; use http::{Request, Response}; use hyper::{service::Service, Body}; use std::future::Future; use std::io::Error as IoError; use std::path::PathBuf; use std::pin::Pin; use std::task::{Context, Poll}; /// High-level interface for serving static files. /// /// This struct serves fil...
use crate::states::loading::LoadingState; use oxygengine::prelude::*; use wasm_bindgen::prelude::*; mod states; #[wasm_bindgen(start)] pub fn main_js() -> Result<(), JsValue> { #[cfg(feature = "console_error_panic_hook")] #[cfg(debug_assertions)] console_error_panic_hook::set_once(); #[cfg(debug_asse...
use super::{FontData, FontDataInternal}; use crate::style::{Color, TextStyle}; use std::convert::From; /// The error type for the font implementation pub type FontError = <FontDataInternal as FontData>::ErrorType; /// The type we used to represent a result of any font operations pub type FontResult<T> = Result<T, Fo...
#![cfg_attr(not(test), no_std)] extern crate alloc; use alloc::{ string::{String, ToString}, vec::Vec, }; use log::{warn, Level, Record}; static DEFAULT_LOG_LEVEL: Level = Level::Info; pub struct LogFilter { patterns: Vec<Pattern>, } struct Pattern { level: Level, module_prefix: String, } impl...
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/ use serde_json::Value; use std::fs; // fn collect_numbers1(value: &Value) -> i64 { match value { Value::...
#[macro_use] extern crate cpython; use std::{mem, cell, vec, cmp}; use cpython::{ToPyObject, PyType, PyList, PyDict, PyObject, ObjectProtocol, PyModule, PyDrop, PyResult, Python}; // add bindings to the generated python module // N.B: names: "librust2py" must be the name of the `.so` or `.pyd` file py_module_initiali...
pub mod cr { pub mod lpds { pub fn get() -> u32 { unsafe { core::ptr::read_volatile(0x40007000u32 as *const u32) & 0x1 } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0x40007000u32 as *const u32);...
extern crate nom; extern crate std; use std::io::{Read, Result}; use std::net::{TcpStream, TcpListener}; use std::{thread, str}; use std::sync::Arc; use std::marker::{Send}; use std::borrow::{Cow, Borrow}; use crate::api::*; use crate::io::*; pub struct Server<'a> { host: Cow<'a, str>, port: u16, } impl<'a> ...
//! Specification of trait object's concurrency used in `App`. pub mod current_thread; use { crate::{ error::Error, future::{Async, Poll, TryFuture}, handler::Handler, input::Input, output::{Respond, Responder, Response}, upgrade::{Error as UpgradeError, Upgrade, Up...
pub mod get_hand; pub fn game(){ println("Game Started"); get_hand(); }
use std::collections::HashMap; use std::fs; use std::io::Write; use std::path::{Path, PathBuf}; use std::str::FromStr; use failure; use rust_htslib::bam; use rust_htslib::bam::Read as BamRead; use assign::*; use barcode_group::*; use depth::*; use frag_purity::*; use purity::*; pub struct CLI { pub bambyname: S...
use crate::api::RequestCounter; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use ratatui::layout::Alignment; use ratatui::widgets::Paragraph; pub struct BottomBar<'a> { request_counter: RequestCounter, pub widget: Paragraph<'a>, pub needs_redraw: AtomicBool, has_data_changed: Arc<...
use eachdo::{ config::{InputType, Config}, Stream, FileInput, StdinInput, InputStream, }; fn main() -> std::io::Result<()> { let config = Config::new(); let delim = config.delimiter; match config.input_type { InputType::File(path) => { let stream = Stream::from( ...
//! Fit-specific configuration and fit builder use super::Fit; use crate::{ error::RegressionResult, glm::Glm, model::Model, num::Float, regularization::{IrlsReg, LassoSmooth, Null, Ridge}, Array1, }; /// A builder struct for fit configuration pub struct FitConfig<'a, M, F> where M: Glm, ...
use crate::utils::read_lines; pub(crate) fn main() { let filename = "B:\\Dev\\Rust\\projects\\aoc2020\\input\\1.1.txt"; println!("filename is {}",filename); if let Ok(lines) = read_lines(filename) { // Create a vector with all numbers let mut all_numbers:Vec<i32> = Vec::new(); // C...
fn main(){ println!("MAX_POINT is: {}", MAX_POINTS); const MAX_POINTS: u32 = 100_000; print(); } fn print(){ println!("MAX_POINTS is: {}", MAX_POINTS); } const MAX_POINTS: u32 = 200_000;
#![allow(non_snake_case)] #[macro_use] extern crate lazy_static; extern crate serde_json; extern crate vmtests; use serde_json::Value; use std::collections::HashMap; use vmtests::{load_tests, run_test}; lazy_static! { static ref TESTS: HashMap<String, Value> = load_tests("tests/vmArithmeticTest/"); } #[test] fn...
//! Engine decorator that performs **head skipping** &ndash; an extremely optimized search for //! the first matching member name in a query starting with a self-looping state. //! This happens in queries starting with a descendant selector. use crate::{ classification::{ mask::Mask, memmem::Memmem,...
pub mod config; pub mod data_reader; pub mod data_sender;
pub mod grid; pub mod console_utils;
pub trait PocHandler<AccountId> { fn remove_history(miner: AccountId); }
use criterion::{criterion_group, Criterion}; use crate::benchmarks::benchtemplate::BenchTemplate; use utilities::template::Template; pub fn bench_filter_one_column_small(c: &mut Criterion) { println!("**filter small **"); let mut bt = Template::new(); bt.generate_random_table("a", 1, 100); bt.add_com...
use crate::errors::Error; use crate::net::{ConnectionManager, SignerID}; use crate::rpc::TapyrusApi; use crate::signer_node::message_processor::create_block_vss; use crate::signer_node::node_state::builder::{Builder, Member}; use crate::signer_node::utils::sender_index; use crate::signer_node::{NodeParameters, NodeStat...
#[no_mangle] pub extern fn rmw_get_implementation_identifier() -> *const u8 { "libdds\0".as_ptr() }
extern crate aoc_runner; #[macro_use] extern crate aoc_runner_derive; // XXX error_chain seems to be deprecated //#[macro_use] //extern crate error_chain; pub mod day1; pub mod day2; pub mod day3; pub mod day4; pub mod day5; pub mod day6; pub mod day7; pub mod day8; pub mod day9; pub mod day10; pub mod day11; pub mo...
extern crate env_logger; #[macro_use] extern crate shared; extern crate nng; // NOTE: Still have nng errors even if we don't use the re-export... use std::convert::TryFrom; use std::process; use std::time::Duration; use nng::options::{Options, SendTimeout}; use nng::{Message, Protocol, Socket}; use shared::{CommandRe...
use tokio::process::Command; use anyhow::{Result, Context}; use async_trait::async_trait; use crate::{ services::model::{Nameable, Ensurable, is_binary_present}, helpers::ExitStatusIntoUnit }; static NAME: &str = "kfctl"; #[derive(Default)] pub struct Kfctl {} impl Nameable for Kfctl { fn...
extern crate mavlink; mod test_shared; #[cfg(test)] #[cfg(feature = "common")] mod test_encode_decode { use mavlink::{common, Message}; #[test] pub fn test_echo_heartbeat() { let mut v = vec![]; let send_msg = crate::test_shared::get_heartbeat_msg(); mavlink::write_v2_msg( ...
use crate::common::*; pub(crate) trait ErrorResultExt<T> { fn eprint(self, color: Color) -> Result<T, i32>; } impl<T, E: Error> ErrorResultExt<T> for Result<T, E> { fn eprint(self, color: Color) -> Result<T, i32> { match self { Ok(ok) => Ok(ok), Err(error) => { if color.stderr().active() {...
use std::panic; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::Arc; use std::time::{Duration, Instant}; use crate::cancel::Cancel; use crate::coroutine_impl::{ current_cancel_data, run_coroutine, Coroutine, CoroutineImpl, EventSource, }; use crate::join::JoinHandle; use crate::scoped::s...
use mikan::{FrameBufferConfig, PixelFormat}; #[derive(Clone, Copy)] pub struct PixelColor { pub r: u8, pub g: u8, pub b: u8, } fn write_pixel_triple(fb_config: &FrameBufferConfig, x: u32, y: u32, abc: (u8,u8,u8)) { let pixel_pos = fb_config.pixels_per_scan_line * y + x; let (c0,c1,c2) = abc; le...
//! //! Terminal Examples //! #![allow(dead_code)] use std::io::{stdout, Write}; use crossterm::{ cursor::MoveTo, execute, terminal::{self, Clear, ClearType, ScrollDown, ScrollUp, SetSize}, Result, }; fn print_test_data() { for i in 0..100 { println!("Test data to test terminal: {}", i);...
use crate::core::{ world::World, }; pub trait Sys { fn run(&self, world: &mut World); } pub struct SystemManager { systems: Vec<Box<dyn Sys>> } impl SystemManager { pub fn new(max_system: usize) -> Self { Self { systems: Vec::with_capacity(max_system), } } p...
/* * Copyright Stalwart Labs Ltd. See the COPYING * file at the top-level directory of this distribution. * * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or * https://www.apache.org/licenses/LICENSE-2.0> or the MIT license * <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your * optio...
use components::*; use eos::*; use prelude::*; use router::RouterAgent; use scatter::*; use stdweb::traits::IEvent; use stdweb::web::document; use views::svg; use yew::services::fetch::FetchTask; pub struct PollVotingPage { props: Props, eos: EosService, poll_task: Option<FetchTask>, poll: Option<Resul...
use amethyst::{ core::{ nalgebra::{Vector2, Vector3}, timing::Time, transform::components::Transform, }, ecs::{Join, Read, ReadStorage, System, WriteStorage}, }; use crate::components::physics::{Dynamics, PhysicalProperties}; /// TODO: Calculate inertia based on ShipParts' masses a...
use std::{ convert::TryInto, io::{self, Read, Seek, SeekFrom} }; use crate::track::Duration; // MP4 reference: // https://developer.apple.com/library/archive/documentation/QuickTime/QTFF/QTFFChap1/qtff1.html #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Metadata { pub duration: ...
use papergrid::{ colors::NoColors, config::{ spanned::SpannedConfig, AlignmentHorizontal, AlignmentVertical, Borders, Entity, Indent, Sides, }, dimension::{spanned::SpannedGridDimension, Estimate}, grid::peekable::PeekableGrid, records::vec_records::{CellInfo, VecRecords}, }; fn...
use parking_lot::RwLock; use {yellow::{GreenNode, RedPtr}, TextUnit}; #[derive(Debug)] pub(crate) struct RedNode { green: GreenNode, parent: Option<ParentData>, children: RwLock<Box<[Option<RedNode>]>>, } #[derive(Debug)] struct ParentData { parent: RedPtr, start_offset: TextUnit, index_in_par...
pub fn problem_001() -> usize { let mut s: usize = 0; for x in 0..1000 { if x % 3 == 0 || x % 5 == 0 { s += x; } } s } #[cfg(test)] mod test { use super::*; use test::Bencher; #[test] fn test_problem_001() { let ans: usize = problem_001(); pr...
fn main() { let mut x = ["this", "is", "a", "sentence"]; x[2] = "a nice"; println!("{} {} {} {}.", x[0], x[1], x[2], x[3]); }
use std::fs; use std::io::{self, BufRead, Seek}; use std::os::unix::fs::MetadataExt; use std::path::PathBuf; use std::time; /// The `FileWatcher` struct defines the polling based state machine which reads /// from a file path, transparently updating the underlying file descriptor when /// the file has been rolled over...
extern crate rustc_serialize; extern crate hyper; use std::io::Read; use rustc_serialize::json; use hyper::Client; use hyper::header::Connection; #[derive(RustcDecodable, RustcEncodable)] struct Koto { hitokoto: String, cat: String, author: String, source: String, like: i32, date: String, ...
use crate::env::{default, memory}; use memory::{MemAccountStore, MemTemplateStore}; use crate::EnvTypes; /// [`MemTemplateStore`] with default serialization. pub type DefaultMemTemplateStore = MemTemplateStore<default::DefaultTemplateSerializer, default::DefaultTemplateDeserializer>; /// [`MemAccountStore`] wit...