text
stringlengths
8
4.13M
//! Rendering in fumarole is handled by drawing 'Shapes' to the window. mod rect; mod anchor; mod line; mod ellipse; mod image; mod text; mod traits; mod frame; mod mask; pub use rect::*; pub use anchor::*; pub use line::*; pub use ellipse::*; pub use self::image::*; pub use text::*; pub use frame::*; pub use mask::*...
use crate::types::Position; pub fn distance2(pos1: Position, pos2: Position) -> i32 { let x = pos1.x - pos2.x; let y = pos1.y - pos2.y; return x * x + y * y; } pub fn distance(pos1: Position, pos2: Position) -> f64 { return (distance2(pos1, pos2) as f64).sqrt(); } #[cfg(test)] mod tests { use sup...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 mod actor; mod message; mod service; pub use actor::*;
extern crate byteorder; extern crate env_logger; extern crate extsort; extern crate memmap; extern crate rand; extern crate tempfile; use byteorder::{ByteOrder, LittleEndian}; use extsort::Record; use memmap::Mmap; use rand::distributions::Uniform; use rand::{Rng, SeedableRng, StdRng}; use std::io::{BufWriter, Write};...
use crate::delay_line::DelayLineFracLin; use crate::filter::FIRFilter; use dasp::frame::Mono; use dasp::{Frame, Sample}; use dasp_signal::{Noise, Signal}; pub struct PluckedString<T> { string_delay: DelayLineFracLin<Vec<Mono<T>>>, string_filter: FIRFilter<Mono<T>>, pick_noise: Noise, pub brightness: f...
#[doc = "Register `RPR2` reader"] pub type R = crate::R<RPR2_SPEC>; #[doc = "Register `RPR2` writer"] pub type W = crate::W<RPR2_SPEC>; #[doc = "Field `RPIF50` reader - configurable event inputs x rising edge pending bit When EXTI_PRIVCFGR.PRIVx is disabled, RPIFx can be accessed with unprivileged and privileged access...
use std::sync::Arc; use failure::Fallible; pub struct LoadedFont { inner: font_kit::loaders::default::Font, } impl LoadedFont { pub fn from_bytes(bytes: Arc<Vec<u8>>) -> Fallible<Self> { Ok(LoadedFont { inner: font_kit::loaders::default::Font::from_bytes(bytes, 0)?, }) } ...
mod git; use crate::git::clone; use std::{ collections::BTreeMap, env, fs::{self, File}, io::Read, path::PathBuf, string::ToString, }; use anyhow::{anyhow, Context, Result}; use clap::{App, Arg, ArgMatches}; use console::{Emoji, Style}; use dialoguer::{Confirm, Input, MultiSelect, Select}; us...
mod ttype; pub use self::ttype::*;
use amethyst::{ assets::{AssetStorage, Handle, Loader}, core::transform::Transform, core::math::Vector3, prelude::*, renderer::{ Camera, ImageFormat, SpriteRender, SpriteSheet, SpriteSheetFormat, Texture, }, input::{VirtualKeyCode, is_key_down}, utils::auto_fov::AutoFov, ...
// Copyright 2014 Pierre Talbot (IRCAM) // 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...
use std::collections::HashMap; use std::collections::HashSet; //sets fn make_set(words: &str) -> HashSet<&str> { words.split_whitespace().collect() } fn main() { //array to vec println!("ARRAY CONVERSION"); let nums = ["5","52","65"]; let iter = nums.iter().map(|s| s.parse::<i32>()); let conve...
//! Miscellaneous utilities for networking. pub mod multihash; pub mod piece_provider; pub(crate) mod prometheus; #[cfg(test)] mod tests; pub(crate) mod unique_record_binary_heap; use event_listener_primitives::Bag; use futures::future::{Fuse, FusedFuture, FutureExt}; use libp2p::multiaddr::Protocol; use libp2p::{Mul...
use crate::{Browser, BrowserOptions, Error, ErrorKind, Result, TargetType}; use objc::{class, msg_send, runtime::Object, sel, sel_impl}; /// Deal with opening of browsers on iOS pub(super) fn open_browser_internal( _browser: Browser, target: &TargetType, options: &BrowserOptions, ) -> Result<()> { // e...
fn main() { let x = [1,2,3]; let y = &x[..]; let (a,b,c) = (1,2,3); let mut z = 5; let zz = &mut z; let p = *zz + 1; println!("{}", p); let test; test = 5; }
//! Implements the engine API to support benchmarking native applications. //! Supports the collection of execution time. Compilation time from high level //! language to native binary is not recorded since (a) compilation is currently //! a separate step taken by the user and (b) Wasm also does not record the //! equi...
use anyhow::Result; pub fn extract(_file_name: &str) -> Result<()> { println!("Extracting"); Ok(()) }
use std::convert::TryFrom; use serde::{Deserialize, Serialize}; use serde_json; use std::collections::HashMap; use log::{debug, error}; use uuid::Uuid; use redis::{FromRedisValue, RedisResult, ToRedisArgs, Value}; use super::memory; use super::redis_connection::RedisConnection; use super::InfocomError; #[derive(Debug...
#[doc = "Register `AF2` reader"] pub type R = crate::R<AF2_SPEC>; #[doc = "Register `AF2` writer"] pub type W = crate::W<AF2_SPEC>; #[doc = "Field `BKINE` reader - BRK BKIN input enable"] pub type BKINE_R = crate::BitReader; #[doc = "Field `BKINE` writer - BRK BKIN input enable"] pub type BKINE_W<'a, REG, const O: u8> ...
use im::{vector, Vector}; use sodium_rust::{Cell, Stream}; #[derive(Clone)] pub enum Command<T> { AddSingle(T), AddMultiple(Vector<T>), Clear, } impl<T> Command<T> where T: Clone, { pub fn merge(&self, other: &Command<T>) -> Command<T> { use Command::*; match (self, other) { ...
use proc_macro2::{Span, TokenStream}; use crate::impls::map::TestCases; use crate::impls::{map, AttributeArgList}; pub(crate) fn generate_test_cases( argument_lists: super::AttributeArgList, func: syn::ItemFn, ) -> proc_macro::TokenStream { // Map the given arguments by their identifier let values = i...
#![allow(non_snake_case)] #![allow(unused_variables)] use super::super::win::types::{WndProc,MSG,WPARAM,LPARAM}; use super::super::win::wnd::DWnd; use super::super::win::api::{CallWindowProcW}; use std::rc::Rc; use std::cell::{RefCell}; use std::collections::HashMap; /* 每一个窗口都有一个自有的事件处理器.它们通过哈希表关联在一起. */...
#[doc = "Reader of register CTL"] pub type R = crate::R<u32, super::CTL>; #[doc = "Writer for register CTL"] pub type W = crate::W<u32, super::CTL>; #[doc = "Register CTL `reset()`'s with value 0"] impl crate::ResetValue for super::CTL { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { ...
use std::fs; fn main() { let input = fs::read_to_string("./input.txt").unwrap_or_default(); dbg!(input .lines() .filter(|line| line .char_indices() .collect::<Vec<(usize, char)>>() .windows(2) .any(|chars| { let two_chars = String:...
use crate::simd::math::powf256_ps; use crate::{Lab, EPSILON, E_0_255, KAPPA}; use std::arch::x86_64::*; use std::{iter, mem}; static BLANK_RGB: [u8; 3] = [0u8; 3]; pub fn rgbs_to_labs(rgbs: &[[u8; 3]]) -> Vec<Lab> { let chunks = rgbs.chunks_exact(8); let remainder = chunks.remainder(); let mut vs = chunks...
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. use criterion::{criterion_group, criterion_main, BatchSize, BenchmarkId, Criterion}; use crypto::hashers::Blake3_256; use math::{fft, fiel...
#[cfg(test)] mod tests { #[test] fn it_works() { assert_eq!(2 + 2, 4); } } pub fn public_function() { println!("called somepackage's `public_function()`"); } fn private_function() { println!("called somepackage's `private_function()`"); } pub fn indirect_access() { print!("called some...
#![allow(clippy::new_without_default)] mod arena; pub mod back; pub mod front; pub mod proc; pub use crate::arena::{Arena, Handle}; use std::{ collections::{HashMap, HashSet}, hash::BuildHasherDefault, num::NonZeroU32, }; pub type FastHashMap<K, T> = HashMap<K, T, BuildHasherDefault<fxhash::FxHasher>>; ...
use crate::api::Downloads; use ratatui::layout::Constraint; use ratatui::style::{Color, Style}; use ratatui::widgets::{Block, Borders, Cell, Row, Table, TableState}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use tokio_stream::StreamExt; pub struct DownloadTable<'a> { pub state: TableState,...
use use_uikit_sys_blog_post::run_app; fn main() { run_app(); }
#![cfg_attr(feature="clippy", feature(plugin))] #![cfg_attr(feature="clippy", plugin(clippy))] #![feature(type_ascription)] use rand; use std::thread; use std::sync::mpsc::{channel, Sender, Receiver}; use rand::Rng; use network::localip::get_localip; use network::peer::{PeerTransmitter, PeerReceiver, PeerUpdate}; ...
extern crate rand; pub mod map; pub mod entity; pub mod coordinate_utils; pub mod update; pub mod item; pub fn lib_func() -> String { return String::from("Hello!"); } pub fn lib_version() -> String { return String::from("1.0"); }
extern crate diesel; extern crate rust_pdx_schedule; use self::models::*; use diesel::prelude::*; use rust_pdx_schedule::*; fn main() { use self::schema::instructor::dsl::*; let connection = establish_connection(); let results = instructor .limit(5) .load::<Instructor>(&connection) ...
#![deny(rust_2018_idioms)] extern crate proc_macro; use proc_macro::TokenStream; use proc_quote::ToTokens as _; #[proc_macro] pub fn scannerless_parser(input: TokenStream) -> TokenStream { // FIXME(eddyb) parse the `proc_macro` tokens instead of strings. input .to_string() .parse::<gll::scann...
use crate::common::Annot; use crate::common::Loc; #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum AstKind { Incr, Decr, Next, Prev, Read, Write, Loop(Vec<Ast>), } pub type Ast = Annot<AstKind>; impl Ast { pub fn incr(loc: Loc) -> Self { Self::new(AstKind::Incr, loc) ...
use std::io::Read; use bitflags::bitflags; use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; use super::header::{Header, OpCode}; use crate::{ bson_util, cmap::{ conn::{command::RawCommand, wire::util::SyncCountReader}, Command, }, error::{Error, ErrorKind, Result}, ...
pub struct Digits { n: usize, divisor: usize, } impl Digits { pub fn new(n: usize) -> Self { let mut divisor = 1; while n >= divisor * 10 { divisor *= 10; } Digits { n, divisor } } } impl Iterator for Digits { type Item = usize; fn next(&mut self) -> Option<Self::Item> { if self.divisor == 0 { ...
/* https://projecteuler.net Triangle, square, pentagonal, hexagonal, heptagonal, and octagonal numbers are all figurate (polygonal) numbers and are generated by the following formulae: Triangle P3,n = n(n+1)/2 1, 3, 6, 10, 15, ... Square P4,n = n2 1, 4, 9, 16, ...
use rustyline::{error::ReadlineError, Editor}; use rustyline; use std::iter; use std::fs::File; use std::io::{prelude::*, BufReader}; use crate::{ lisp_object::{ Symbol, ParamList, EvalError, LispObject, SpecialForm, SerializeSymbol, }, lisp_ob...
fn match_char(slice: &str) { for c in slice.chars() { match c { 'a' ... 'z' => println!("letter"), '0' ... '9' => println!("digit"), 'A' ... 'Z' => println!("capital"), ' ' | '\n' | '\t' => println!("whitespace"), _ => println!("other") } ...
use crate::stt_model::recognition_server::{Recognition, RecognitionServer}; use crate::stt_model::{RecognitionRequest, RecognitionResponse}; use tonic::transport::Server; use tonic::{Request, Response, Status}; mod stt_model { include!("../proto/stalin.rs"); } struct GrpcServer {} #[tonic::async_trait] impl Recog...
extern crate futures; #[macro_use] extern crate lazy_static; #[macro_use] extern crate mime; extern crate hyper; extern crate slog; extern crate tokio_core; extern crate papers; extern crate serde_json as json; use futures::future; use futures::{Future, Stream}; use hyper::client::{Client, Request}; use hyper::header:...
extern crate genmesh; extern crate obj; mod vector; mod image; mod scene; use std::env; use std::process; use std::path; use scene::Scene; use std::io::BufReader; fn main() { let args: Vec<_> = env::args().collect(); if args.len() < 6 { println!("Usage: {} <Thread Count> <Image Width> <Image H...
// rustc 1.1.0 (35ceea399 2015-06-19) // rustc 1.9.0 (e4e8b6668 2016-05-18) fn main() { let mut summ = 0; let mut a = 0; let mut b = 1; let mut c = 0; while c < 4000000 { c = a + b; a = b; b = c; if c % 2 == 0 { summ += c; } } println!("{}...
use crate::vector::Vector3; use crate::matrix::Matrix4; use crate::camera::Camera; use std::f64; use sfml::graphics::Color; pub struct Vertex { pub pt: Vector3, pub color: Option<Color>, } pub struct Face { pub a: usize, pub b: usize, pub c: usize, pub color: Option<Color>, } pub struct Mes...
fn strip_characters(original : &str, to_strip : &str) -> String { original.chars().filter(|&c| !to_strip.contains(c)).collect() } fn main() { println!("{}", strip_characters("She was a soul stripper. She took my heart!", "aei")); }
extern crate nalgebra as na; use na::{Vector2, Point2}; use ncollide2d::pipeline::CollisionGroups; use ncollide2d::shape::{Cuboid, ShapeHandle}; use nphysics2d::force_generator::{DefaultForceGeneratorSet}; use nphysics2d::joint::DefaultJointConstraintSet; use nphysics2d::joint::{PrismaticConstraint, RevoluteConstraint...
use ascii::{AsciiChar, AsciiStr}; use std::iter::FusedIterator; use std::iter::Peekable; use std::slice::Chunks; use std::str::{from_utf8_unchecked, CharIndices}; pub struct StrChunks<'a> { iterator: Peekable<CharIndices<'a>>, value: &'a str, count: usize, } pub struct AsciiChunks<'a> { value: Chunks<...
use stainless_ffmpeg::{audio_decoder::AudioDecoder, video_decoder::VideoDecoder}; pub enum InnerDecoder { AudioDecoder(AudioDecoder), VideoDecoder(VideoDecoder), // EbuTtmlLiveDecoder(EbuTtmlLiveDecoder), }
//! Link: https://adventofcode.com/2019/day/2 //! Day 2: 1202 Program Alarm //! //! On the way to your gravity assist around the Moon, //! your ship computer beeps angrily about a "1202 program alarm". //! On the radio, an Elf is already explaining how to handle the situation: //! - "Don't worry, that's perfectly n...
use core::cell::RefCell; use js_sys::Function; use std::fmt::Debug; use std::future::Future; use std::rc::Rc; use std::task::Poll; use std::task::Waker; use wasm_bindgen::prelude::Closure; use wasm_bindgen::JsValue; /// A `Callback<F>` is a wrapper around a `wasm_bindgen::prelude::Closure<F>` which supports TODO: #[de...
use serde_json::Value; use std::str::FromStr; use arkecosystem_client::api::models::transaction::{ TransactionFeesCore, TransactionFeesMagistrate, }; pub fn assert_transaction_core_fees(core: TransactionFeesCore, expected: &Value) { assert_eq!( core.transfer, u64::from_str(expected["transfer"]...
use hyper::service::{make_service_fn, service_fn}; use hyper::{Body, Method, Request, Response, Server}; use std::net::SocketAddr; pub type GenericServerError = Box<dyn std::error::Error + Send + Sync>; const SVG_BASE_URL: &str = "https://img.shields.io"; const HEALTH_CHECK_BODY: &str = concat!( r#"{{"status":"pa...
/// <summary> /// If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. /// Find the sum of all the multiples of 3 or 5 below 1000. /// </summary> /// <returns>return the answer to the problem</returns> pub fn compute() -> String { let rang...
struct Artwork { view_count: i32, name: String, } fn admire_art(art: &mut Artwork) { println!("{} people have seen {} today!", art.view_count, art.name); art.view_count += 1; } fn main() { let mut art1 = Artwork { view_count: 0, name: "".to_string(), }; admire_art(&mut art1); admire_art(&mut ...
use core::fmt::*; pub use uart_16550::*; use lazy_static::lazy_static; use spin::Mutex; lazy_static! { static ref SERIAL : Mutex<SerialPort> = Mutex::new(unsafe {SerialPort::new(0x3f8)}); } pub fn write_u8(byte : u8) { SERIAL.lock().send(byte); } pub fn read_u8() -> u8 { SERIAL.lock().receive() } pub f...
// Copyright 2018 Steven Bosnick // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE-2.0 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 distributed // except accord...
pub fn goodbye() ->String{ "Good bye fucking japan".to_string() }
// Copyright (c) The diem-devtools Contributors // SPDX-License-Identifier: MIT OR Apache-2.0 use nextest_runner::dispatch::Opts; use structopt::StructOpt; fn main() -> anyhow::Result<()> { let opts = Opts::from_args(); opts.exec() }
extern crate sdl2; use sdl2::pixels::Color; use std::thread; fn main() { // Initialize SDL2 let sdl_context = sdl2::init().unwrap(); let video_subsystem = sdl_context.video().unwrap(); // Create the window let window = video_subsystem.window("ArcadeRS Shooter", 800, 600) .position_centere...
use std::io; mod lib; fn main() { println!("{}", lib::functions::math_fibonacci(45)); }
use std::env::current_dir; use std::error::Error; use std::fs::File; use std::io::Write; use std::fmt::{self, Display, Formatter}; use git2::Repository; use structopt::StructOpt; use crate::PROJECT_FILE_NAME; use crate::model::*; #[derive(Debug, StructOpt)] pub struct Init { /// The name of your project. Defaults ...
//! Traits for deriving repository objects from atom objects /// A trait for declaring that `<self>` can produce a `::repository::<thing>` /// by using a `::atom::<thing>` pub trait DeriveAtom<Atom, Target> { /// Yield a kind of `Target` by consuming a kind of `Atom` fn derive(&self, a: Atom) -> Target; }
use super::QName; use super::lazy_hash_map::LazyHashMap; use typed_arena::Arena; use string_pool::{StringPool,InternedString}; use std::marker::PhantomData; use std::slice; struct InternedQName { namespace_uri: Option<InternedString>, local_part: InternedString, } impl InternedQName { fn as_qname(&self) ...
use crate::{auth::DeviceAuthenticator, downstream::CoapCommandSender, error::CoapEndpointError}; use coap_lite::{CoapOption, CoapRequest, CoapResponse}; use drogue_cloud_endpoint_common::{ command::Commands, error::EndpointError, sender::{self, DownstreamSender}, sink::Sink, }; use drogue_cloud_service_...
table! { users (id) { id -> Int4, login -> Text, } }
fn main() { let s1 = gives_ownership(); let s2 = String::from("hello"); let s3 = takes_and_gives_back(s2); let a1 = String::from("hello"); let (a2, len) = calculate_length(a1); println!("The length of {} is {}", a2, len); } fn calculate_length(s:String) -> (String, usize){ let length =...
use crate::tcpdiag::{gather_sockets, DiagWithInode, TCP_STATE, TCPInfo}; use std::vec::Vec; use std::collections::VecDeque; use tui::widgets::TableState; use std::collections::HashMap; use trust_dns_resolver::Resolver; use trust_dns_resolver::config::*; use std::net::IpAddr; use std::sync::mpsc::{self, Sender, TryRecvE...
//! Contains the types needed to specify the auth configuration for a //! [`Client`](struct.Client.html). #[cfg(feature = "aws-auth")] pub(crate) mod aws; pub(crate) mod oidc; mod plain; mod sasl; mod scram; #[cfg(test)] mod test; mod x509; use std::{borrow::Cow, fmt::Debug, str::FromStr}; use derivative::Derivative...
use amethyst::{ assets::{AssetStorage, Loader}, core::timing::Stopwatch, core::transform::Transform, ecs::prelude::{Component, DenseVecStorage}, input::{get_key, is_close_requested, is_key_down, VirtualKeyCode}, prelude::*, renderer::{ sprite::SpriteSheetHandle, Camera, ImageFormat, ...
use bevy::{prelude::*, reflect::TypeRegistry}; fn main() { App::build() .add_plugins(DefaultPlugins) .add_startup_system(setup.system()) .register_type::<MyType>() .run(); } #[derive(Reflect)] #[reflect(DoThing)] struct MyType { value: String, } impl DoThing for MyType { f...
#![cfg(feature = "std")] use tabled::{ grid::dimension::{DimensionPriority, PoolTableDimension}, settings::{formatting::AlignmentStrategy, Alignment, Margin, Padding, Style}, tables::{PoolTable, TableValue}, }; use crate::matrix::Matrix; use testing_table::test_table; #[cfg(feature = "color")] use tabled...
#[doc = "Register `MDIOS_IPIDR` reader"] pub type R = crate::R<MDIOS_IPIDR_SPEC>; #[doc = "Field `ID` reader - ID"] pub type ID_R = crate::FieldReader<u32>; impl R { #[doc = "Bits 0:31 - ID"] #[inline(always)] pub fn id(&self) -> ID_R { ID_R::new(self.bits) } } #[doc = "MDIOS identification regi...
extern crate floating_duration; use std::time::Instant; use floating_duration::{TimeAsFloat, TimeFormat}; use std::{thread, time}; use serde; pub trait Motor { fn force_of_voltage(&self, v: f64) -> f64; fn voltage_of_force(&self, v: f64) -> f64; } pub struct SimpleMotor; impl Motor for SimpleMotor { fn force...
use serde::{Deserializer, de, Deserialize}; use serde_json::Value; pub mod analytics; pub mod balance; pub mod client; pub mod journal; pub mod lookup; pub mod pricing; pub mod sms; pub mod status; pub mod subaccounts; pub mod voice; pub mod hooks; pub mod validate_for_voice; pub mod contacts; fn to_string<'de, D: De...
use std::env; fn main() { let args: Vec<String> = env::args().collect(); if args.len() < 2 { println!("Provide index of desired Fibonacci number."); return } let ind: u32 = match args[1].trim().parse() { Ok(val) => val, Err(_) => { println!("Provide index of desired Fi...
mod db; mod form; mod in_; #[cfg(feature = "postgres")] pub mod pg; #[cfg(feature = "sqlite")] pub mod sqlite; #[cfg(feature = "postgres")] pub mod point; pub mod sql_types; mod utils; pub use form::{Form, FormErrors}; pub use in_::{In, In0, UD}; pub use sql_types::{citext, CiString}; pub use utils::elapsed; pub ty...
use opencv::{core::*, highgui::*, prelude::*, videoio::*}; use std::{thread, time}; pub fn show_frame(name: &str, frame: &Mat) -> opencv::Result<()> { let window = name; named_window(window, WND_PROP_FULLSCREEN)?; set_window_property(name, WND_PROP_FULLSCREEN, WINDOW_FULLSCREEN as f64)?; imshow(window,...
#[macro_use] extern crate clap; extern crate advent2018; use clap::{App, Arg}; fn main() { let matches = App::new("Advent of Code 2018") .arg(Arg::with_name("day") .short("d") .long("day") .takes_value(true)) .get_matches(); let day = value_t!(matches.va...
//! Abstract syntax tree. //! //! Defines syntatic constructs and translation of source code into an AST. //! //! There are a few variants of AST members that have associated //! SourcePosition, used for reporting of translation errors. Position //! information isn't included in most because valid syntax implies //! tr...
use std::{ collections::{HashMap, VecDeque}, io::Read, }; fn main() { let mut stdin = std::io::stdin(); let mut buf = String::new(); stdin.read_to_string(&mut buf).unwrap(); let out = solve(&buf); println!("{out}"); } fn solve(input: &str) -> String { let lines = input .lines() .map(|l| { l.split_white...
use itertools::Itertools; use std::collections::HashMap; #[aoc::main(16)] pub fn main(input: &str) -> (i64, i64) { solve(input) } #[aoc::test(16)] pub fn test(input: &str) -> (String, String) { let res = solve(input); (res.0.to_string(), res.1.to_string()) } fn solve(input: &str) -> (i64, i64) { let ...
use std::{collections::HashMap, sync::Arc, time::Duration}; use bson::Document; use serde::Deserialize; use super::TestSdamEvent; use crate::{ bson::{doc, oid::ObjectId}, client::Client, cmap::{conn::ConnectionGeneration, PoolGeneration}, error::{BulkWriteFailure, CommandError, Error, ErrorKind}, ...
use serde::{Deserialize, Serialize}; use serde_bolt::constants::marker; use serde_bolt::{from_bytes, to_bytes, Value}; use serde_derive::{Deserialize, Serialize}; use std::fmt::Debug; macro_rules! bytes { ($($slice:expr),* $(,)*) => { { let mut __arr: Vec<u8> = Vec::new(); $(__arr.e...
use crate::{RawStr, Value}; /// Something that is named. pub trait Named { /// The name of the named thing. const NAME: RawStr; } impl Named for String { const NAME: RawStr = RawStr::from_str("String"); } impl Named for Vec<Value> { const NAME: RawStr = RawStr::from_str("Vec"); } impl Named for i64 ...
#![no_std] pub use noexcept_impl::abort_on_panic; #[doc(hidden)] pub mod __private { pub struct AbortOnDrop; impl Drop for AbortOnDrop { #[inline] fn drop(&mut self) { abort(); } } #[inline] fn abort() -> ! { //debug_assert!(std::thread::panicking()); ...
use std::{thread, time}; use crate::protocol::Protocol; pub struct Stopper { protocol: Protocol, processor_quantity: u32 } impl Stopper { pub fn new(host: String, processor_queue: String, processor_places_queue: String, processor_quantity: u32) -> Stopper { Stopper { proto...
extern crate peko_crypto; mod hash;
use std::collections::{HashMap, HashSet}; fn main() { let input = "input/day24"; let input = String::from_utf8(std::fs::read(input).unwrap()).unwrap(); let mut black_tiles = HashSet::new(); const DIR_TO_OFFSET: [(&str, [i32; 2]); 6] = [ ("nw", [0, 1]), ("ne", [1, 1]), ("sw", [-1...
impl<U, REG> Reg<U, REG> where Self: Readable + Writable, U: Copy + Default + core::ops::Not<Output = U>, { /// Set high every bit in the register that was set in the write proxy. Leave other bits /// untouched. The write is done in a single atomic instruction. #[inline(always)] pub unsafe fn se...
#![allow(dead_code)] use core::intrinsics::transmute; #[allow(non_camel_case_types)] #[repr(u8)] pub enum c_void { __variant1, __variant2, } pub const REQ_ADC0_SINGLE: u32 = ((8 << 16) + 0); pub const REQ_ADC0_SCAN: u32 = ((8 << 16) + 1); pub const REQ_USART1_RXDATAV: u32 = ((13 << 16) + 0); pub const...
use std::collections::HashMap; pub fn run() { let field_name = String::from("Blue"); let mut scores = HashMap::new(); scores.insert(String::from("Blue"), 10); scores.insert(String::from("Yellow"), 50); scores.insert(field_name, 60); // a HashMap takes ownership of its keys and values // println!("{}", ...
#[doc = "Reader of register RX_DATA_FIFO_RD2"] pub type R = crate::R<u32, super::RX_DATA_FIFO_RD2>; #[doc = "Reader of field `DATA0`"] pub type DATA0_R = crate::R<u8, u8>; #[doc = "Reader of field `DATA1`"] pub type DATA1_R = crate::R<u8, u8>; impl R { #[doc = "Bits 0:7 - RX data (read from RX data FIFO, first byte...
use crate::user::settings::{ProjectSettings, ProjectType}; use crate::{commands, install}; use binary_install::Cache; use std::path::PathBuf; use std::process::Command; use crate::emoji; pub fn generate(name: &str, template: &str, cache: &Cache) -> Result<(), failure::Error> { let tool_name = "cargo-generate"; ...
/* * YNAB API Endpoints * * Our API uses a REST based design, leverages the JSON data format, and relies upon HTTPS for transport. We respond with meaningful HTTP response codes and if an error occurs, we include error details in the response body. API Documentation is at https://api.youneedabudget.com * * The ve...
// MIT License // // Copyright (c) 2021 Miguel Peláez // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modif...
/* Copyright (c) 2023 Uber Technologies, Inc. <p>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 <p>http://www.apache.org/licenses/LICENSE-2.0 <p>Unless required by applicable law or agreed to...
#[derive(Debug)] enum List { Cons(i32, Box<List>), Nil, } use crate::List::{Cons, Nil}; use std::ops::Deref; #[derive(Debug)] enum ListRc { Cons(i32, Rc<ListRc>), NilRc, } use crate::ListRc::{Cons as ConsRc, NilRc}; use std::cell::RefCell; use std::rc::Rc; #[derive(Debug)] enum ListRefCell { Con...
use crate::error::Error; use crate::header::{self, Header}; use async_trait::async_trait; use crypto::digest::Digest; use crypto::sha1::Sha1; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::TcpStream; const MAGIC: u32 = 0; const CHECKSUM_SIZE: usize = 4; pub trait Serializable { fn serialize(&self) ...
use crate::interpreter::LoxCallable; use crate::interpreter::LoxValue; use crate::interpreter::RuntimeError; use crate::interpreter::Interpreter; pub struct ClockFunction; impl LoxCallable for ClockFunction { fn call(&self, interpreter: &mut Interpreter, arguments: Vec<LoxValue>) -> Result<LoxValue, RuntimeError>...