text
stringlengths
8
4.13M
extern crate proc_macro; extern crate syn; #[macro_use] extern crate quote; use proc_macro::TokenStream; use quote::Tokens; use syn::{FnArg, Ident, Item}; #[proc_macro_attribute] pub fn power_method(_metadata: TokenStream, input: TokenStream) -> TokenStream { let item: syn::Item = syn::parse(input).expect("failed...
use rustix::rand::{getrandom, GetRandomFlags}; #[test] fn test_getrandom() { let mut buf = [0_u8; 256]; let _ = getrandom(&mut buf, GetRandomFlags::empty()); }
use std::cell::RefCell; use std::rc::Rc; type NodeRef<T> = Rc<RefCell<Node<T>>>; pub type NodeOption<T> = Option<NodeRef<T>>; #[derive(Debug)] pub struct Node<T> { pub data: T, pub next: NodeOption<T>, } impl<T> Node<T> { pub fn new(data: T) -> NodeRef<T> { return Rc::new(RefCell::new(Node { data, next: No...
extern crate yk_lexer; extern crate rand; extern crate rand_pcg; mod rnd; mod str_gen; mod fuzz_gen; use yk_lexer::{StandardLexer, Lexer, TokenType, Token}; use str_gen::*; use fuzz_gen::*; use std::io::Write; #[derive(Lexer, Clone, PartialEq, Eq, Debug)] enum TokenKind { #[error] Error, #[end] End...
use std::{collections::HashMap, fmt::Debug}; use super::{ dynamic::Dynamic, expression::Expression, function::Function, interpreter::Interpreter, method::Method, operator::Operator, runtime_error::RuntimeResult, }; #[derive(Clone, Debug)] pub struct Class { pub name: String, pub fields: HashMap<String...
use std::{any::TypeId, fmt}; use log::trace; use reqwest::Url; use serde_json::{from_value, json}; use crate::client_error::ClientError; #[derive(Debug)] pub struct Client { address: Url, http: reqwest::blocking::Client, } #[derive(Debug)] pub struct Error(ClientError); impl fmt::Display for Error { fn...
#[cfg(windows)] extern crate winapi; use std::io::Error; use std::mem; use std::mem::{size_of}; use std::ptr::null_mut; use winapi::shared::minwindef::LPVOID; use winapi::shared::windef::{HICON, HWND}; use winapi::shared::dxgi::*; use winapi::shared::dxgitype::*; use winapi::shared::dxgiformat::*; use winapi::um::d3d...
#[derive(Debug)] struct User { name: String, email: String, pass: u32, active: bool, } #[derive(Debug)] struct Rectangulo { width: u32, height: u32, } impl Rectangulo { //metodo da struct Rectangulo, qualquer metodo criado para esta struct será construido dentro do impl(implementation) fn area_s(& self) -> u3...
extern crate cmake; use std::env; use std::fs; use cmake::Config; fn main() { let src = env::current_dir().unwrap().join("snappy"); let out = Config::new("snappy") .define("CMAKE_VERBOSE_MAKEFILE", "ON") .build_target("snappy") .build(); let mut build = out.join("build"); // NOTE: the cfg! macro doesn't...
use crate::JudgeStatus; pub mod gpp; pub mod python; pub trait CompilerDescriptor { fn support_sufix() -> Vec<&'static str>; fn check_environment() -> CompilerEnvironmentStatus; } pub trait Compiler { fn compile(&self, src: String) -> CompileResult; } #[derive(Debug)] pub enum CompilerEnvironmentStatus ...
// Copyright (c) 2020 Alex Chi // // This software is released under the MIT License. // https://opensource.org/licenses/MIT pub use crate::symbols::*; pub const MAX_PAGE: usize = 128 * 1024 * 1024 / (1 << 12); pub struct Allocator { pub base_addr: usize, pub page_allocated: [usize;MAX_PAGE] } const PAGE_O...
mod bytes; mod list; mod map; mod maybe; pub use bytes::*; pub use list::*; pub use map::*; pub use maybe::*;
///! Various utilities or small types that only serve to clutter the more focused cpu files pub struct ProgramCounter { pub address: u32, } impl ProgramCounter { pub fn new(address: u32) -> ProgramCounter { ProgramCounter { address } } /// Increments the address and returns the original value...
fn main() { let mut primes = vec![2]; let mut prime_count = 1; let mut p = 3; loop { let mut is_prime = true; for div in primes.iter() { if p % *div == 0 { is_prime = false; break; } } if is_prime { pr...
pub use self::instance::Instance; //pub use self::window::Window; mod instance; mod window;
use std::collections::HashMap; fn main(){ let golf_scores: HashMap<&str, i32> = [("albatross", -3),("eagle", -2),("birdie", -1),("par",0),("bogey",1),("double-bogey",2),("triple-bogey",3)].iter().cloned().collect(); let input_list = ["eagle" , "bogey" , "par" , "bogey" , "double-bogey" , "birdie" ,"bogey" ,"pa...
// //! Copyright 2020 Alibaba Group Holding Limited. //! //! 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 ...
use arch::segmentation::{self, SegmentSelector}; use super::bit_field::BitField; use super::{HandlerFunc, InterruptVector}; /// Interrupt descriptor table. pub struct Idt([Entry; 256]); /// An entry of the interrupt descriptor table. #[derive(Debug, Clone, Copy)] #[repr(C, packed)] pub struct Entry { pointer_low:...
pub(super) mod uri; pub mod uring;
use rouille::{assert_or_400, router, Request, Response, Server}; use std::io::{BufRead, BufReader, Read}; use std::{env, io, str}; use syslog_heroku::Message as LogplexMessage; fn main() -> () { let host = match env::var("PORT") { Ok(port) => format!("0.0.0.0:{}", port), _ => "0.0.0.0:0".to_string(...
use crate::alignments::*; use crate::models::{AlignmentFactory, BasedAlignedDim, DimAlignFactory, ChainAlignFactory, Representation}; use crate::readers::RAReader; use fnv::FnvHashMap; use petgraph::prelude::*; use petgraph::visit::{depth_first_search, Control, DfsEvent}; pub struct BasicAlignmentInference<'a> { rep...
use math::Vector3; use raytracing::Ray; #[derive(Debug)] pub struct Sphere { pub origin: Vector3, pub radius: f64, pub color: Vector3, } impl Sphere { pub fn new(origin: Vector3, radius: f64, color: Vector3) -> Sphere { Sphere { origin, radius, color, ...
use super::super::{ PathType, Path }; use crate::parser::Polarity; use super::{ split_region_paths, to_stroke_around_path }; use super::super::Tree; pub struct Region { pub starting_polirity: Polarity, pub paths: Tree<Path> } impl Region { pub fn from_raw_region(path: Path) -> Vec<Self> { println!("read reg...
struct Solution; impl Solution { fn remove_interval(intervals: Vec<Vec<i32>>, to_be_removed: Vec<i32>) -> Vec<Vec<i32>> { let l = to_be_removed[0]; let r = to_be_removed[1]; let mut res = vec![]; for interval in intervals { if interval[1] < l || interval[0] > r { ...
use crossterm::event; use std::error::Error; use std::time::Duration; pub type TestResult = std::result::Result<(), Box<dyn Error>>; /// Returns standard Crossterm Key Event from a character (doesn't include Alt/Ctrl/etc.) pub fn crossterm_key(letter: char) -> event::Event { event::Event::Key(event::KeyEvent::fro...
#[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum EscapedChar { DoubleQuote, Slash, Backslash, Backspace, FormFeed, Newline, CarriageReturn, Tab, } #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum Token { Quote, SimpleEscape(EscapedChar), UnicodeEscape(u16), Cha...
use blk::{blockchain, Block, Blockchain, ByteHash, Hashable, Timestamp}; fn main() -> Result<(), blockchain::ValidationError> { let difficulty = 0x0000FFFFFFFFFFFFFFFFFFFFFFFFFFFF; let mut block = Block::new( 0, 0, ByteHash::from(vec![0; 32]), 0, String::from("Genesis bl...
use crate::utils::tree::TreeNode; use std::cell::RefCell; use std::rc::Rc; pub struct Solution {} impl Solution { pub fn is_symmetric(root: Option<Rc<RefCell<TreeNode>>>) -> bool { if let Some(r) = root { return Self::_symmetric_eq( r.as_ref().borrow().left.clone(), ...
use crate::expert::{Anchor, AnchorInner, Engine, OutputContext, Poll, UpdateContext}; use std::panic::Location; pub struct RefMap<A, F> { pub(super) f: F, pub(super) anchors: A, pub(super) location: &'static Location<'static>, } impl<F, In: 'static, Out: 'static, E> AnchorInner<E> for RefMap<(Anchor<In, E...
pub fn print(input: &str) -> String { input.to_string() }
struct Solution; struct Word { data: Vec<(char, usize)>, } impl Word { fn new(s: String) -> Self { let mut data = vec![]; let mut prev: Option<(char, usize)> = None; for c in s.chars() { if let Some(p) = prev { if c == p.0 { prev = Some((...
use jomini_derive::JominiDeserialize; use serde::{de, Deserializer}; use std::fmt; #[derive(JominiDeserialize)] pub struct Model { #[jomini(deserialize_with = "deserialize_token_bool")] human: bool, first: u16, fourth: u16, #[jomini(duplicated)] core: Vec<u32>, names: Vec<String>, } fn des...
use aoc2015::util::read_to_parsed_lines; use aoc2015::{format_err, Error, Result}; #[derive(Debug, Clone)] struct Reindeer { name: String, speed: usize, fly_duration: usize, rest_duration: usize, } impl std::str::FromStr for Reindeer { type Err = Error; fn from_str(s: &str) -> Result<Self> { ...
use rand::seq::IteratorRandom; use rand::Rng; use std::fs::{metadata, read_dir, File}; use std::io::{BufRead, BufReader, Result, Seek, SeekFrom}; fn get_random_fortune_file() -> String { let path = "src/datfiles"; let entries = read_dir(path) .unwrap() .map(|result| result.map(|e| e.path())) ...
use std::collections::HashMap; use std::result::Result; use types::{LispValue, LispType, HostFn, EvaluationResult, Seq, new_list, new_fn, new_number, new_nil, new_string, new_atom, new_boolean, new_symbol, new_lambda, new_macro, new_keyword, new_vector, new_map, new_map_from_seq, Assoc}; use error::{error_message, Read...
pub mod atoms; pub mod base; pub mod composites; pub mod segments; pub mod spanners; pub mod score; #[doc(inline)] pub use atoms::*; #[doc(inline)] pub use base::*; #[doc(inline)] pub use composites::*; #[doc(inline)] pub use segments::*; #[doc(inline)] pub use spanners::*; #[doc(inline)] pub use score::*;
use std::{ io, env, string }; use tokio_tungstenite::tungstenite; #[derive(Debug)] pub enum AdapterError { IoError(io::Error), EnvError(env::VarError), WsError(tungstenite::Error), Utf8Error(string::FromUtf8Error) } impl From<io::Error> for AdapterError { fn from(err: io::Error) -> Se...
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] pub const FOO: u32 = 1; pub const BAR: u32 = 4; pub const BAZ: u32 = 5; pub const MIN: i64 = -9223372036854775808; pub const BARR: u32 = 1; pub const BAZZ: u32 = 7; pub const I_RAN_OUT_OF_DUMB_NAMES: u32 = 7; pub const...
pub mod redis_helpers; pub mod store_helpers;
use std::fs; use std::io::Error; use std::io::{BufRead, BufReader, Error, ErrorKind, Read}; pub fn first(size: usize) -> Result<(), Error> { let mut v = ints_from(fs::File::open("input.txt")?)?; v.sort(); let mut answer = vec![0; size]; if summing_elements(&v, size, 2020, &mut answer) { printl...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::blob::Blob; use crate::node_type::{SparseMerkleInternalNode, SparseMerkleLeafNode}; use anyhow::{bail, ensure, Result}; use serde::{Deserialize, Serialize}; use starcoin_crypto::hash::*; /// A proof that can be used to a...
//! Url building constants and data structures used over the wire. //! use crate::entities::{Cycle, FormattedAction}; pub const API_BASE: &str = "/api"; pub const ACTIONS2_BASE: &str = "/v2/actions"; pub const ANNOTATIONS: &str = "/annotations"; pub const RECOMMENDATIONS: &str = "/recommendations"; /// A request to c...
use std::sync::Arc; use ethereum_types::H256; use serde::{Deserialize, Deserializer}; use serde_json::Value; use ethportal_api::types::execution::accumulator::EpochAccumulator; use ethportal_api::types::execution::header::{Header, TxHashes}; use ethportal_api::types::execution::transaction::Transaction; /// Helper t...
fn fourier_transform(polynomial: &mut [f64], n: usize) -> *mut [f64] { // Fourier transform of Polynomial with degree n // n is assumed to be a power of 2 let mut even = (0..n).steb_by(2).map(|i| polynomial[i]).collect::<Vec<f64>>(); let mut odd = (1..n).steb_by(2).map(|i| polynomial[i]).collect::<Vec<...
// Copyright 2020 WHTCORPS INC Project Authors. Licensed Under Apache-2.0 use std::fs::File; use std::io::Read; use std::path::PathBuf; use slog::Level; use batch_system::Config as BatchSystemConfig; use encryption::{EncryptionConfig, FileConfig, MasterKeyConfig}; use engine_lmdb::config::{BlobRunMode, CompressionTy...
//struct Poly([i32;10], usize); // use std::ops::AddAssign; // use std::ops::Mul; //use std::ops::{Add, Sub, Mul}; //use num_traits::Float; //use num::{Float, NumCast}; fn main(){ let new_poly = Poly::new([3,4,0,2,0,0,0,0,0,0]); println!("{}", new_poly.eval(2.0)); } pub struct Poly { coefficients : [i32...
use crate::types::node::*; use std::collections::BinaryHeap; pub fn update_with_data(heap_buffer: &mut [u32], data: &[u8]) { for &byte in data.iter() { heap_buffer[byte as usize] += 1; } } pub fn convert_to_heap( heap_buffer: &mut [u32] ) -> BinaryHeap<Element> { heap_buffer.iter().enumerate().f...
struct Solution; use util::*; impl Solution { fn generate_trees(n: i32) -> Vec<TreeLink> { if n == 0 { return vec![]; } Self::generate(1, n) } fn generate(left: i32, right: i32) -> Vec<TreeLink> { let mut res = vec![]; if left > right { retur...
use http::header::PROXY_AUTHORIZATION; use super::Credentials; header! { /// `Proxy-Authorization` header, defined in [RFC7235](https://tools.ietf.org/html/rfc7235#section-4.4) /// /// The `Proxy-Authorization` header field allows a user agent to authenticate /// itself with an HTTP proxy -- usually, ...
use std::fmt; #[derive(Debug, Clone, PartialEq)] pub enum TokenType { IntLiteral, FloatLiteral, StringLiteral, BoolLiteral, Symbol, Operator, Identifier, Type, Whitespace, EOL, EOF, } #[derive(Debug, Copy, Clone)] pub struct TokenPosition { pub line: usize, pub col:...
#[no_mangle] pub fn schedule(c_p_course_id: *const i32, c_p_student_id: *const i32, c_p_period: *const i32, c_p_num: usize, c_c_id: *mut i32, c_c_course_id: *mut i32, c_c_period: *mut i32, c_c_num: *mut i32...
use surf::Client; pub struct XbmcService { client: Client, } impl XbmcService { pub fn new(client: &Client) -> Self { Self { client: client.clone(), } } pub fn get_info_booleans(&self) {} pub fn get_info_labels(&self) {} }
use std::sync::Arc; use derive_more::{Display, From}; use futures::executor::block_on; use protocol::traits::{ChainQuerier, Context, Storage}; use protocol::types::{Block, Hash, Receipt, SignedTransaction}; use protocol::{ProtocolError, ProtocolErrorKind, ProtocolResult}; pub struct DefaultChainQuerier<S: Storage> {...
//! A safe library for interacting with epoll, specifically for this project. //! //! [`Epoll`] provides all the necessary functions to interact with epoll. //! //! This crate *does not* expose all the interest bitflags available for epoll //! since they were not necessary for this project. use std::fmt::Display; use ...
use proc_macro2::{Ident, Span, TokenStream}; use quote::{quote, ToTokens}; use syn::parse::Error; use crate::field_info::{FieldBuilderAttr, FieldInfo}; use crate::util::{ apply_subsections, empty_type, empty_type_tuple, expr_to_single_string, first_visibility, modify_types_generics_hack, path_to_single_string,...
fn reader(path: &str) -> Result<std::io::BufReader<std::fs::File>, ()> { let path = std::path::Path::new(path); if !path.exists() { eprintln!("File path does not exists: {:?}", path); return Err(()); } let f = std::fs::File::open(path).unwrap(); Ok(std::io::BufReader::new(f)) } pub...
#![feature(alloc_error_handler)] #![no_std] #![no_main] // Required to use the `alloc` crate and its types, the `abort` intrinsic, and a // custom panic handler. #![feature(core_intrinsics, lang_items)] extern crate alloc; extern crate wee_alloc; // Use `wee_alloc` as the global allocator. #[global_allocator] static ...
use num_derive::FromPrimitive; pub const SCREEN_WIDTH: usize = 80; pub const SCREEN_HEIGHT: usize = 25; /// A single character in the `ConsoleState`'s buffer. #[derive(Clone, Copy, Debug, PartialEq)] pub struct ConsoleChar { pub char_code: u8, /// Note that background colours 0x8-0xf are actually the same as 0x0-0x...
pub mod parse; pub mod token; pub use token::tokenize;
use crate::runtime::COMPONENT_CALL_STACK; use crate::tracked_call::TrackedCallId; #[derive(Default)] pub struct __ComponentCallStack(Vec<TrackedCallId>); impl __ComponentCallStack { pub fn push(component_id: TrackedCallId) { COMPONENT_CALL_STACK.with(|call_stack| { call_stack ....
extern crate rand; // ADDITIONAL FUNCTIONS pub fn random_fields_indexes() -> Vec<usize> { let mut indexes : Vec<usize> = (0..12).into_iter().collect(); for i in 0..12{ // rand % (12-i) --> choose index among (12-i) indexes // + i --> the first i indexes are set up, we want to set the ...
use glium::{ Surface, uniform, index::NoIndices, index::PrimitiveType, glutin::{ event_loop::ControlFlow, event::*, }, }; use std::time::{Duration,Instant}; use vsm::{ gl::*, util::*, app::*, vm::*, }; use nalgebra_glm as glm; use glm::{ Vec2,Mat4, }; const F...
use serde::{Deserialize, Serialize}; use serde_json::Value as Json; use svm_layout::{FixedLayout, Id, Layout}; use svm_types::{CtorsSection, DataSection}; // Note: at the time of writing (2021-07-26), we don't care about most fields // within the "meta" JSON. As such, the [`TemplateMeta`] sub-entities can be // remov...
// Physical memory layout // qemu -machine virt is set up like this, // based on qemu's hw/riscv/virt.c: // // 00001000 -- boot ROM, provided by qemu // 02000000 -- CLINT // 0C000000 -- PLIC // 10000000 -- uart0 // 10001000 -- virtio disk // 80000000 -- boot ROM jumps here in machine mode // -kernel load...
use crate::{utils::g2, EcdaaError}; use alloc::{format, vec}; use mcl_rust::{Fr, G2}; use crate::utils::rand_fr; pub struct ISK { pub x: Fr, pub y: Fr, } impl ISK { pub fn new(x: Fr, y: Fr) -> Self { Self { x, y } } pub fn random() -> Self { let x = rand_fr(); let y = ran...
use std::{ collections::BTreeMap, fs::{self, File}, io::{BufRead, BufReader, BufWriter, Write}, path::PathBuf, }; use indicatif::{ProgressBar, ProgressStyle}; use memmap::{Mmap, MmapOptions}; use rayon::prelude::*; use crate::output_set::{ index::{LowerInvert, OutputSetIndex}, OutputSet, }; s...
//! Readers and writers for common bioinformatics file formats. pub mod fastq; pub mod fasta; pub mod bed; pub mod gff;
pub mod conf_file; pub mod interface; pub use interface::Interface; pub mod peer; pub use peer::Peer; pub mod privatekey; pub use privatekey::PrivateKey; pub mod publickey; pub use publickey::PublicKey; pub mod presharedkey; pub use presharedkey::PresharedKey; pub struct Config { pub name: String, pub int...
#[allow(unused_imports)] use crate::core::matcher::{Matcher, Matcherable};
//! A lightweight logger. //! //! The `Logger` provides a single logging API that abstracts over the actual log //! sinking implementation. //! //! A log request consists of a _level_ and a _message_. //! //! # Use //! //! The basic logging of the `Logger` is through the following macros: //! //! - [`emerge!`] system i...
use std::mem::transmute; use schema::Schema; use types::{ToAvro, Value}; use util::{zig_i32, zig_i64}; /// Encode a `Value` into avro format. /// /// **NOTE** This will not perform schema validation. The value is assumed to /// be valid with regards to the schema. Schema are needed only to guide the /// encoding for ...
//! A simple reverse proxy, to be used with [Hyper] and [Tokio]. //! //! The implementation ensures that [Hop-by-hop headers] are stripped correctly in both directions, //! and adds the client's IP address to a comma-space-separated list of forwarding addresses in the //! `X-Forwarded-For` header. //! //! The implement...
use std::fmt; use crate::gen::rust::component::RustPathComponent; use crate::gen::rust::ident::RustIdent; use crate::gen::rust::ident_with_path::RustIdentWithPath; use crate::gen::rust::rel_path::RustRelativePath; #[derive(Default, Eq, PartialEq, Debug, Clone)] pub(crate) struct RustPath { pub(crate) absolute: bo...
extern crate crc; use self::crc::crc32; #[derive(PartialEq, Debug)] pub enum RconMessageType { Login = 0, Command = 1, Log = 2, } fn calc_crc(payload: &Vec<u8>) -> [u8; 4] { return unsafe { std::mem::transmute(crc32::checksum_ieee(payload.as_slice()).to_le()) }; } fn create_header() -> Vec<u8> { v...
use std::sync::atomic::{AtomicBool, Ordering}; use futures::channel::mpsc::UnboundedSender; use log::{debug, error}; use tentacle::secio::error::SecioError; use tentacle::{ context::ServiceContext, error::{DialerErrorKind, HandshakeErrorKind, ListenErrorKind}, multiaddr::Multiaddr, service::{ServiceErr...
use std::io::{self, Cursor}; use std::net::SocketAddr; use std::thread; use nom::IResult; use umio::{ELoopBuilder, Dispatcher, Provider}; use announce::AnnounceRequest; use error::ErrorResponse; use request::{self, TrackerRequest, RequestType}; use response::{TrackerResponse, ResponseType}; use scrape::ScrapeRequest;...
use std::fmt; use std::slice; use std::str::{self, FromStr}; /// A value paired with its "quality" as defined in [RFC7231]. /// /// Quality items are used in content negotiation headers such as `Accept` and `Accept-Encoding`. /// /// [RFC7231]: https://tools.ietf.org/html/rfc7231#section-5.3 #[derive(Debug, Clone, Par...
use crate::std::backends::sfml::Sfml; use std::sync::mpsc::Sender; use crate::bounds::{Bounds, ArbitratedBounds}; use crate::action::draw::{Draw, DrawAction, DynamicDrawableComponent, Color}; use crate::backend::Backend; use crate::cartesian::Cartesian; fn rotate( point: (f64, f64), angle: f64) -> (f64, f64) { let...
extern crate wiringpi; use wiringpi::pin::Value::{High, Low}; use std::time::Duration; use std::thread; fn main() { //Setup WiringPi with its own pin numbering order let pi = wiringpi::setup(); //Use WiringPi pin 0 as output let pin = pi.output_pin(0); loop { //Set pin 0 to high and wait...
use std::env; use std::f32; use std::process; fn usage() { println!("Usage: spiral num"); } fn find_range(n: u32) -> (u32, u32) { let sq = (n as f32).sqrt().floor() as u32; if sq % 2 == 0 { return ( (sq - 1).pow(2), (sq + 1).pow(2)) } else { return (sq.pow(2), (sq + 2).pow(2)); } ...
#![allow(dead_code)] #![feature(core,collections,old_path,old_io)] extern crate regex; extern crate num; use std::old_io::{File, BufferedReader, Append, Write}; mod counting_dna; mod dna_rna_transcription; mod dna_reverse_complement; mod rabbit_fib; mod calculate_max_gc_content; mod hamming_distance; mod mendel; mod...
use crate::front_models::user_equipments::FrontDisplayUserEquipment; use crate::get_guid_value; use crate::models::user_equipments::{NewUserEquipment, UserEquipment}; use crate::schema::user_equipments; use anyhow::{bail, Result}; use diesel::prelude::*; impl UserEquipment { pub fn get_front_display_user_equipment...
use hdk::prelude::holo_hash::EntryHashB64; use hdk::prelude::*; use crate::chess_game_result::game_result_tag; pub fn get_my_current_games() -> ExternResult<Vec<EntryHashB64>> { let links = get_current_games_for(agent_info()?.agent_initial_pubkey)?; Ok(links .into_iter() .map(|l| EntryHashB64...
// TODO: write some tests use std::collections::VecDeque; use super::Endpoint; use super::Message; /// A message queue which is checked in ipc RETRIEVE, to /// check for available messages pub struct MessageQueue { // Vector containing held messages. When an entry is consumed, // we replace it with a `None`...
use std::env; use std::fs; use std::path::Path; use std::ffi::OsStr; fn main() { let args: Vec<String> = env::args().collect(); println!("{:?}", args); let path = &args[1]; println!("Scanning {}", path); let php_file_paths: Vec<String> = get_php_files_in(&path); for file_path in php_file_pa...
#![feature(rust_2018_preview)] extern crate juniper; extern crate juniper_codegen_proc; mod simple { use juniper::GraphQLType; use juniper_codegen_proc::graphql_object; struct Simple; #[graphql_object] impl GraphQLType for Simple { type Context = (); fn simple(&self) -> i32 { ...
// create a trait to use on objects pub trait Weighted{ fn weight(&self) ->i32; } // implement trait for any i32 object impl Weighted for i32 { // named as weight will return a reference to a i32 fn weight(&self) ->i32 { *self } }
// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the MIT License, <LICENSE or http://opensource.org/licenses/MIT>. // This file may not be copied, modified, or distributed except according to those terms. use byteorder::{BigEndian, ReadBytesExt}; use bytes::{MutBuf, Take}; use futures::Async; us...
use crate::prelude::*; use core::convert::TryFrom; #[allow(non_camel_case_types)] #[derive(Clone, Debug)] #[repr(u8)] pub enum PrioWhich { PRIO_PROCESS = 0, PRIO_PGRP = 1, PRIO_USER = 2, } impl TryFrom<i32> for PrioWhich { type Error = crate::error::Error; fn try_from(raw: i32) -> Result<Self> { ...
use std::fmt::{Binary, Debug, Display, LowerHex, Octal, UpperHex}; use std::num::Wrapping; use std::ops::{ Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div, DivAssign, Mul, MulAssign, Not, Rem, RemAssign, Shl, ShlAssign, Shr, ShrAssign, Sub, SubAssign, }; macro_rules! def_har...
use ggez::graphics::Point2; use ggez::timer::get_delta; use ggez::Context; use debug::DebugText; use entities::{Entity, EntityData, EntityTag, Renderable}; use math::VectorUtils; use messages::{Message, MessageSender}; use std::time::Duration; use mekano::Mekano; use mekano_renderer; use mekano_renderer::Render; co...
/* https://leetcode-cn.com/problems/valid-palindrome/ 125. 验证回文串 给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。 说明:本题中,我们将空字符串定义为有效的回文串。 示例 1: 输入: "A man, a plan, a canal: Panama" 输出: true 示例 2: 输入: "race a car" 输出: false */ struct Solution; impl Solution { pub fn is_palindrome(s: String) -> bool { // le...
use chrono::{offset::Utc, DateTime}; use serde::{Deserialize, Serialize}; #[derive(Default, Serialize, Deserialize, Debug)] pub struct UserModel { #[serde(rename = "_id", skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(rename = "googleId", skip_serializing_if = "Option::is_none")...
use crate::error::Error; use crate::migrate::{AppliedMigration, MigrateError, Migration}; use futures_core::future::BoxFuture; use std::time::Duration; pub trait MigrateDatabase { // create database in url // uses a maintenance database depending on driver fn create_database(url: &str) -> BoxFuture<'_, Res...
use std::convert::TryInto; use std::fmt; use std::io::{self, Read, Write}; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use super::entropy::Entropy; use super::markers::{self, has_entropy, has_length}; use crate::Result; /// The representation of a single segment composing a Jpeg image. #[derive(Clone, P...
//! etc errors use std::{ convert::From, error::Error as StdError, fmt, fmt::{Debug, Display}, io::Error as IoError, }; /// etc Error #[derive(Debug)] pub enum Error { /// custom error type in etc Custom(String), /// io error transport IO(String), } /// support errors impl From<Io...
use rand::{Rng, weak_rng}; use rust_crypto::digest::Digest; use sha1::{Sha1, Sha1State}; use util::{read_u32v_be, write_u64_be}; fn mac_validation_oracle(key: &[u8], msg: &[u8], mac: &[u8]) -> bool { let mut m = Sha1::new(); m.input(key); m.input(msg); let mut out = [0_u8; 20]; m.result(&mut out); &out...
//---------------------------------------------------------------------------// // Copyright (c) 2017-2019 Ismael Gutiérrez González. All rights reserved. // // This file is part of the Rusted PackFile Manager (RPFM) project, // which can be found here: https://github.com/Frodo45127/rpfm. // // This file is licensed ...
use rand::Rng; use std::fmt; extern crate rand; #[derive(Clone)] pub struct Color { pub r: u8, pub g: u8, pub b: u8, } impl fmt::Display for Color { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Color({}, {}, {})", self.r, self.g, self.b) } } impl Color { pub fn gr...
use std::fmt::{self, Debug}; use super::{Block, BlockBuilder, BlockNum, Edge, Op}; /// A `BlockRef` is a reference for one of: /// /// * Not ready yet `Block` (i.e it's still being built) /// /// * Ready `Block` /// /// * No Block - references no `Block. /// Generally, it's a temporary state that should be use when...