text
stringlengths
8
4.13M
// Copyright (c) The diem-devtools Contributors // SPDX-License-Identifier: MIT OR Apache-2.0 //! Metadata management. use crate::{ reporter::TestEvent, runner::{RunDescribe, TestRunStatus, TestStatus}, test_list::TestInstance, }; use anyhow::{Context, Result}; use camino::{Utf8Path, Utf8PathBuf}; use chr...
use api_client::ApiClient; use serde_json; use serde_json::Value; use std::collections::HashMap; use std::io; use std::io::{Cursor, Read}; use std::io::ErrorKind as IoErrorKind; use utils::decode_list; use errors::*; chef_json_type!(NodeJsonClass, "Chef::Node"); chef_json_type!(NodeChefType, "node"); #[derive(Debug, ...
use std::ops::Index; use super::View; use crate::{dim, dim::Dim, Matrix}; pub trait RowView<'a>: View<'a, M = dim!(1)> {} impl<'a, T: 'a, V> RowView<'a> for V where V: View<'a, M = dim!(1), Entry = T> {} #[derive(Debug)] pub struct RowSlice<'a, T, M, N> { mat: &'a Matrix<T, M, N>, i: usize, } impl<'a, T, M...
use super::position::{Dir, Position}; use crate::util::clip; #[derive(PartialOrd, PartialEq, Copy, Clone, Debug)] pub struct Health(pub f32); pub(super) type Damage = Health; impl Health { pub fn suffer(&mut self, attack: Attack) -> Damage { self.0 -= attack.0; Health(attack.0) } } impl std::o...
fn main() { proconio::input! { n: usize, ab: [(usize, usize); n], } let mut ans = 0; for i in 0..n { for j in ab[i].0..=ab[i].1 { ans += j; } } println!("{}", ans); }
use crate::{ bson::doc, bson_util, cmap::StreamDescription, coll::Namespace, concern::ReadConcern, operation::{ test::{self, handle_response_test}, Operation, }, options::{CountOptions, Hint}, }; use super::CountDocuments; #[test] fn build() { let ns = Namespace { ...
use crate::grammar::ast::{BooleanLit, CharLit, Identifier, NumLit, ScopedName, StringLit}; use std::fmt::Debug; /// A Pattern used in pattern matching. #[allow(missing_docs)] #[derive(Clone, Debug)] pub enum Pattern<SourceCodeReference: Clone + Debug> { NumLit(NumLitPattern<SourceCodeReference>), CharLit(CharL...
#[cfg(test)] mod tests { extern crate rust_sike; use self::rust_sike::KEM; #[test] fn basic_sike_test() { let params = rust_sike::sike_p751_params(None, None).unwrap(); let kem = KEM::setup(params); // Alice runs keygen, publishes pk3. Values s and sk3 are secret l...
// Copyright (C) 2017 1aim GmbH // // 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 wr...
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use crate::server::Service; use failure_ext::Result; use serde::{Deserialize, Serialize}; /// Implementation of the control service. #[d...
/* * 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::io; use reverie::Pid; use safeptrace::Error as TraceError; use thiserror::Error; use sup...
fn square_area_to_circle(size:f64) -> f64 { std::f64::consts::PI * (size / 4.0) } #[test] fn test0() { assert_close(square_area_to_circle(9.0), 7.0685834705770345, 1e-8); } #[test] fn test1() { assert_close(square_area_to_circle(20.0), 15.70796326794897, 1e-8); } #[test] fn test2() { assert_close(square_area...
//! Handles finding a hooking library, and provides types and macros for using the library //! to hook game code. use cached::proc_macro::cached; use dlopen::symbor::Library; use eyre::Context; use log::error; fn get_single_symbol<T: Copy>(path: &str, sym_name: &str) -> eyre::Result<T> { let lib = Library::open(p...
use crate::common::{check_installed, create_virtualenv, maybe_mock_cargo, test_python_path}; use anyhow::{bail, Context, Result}; #[cfg(feature = "zig")] use cargo_zigbuild::Zig; use clap::Parser; use maturin::{BuildOptions, PlatformTag, PythonInterpreter}; use std::env; use std::path::Path; use std::process::Command; ...
use error_chain::{bail, error_chain}; error_chain! { foreign_links { IO(std::io::Error); String(std::string::FromUtf8Error); Regex(regex::Error); Env(std::env::VarError); } } pub fn run_cmd() -> Result<()> { use std::process::Command; use regex::Regex; #[derive(Pa...
use serde::{Deserialize}; use serde_json; use std::convert::TryFrom; use std::fmt::Display; use serde_repr::*; use cached::proc_macro::cached; #[derive(Deserialize, Debug)] pub struct Move { pub name: String, pub move_id: MoveId, pub available: bool, pub effects: String, #[serde(rename =...
use yew::prelude::*; pub struct Header { pub title: String, } #[derive(Clone, Default, PartialEq)] pub struct Props { pub title: String, } impl Component for Header { type Message = (); type Properties = Props; fn create(props: Self::Properties, _: ComponentLink<Self>) -> Self { Header {...
use iced::{Align, button, Button, Checkbox, Element, Row, Text, text_input, TextInput, VerticalAlignment}; use crate::central_ui; use crate::puzzle_backend; #[derive(Debug, Clone)] pub enum State { Main, New, Save, Open, OperationResult(String), } pub struct ControlsRow { new_but: button::Stat...
// use std::cmp::max; fn countSumOfTwoRepresentations3(n: i32, l: i32, r: i32) -> i32 { // max(n / 2 - max(l, n-r) + 1, 0) 0.max(n / 2 - l.max(n-r) + 1) }
use rusty8::cpu::CPU; use std::env; use std::fs::File; use std::time::Duration; use sdl2::event::Event; use sdl2::keyboard::Keycode; use sdl2::pixels::{Color, PixelFormatEnum}; use sdl2::render::TextureAccess; const WINDOW_WIDTH: u32 = 800; const WINDOW_HEIGHT: u32 = 600; fn main() -> std::io::Result<()> { let ...
extern crate wasm_bindgen; use wasm_bindgen::prelude::*; #[wasm_bindgen] pub fn sums(value: i32) -> i32 { value + 1 } #[wasm_bindgen] pub fn fibonacci(n: i32) -> i32 { match n { 0 | 1 => 1, _ => fibonacci(n - 1) + fibonacci(n - 2), } } #[cfg(test)] mod tests { #[test] fn it_works() { assert_eq...
//! `Monotonic` implementation based on RTC peripheral //! //! The RTC provides TICK events to the TIMER task via ppi in //! addition to handling the COMPARE events for the RTIC timer queue. // TODO - revisit this, probably just use the RTC for ticks, 24 bits of ticks // is probably fine // use absolute val in set_com...
#![allow(non_snake_case)] #![doc(html_logo_url = "https://s3-us-west-1.amazonaws.com/passivetotal-website/public/core-pt-logo-sm.png", html_favicon_url = "https://passivetotal.org/static/img/favicon/png", html_root_url = "https://passivetotal.org/")] // Disable warnings that JSON struct fields are camelCa...
use crate::player::{PlayerPlugin, Player}; use bevy::window::WindowMode; use bevy::prelude::*; mod screens; mod gamedata; mod gamestate; mod ground; mod player; use crate::ground::GroundPlugin; use crate::gamestate::*; use crate::screens::ScreensPlugin; use crate::gamedata::GameData; const SCREEN_WIDTH: f32 = 1280.0...
use std::cmp::Ordering; use std::collections::{HashMap, HashSet}; use std::fs::File; use std::io::{stdin, Write}; use tokenizers::tokenizer::Tokenizer; use vsm::indexing::build_index; use vsm::posting_list::{DocId, Frequency}; fn get_input() -> String { println!("Enter your query:"); let mut query = String::ne...
pub mod file_select; pub mod artifact;
mod builder; mod css; mod menu; mod stack; mod state; mod statusbar; mod toolbar; pub mod prelude; pub use state::{Message, SortOrder, State, ViewStyle}; use glib::clone; use std::path::Path; use std::thread; use super::nix_query_tree::exec_nix_store::NixStoreErr; use prelude::*; fn render_nix_store_err( stat...
use std::time::{Duration, Instant}; use toykio_runtime::{Delay, Toykio}; fn main() { let mut runtime = Toykio::new(); runtime.spawn(async { println!("Spawned"); let when = Instant::now() + Duration::from_millis(1500); let future = Delay { when }; println!("Wait 1.5sec..."); ...
/* Copyright ⓒ 2016 rust-custom-derive contributors. Licensed under the MIT license (see LICENSE or <http://opensource.org /licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of <http://www.apache.org/licenses/LICENSE-2.0>), at your option. All files in the project carrying such notice may not be copied, m...
#[doc = "Reader of register LLH_FEATURE_CONFIG"] pub type R = crate::R<u32, super::LLH_FEATURE_CONFIG>; #[doc = "Writer for register LLH_FEATURE_CONFIG"] pub type W = crate::W<u32, super::LLH_FEATURE_CONFIG>; #[doc = "Register LLH_FEATURE_CONFIG `reset()`'s with value 0x06"] impl crate::ResetValue for super::LLH_FEATUR...
use serde::*; use std::fs::File; use std::io::BufReader; const UNIXEPOCH_U8_SIZE: usize = 10; const GEOHASH_U8_SIZE: usize = 10; const QUERY_U8_SIZE: usize = UNIXEPOCH_U8_SIZE + GEOHASH_U8_SIZE; // バファリングするクエリはせいぜい10000なので64bitで余裕 pub type QueryId = u64; #[derive(Serialize, Deserialize, Debug)] pub struct QueryData ...
use nom::branch::alt; use nom::bytes::complete::escaped_transform; use nom::bytes::complete::is_not; use nom::bytes::complete::tag; use nom::character::complete::one_of; use nom::character::complete::space1; use nom::multi::many0; use nom::multi::separated_list0; use nom::sequence::delimited; use nom::sequence::pair; u...
extern crate shred; use shred::{DispatcherBuilder, Read, ResourceId, System, SystemData, World, Write}; #[derive(Debug, Default)] struct ResA; #[derive(Debug, Default)] struct ResB; #[derive(SystemData)] struct Data<'a> { a: Read<'a, ResA>, b: Write<'a, ResB>, } struct EmptySystem(*mut i8); // System is no...
#![allow(non_snake_case)] #[macro_use] use std::fs; use regex::Regex; use std::collections::HashMap; pub fn solve() { println!("\n************* Day - 3 ******************"); let txtPath = [env!("CARGO_MANIFEST_DIR"), "/inputs/day3.input1.txt"].join(""); let contents = fs::read_to_string(txtPath).expect...
use cgmath; use crate::model::model_utils::SpriteAnimationMetaData; use crate::model::animation_trait::SpriteAnimation; pub struct Fox { pub pos: cgmath::Vector2<f32>, sprite_animations: std::collections::HashMap<&'static str, SpriteAnimationMetaData>, current_animation: &'static str, animation_time: f...
/// This can be used in `Vec::from_iter` to create a vector that has more capacity than /// the `inner` iterator needs. pub struct SizeHintExtendingIter<TInner> { inner: TInner, extend_size_by: usize, } impl<TInner> SizeHintExtendingIter<TInner> { pub fn new(inner: TInner, extend_size_by: usize) -> Self { ...
use tokio::io::AsyncRead; use crate::error::TychoResult; use crate::read::async_::func::read_byte_async; pub(crate) async fn read_length_async<R: AsyncRead + Unpin>(reader: &mut R) -> TychoResult<usize> { let mut number: u64 = 0; let mut count = 0_i32; loop { let byte = read_byte_async(reader).aw...
use std::thread::Thread; use std::sync::{Arc,Mutex}; /* simple example fn main() { for _ in range(0u64, 10u64) { /* * Thread::spawn() get one argument: closure ({} of statements) * move keyword + || + closure, means moving closure. */ Thread::spawn(move || { p...
use crate::Result; use flume::{Receiver, Sender}; use std::task::Poll; use tracing::trace; pub(crate) struct SocketState { readable: bool, writable: bool, events: Receiver<SocketEvent>, handle: SocketStateHandle, } impl Default for SocketState { fn default() -> Self { let (sender, receiver...
#![forbid(unknown_lints)] use binds::{BindCount, BindsInternal, CollectBinds}; use join::CastVecJoin; use row_locking::RowLocking; use std::fmt; use std::fmt::Write; use std::marker::PhantomData; use write_sql::WriteSql; mod macros; #[cfg(test)] mod test; mod binds; mod cte; mod distinct; mod expr; mod filter; mod ...
// コマンドライン引数 pub mod a { use std::env; // コマンドライン引数の数を得る。 pub fn args_count() -> i32 { let argv: Vec<String> = env::args().collect(); (argv.len() - 1) as i32 } // コマンドライン引数のリストを得る。 pub fn args() -> Vec<String> { let mut argv: Vec<String> = env::args().collect(); argv.remove(0); argv ...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::account_state::AccountState; use libra_types::account_address::AccountAddress; use std::collections::BTreeMap; use std::ops::{Deref, DerefMut}; //TODO (jole) need maintain network state? #[derive(Clone, Debug, Copy, Ord...
use anyhow::Result; use log::info; use proger_backend::{DynamoDbDriver, Server}; use rusoto_core::Region; use rusoto_dynamodb::DynamoDbClient; use std::env; use std::str::FromStr; fn main() -> Result<()> { // Set the logging verbosity env::set_var( "RUST_LOG", format!( "actix_web={}...
extern crate structopt; use assembly_maps::raw::reader::*; use byteorder::{ReadBytesExt, LE}; use std::fs::File; use std::io::BufReader; use std::io::Write; use std::path::PathBuf; use structopt::StructOpt; #[derive(Debug, StructOpt)] #[structopt(name = "read-raw", about = "Analyze a LU Terrain File.")] struct Opt {...
//! Rust API wrapper for the Tendermint JSONRPC/HTTP, with support for querying //! state from a running full node. #![deny(warnings, missing_docs, unused_import_braces, unused_qualifications)] #![forbid(unsafe_code)] #![doc(html_root_url = "https://docs.rs/tendermint-rpc/0.0.0")] #[macro_use] extern crate serde_deri...
//! Crate `inspector` extends popular data structures (such as `Option` and `Result`) //! with additional methods for inspecting their payload. It is inspired by the `Iterator::inspect`. //! Since no such methods are available by default on `Option` and `Result` types, this crate //! implements a new traits for these t...
use crate::db::Db; use crate::error::Result; use crate::query::Query; pub fn render_query(query: &Query, db: &Db) -> Result<String> { let mut b = String::with_capacity(2048); let model = db.get_model(&query.model)?; b.push_str("<table><tr>"); let mut fields = Vec::new(); for select in &query.fields...
pub mod component; pub mod entity; pub mod system;
use serenity::framework::standard::{macros::command, Args, CommandError, CommandResult}; use serenity::model::prelude::{Member, Message, UserId}; use serenity::prelude::Context; use serenity::utils::{parse_username, Colour}; use crate::core::consts::MAIN_COLOUR; fn user_id_from_message(message: &Message, mut args: Ar...
//! `loggest` provides a high performance logging facility for Rust's [log](https://docs.rs/log) crate. //! //! Instead of writing logs to a file, `loggest` writes them to a pipe. The other end of the pipe is //! opened by a daemon which is responsible for writing the logs (and possibly compressing them). //! # Multit...
/* Copyright 2019-2023 Didier Plaindoux 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...
use myexponent::pow; fn main() { print!("8 raised to 2 is {}", pow(8, 2)); }
use crate::App; use bincode::deserialize; use dominator::Dom; use onitama_lib::ServerMsg; use wasm_bindgen::{prelude::Closure, JsCast, JsValue}; use web_sys::{window, MessageEvent}; pub fn game_dom(url: &str) -> Dom { let socket = web_sys::WebSocket::new(url).unwrap(); socket.set_binary_type(web_sys::BinaryTyp...
// Copyright 2018 Jeffery Xiao, 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable l...
//#![allow(dead_code, unused_imports)] extern crate amethyst; extern crate tiled; mod tiled_map; use tiled_map::load_tmx_map; use amethyst::prelude::*; use amethyst::input::{InputBundle, InputHandler}; use amethyst::ecs::{Component, Entity, Join, NullStorage, Read, ReadStorage, System, WriteStorage}; use amethyst::c...
extern crate duktape_sys; #[macro_use] extern crate error_chain; extern crate typemap; #[macro_use] extern crate bitflags; #[cfg(feature = "value")] extern crate value; mod callable; pub mod class; mod context; pub mod error; mod macros; mod privates; pub mod types; pub use self::callable::Callable; pub use self::cont...
use yew::prelude::*; enum Msg { Update(String), AddTodo, DeleteTodo(usize), } struct Todo { completed: bool, text: String, } struct App { // `ComponentLink` is like a reference to a component. // It can be used to send messages to the component link: ComponentLink<Self>, value: Str...
pub fn brackets_are_balanced(string: &str) -> bool { let mut chars: Vec<char> = Vec::new(); for c in string.chars() { match c { '{' | '[' | '(' => chars.push(c), '}' => { if chars.pop() != Some('{') { return false; } ...
#[doc = "Reader of register CR1"] pub type R = crate::R<u32, super::CR1>; #[doc = "Writer for register CR1"] pub type W = crate::W<u32, super::CR1>; #[doc = "Register CR1 `reset()`'s with value 0"] impl crate::ResetValue for super::CR1 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { ...
use super::ffi::LIBC; /// mmap API business logic. use std::os::raw::{c_int, c_void}; /// Need to use pattern here: https://stackoverflow.com/a/37608197/6214034 pub trait MmapAPI { /// Call if we're not reentrant. fn call_if_tracking<F: FnMut()>(&self, f: F); /// Implement removal of tracking metdata. ...
use git2::{Branch, Commit}; /// A set of extension methods for the `Branch` type in git2. pub trait BranchExt { /// Gets the `Commit` at the tip of this `Branch`. fn tip_commit(&self) -> Option<Commit>; } impl<'repo> BranchExt for Branch<'repo> { fn tip_commit(&self) -> Option<Commit> { self.get()...
use crate::{Call, Event, Runtime}; impl pallet_sudo::Trait for Runtime { type Event = Event; type Call = Call; }
use serde_derive::Serialize; use std::fmt; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; use rayon::prelude::*; /// Structure representing the results of a file analysis. #[derive(Serialize)] pub struct FileStats { /// Number of lines in the file. Based on \n and \r\n pub lines: Option<...
#![feature(test)] #[macro_use] extern crate maplit; extern crate test; extern crate kite; use test::Bencher; use kite::term::Term; use kite::token::Token; use kite::schema::{FieldType, FIELD_INDEXED}; use kite::document::Document; use kite::store::{IndexStore, IndexReader}; use kite::store::memory::{MemoryIndexStore...
use parser::{Expression}; use instructions::Instructions; use memory::MemoryLayout; use super::errors::Error; pub fn output_expr( instructions: &mut Instructions, mem: &mut MemoryLayout, expr: Expression ) -> Result<(), Error> { match expr { Expression::StringLiteral(text) => { let...
use crate::common::Type; pub trait Name<'a> { fn as_name(&self) -> &'a str { self.name().unwrap() } fn name(&self) -> Option<&'a str> { None } } impl<'a> Name<'a> for Type<'a> { fn name(&self) -> Option<&'a str> { match self { Type::NamedType(t) => Some(*t), ...
use crate::problem::{AccessTokenProblemCategory::*, Problem}; use crate::models::UserId; use astroplant_auth::token; use warp::{Filter, Rejection}; /// A filter to authenticate a user through a normal token in the Authorization header. /// If there is no Authorization header, returns None. /// /// Rejects the reques...
use quick_renderer::egui; pub trait DrawUI { type ExtraData; fn draw_ui(&self, extra_data: &Self::ExtraData, ui: &mut egui::Ui); fn draw_ui_edit(&mut self, extra_data: &Self::ExtraData, ui: &mut egui::Ui); }
use crate::numeric::Numeric; pub trait Float: Numeric { fn f_sqrt(self) -> Self; } impl Float for f32 { fn f_sqrt(self) -> f32 { self.sqrt() } } impl Float for f64 { fn f_sqrt(self) -> f64 { self.sqrt() } }
fn main() { messages::main(); ip::main() } mod ip { pub fn main() { let home = IpAddr { kind: IpAddrKind::V4, address: String::from("127.0.0.1"), }; let loopback = IpAddr { kind: IpAddrKind::V6, address: String::from("::1"), }; } enum IpAddrKind { V4, V6, } fn route(ip_kind: IpAdd...
use crate::{ bytecode::{ByteCode, OpCode}, {OpArgBuf, WORD_SIZE}, }; #[derive(Debug)] pub struct Vm<'a> { stack: Vec<usize>, bp: usize, parser: VmParser<'a>, } #[derive(Debug)] struct VmParser<'a> { // invariant: self.bytecode.data[self.next_code_offset] always contains the u8 repr of an opcod...
use std::env; use serenity::{ model::{channel::Message, gateway::Ready}, prelude::*, }; mod lib; use lib::*; fn main() { let token = env::var("DISCORD_TOKEN") .expect("Expected a token in the environment"); let handler = Handler::new(); let mut client = Client::new(&token, handler).expect...
use crate::maze::maze_genotype::PathGene; use crate::maze::maze_phenotype::MazeCell; use crate::maze::{Orientation, PathDirection}; #[derive(Debug, Clone)] pub struct MazeValidator { pub width: u32, pub height: u32, pub first_direction: Orientation, pub grid: Vec<Vec<MazeCell>>, } impl MazeValidator {...
use std::vec::Vec; use utils::vec3::Vec3; use utils::ray::Ray; use utils::material::Material; use utils::aabb::{AABB, surrounding_box}; #[allow(dead_code)] #[derive(Clone)] pub struct HitRecord { pub t: f32, pub u: f32, pub v: f32, pub p: Vec3, pub normal: Vec3, pub mat: Box<Material>, } #[all...
// Copyright (c) 2016 Anatoly Ikorsky // // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT // license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. All files in the project carrying such notice may not be copied, // m...
use super::super::types::PunterId; use super::super::proto::{Move, Setup}; use super::super::game::{GameState, GameStateBuilder}; pub struct AlwaysPassGameStateBuilder; impl GameStateBuilder for AlwaysPassGameStateBuilder { type GameState = AlwaysPassGameState; fn build(self, setup: Setup) -> Self::GameState...
use anyhow::Result; use serde::de::{Unexpected, Visitor}; use serde::export::Formatter; use serde::{Deserialize, Deserializer, Serialize}; use std::path::PathBuf; use std::result::Result as stdResult; use crate::cfg::{CfgError, LocalSetupCfg, SetupCfg}; pub type SetupName = String; #[derive(Debug, Serialize, Deseria...
use std::io::{self, Write}; fn main() { loop { let mut buf = String::new(); io::stdin().read_line(&mut buf) .expect("could not read line"); if buf.starts_with("exit") { std::process::exit(0); } io::stdout().write(&buf.as_bytes()) .expect("could not write line"); } }
fn main() { let x = 5; // x = 6; // エラー! let mut x = 5; x = 6; // 問題なし! // ミュータブル参照 let mut x = 5; let y = &mut x; }
//! Responsible for dealing with all input. use piston::input::{Button, GenericEvent, Key, MouseButton}; use serde_json::json; use std::error::Error; use std::fs::File; use std::path::Path; use crate::common::{ButtonInteraction, Cell, Directions, DIMENSIONS_CHOICES}; use crate::nonogram_board::NonogramBoard; /// Han...
//! # Nom parsers use std::string::FromUtf8Error; use nom::{ combinator::{map, map_res}, error::{FromExternalError, ParseError}, multi::length_data, number::complete::{le_i32, le_u32}, IResult, Parser, }; use super::CRCTreeNode; /// Parse a CRC node pub fn parse_crc_node<'r, D, P, E>( mut pa...
use async_trait::async_trait; use messagebus::{ derive::{Error as MbError, Message}, error::{self, GenericError}, AsyncHandler, Bus, Message, TypeTagged, }; use messagebus_remote::relays::QuicServerRelay; use serde_derive::{Deserialize, Serialize}; use thiserror::Error; #[derive(Debug, Error, MbError)] enu...
use super::*; pub(super) fn log_entry( entry_serial_number: LogEntrySerialNumber, earliest_entry_needed: LogEntrySerialNumber, last_entry_location: FileLocation, txs: &Vec<&RefCell<Tx>>, allocs: &Vec<&RefCell<Alloc>>, tx_deletions: &Vec<TxId>, alloc_deletions: &Vec<TxId>, stream: &Box<d...
pub fn run() { // print to console println!("Hello from printrs"); // Basic forrmating println!("Number {}", 1); // Basic formatting println!("New {} is {}","Name", "Wolf"); // Positional params println!("New {0} is {1}","Name", "Wolf"); // Named Arguments println!("New {...
use std::iter::Iterator; use super::ast::*; use super::ast::BuilderKind::*; use super::ast::ScalarKind::*; use super::ast::Type::*; use super::ast::ExprKind::*; use super::partial_types::*; // TODO: These methods could take a mutable string as an argument, or even a fmt::Format. /// A trait for printing types. pub t...
use std::path::PathBuf; use crate::Cargo; pub struct External; impl External { /// The external content directory pub fn dir() -> PathBuf { let mut path = Cargo::crate_dir(); path.push(".external"); path } /// Checks that external content is present and valid pub fn is_v...
pub mod b16; pub mod b36; pub mod bitop; #[cfg(test)] mod tests { use crate::b36::B36; use crate::bitop::BitOp; use crate::bitop::BitOpBase; use rand::Rng; const COUNT : i32 = 100; #[test] fn test_candidates() { let inturn : u64 = 7913472; let opponent : u64 = 251666496; ...
use std::cmp::{max, min}; mod line_bresenham; pub mod lines; pub mod point; pub mod point3; pub use {lines::line2d, point::Point, point3::Point3}; mod line_vector; pub use line_bresenham::Bresenham; pub use line_vector::VectorLine; mod circle_bresenham; pub use circle_bresenham::{BresenhamCircle, BresenhamCircleNoDiag}...
extern crate base; extern crate parser; extern crate check; mod functions; use functions::*; #[test] fn dont_stack_overflow_on_let_bindings() { let text = r#" let _ = 1 in let _ = 1 in let _ = 1 in let _ = 1 in let _ = 1 in let _ = 1 in let _ = 1 in let _ = 1 in let _ = 1 in let _ = 1 in let _ = 1 in let _ = 1 in let...
use apllodb_shared_components::{ApllodbError, ApllodbResult, NnSqlValue, SqlValue}; use apllodb_sql_parser::apllodb_ast; use crate::ast_translator::AstTranslator; impl AstTranslator { /// # Failures /// /// - [DataExceptionNumericValueOutOfRange](apllodb_shared_components::SqlState::DataExceptionNumericVa...
pub fn reply(input: &str) -> &str { if input.is_empty() { "Fine. Be that way!" } else if input.ends_with("?") { "Sure." } else if !input.chars().any(|char| char.is_lowercase()) { "Whoa, chill out!" } else { "Whatever." } }
use std::cmp::Ordering; use std::fs; use std::io::{BufRead, BufReader}; use std::path::PathBuf; pub type Name = String; pub type Title = String; pub type Children = Vec<Node>; fn main() { let root = PathBuf::from("example"); let tree = get_hierarchy(root).unwrap(); print_hierarchy(tree); } fn print_hier...
// Copyright (c) 2018-2020 Brendan Molloy <brendan@bbqsrc.net> // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or d...
use super::super::mem; use crate::cpu::{interrupt, ioregister}; pub struct Timer { /// The timer overflow behavior is delayed. timer_overflow: bool, tima_cycles_counter: u32, } impl Default for Timer { fn default() -> Timer { Timer { timer_overflow: false, tima_cycles_c...
#![doc( test(attr(deny(warnings))), test(attr(allow(bare_trait_objects, unknown_lints))) )] #![warn(missing_docs)] // Don't fail on links to things not enabled in features #![allow( unknown_lints, renamed_and_removed_lints, intra_doc_link_resolution_failure, broken_intra_doc_links )] // These li...
#[doc = "Register `LPTIM_PIDR` reader"] pub type R = crate::R<LPTIM_PIDR_SPEC>; #[doc = "Field `P_ID` reader - P_ID"] pub type P_ID_R = crate::FieldReader<u32>; impl R { #[doc = "Bits 0:31 - P_ID"] #[inline(always)] pub fn p_id(&self) -> P_ID_R { P_ID_R::new(self.bits) } } #[doc = "LPTIM periphe...
use std::collections::BTreeSet; use ggez::{Context}; use ggez::graphics::{MeshBuilder,DrawMode,Color,Image,draw}; use ggez::nalgebra::Point2; use crate::shot::{Shot,ShotStatus}; use crate::enemy::Enemy; use crate::enemy_grid::EnemyGrid; use crate::common::Point; const PLAYERSIZE: f32 = 81.0; const PLAYERWIDTH: f32 = 6...
use aoc::*; use itertools::Itertools; use std::cmp::Ordering; use std::collections::HashMap; fn main() -> Result<()> { let input = input("14.txt")?; let reactions: HashMap<&str, Reaction> = input .lines() .map(&Reaction::parse) .map(|r| (r.output.name, r)) .collect(); let ...
extern crate alloc; use super::{SqDir, SquareMaze}; use alloc::vec::Vec; use bit_vec::BitVec; use rand::prelude::*; use rand::{distributions::Uniform, rngs::SmallRng}; impl SquareMaze { pub fn init_wilson(&mut self) { let mut rng = SmallRng::seed_from_u64(self.seed); let mut ccount = self.width * ...
use std::fmt::format; use crate::jack_tokenizer::TokenData; #[derive(Debug, Clone)] pub struct VMWriter { vm: Vec<String> } impl VMWriter { pub fn new() -> Self { VMWriter { vm: Vec::new(), } } pub fn write_push(&mut self, segment: &str, n: u16) { let line = forma...