text
stringlengths
8
4.13M
use actix_web::{http::StatusCode, HttpResponse, ResponseError}; use serde::Serialize; use std::fmt; #[derive(Debug, Serialize)] struct ErrorResponse { pub code: u16, pub message: String } impl ErrorResponse { pub fn from_error<T: ResponseError>(err: &T) -> Self { Self { code: err.stat...
#[doc = "Register `CSR2` reader"] pub type R = crate::R<CSR2_SPEC>; #[doc = "Register `CSR2` writer"] pub type W = crate::W<CSR2_SPEC>; #[doc = "Field `WUPF1` reader - Wakeup Pin flag for PA0"] pub type WUPF1_R = crate::BitReader; #[doc = "Field `WUPF2` reader - Wakeup Pin flag for PA2"] pub type WUPF2_R = crate::BitRe...
//! Represents a bot's intent to move to a new location. //! Currently only bots are allowed to move! //! use crate::components::{self, EntityComponent, PositionComponent}; use crate::indices::{EntityId, UserId, WorldPosition}; use crate::scripting_api::OperationResult; use crate::storage::views::View; use crate::table...
#![no_std] #![no_main] // Define necessary functions for flash loader // // These are taken from the [ARM CMSIS-Pack documentation] // // [ARM CMSIS-Pack documentation]: https://arm-software.github.io/CMSIS_5/Pack/html/algorithmFunc.html use core::slice; use gd32vf103_pac::{FMC, RCU}; use panic_abort as _; /// Segger...
#![cfg_attr(feature = "clippy", feature(plugin))] #![cfg_attr(feature = "clippy", plugin(clippy))] #[macro_use] extern crate error_chain; extern crate hex; extern crate log; extern crate reqwest; extern crate ring; extern crate serde; extern crate serde_json; extern crate tungstenite; extern crate url; #[macro_use] ...
#[cfg(test)] mod tests { use crate::ctr::break_ctr; use crate::ctr::ctr; use crate::util::read_base64_file_line_by_line; use std::iter; use std::str; // Twentieth cryptopals challenge - https://cryptopals.com/sets/3/challenges/20 #[test] fn challenge20() { let key = "YELLOW SUBM...
use crate::SwappableVec; pub fn sort(arr: &mut SwappableVec) { build_max_heap(arr); for i in (0..arr.len()).rev() { arr.swap(0, i); max_heapify(arr, 0, i); } } /// Creates an in-place max-heap of given slice. /// The largest value will be at the first index. fn build_max_heap(a...
use crate::constants::{CAP_SHIFT, MOVE_CAPTURE, MOVE_CASTLING, MOVE_DOUBLE_PUSH, MOVE_ENPASSANT, MOVE_NORMAL, MOVE_PROM_CAP, MOVE_PROMOTION, PROM_SHIFT}; #[derive(Eq, PartialEq, Copy, Clone)] pub struct Rank(pub u8); #[derive(Eq, PartialEq, Copy, Clone)] pub struct File(pub u8); #[derive(Eq, PartialEq, Copy, Clone)]...
use crate::math::*; use crate::types::*; use ndarray::{Array, Dimension}; use std::cell::{Ref, RefCell}; use std::ops::Deref; use std::rc::Rc; pub trait Param<T> { // fn new(p: T) -> Self; fn store(&self, g: T); fn p(&self) -> Ref<T>; } #[derive(Default)] pub struct P1<T: Default> { /// データ本体 _p: ...
extern crate dcp_utils; use std::collections::HashMap; // 1.1 // Get Product of all other elements without using division // expects elements len to be greater than 1 fn get_product_of_other(elements: &Vec<i32>, products_out: &mut Vec<i32>) { // [1,2,3,4,5] // before [1, 2, 6, 24, 120] // after[120, 120,...
fn main ( ) { fn factor_sum(n: i32) -> i32 { let mut v = Vec::new(); //create new empty array for x in 1..n-1 { //test vaules 1 to n-1 if n%x == 0 { //if current x is a factor of n v.push(x); //add x to the array } } let sum = v.iter().sum(); //iterate over array and ...
#[doc = "Register `ATCR1` reader"] pub type R = crate::R<ATCR1_SPEC>; #[doc = "Register `ATCR1` writer"] pub type W = crate::W<ATCR1_SPEC>; #[doc = "Field `TAMP1AM` reader - Tamper 1 active mode"] pub type TAMP1AM_R = crate::BitReader; #[doc = "Field `TAMP1AM` writer - Tamper 1 active mode"] pub type TAMP1AM_W<'a, REG,...
use iron::prelude::*; use iron_sessionstorage::traits::SessionRequestExt; use lettre::email::EmailBuilder; use lettre::transport::smtp::{SecurityLevel, SmtpTransportBuilder}; use lettre::transport::smtp::authentication::Mechanism; use lettre::transport::EmailTransport; use uuid::Uuid; use common::http::*; use common::...
use super::log::DataDogLog; use crate::client::AsyncDataDogClient; use flume::{Receiver, RecvError, Sender, TryRecvError}; pub(crate) async fn logger_future<T>( mut client: T, logs: Receiver<DataDogLog>, mut selflog: Option<Sender<String>>, ) where T: AsyncDataDogClient, { let mut store = Vec::new(...
/// Formatting represent a logic of formatting of a cell. #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub struct Formatting { /// An setting to allow horizontal trim. pub horizontal_trim: bool, /// An setting to allow vertical trim. pub vertical_trim: bool, /// An setting ...
pub fn setup() { println!("We are setting things up!") }
pub(crate) mod map; pub(crate) mod restructure; use std::fmt::Formatter; use syn::braced; use syn::parse::{Parse, ParseStream, Result}; use syn::punctuated::Punctuated; /// An ordered list of attribute arguments, which consists of (id, param-args) pairs. #[derive(Clone)] pub(crate) struct AttributeArgList { pub(c...
//! TDigest implementation. use std::cell::RefCell; use std::f64; use std::fmt::Debug; #[derive(Clone, Debug)] struct Centroid { sum: f64, count: f64, } impl Centroid { fn fuse(&self, other: &Self) -> Self { Self { count: self.count + other.count, sum: self.sum + other.sum,...
#![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 AzureAdOnlyAuthenticationProperties { #[serde(rename = "azureADOnlyAuthentication")] pub azure_ad_only_auth...
//! blcfill /// Fill from lowest clear bit pub trait Blcfill { /// Clears all bits below the least significant zero bit of `self`. /// /// If there is no zero bit in `self`, it returns zero. /// /// # Instructions /// /// - [`BLCFILL`](http://support.amd.com/TechDocs/24594.pdf): /// -...
use crate::{client::Client}; use ureq::{Error}; use serde::{Deserialize}; const ENDPOINT: &str = "subaccounts"; #[derive(Deserialize)] pub struct AutoTopUp { pub amount: Option<f32>, pub threshold: Option<f32>, } #[derive(Deserialize)] pub struct Contact { pub name: String, pub email: String, } #[de...
#[doc = "Reader of register ADV_CONFIG"] pub type R = crate::R<u32, super::ADV_CONFIG>; #[doc = "Writer for register ADV_CONFIG"] pub type W = crate::W<u32, super::ADV_CONFIG>; #[doc = "Register ADV_CONFIG `reset()`'s with value 0x20ff"] impl crate::ResetValue for super::ADV_CONFIG { type Type = u32; #[inline(a...
//! Hydroflow's inner (intra-subgraph) compiled layer. //! //! The compiled layer mainly consists of [`Iterator`]s (from standard Rust) //! and [`Pusherator`](::pusherator::Pusherator)s (from the [`pusherator`] crate). This module //! contains some extra helpers and adaptors for Hydroflow to use with them. pub mod pull...
use apllodb_shared_components::{ApllodbError, ApllodbResult, Expression}; use apllodb_storage_engine_interface::{RowSelectionQuery, SingleTableCondition, TableName}; use serde::{Deserialize, Serialize}; use crate::Record; /// Conditional expression. Given a Record, this is evaluated into boolean. #[derive(Clone, Part...
fn sum_of_any_subset(n: isize, f: &[isize]) -> bool { let len = f.len(); if len == 0 { return false; } if f.contains(&n) { return true; } let mut total = 0; for i in 0..len { total += f[i]; } if n == total { return true; } if n > total { ...
use thiserror::Error; /// Main error type that SteamAuthenticator uses. /// /// If an internal error occurs, it simply delegates to the correct error type. /// Generally, this isn't a good strategy, but 90% of the errors happen because of a /// misconfiguration, they are not recoverable and we choose to just fail fast...
static INPUT: &str = include_str!("input"); fn main() { println!("Day 5, Part 1: {}", part1(INPUT.trim().chars())); println!("Day 5, Part 2: {}", part2(INPUT.trim().chars()).unwrap()); } fn part1<T: Iterator<Item = char>>(s: T) -> usize { s.fold(Vec::new(), |mut cache, c| { match cache.last() { ...
pub mod expr; pub mod stmt; use std::iter::Peekable; use crate::{ ast::Stmt, lexer::{ token_kind::TokenKind, types::{Span, Token}, Lexer, }, }; /// Parser which holds the input string to extract the source text of tokens and the lexer itself pub struct Parser<'input...
#![cfg(feature = "std")] #![cfg(feature = "additional-controls")] #![cfg(not(target_arch = "wasm32"))] use cddl::{parser, validate_json_from_str, validator::json}; use std::fs; #[test] fn verify_cddl_compiles() -> Result<(), parser::Error> { for file in fs::read_dir("tests/fixtures/cddl/").unwrap() { let file =...
#![feature(test)] #[macro_use] extern crate stream_cipher; extern crate salsa20; bench_sync!(salsa20::Salsa20);
mod contract { #![allow(non_snake_case)] #![allow(dead_code)] use pwasm_abi_derive::eth_abi; use pwasm_abi::types::{U256, Address}; use std::collections::HashMap; #[eth_abi(Endpoint, Client)] pub trait TokenContract { fn constructor(&mut self, total_supply: U256); #[constant] fn balanceOf(&mut self, _own...
use crate::itertools::Itertools; use std::str; pub(crate) fn day08() { let line = std::fs::read_to_string("data/day08.txt").expect("Failed to open input"); let layers = line .trim() .as_bytes() .chunks(150) .map(str::from_utf8) .collect::<Result<Vec<_>, _>>() .un...
use crate::core::*; pub fn client_loop() { let mut stream = match cmd::open() { Ok(s) => s, Err(e) => { println!("{}", e); return; } }; match cmd::login(&mut stream) { Ok(m) => println!("{}", m), Err(e) => { println!("{}", e); ...
#![allow(clippy::declare_interior_mutable_const)] use std::cmp; use xitca_http::http::header::HeaderValue; pub(super) trait QueryParse { fn parse_query(self) -> u16; } impl QueryParse for Option<&str> { fn parse_query(self) -> u16 { let num = self .and_then(|this| { use a...
#[cfg(test)] pub mod evo; #[test] pub fn gen_test() { println!("gen"); }
use nom::multispace; use nom::{IResult, Err, ErrorKind, Needed}; use std::str; use column::Column; use common::FieldExpression; use common::{as_alias, field_definition_expr, field_list, unsigned_number, statement_terminator, table_list, table_reference, column_identifier_no_alias}; use condition::{conditi...
extern crate openssl; extern crate rand; use openssl::symm::{Cipher, Crypter, Mode}; use std::io::prelude::*; use read; use write; pub const TEST: &[u8] = b"It was the best of times, it was the worst of times."; #[test] fn basic_read_encrypt() { let source: &[u8] = TEST; let key: [u8; 128 / 8] = rand::rando...
use criterion::BenchmarkId; use criterion::Criterion; use criterion::{criterion_group, criterion_main}; use lc_render::{BandScale, BarsValues, Chart, LineView, LinearScale, VerticalBarView}; const SIZE: i32 = 800; const MARGIN: i32 = 40; fn create_line_and_vertical_bar_chart(values_count: usize) { let x_scale = B...
#[macro_use] pub mod macros; pub mod traits; pub mod mesh; pub mod material; pub mod texture; pub mod camera; pub mod light; pub mod animation; pub mod node; pub use traits::*; pub use macros::*; pub use mesh::*; pub use material::*; pub use texture::*; pub use camera::*; pub use light::*; pub use animation::*; pub...
#![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 storage_insights { use crate::models::*; use reqwest::StatusCode; use snafu::{ResultExt, Snafu}; pub a...
use std::{thread, time::Duration}; use sudo_test::{Command, Env, TextFile}; use crate::{Result, PANIC_EXIT_CODE, SUDOERS_ALL_ALL_NOPASSWD}; mod flag_check; mod flag_file; mod flag_help; mod flag_no_includes; mod flag_owner; mod flag_perms; mod flag_quiet; mod flag_strict; mod flag_version; mod include; mod sudoers; ...
//! A [`Visitor`](`crate::visit::Visitor`) implementation which creates events for //! files which differ from the content it would have once deployed. use crate::{ profile::LayeredProfile, profile::{source::PunktfSource, transform::Transform}, visit::*, }; use std::path::Path; /// Applies any relevant [`Transform...
use super::schema::*; use diesel::*; use schema_dsl::*; #[test] fn union_set_returns_set() { use schema::users::dsl::*; let connection = connection(); connection.execute("INSERT INTO users (name) VALUES ('A'), ('B'), ('C'), ('D')") .unwrap(); let expected_data = vec![ "Tess".to_string...
pub use typehack::binary::{Nat, B0, B1, B2, B3, B4, B5, B6, B7, B8, B9, B10, B11, B12, B13, B14, B15, B16, B17, B18, B19, B20, B21, B22, B23, B24, B25, B26, B27, B28, B29, B30, B31, B32, B64, B128, B256, B512}; pub use typehack::data::{Data, DataVec}; pub use typeha...
// 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 core::{ fmt::{self, Debug, Display, Formatter, LowerHex}, ops::{Deref, DerefMut}, }; use crate::{ par...
use byteorder::ByteOrder; /// Timestamp resolution of the pcap #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum TsResolution { MicroSecond, NanoSecond } /// Endianness of the pcap #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum Endianness { Big, Little } impl Endianness { pub fn is_li...
fn box_it() { let t = (12, "eggs"); let b = Box::new(t); // allocate a tuple in the heap }
use std::fmt; #[derive(Debug)] pub enum Route { UserAbout(String), SubredditAbout(String), SubredditHot(String), SubredditNew(String), SubredditRising(String), SubredditArticle(String, String), Info, Comment, Submission(String), SubmissionComment(String, String), Custom(Stri...
pub struct QueryBuilder { table: String, select: String, _where: String, } impl QueryBuilder { pub fn new() -> QueryBuilder { QueryBuilder { table: "".to_string(), select: "".to_string(), _where: "".to_string(), } } pub fn table(&mut self, arg: String) -> &mut QueryBuilder { ...
use crate::domain::{self, UserId}; use anyhow::anyhow; use tide::{http::headers::AUTHORIZATION, Request, Response, StatusCode}; pub async fn secret(req: Request<impl domain::db::Db>) -> tide::Result { let user = UserId(req.param("user")?.to_string()); if domain::can_access_secret(req.state(), &user)? { ...
//! Parsing logic use syn::punctuated::Punctuated; use syn::{parenthesized, token, Attribute, Expr, ExprLet, Ident, Result, Token, Visibility}; use syn::{ parse::{Parse, ParseStream}, Field, }; #[derive(Clone)] pub struct Program { pub relations: Vec<Relation>, pub rules: Vec<Rule>, } impl Parse for ...
pub fn largest_number(nums: Vec<i32>) -> String { let mut nums = nums.into_iter().map(|num| format!("{}", num)).collect::<Vec<String>>(); nums.sort_by(|a, b| (b.to_string() + a).cmp(&(a.to_string() + b))); if nums[0] == "0" { nums[0].clone() } else { nums.into_iter().fold("".to_string(),...
#[doc = "Register `CALIBR` reader"] pub type R = crate::R<CALIBR_SPEC>; #[doc = "Register `CALIBR` writer"] pub type W = crate::W<CALIBR_SPEC>; #[doc = "Field `DC` reader - Digital calibration"] pub type DC_R = crate::FieldReader; #[doc = "Field `DC` writer - Digital calibration"] pub type DC_W<'a, REG, const O: u8> = ...
#![allow(dead_code, non_snake_case)] /// This file contains various traits/functions for interacting with Cocoa/objc classes which /// are not available in the cocoa/objc crates. They should probably be migrated to them soon. use cocoa::base::{BOOL, class, id}; use cocoa::foundation::NSUInteger; use std::any::Any; p...
use crate::core::bearer_token_client::BearerTokenClient; use crate::core::key_client::get_sas_token_parms; use crate::core::rest_client::ServiceType; use crate::core::{ConnectionString, KeyClient}; use crate::PerformRequestResponse; use azure_core::errors::AzureError; use http::request::Builder; use hyper::{self, Metho...
/// This is the lower level abstraction over hal-gfx. You may want to use this if you /// are doing some higher level stuff but you probably don't *need* to touch this #[macro_use] /// the lower level abstractions for graphics, a regular user /// shouldn't really need to deal with this. pub mod gfxal; mod renderer; pu...
use std::io::{stdin, stdout, Write}; const MAX: usize = 9; struct Candidate { name: String, votes: u8 } fn main() -> Result<(), Box<dyn std::error::Error>> { use std::env::args; use std::process::exit; if args().len() < 2 { exit(1); } let candidate_count = args().len() - 1; if candidate_...
#[doc = "Reader of register RES_CAUSE"] pub type R = crate::R<u32, super::RES_CAUSE>; #[doc = "Writer for register RES_CAUSE"] pub type W = crate::W<u32, super::RES_CAUSE>; #[doc = "Register RES_CAUSE `reset()`'s with value 0"] impl crate::ResetValue for super::RES_CAUSE { type Type = u32; #[inline(always)] ...
use caolo_sim::{ components::{EntityComponent, TerrainComponent}, executor::{GameConfig, SimpleExecutor}, indices::WorldPosition, pathfinding::find_path, prelude::{FromWorld, World}, }; use criterion::{criterion_group, Criterion}; use rand::prelude::SliceRandom; use rand::{rngs::SmallRng, SeedableRn...
//! This module implements a scheduler. use super::tcb::SleepTimeSortedTCB; use super::{ThreadState, TCB}; use alloc::binary_heap::BinaryHeap; use arch::{self, schedule, Architecture}; use core::mem::swap; use sync::time::Timestamp; use sync::Mutex; use sync::{disable_preemption, enable_preemption, restore_preemption_...
pub mod alter_table; pub mod create_table; pub mod delete; pub mod insert; pub mod select; pub mod update;
//! The `Error` type, which is a minimal wrapper around an errno value. //! //! We define the errno constants as individual `const`s instead of an //! enum because we may not know about all of the host's errno values //! and we don't want unrecognized values to create UB. #![allow(missing_docs)] use crate::imp; use s...
use crate::{ html::{DocumentNode, HtmlDocument, HtmlNode}, xpath::DocumentNodeSet, }; use super::{ApplyError, XpathAxes, XpathSearchItem, XpathSearchNodeType}; /// Search for an HTML tag matching the given search parameters in the given list of nodes. /// /// # Example: search for a root node using `has_super...
mod arg_parse; mod fetch_ip_addr; mod ip_addr_client; use anyhow::Result; use fetch_ip_addr::*; #[tokio::main] async fn main() -> Result<()> { let app = arg_parse::get_clap_app(); let matches = app.get_matches(); let client = arg_parse::from_ipaddr_client(&matches); eprintln!("fetch for {}", client....
// This file is part of Substrate. // Copyright (C) 2017-2020 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // ht...
use std::rc::Rc; pub mod chunk; pub mod reader; pub mod writer; /// decode Lua binary chunk to prototype structure pub fn decode(data: Vec<u8>) -> Rc<chunk::Prototype> { let mut r = reader::Reader::new(data); r.check_header(); r.read_byte(); r.read_proto() } pub fn encode(proto: Rc<ch...
/* TODO expand syntax test test test less fields in the Parser use Result? use combinators? */ use crate::lexer::{LexPos, Lexer, Token, TokenSet}; use crate::strtab::{Ident, Type}; use std::fmt; #[derive(Debug, Clone, PartialEq, Eq)] pub enum CompileError { ParseErr { position: LexPos,...
//! SChannel-specific functionality. pub use imp::TlsStreamExt; pub use imp::ErrorExt;
#![allow(proc_macro_derive_resolution_fallback)] extern crate base64; extern crate chrono; extern crate config as config_crate; #[macro_use] extern crate diesel; #[macro_use] extern crate failure; extern crate futures; extern crate futures_cpupool; extern crate hyper; extern crate hyper_tls; extern crate jsonwebtoken; ...
use std::collections::HashMap; use models::{Yaku, Card}; fn get_hand_score(cards: &Vec<Card>, month: usize) -> usize { let mut point_counters: HashMap<usize, usize> = HashMap::new(); let mut yaku_counters: HashMap<Yaku, usize> = HashMap::new(); let mut points = 0; for card in cards { *point_c...
pub mod aoc { use std::fs::File; use std::io::BufReader; pub fn load_data( filename: &str, ) -> std::result::Result<BufReader<File>, Box<dyn std::error::Error>> { let file = File::open(filename)?; Ok(BufReader::new(file)) } pub type Res<A> = std::result::Result<A, Box<...
use crate::Entity; pub trait Remove<E: Entity> { fn remove(&mut self, k: E::Key); } impl<E, T> Remove<E> for &mut T where E: Entity, T: Remove<E>, { fn remove(&mut self, k: E::Key) { (**self).remove(k) } }
extern crate roaring; use roaring::RoaringBitmap; #[test] fn array() { let bitmap: RoaringBitmap<u32> = (0..2000u32).collect(); assert_eq!((2000, Some(2000)), bitmap.iter().size_hint()); assert_eq!((0, Some(0)), bitmap.iter().skip(2000).size_hint()); } #[test] fn bitmap() { let bitmap: RoaringBitmap<u...
use crate::*; #[derive(Debug, Clone)] pub struct EnumInfo { method: IdentId, receiver: Value, args: Args, } impl EnumInfo { pub fn new(method: IdentId, receiver: Value, mut args: Args) -> Self { args.block = Some(MethodRef::from(0)); EnumInfo { method, receiver,...
// Copyright 2013 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-MIT or ...
use specs::*; use std::any::Any; use dispatch::sysbuilder::*; use dispatch::sysinfo::*; use dispatch::syswrapper::*; pub struct Builder<'a, 'b> { builder: DispatcherBuilder<'a, 'b>, } impl<'a, 'b> Builder<'a, 'b> { pub fn new() -> Self { Self { builder: DispatcherBuilder::new(), } } pub fn with<T>(self)...
// use crate::dsp::types::*; // use sdl2::event::Event as SdlEvent; // use sdl2::event::Event::MouseMotion as SdlMouseMotion; // use sdl2::gfx::primitives::DrawRenderer; // use std::path::Path; // use lyon::math::{point, Point}; // use lyon::path::builder::*; // use lyon::path::Path as LPath; // use lyon::tessellation...
use serde_json::Value as JSONValue; // use arrayvec::ArrayString; use std::hash::{Hash, Hasher}; use std::collections::hash_map::DefaultHasher; #[derive(Debug, Clone)] pub struct Value(u64, JSONValue); impl From<JSONValue> for Value { fn from(value: JSONValue) -> Self { Value( // could probabl...
use bigint::{Address, H256, U256}; use hexutil::*; use block::{Log, Receipt}; use sha3::{Digest, Keccak256}; use std::str::FromStr; use std::collections::HashMap; use std::sync::{Arc, Mutex}; use blockchain::chain::HeaderHash; use rpc::RPCLogFilter; use super::{RPCLog, Either}; use super::util::*; use error::Error; u...
use image::{self, DynamicImage}; use conrod_core::text::{font, Font}; use find_folder; use std; pub fn load_font(filename: &str) -> Font { let assets = find_folder::Search::KidsThenParents(3, 5).for_folder("assets").unwrap(); let path = assets.join(filename); match font::from_file(path) { Ok(data) =...
pub fn quad_eqn(a: f32, b: f32, c: f32) -> Option<(f32, f32)> { if a == 0.0 { return None; } let d = b.powi(2) - (4.0 * a * c); if d < 0.0 { return None; } let first = (-b + d.sqrt()) / (2.0 * a); let second = (-b - d.sqrt()) / (2.0 * a); Some((first, second)...
//! //! Error Handling //! use crate::JsonError; use crate::ReqwError; use crate::Deserialize; pub(crate) type InfluxResult<T> = Result<T, InfluxError>; pub(crate) trait InfluxErrorAnnotate<T> { fn annotate<M: ToString>(self, msg: M) -> InfluxResult<T>; } /// ## Chaining Support /// /// Project wide enumera...
mod ray; mod scene; mod material; // mod noise; mod bvh; mod object; pub use scene::*; pub use ray::*; pub use material::*; pub use bvh::*; // pub use noise::*;
#[macro_export] macro_rules! impl_fungible_token_core { ($contract: ident, $token: ident, $on_tokens_burned_block: block,) => { use near_contract_standards::fungible_token::core::FungibleTokenCore; use near_contract_standards::fungible_token::resolver::FungibleTokenResolver; #[near_bindgen]...
#[cfg(feature = "extern")] pub mod ex; #[cfg(feature = "python")] pub mod py; mod test; use std::f64::consts::PI; use crate::physics:: { PLANCK_CONSTANT, BOLTZMANN_CONSTANT }; use crate::physics::single_chain::ZERO; /// The structure of the thermodynamics of the SWFJC model in the isotension...
use std::iter::FromIterator; use serde_json; use super::genesis::PoolTransactions; use super::handlers::{ build_pool_catchup_request, build_pool_status_request, handle_catchup_request, handle_consensus_request, handle_full_request, handle_status_request, CatchupTarget, NodeReplies, }; use super::pool::Poo...
use aes_ctr::stream_cipher::generic_array::*; use aes_ctr::stream_cipher::*; use aes_ctr::*; use crate::key; pub fn aes_ctr_decrypt(data: &mut [u8], key: &[u8; 16], ctr: &[u8; 16], offset: u64) { let key = GenericArray::from_slice(key); let ctr = GenericArray::from_slice(ctr); let mut cipher = Aes128Ctr::n...
use crate::{ AccountName, Checksum256, UnsignedInt, Digest, Read, Write, NumBytes, SerializeData, utils::flat_map::FlatMap }; use alloc::string::String; use alloc::vec::Vec; use core::str::FromStr; use codec::{Encode, Decode}; #[cfg(feature = "std")] use serde::de::Error; #[derive(Clone, Debug, Read, Write...
mod cargo; pub mod lang; pub mod remote; pub mod util; use colored::*; use failure::Error; use indexmap::indexmap; use indexmap::IndexMap; use indexmap::IndexSet; use remote::Remote; use semver::Version; use semver::VersionReq; use std::collections::BTreeMap; use std::fs; use std::io::prelude::*; use std::path::Path; ...
#![feature(phase, globs)] #[phase(plugin)] extern crate regex_macros; extern crate regex; pub use client::{Client, ClientBuilder, ClientCallbacks}; pub use message::Message; pub mod client; pub mod constants; pub mod message;
use std::{ io::Read, net::TcpListener, sync::{mpsc, Arc, Mutex}, thread, time::{Duration, Instant}, }; use kiss3d::{camera::ArcBall, light::Light, window::Window}; use na::{ geometry::{Quaternion, UnitQuaternion}, Point3, }; use nalgebra as na; use visualizer::graphics::*; const HEADER: ...
fn main() { let mut v = Vec::new(); v.push(5); v.push(6); v.push(7); v.push(8); println!("{:#?}", v); let v2 = vec![1, 2, 3, 4, 5]; let third: &i32 = &v2[2]; println!("The third element is {}", third); match v2.get(3) { Some(fourth) => println!("The fourth element is {}", fourth), ...
// El discurso de Zoe // // Copyright (C) 2016 GUL UC3M // // 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 Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Th...
#[doc = "Register `CFGR` reader"] pub type R = crate::R<CFGR_SPEC>; #[doc = "Register `CFGR` writer"] pub type W = crate::W<CFGR_SPEC>; #[doc = "Field `PE` reader - Peripheral enable"] pub type PE_R = crate::BitReader; #[doc = "Field `PE` writer - Peripheral enable"] pub type PE_W<'a, REG, const O: u8> = crate::BitWrit...
#![crate_id = "ogg#0.1"] //use std::path::posix::Path; //use std::option::Option; //use std::vec::Vec; // A bitstream is represented by the stream itself (read to a certain point), // plus any information needed to process the remainder of the stream at that // point pub struct OggBitstream { bitstream : Box<Read...
use super::*; #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum Type { Var(Var), Infer(Underscore), Paren(Paren<Self>), Tuple(Tuple<Self>), Fn { args: Paren<Punctuated0<Self, Comma>>, ret: RetType, }, } impl Type { pub fn span(&self) -> Span { match self { ...
use objc::runtime::{Imp, Object}; use objc::*; use std::ffi::CStr; use std::os::raw::{c_char, c_void}; use crate::objc::*; #[inline(always)] pub fn to_c_str(s: &str) -> *const c_char { let mut bytes = String::from(s).into_bytes(); bytes.push(0); let ptr = bytes.as_ptr(); std::mem::forget(bytes); unsafe { std::ff...
use core::panic; use std::{ io::Read, net::{TcpListener, TcpStream}, }; use array2d::Array2D; use serde::__private::ser; use websocket::{ server::NoTlsAcceptor, sync::{Client, Server}, Message, }; use crate::puzzle::Puzzle; const SLEEP_TIME: u64 = 1000; #[derive(Debug, Clone)] pub struct ColumnB...
use nu_engine::CallExt; use nu_protocol::ast::Call; use nu_protocol::engine::{Command, EngineState, Stack}; use nu_protocol::{ Category, Example, IntoInterruptiblePipelineData, IntoPipelineData, PipelineData, Signature, Span, SyntaxShape, Value, }; #[derive(Clone)] pub struct Zip; impl Command for Zip { f...
use std::cmp::Reverse; use std::collections::{HashSet, VecDeque}; use hymns::grid::Grid; use hymns::runner::timed_run; use hymns::vector2::Point2; const INPUT: &str = include_str!("../input.txt"); type Point = Point2<usize>; fn find_low_points(grid: &Grid<u8>) -> Vec<Point> { grid.iter_points_values() ....