text
stringlengths
8
4.13M
use board_formatter; use lines; use board::Board; const OFFSET: usize = 1; pub fn format_board(board: &Board) -> String { let split_board = lines::split_board_into_rows( &number_spaces(&board_formatter::expand_board(board)), board.get_size().abs(), ); let mut formatted_board: String = "".t...
#![allow(dead_code)] use {Timer, EventEntry, now_micro}; use sys::Selector; use {EventFlags, EventBuffer, TimerCb, AcceptCb, EventCb, EndCb}; use std::io; use std::any::Any; use psocket::{TcpSocket, SOCKET}; ///回调的函数返回值, 如果返回OK和CONTINUE, 则默认处理 ///如果返回OVER则主动结束循环, 比如READ则停止READ, 定时器如果是循环的则主动停止当前的定时器 pub enum RetValue ...
fn main() { let i = 0; let _j: u16 = i; }
pub fn simplify_path(path: String) -> String { let mut directories = vec![]; for s in path.split('/') { if s == "." || s == "" { continue } else if s == ".." { if directories.len() > 0 { directories.pop(); } } else { directo...
use crate::completions::{Completer, CompletionOptions, SortBy}; use nu_engine::eval_call; use nu_protocol::{ ast::{Argument, Call, Expr, Expression}, engine::{EngineState, Stack, StateWorkingSet}, PipelineData, Span, Type, Value, CONFIG_VARIABLE_ID, }; use reedline::Suggestion; use std::sync::Arc; pub stru...
$NetBSD: patch-third__party_rust_authenticator_src_netbsd_mod.rs,v 1.1 2023/02/05 08:32:24 he Exp $ --- third_party/rust/authenticator/src/netbsd/mod.rs.orig 2020-09-02 20:55:30.875841045 +0000 +++ third_party/rust/authenticator/src/netbsd/mod.rs @@ -0,0 +1,10 @@ +/* This Source Code Form is subject to the terms of th...
//! //! //! This module provides Traits reprensentating open devices //! and their surfaces to render contents. //! //! --- //! //! Initialization of devices happens through an open file descriptor //! of a drm device. //! //! --- //! //! Initialization of surfaces happens through the types provided by //! [`drm-rs`](d...
use thiserror::Error; /// Library errors. #[derive(Error, Debug)] #[error("libsystemd error: {0}")] pub struct SdError(pub(crate) String); impl From<&str> for SdError { fn from(arg: &str) -> Self { Self(arg.to_string()) } } impl From<String> for SdError { fn from(arg: String) -> Self { Se...
use hydroflow::hydroflow_syntax; fn main() { let mut df = hydroflow_syntax! { source_iter() -> for_each(); }; df.run_available(); }
extern crate libloading as lib; extern crate patronus_provider; use self::error::Error; use patronus_provider as provider; pub use patronus_provider::AnnotationKind; use std::borrow::Cow; use std::env; use std::ffi::CStr; use std::ffi::CString; use std::fs; use std::os::raw::c_int; use std::path::Path; use std::path::...
#![allow(dead_code)] #[macro_use] extern crate failure; pub mod config;
#[derive(Debug, PartialEq, Eq, Clone)] /// A comment, effectively should be treated /// as white space. There are 3 kinds of comments /// according to the specification. /// /// - Single line comments: //comment /// - Multi line comments: /* comment */ /// - HTML comments: <!-- comment --> plus more! pub struct Comment...
pub enum TimeUnit { SECONDS, MINUTES, HOURS, } struct DateParser; impl DateParser { pub fn parse(date: &str) { } } #[cfg(test)] mod test { use super::DateParser; #[test] #[should_panic] fn date_parser_panic() { DateParser::parse(""); assert!(false); } }
//! Representation of the JSON format used by CNI. See the [CNI Specification](https://github.com/containernetworking/cni/blob/master/SPEC.md). use std::net::IpAddr; use std::{collections::HashMap, fmt}; use serde::{de, Deserialize, Serialize}; use serde_json::Value; /// A versioned CNI object. Many objects in the C...
#![cfg(feature = "alter-table")] use std::prelude::v1::*; use { super::MemoryStorage, crate::{ ast::ColumnDef, result::{Error, MutResult}, store::AlterTable, }, async_trait::async_trait, }; #[async_trait(?Send)] impl AlterTable for MemoryStorage { async fn rename_schema(se...
fn main() { // Statements are instructions that perform some action and do not return a value // Expressions evaluate to a resulting value let y = { let x = 3; x + 1 // expression }; println!("y is {}", y); print_labeled_measurement(5, 'h'); } fn print_labeled_measurement(value...
use syn::{parse_quote, ItemImpl}; use crate::generate::context::Context; impl Context { pub fn gen_partition(&self) -> ItemImpl { let ctx = self.get_context_ident(); parse_quote! { impl<'a, H> #ctx <'a, H> { pub fn get_partition_status(&self) -> a653rs::prelude::Partiti...
use super::Sha512; use super::K64; macro_rules! S0 { ($v:expr) => { $v.rotate_right(1) ^ $v.rotate_right(8) ^ ($v >> 7) }; } macro_rules! S1 { ($v:expr) => { $v.rotate_right(19) ^ $v.rotate_right(61) ^ ($v >> 6) }; } macro_rules! S2 { ($v:expr) => { $v.rotate_right(28) ^ $v....
#![allow(unused)] use std::{ future::Future, ops::Deref, pin::Pin, sync::{Arc, Mutex}, task::{Context, Poll, Waker}, time::Duration, }; use bevy::tasks::{Task, TaskPool}; use futures::{stream, Stream}; use turbulence::{ buffer::BufferPool, packet::{Packet, PacketPool}, packet_mult...
/* * Datadog API V1 Collection * * Collection of all Datadog Public endpoints. * * The version of the OpenAPI document: 1.0 * Contact: support@datadoghq.com * Generated by: https://openapi-generator.tech */ /// DashboardListDeleteResponse : Deleted dashboard details. #[derive(Clone, Debug, PartialEq, Serial...
use crate::{ animation::Animation, frame::Frame, sdf::{render_sdf, MultiUnion}, }; use itertools::Itertools; use nalgebra::{vector, SMatrix, Vector3}; use palette::{LinSrgba, Mix}; use rand::Rng; use sdfu::SDF; #[cfg_attr(feature = "visual", derive(bevy_inspector_egui::Inspectable))] pub struct Waves { ...
use {check_len, Error, Result, TryRead, TryWrite}; /// Context for &[u8] to determine where the slice ends. /// /// Pattern will be included in the result /// /// # Example /// /// ``` /// use byte::*; /// use byte::ctx::*; /// /// let bytes: &[u8] = &[0xde, 0xad, 0xbe, 0xef, 0x00, 0xff]; /// /// let sub: &[u8] = byte...
#![feature(exact_chunks)] #[macro_use] extern crate serde_derive; extern crate image; extern crate serde; extern crate serde_json; extern crate byteorder; use std::mem; use byteorder::{ WriteBytesExt, BigEndian}; use image::{RgbaImage, imageops}; #[derive(Deserialize, Debug)] struct Metadata { context: Option<st...
use serde::{Deserialize, Serialize}; pub type Date = i64; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Record { pub remotehost: String, pub rfc931: String, pub authuser: String, pub date: Date, pub request: String, pub status: u16, pub bytes: u64, }
use crate::ast::*; use crate::errors::MomoaError; use crate::location::*; use crate::tokens::*; use crate::Mode; use std::collections::HashMap; //----------------------------------------------------------------------------- // Parser //----------------------------------------------------------------------------- stru...
pub struct Image { pub width: u32, pub height: u32, pub pointer: usize, } impl Image { pub fn new(width: u32, height: u32, pointer: usize) -> Self { Image { width, height, pointer } } }
pub fn raindrops(n: usize) -> String { let mut out = "".to_string(); if (n % 3) == 0 { out.push_str("Pling"); } if (n % 5) == 0 { out.push_str("Plang"); } if (n % 7) == 0 { out.push_str("Plong"); } if out.is_empty() { out.push_str(&n.to_string()); }...
use std::ops::{Add,Mul,Sub}; #[derive(Debug, PartialEq, PartialOrd, Clone, Copy)] struct Point { x: f64, y: f64, } impl Add for Point { type Output = Self; fn add(self, other: Self) -> Self { Point { x: self.x + other.x, y: self.y + other.y, } } } impl...
pub fn evaluate(x: &[u8]) -> usize { let (remaining, result) = evaluate_expr(x); assert!(remaining.is_empty()); result } fn evaluate_expr(xs: &[u8]) -> (&[u8], usize) { match xs { [b' ', xs @ ..] => evaluate_expr(xs), [a @ b'0'..=b'9', xs @ ..] => evaluate_partial(xs, (*a - b'0') as usi...
use bevy::prelude::*; use crate::{ Materials, collider::{BallHitEvent}, }; pub struct SoundPlugin; impl Plugin for SoundPlugin { fn build(&self, app: &mut AppBuilder) { app .add_startup_system_to_stage("spawn", spawn_music.system()) .add_system(play_or_stop_musi...
pub struct TabsState { pub index: usize, } impl TabsState { pub const TITLES: &'static [&'static str] = &["Subscriptions", "Stream", "Retain"]; pub fn default() -> TabsState { TabsState { index: 0 } } pub fn next(&mut self) { self.index = (self.index + 1) % Self::TITLES.len(); ...
use connect_four::*; fn main() { let board = Board::new(); println!("{}", full_search(&board)); }
use std::ffi::OsStr; use std::path::PathBuf; use super::{debug_tool_message, ToolCommand}; use crate::error::{ErrorKind, Fallible}; use crate::layout::volta_home; use crate::platform::{CliPlatform, Platform, Sourced}; use crate::session::{ActivityKind, Session}; use crate::tool::bin_full_path; use crate::tool::{BinCon...
// Coding up the calculator example from this helpful video - superb playlist by engineer man! // https://youtu.be/RYTMn_kLItw use std::io::{ stdin, stdout, Write}; fn main() { println!("Welcome to the calculator!"); println!("--------------"); let mut num1 = String::new(); let mut num2 = String::ne...
// Copyright 2017 Google Inc. // // 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::distribution::{Continuous, ContinuousCDF}; use crate::function::{beta, gamma}; use crate::is_zero; use crate::statistics::*; use crate::{Result, StatsError}; use core::f64::INFINITY as INF; use rand::Rng; /// Implements the [Beta](https://en.wikipedia.org/wiki/Beta_distribution) /// distribution /// /// # E...
// Let's not care if the TERM variable is 'dumb' // since we depend on escape sequences pub const ALTERNATE_ON: &str = "\x1b[?1049h"; pub const ALTERNATE_OFF: &str = "\x1b[?1049l"; pub const CURSOR_SHOW: &str = "\x1b[?25h"; pub const CURSOR_HIDE: &str = "\x1b[?25l"; pub const CURSOR_TOP_LEFT: &str = "\x1b[;H"; pub cons...
// 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 ...
#[macro_use] extern crate log; extern crate getopts; extern crate rand; extern crate sdl2; extern crate simplelog; // External use getopts::Options; use sdl2::event::Event; use sdl2::keyboard::Keycode; // Std use std::env; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::path::Path; use std::time::{Duration, In...
extern crate bodyparser; use std::sync::Arc; use rustc_serialize::json; use iron::prelude::*; use iron::status; use iron::middleware::Handler; use router::Router; use uuid::Uuid; use repository::Repository; use todo::Todo; macro_rules! handler { ($x:ident) => { pub struct $x { repository: Ar...
#[doc = "Reader of register IPTAT_TRIM0"] pub type R = crate::R<u32, super::IPTAT_TRIM0>; #[doc = "Writer for register IPTAT_TRIM0"] pub type W = crate::W<u32, super::IPTAT_TRIM0>; #[doc = "Register IPTAT_TRIM0 `reset()`'s with value 0"] impl crate::ResetValue for super::IPTAT_TRIM0 { type Type = u32; #[inline(...
/// InternalTracker represents settings for internal tracker #[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct InternalTracker { /// Let only contributors track time (Built-in issue tracker) pub allow_only_contributors_to_track_time: Option<bool>, /// Enable dependencies for issues and pu...
fn main() {let vector_name = vec![val1,val2,val3]}
use crate::problem_datatypes::Solution; use crate::problem_datatypes::DataPoints; use crate::problem_datatypes::Constraints; use crate::fitness_evaluation_result::FitnessEvaluationResult; use crate::arg_parser::SearchType; use rand::Rng; use rand::rngs::StdRng; use rand::seq::SliceRandom; use std::io::{stdin, stdout, ...
use crate::{ ast::{ dec::{Dec, DecData}, exp::ASTExpData, field::Field_, stm::{AssignType, StmList, Stm_}, ty::{Type, TypeData, Type_}, var::Var_, }, wasm::il::{ module::{ModuleList, Module_}, stm::Stm_ as WASMStm_, util::WasmExpTy, ...
//! Game Management API. use crate::{ db::{self, Pool}, sync_match::{CurrentMatchState, MatchParameters, SynchronizedMatch}, timer::TimerConfig, ws, AppState, ServerError, }; use axum::{ extract::{Path, State}, routing::{get, post}, Json, Router, }; use serde::Deserialize; /// Adds the gam...
use std::io::Result; pub fn enable_vt_processing() -> Result<()> { #[cfg(windows)] { use crossterm_winapi::{ConsoleMode, Handle}; pub const ENABLE_PROCESSED_OUTPUT: u32 = 0x0001; pub const ENABLE_VIRTUAL_TERMINAL_PROCESSING: u32 = 0x0004; // let mask = ENABLE_VIRTUAL_TERMINAL_P...
fn main() { let program = vec![1,0,0,3,1,1,2,3,1,3,4,3,1,5,0,3,2,1,9,19,1,19,5,23,2,6,23,27,1,6,27,31,2,31,9,35,1,35,6,39,1,10,39,43,2,9,43,47,1,5,47,51,2,51,6,55,1,5,55,59,2,13,59,63,1,63,5,67,2,67,13,71,1,71,9,75,1,75,6,79,2,79,6,83,1,83,5,87,2,87,9,91,2,9,91,95,1,5,95,99,2,99,13,103,1,103,5,107,1,2,107,111,1,111...
#[macro_use] mod leak; use core::sync::atomic::{AtomicBool, AtomicPtr, Ordering}; use crate::song::{PlayData, Song, PlaybackCmd, CallbackState}; use crate::module_reader::{SongData, read_module}; use crate::producer_consumer_queue::{PCQHolder, ProducerConsumerQueue}; use std::sync::{mpsc, Mutex, Arc}; use core::optio...
extern crate clap; extern crate env_logger; #[macro_use] extern crate log; extern crate atty; extern crate shlex; extern crate skim; extern crate time; use derive_builder::Builder; use std::env; use std::fs::File; use std::io::{BufRead, BufReader, BufWriter, Write}; use clap::{crate_version, App, Arg, ArgMatches}; us...
#![no_main] #![no_std] extern crate cortex_m; extern crate cortex_m_rt; extern crate embedded_hal; extern crate panic_halt; extern crate stm32f042_hal as hal; extern crate numtoa; use hal::i2c::*; use hal::prelude::*; use hal::stm32; use embedded_hal::blocking::i2c::Write; use numtoa::NumToA; use cortex_m_rt::en...
#[doc = "Register `EWCR` reader"] pub type R = crate::R<EWCR_SPEC>; #[doc = "Register `EWCR` writer"] pub type W = crate::W<EWCR_SPEC>; #[doc = "Field `EWIT` reader - Watchdog counter window value These bits are write access protected (see ). They are written by software to define at which position of the IWDCNT down-c...
#![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 BlockchainMember { #[serde(flatten)] pub tracked_resource: TrackedResource, #[serde(default, skip_seria...
#[macro_use] extern crate approx; use itertools::enumerate; use ndarray::linalg; use ndarray::{LinalgScalar,ArrayView,ArrayViewMut,Array, Ix2}; use rand::Rng; use std::fs::File; use std::io::Write; use matrix_mult::naive_sequential; use matrix_mult::faster_vec; use std::ops::AddAssign; use matrix_mult::vectorisation; u...
use crate::parser::parser_defs; use crate::parser::svg_util; pub fn calculate_eliptical_arcs() { } fn calc_point_on_elipsis() -> (f32, f32) { (0.0, 0.0) }
extern crate game_of_life; use game_of_life::parsers::rle::*; #[test] fn test_rle_correct_file() { let input = "#N Pulsar #O John Conway #C A period 3 oscillator. Despite its size, this is the fourth most common oscillator (and by #C far the most common of period greater than 2). #C www.conwaylife.com/wiki/index.p...
//! This is the model object for a QueryPlan trimmed down to only contain _owned_ fields //! that are required for executing a QueryPlan as implemented in the existing Apollo Gateway. //! //! The [SelectionSet] in the `requires` field of a [FetchNode] is trimmed to only be a list of //! either a [Field] or an [InlineFr...
extern crate rayon; use itertools::enumerate; use matrix_mult::benchmark; use ndarray::LinalgScalar; use ndarray::{Array, ArrayView, Ix2,linalg}; use rayon_adaptive::Policy; use std::fs::File; use std::io::Write; use matrix_mult::vectorisation_packed_simd; use rand::Rng; const ITERS: usize = 5; fn average(numbers: [f...
struct AdamOptimizer { } struct CheckConfig { default: bool, alpha:f64, beta1:f64, beta2:f64, epsilon:f64, epoch:f64 } struct GradientDescent { } //impl CheckConfig { // fn is_default(&self) { // if self.default == true { // let (alpha, beta1, beta2, epsilon, epoch) = (0....
// The wasm-pack uses wasm-bindgen to build and generate JavaScript binding file. // Import the wasm-bindgen crate. use wasm_bindgen::prelude::*; // Our Add function // wasm-pack requires "exported" functions // to include #[wasm_bindgen] #[wasm_bindgen] pub fn add(a: i32, b: i32) -> i32 { return a + b; }
pub use super::blob::{ BlobBlockType, BlockList, BlockListRequired, BlockListSupport, BlockListType, BlockListTypeRequired, BlockListTypeSupport, }; pub use super::container::{ PublicAccess, PublicAccessRequired, PublicAccessSupport, StoredAccessPolicyListOption, StoredAccessPolicyListSupport, }; pub us...
use crate::error::*; use crate::*; use std::io::Write; use tempfile::Builder; pub struct Msi; pub type ModuleMsiInstaller = Installer<UnityModule, Msi, InstallerWithCommand>; impl InstallHandler for ModuleMsiInstaller { fn install_handler(&self) -> Result<()> { let installer = self.installer(); d...
trait Monad<A> { fn flatmap<B, C: Monad<B>>(&self, f: fn(A) -> C) -> C; } fn main() { println!("It compiled!"); }
//! Allows you to flip the outward face of a `Hittable`. use crate::{ aabb::AABB, hittable::{HitRecord, Hittable}, ray::Ray, }; /// A "holder" that does nothing but hold a `Hittable` and flip its face. #[derive(Debug, Clone)] pub struct FlipFace(Box<dyn Hittable>); impl FlipFace { /// Create a new ho...
#![no_main] #![no_std] extern crate stm32f411e_disco; use stm32f411e_disco::led; #[no_mangle] pub fn main() -> ! { unsafe { led::init(); } let red_led = led::Colour::Red; let blue_led = led::Colour::Blue; let green_led = led::Colour::Green; let orange_led = led::Colour::Orange; loop { ...
fn main() { let mut buffer = Vec::new(); let coefficients: [i64; 12]; let qlp_shift: i16; for i in 0..40{ buffer.push(i); } coefficients = [1,2,3,4,5,6,7,8,9,10,11,12]; qlp_shift = 3; for i in 12..buffer.len() { let prediction = coefficients .iter() ...
use amethyst::{ core::transform::components::{Parent, Transform}, ecs::prelude::Entity, prelude::*, renderer::{Camera, Projection}, }; pub fn init_camera(world: &mut World, view_dim: (u32, u32,), parent: Entity,) { let mut transform = Transform::default(); transform.translate_z(100.0); wor...
#[doc = "Reader of register IC_INTR_STAT"] pub type R = crate::R<u32, super::IC_INTR_STAT>; #[doc = "See IC_RAW_INTR_STAT for a detailed description of R_MASTER_ON_HOLD bit.\\n\\n Reset value: 0x0\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum R_MASTER_ON_HOLD_A { #[doc = "0: R_MASTER_ON_H...
#[macro_use] extern crate log; pub mod storage_manager;
use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug, PartialEq)] pub struct Source { pub tid: Option<String>, #[serde(rename(serialize = "ts", deserialize = "ts"))] pub supply_chain_start_timestamp_ms: Option<i64>, #[serde(rename(serialize = "ds", deserialize = "ds"))] pub ...
use crate::{cmd::*, keypair::Keypair, service::api, Error, PublicKey, Result, Settings}; use helium_crypto::Sign; use helium_proto::{BlockchainTxn, BlockchainTxnAddGatewayV1, Message, Txn}; use serde_derive::Deserialize; use serde_json::json; use std::{fmt, str::FromStr}; use structopt::StructOpt; /// Construct an add...
use lazy_static::lazy_static; use lox_proc_macros::U8Enum; #[cfg(feature = "debug_print_code")] use crate::debug::disassemble_chunk; use crate::{chunk::{Chunk, OpCode}, error::{CompileError, ErrorInfo}, scanner::{Scanner, Token, TokenKind}, value::{Objects, Value}}; pub struct Compiler<'source, 'objects> { chunk:...
use itertools::Itertools; use itertools::FoldWhile::{Continue, Done}; //use modular::*; use std::collections::{HashMap, HashSet}; use std::error; use std::io; use std::io::Read; use crate::day; use std::fmt; use std::ops::{Add, Mul, Sub}; /// Trait for modular operations on integers /// /// Implementing this trait al...
#![allow(dead_code)] use crate::prime::{sieve_of_eratosthenes}; fn problem(roof: u64) -> u64 { // @TODO replace for Sieve of Sundaram let primes = sieve_of_eratosthenes(roof); primes.into_iter().fold(0, |sum, p| sum + p) } #[cfg(test)] mod tests { use super::*; #[ignore] // this one unfortunately...
use std::{future::Future, marker::PhantomData, pin::Pin}; struct App { // handlers: Vec<Box<dyn Handler>>, services: Vec<Box<dyn Service>>, } impl App { pub fn new() -> Self { Self { services: vec![] } } pub fn handler<F, T, R>(mut self, f: F) -> Self where F: Handler<T, R>, ...
use super::obj::{GTwzobj, Twzobj}; use std::sync::atomic::{AtomicU32, Ordering}; pub struct Transaction { leader: GTwzobj, followers: Vec<GTwzobj>, } pub enum TransactionErr<E> { LogFull, Abort(E), } #[repr(C, packed)] struct RecordEntry<T> { ty: u8, fl: u8, len: u16, pad: u32, data: T, } const RECORD_ALLO...
#[doc = "Register `C1ISR` reader"] pub type R = crate::R<C1ISR_SPEC>; #[doc = "Field `ISF0` reader - Interrupt(N) semaphore n status bit before enable (mask)"] pub type ISF0_R = crate::BitReader<ISF0_A>; #[doc = "Interrupt(N) semaphore n status bit before enable (mask)\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug...
mod auth; mod error; use std::{fmt, net::SocketAddr, sync::Arc}; use eyre::Report; use handlebars::Handlebars; use hyper::{ client::{connect::dns::GaiResolver, HttpConnector}, header::{AUTHORIZATION, CONTENT_TYPE, LOCATION}, server::Server, Body, Client as HyperClient, Request, Response, StatusCode, }...
use crate::common::{self, *}; use std::{thread, time, any::TypeId}; pub struct TestableApplication { pub(crate) root: *mut Application, name: String, sleep: u32, } pub type Application = AApplication<TestableApplication>; impl<O: controls::Application> NewApplicationInner<O> for TestableApplic...
pub mod ast; pub mod printer; #[macro_use] extern crate lalrpop_util; lalrpop_mod!(pub grammar); // synthesized by LALRPOP pub fn parse(input: &str) -> Result<ast::Query, String> { match grammar::QUERYParser::new().parse(input) { Ok(ast) => Ok(ast), Err(e) => Err(format!("{:?}", e)), } } #[...
use crate::common::*; use crate::parse::Rule; use codespan::{FileId, Span}; use codespan_reporting::diagnostic::{Diagnostic, Label}; use codespan_reporting::term::emit; use pest::error::InputLocation; pub type Result<T> = std::result::Result<T, Error>; #[derive(Debug, Clone)] pub struct Error(Diagnostic); impl Error ...
use crate::parser::parser_defs; use crate::parser::svg_util; use crate::regex_defs; use crate::parser::svg_commands::bezier; use crate::parser::svg_commands::line; use crate::parser::path_defs; use regex::*; const BEZIER_RESOLUTION: f32 = 0.01; pub fn parse_svg_path(element: &quick_xml::events::BytesStart) -> Result...
#![allow(missing_docs)] use std::fmt::Debug; use std::num::ParseIntError; use num::traits::{ PrimInt, Num }; pub enum Either<Left, Right> { Left(Left), Right(Right) } pub trait Halveable { type HalfSize: ExtInt; fn split(self) -> (Self::HalfSize, Self::HalfSize); fn join(h1: Self::HalfSize, h2: Self::H...
use bevy_ecs::{reflect::ReflectComponent, system::Query}; use bevy_math::{vec3, Vec2}; use bevy_reflect::{Reflect, TypeUuid}; use bevy_render::camera::Camera; use bevy_transform::components::{GlobalTransform, Transform}; /// Component for sprites that should render according to a parallax relative to the camera. /// N...
// Copyright (c) 2018, ilammy // // Licensed under the Apache License, Version 2.0 (see LICENSE in the // root directory). This file may be copied, distributed, and modified // only in accordance with the terms specified by the license. use exonum::{ api::ServiceApiBuilder, blockchain::{Service, Transaction, Trans...
use crate::aoc_utils::read_input; use regex::Regex; pub fn run(input_filename: &str) { let input = read_input(input_filename); part1(&input); part2(&input); } struct Bag { color: String, number: u32, parent_color: String, } // Add this to the struct so we can `println!("{:?}", bags)` impl st...
use std::prelude::v1::*; use std::{i16, f64}; use super::super::*; use flt2dec::*; use flt2dec::bignum::Big32x36 as Big; use flt2dec::strategy::dragon::*; #[test] fn test_mul_pow10() { let mut prevpow10 = Big::from_small(1); for i in 1..340 { let mut curpow10 = Big::from_small(1); mul_pow10(&mu...
pub mod cornell_box; pub mod cornell_smoke; pub mod earth; pub mod last; pub mod random; pub mod simple_light; pub mod two_perlin_spheres; pub mod two_spheres;
/// Find all prime numbers less than `n`. /// For example, `sieve(7)` should return `[2, 3, 5]` pub fn sieve(n: u32) -> Vec<u32> { // TODO let mut ans = Vec::new(); let mut flag; for i in 2..n+1 { flag = 0; for j in 2..i { if i%j == 0 { flag = 1; }...
// Copyright (c) 2018-2020 Jeron Aldaron Lau // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0>, the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, or the ZLib // license <LICENSE-ZLIB or https://www.zlib.net/zlib_license.html> at ...
// Copyright 2020 IOTA Stiftung // // 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 w...
use crate::cli::Args; use color_eyre::eyre; use serenity::{ builder::CreateInteraction, http::Http, model::{ id::GuildId, interactions::{ApplicationCommandOptionType, Interaction}, }, prelude::*, }; mod event_handler; pub struct Bot { args: Args, } impl Bot { pub fn new() ...
use scene::Scene; use regex::Regex; use std::result; use std::num::ParseIntError; use std::str::FromStr; use vector::Vector3; use light::Light; use triangle::Triangle; use sphere::Sphere; use material::Material; struct ParsedScene<'a> { tokens: Vec<&'a str>, scene: &'a mut Scene, } pub fn parse_scene(scenedef...
pub fn get_conf() -> Result<ApiConfig, config::ConfigError>{ let mut file_path = dirs::config_dir().expect("Error locating config folder"); file_path.push("whothis_config.yaml"); let mut default_conf = config::Config::default(); match default_conf.merge(config::File::from(file_path)){ Ok(co...
extern crate rand; extern crate time; extern crate timely; extern crate differential_dataflow; use timely::dataflow::*; use timely::dataflow::operators::*; use timely::progress::timestamp::RootTimestamp; use rand::{Rng, SeedableRng, StdRng}; use differential_dataflow::operators::*; use differential_dataflow::collect...
#[macro_use] extern crate log; extern crate pretty_env_logger; #[macro_use] extern crate failure; #[macro_use] extern crate structopt; extern crate glob; extern crate pnet; use std::fmt; use std::fs::File; use std::io::{self, BufWriter, Read, Write}; use std::path::PathBuf; use failure::Error; use glob::glob; use str...
use log::*; use serde_json::Value; use tantivy::tokenizer::StopWordFilter; #[derive(Clone)] pub struct StopWordFilterFactory {} impl StopWordFilterFactory { pub fn new() -> Self { StopWordFilterFactory {} } pub fn create(self, json: &str) -> StopWordFilter { let v: Value = match serde_jso...
use std::{fs, io}; use std::sync::Arc; use io::{BufReader, ErrorKind}; use fs::File; use tokio_rustls::rustls::internal::pemfile; use tokio_rustls::rustls::{Certificate, NoClientAuth, PrivateKey, ServerConfig}; fn load_certs(filename: &str) -> io::Result<Vec<Certificate>> { let cert_file = File::open(filename)...
use aoc::read_data; use std::convert::Infallible; use std::error::Error; use std::str::FromStr; /// top-left (0,0) struct Position(usize, usize); impl Position { fn walk(&self, data: &[Iline]) -> Obj { data[self.1].get(self.0) } // walk_by (right, down) fn walk_by(&mut self, right: usize, down...
use std::f64::{INFINITY, NAN}; use wasm_bindgen::JsValue; use wasm_bindgen_test::*; use js_sys::*; #[wasm_bindgen_test] fn is_finite() { assert!(Number::is_finite(&42.into())); assert!(Number::is_finite(&42.1.into())); assert!(!Number::is_finite(&"42".into())); assert!(!Number::is_finite(&NAN.into()))...