text
stringlengths
8
4.13M
//! YAML Functions //! These functions can be used to allow an object to perform YAML actions. use std::error::Error; use uuid::Uuid; /// Convert an object that implements Serialize to a String pub fn object_to_string<T>(object: (Uuid, T)) -> Result<String, Box<dyn Error>> where T: serde::ser::Serialize, { Ok(...
// Copyright 2019 The Tari Project // SPDX-License-Identifier: BSD-3-Clause /// Adds some variations of `Add` given a definition for `Add` that takes references. i.e. assuming we have /// ```ignore /// impl<'a, 'b> Add<&'b Foo> for &'a Foo { /// type Output = Foo; /// fn add(self, rhs: &'b rhs) -> Foo {....
#[doc = "Reader of register SPISR2"] pub type R = crate::R<u32, super::SPISR2>; #[doc = "Reader of field `SPISR2`"] pub type SPISR2_R = crate::R<u32, u32>; impl R { #[doc = "Bits 0:31 - shared peripheral interrupt"] #[inline(always)] pub fn spisr2(&self) -> SPISR2_R { SPISR2_R::new((self.bits & 0xff...
extern crate der_parser; extern crate nom; extern crate rusticata_macros; extern crate x509_parser; use std::io::Cursor; use x509_parser::parse_x509_der; use x509_parser::pem::{pem_to_der, Pem}; static IGCA_PEM: &[u8] = include_bytes!("../assets/IGC_A.pem"); #[test] fn test_x509_parse_pem() { let (rem, pem) = pe...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use types::U256; pub const BLOCK_TIME_SEC: u32 = 20; pub const BLOCK_WINDOW: u64 = 24; use anyhow::Result; use logger::prelude::*; use traits::ChainReader; pub fn difficult_1_target() -> U256 { U256::max_value() } pub fn cur...
use super::*; use std::io::Read; pub struct TableSection<'a> { pub count: u32, pub entries_raw: &'a [u8], } pub struct TableEntryIterator<'a> { count: u32, iter: &'a [u8] } pub struct TableEntry { pub ty: u8, pub limits: ResizableLimits, } impl<'a> TableSection<'a> { pub fn entries(&self...
use std::cmp::Ordering; use std::collections::HashMap; fn main() { main_ordering(); main_account(); } fn main_ordering() { assert_eq!(Ordering::Less, compare(2, 3)); } fn compare(n: i32, m: i32) -> Ordering { if n < m { Ordering::Less } else if n > m { Ordering::Greater } els...
use log::*; use crate::bus::ModuleMsgEnum; use crate::system::SystemModules; use msgbus::{MsgBusHandle, Message}; use serde::{Serialize, Deserialize}; use tokio::sync::mpsc::Receiver; use tokio::sync::{Mutex}; use std::sync::Arc; mod terminal; #[derive(Debug, PartialEq, Clone, Serialize, Deserialize)] pub struct CliC...
use crate::{qs_params, session::CallbackProvider, Messages}; use crate::{MarketSession, Product, SecurityType, Session, Store}; use anyhow::Result; use http::Method; use std::sync::Arc; use strum::EnumString; pub struct Api<T: Store> { session: Arc<Session<T>>, } impl<T> Api<T> where T: Store, { pub fn new(sess...
fn product_except_self(nums: Vec<i32>) -> Vec<i32> { let mut res = vec![1]; for i in 0..nums.len() - 1 { res.push(nums[i] * res[i]); } let mut prefix = 1; for i in (1..nums.len()).rev() { prefix = nums[i] * prefix; res[i - 1] = res[i - 1] * prefix; } res } fn mai...
use enigo::*; use websocket::ClientBuilder; use websocket::OwnedMessage; const TABLET_MAX_X: i64 = 20966; const TABLET_MAX_Y: i64 = 15725; const SCREEN_MAX_X: i64 = 1920; const SCREEN_MAX_Y: i64 = 1080; const RATIO_X: i64 = TABLET_MAX_X / SCREEN_MAX_X; const RATIO_Y: i64 = TABLET_MAX_Y / SCREEN_MAX_Y; fn main() { ...
const PI: f64 = 3.141592; const MAX_SECTOR: i16 = 36; const MAX_CYLINDER: i16 = 5; const MAX_RADIUS: i16 = 300; const RADIUS_PER_CYLINDER: f64 = (MAX_RADIUS / MAX_CYLINDER) as f64; pub const CENTER_X: i16 = 400; pub const CENTER_Y: i16 = 300; pub fn cylinders_to_triangles() -> Vec<Vec<i16>> { let mut points: Vec<V...
use wasm_bindgen::prelude::*; use std::ops::Range; #[wasm_bindgen] pub fn set_panic_hook() { // When the `console_error_panic_hook` feature is enabled, we can call the // `set_panic_hook` function at least once during initialization, and then // we will get better error messages if our code ever panics. ...
use crate::components::HpComponent; use crate::indices::*; use crate::profile; use crate::storage::views::{DeferredDeleteEntityView, View}; use tracing::{debug, trace}; pub fn death_update(mut delete: DeferredDeleteEntityView, (hps,): (View<EntityId, HpComponent>,)) { profile!("DeathSystem update"); debug!("up...
fn main() { const INPUT: &'static str = include_str!("inputs/day05.txt"); let highest_id = INPUT .lines() .map(|x| get_row_and_col(x)) .map(|x| x.0 * 8 + x.1) .max() .unwrap(); println!("max: {}", highest_id) } fn get_row_and_col(s: &str) -> (isize, isize) { let...
use crate::image_data::{ImageData, ImageFormat}; use crate::resources::{self, GraphicResourceManager, GraphicResource, GraphicResourceError}; use crate::texture_resource::{TextureResource, TextureHandle}; use crate::vec2::Vec2; use crate::rect::Rect; use std::fmt; use std::any::Any; use std::sync::{Arc, Mutex}; use st...
// unihernandez22 // https://codeforces.com/problemset/problem/1154/A // math use std::io::stdin; fn main() { let mut s = String::new(); stdin().read_line(&mut s).unwrap(); let mut words: Vec<i32> = s .split_whitespace() .map(|x| x.parse().unwrap()) .collect(); words.sort(); ...
use std::cmp::Ordering; use std::{env, fs, process}; use handlebars::TemplateRenderError; use serde::Deserialize; use thiserror::Error; const CFG_PATH: &str = "$HOME/.config/polybar-forecast/config.toml"; // Represents user configs #[derive(Debug, Deserialize, Clone)] pub struct Configuration { #[serde(default =...
use std::fmt::{self, Display, Formatter}; use serde::{Serialize, Deserialize}; #[derive(Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Clone, Debug)] pub struct Id(String); impl Id { pub fn new<I: AsRef<str>>(id: I) -> Self { Self(id.as_ref().to_string()) } } impl Display for Id { fn fmt(&self, f: &...
use std::io; use anyhow::{anyhow, Context, Result}; use serde::Deserialize; use crate::config::read_config; use crate::note::{InputNote, DbNote}; use crate::db::{init_schema, insert_notes}; pub fn exec() -> Result<()> { let cfg = read_config() .context("Reading config")?; let db = sqlite::open(&cfg.d...
fn main() { println!("Another top-level source"); }
use crate::{backend::Backend, error::error}; use cloudevents::{ event::{Data, ExtensionValue}, AttributesReader, Event, }; use drogue_cloud_service_api::{EXT_APPLICATION, EXT_DEVICE}; use itertools::Itertools; use patternfly_yew::*; use unicode_segmentation::UnicodeSegmentation; use wasm_bindgen::{closure::Clos...
use std::sync::Arc; use hashbrown::HashSet; use rosu_v2::prelude::{GameMode, OsuError, Username}; use crate::{ embeds::{EmbedData, UntrackEmbed}, util::{ constants::{GENERAL_ISSUE, OSU_API_ISSUE}, MessageExt, }, BotResult, CommandData, Context, MessageBuilder, }; use super::TrackArgs;...
use std::iter::Peekable; use std::str::Chars; use crate::token::Token; use crate::token::Token::{Values, Value, Pipe}; trait VecExt<T> { fn push_value(&mut self, ele: T); } impl VecExt<Token> for Vec<Token> { fn push_value(&mut self, token: Token) { if token.value().is_some() { self.push(token) } ...
#[macro_use] extern crate criterion; use criterion::{BatchSize, Criterion}; use hacspec_chacha20::*; use hacspec_chacha20poly1305::*; use hacspec_dev::rand::random_byte_vec; use hacspec_lib::prelude::*; fn benchmark(c: &mut Criterion) { c.bench_function("ChaCha20Poly1305 encrypt", |b| { b.iter_batched( ...
mod art; mod artist; mod postgres; pub mod scheduler; #[allow(unused_imports)] mod schema; pub use art::PgArtRepository; pub use artist::PgArtistRepository; pub use postgres::{Connection, Postgres}; pub use scheduler::PgSchedulerRepository;
use std::fs::File; use std::io::{BufRead, BufReader}; fn main() { let filename = "input/input.txt"; let binary_numbers = parse_input_file(filename); // println!("{:?}", binary_numbers); // Part 1 let gamma_str = calculate_gamma_rate_str(&binary_numbers); let gamma_val = binary_str_to_num(&gam...
use crate::bstream::BstreamHdr; use crate::io::TwzIOHdr; use crate::io::{PollStates, ReadFlags, ReadOutput, ReadResult, WriteFlags, WriteOutput, WriteResult}; use twz::event::Event; use twz::mutex::TwzMutex; use twz::obj::CreateSpec; use twz::obj::Twzobj; use twz::ptr::Pptr; use twz::refs::Pref; use twz::TwzErr; const...
use ptgui::prelude::*; use std::cmp::{max, min}; pub trait PhysicsCollider { fn is_colliding<T>(&self, other: T) -> bool where T: PhysicsCollider, { let t_size = self.get_size(); let t_pos = self.get_pos(); let o_size = other.get_size(); let o_pos = other.get_pos(); ...
fn plus_one(x: Option<i32>) -> Option<i32> { match x { None => None, Some(i) => Some(i+1), } } fn main() { let x = 5; println!("Val: {}, plus one: {}", x, plus_one(Some(x)).unwrap_or(1)); let x = Some(x); println!("Val: {}, plus one: {}", x.unwrap(), plus_one(x).expect("Bad val")); ...
use std::{env, path}; use ggez::event::{self, EventHandler}; use ggez::nalgebra::Point2; use ggez::{filesystem, graphics, timer}; use ggez::{Context, GameResult}; impl EventHandler for VSync { fn update(&mut self, ctx: &mut Context) -> GameResult<()> { println!( "[update] ticks: {}\tfps: {}\td...
pub const VOICE_COUNT: usize = 16; pub const CHANNEL_COUNT: usize = 3; pub const SAMPLE_HZ: f32 = 48000.0; pub const MAX_STEPS: usize = 24;
use kube_derive::CustomResource; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; #[derive(CustomResource, Serialize, Deserialize, Debug, Clone, JsonSchema)] #[kube(group = "clux.dev", version = "v1", kind = "FooEnum")] #[serde(rename_all = "camelCase")] #[allow(clippy::enum_variant_names)] enum FooEnumS...
#[doc = "Register `PATT3` reader"] pub type R = crate::R<PATT3_SPEC>; #[doc = "Register `PATT3` writer"] pub type W = crate::W<PATT3_SPEC>; #[doc = "Field `ATTSETx` reader - ATTSETx"] pub type ATTSETX_R = crate::FieldReader; #[doc = "Field `ATTSETx` writer - ATTSETx"] pub type ATTSETX_W<'a, REG, const O: u8> = crate::F...
// Copyright (c) 2019 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...
extern crate bme280; use bme280::{Bme280Device, DEFAULT_DEVICE, DEFAULT_ADDRESS}; fn main() { let mut dev = Bme280Device::new(DEFAULT_DEVICE, DEFAULT_ADDRESS)?; let r = dev.read_all()?; println!("temperature: {}", r.temperature); println!("humidity: {}", r.humidity); println!("pressure: {}", r.pressure); }
use std::net::TcpStream; pub use craftping::sync::ping; fn main() { let servers = ["us.mineplex.com", "mc.hypixel.net"]; for &server in servers.iter() { let mut stream = TcpStream::connect((server, 25565)).unwrap(); let response = ping(&mut stream, server, 25565).unwrap(); println!("pi...
#[doc = "Reader of register UARTPCELLID3"] pub type R = crate::R<u32, super::UARTPCELLID3>; #[doc = "Reader of field `UARTPCELLID3`"] pub type UARTPCELLID3_R = crate::R<u8, u8>; impl R { #[doc = "Bits 0:7 - These bits read back as 0xB1"] #[inline(always)] pub fn uartpcellid3(&self) -> UARTPCELLID3_R { ...
#![cfg(test)] use super::*; use crate::physics::single_chain::test::Parameters; mod base { use super::*; use rand::Rng; #[test] fn init() { let parameters = Parameters::default(); let _ = SWFJC::init(parameters.number_of_links_minimum, parameters.link_length_reference, par...
#![no_std] use num_derive::*; #[derive(FromPrimitive, ToPrimitive)] pub enum ABC { A, B, C, } #[derive(PartialEq, FromPrimitive, Num, NumCast, NumOps, One, ToPrimitive, Zero)] pub struct NewFloat(f32);
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // // Portions Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the THIRD-PARTY file. #![allow(unused)] #![d...
use super::*; use std::ffi::CStr; pub fn expression() -> Expression { Expression { boostrap_compiler: boostrap_compiler, typecheck: typecheck, codegen: codegen, } } fn boostrap_compiler(compiler: &mut Compiler) { add_function_to_compiler(compiler, "int", Type::Int, &vec![Type::Stri...
use jsonwebtoken::errors::ErrorKind; use jsonwebtoken::jwk::Jwk; use jsonwebtoken::{ crypto::{sign, verify}, decode, decode_header, encode, Algorithm, DecodingKey, EncodingKey, Header, Validation, }; use serde::{Deserialize, Serialize}; use time::OffsetDateTime; #[derive(Debug, PartialEq, Eq, Clone, Serialize,...
use postgrest::Postgrest; use std::error::Error; const REST_URL: &str = "http://localhost:3000"; #[tokio::test] async fn basic_data() -> Result<(), Box<dyn Error>> { let client = Postgrest::new(REST_URL); let resp = client .from("users") .select("username") .eq("status", "OFFLINE") ...
use crate::env_file::entry::Entry; use crate::env_file::{Env, Var}; #[derive(Debug)] pub struct EnvIterator<'a> { env: &'a Env, index: usize, } impl<'a> EnvIterator<'a> { pub fn new(env: &'a Env) -> Self { Self { env, index: 0 } } } impl<'a> Iterator for EnvIterator<'a> { type Item = &'a ...
#[cfg(test)] #[macro_use] extern crate pretty_assertions; #[cfg(test)] mod vertex_tests { use graphific::Vertex; #[test] fn new_vertex_test() { let v1: Vertex<i32, i32> = Vertex::new(0); let v2: Vertex<i32, i32> = Vertex::new(1); let v3: Vertex<i32, f32> = Vertex::new(2); ...
//! ITP1_10_Dの回答 //! [https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_10_D](https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_10_D) use std::io::BufRead; /// ITP1_10_Dの回答 #[allow(dead_code)] pub fn main() { let dataset = Dataset::read(std::io::stdin().lock()); let answer = dataset....
extern crate rand; extern crate common; use common::*; use common::HandEnum::*; use common::HandCard::*; use common::Turn::*; use common::Participant::*; use common::Score::*; use common::KnockerOrWinner::*; use std::collections::HashMap; use rand::{StdRng, SeedableRng, Rng}; macro_rules! s { ($($expr: expr),*...
use actix_files as fs; use actix_web::{web, App, HttpResponse, HttpServer, Responder}; use serde::Deserialize; use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod}; #[derive(Deserialize)] struct FormData { fname: String, lname: String, city: String, } fn index() -> impl Responder { HttpResponse::Ok...
use crate::{format_context::FormatContext, frame::Frame, packet::Packet, tools}; use ffmpeg_sys_next::*; use std::ptr::null_mut; #[derive(Debug)] pub struct AudioDecoder { pub identifier: String, pub stream_index: isize, pub codec_context: *mut AVCodecContext, } impl AudioDecoder { pub fn new( identifier:...
#[doc = "Register `TIMCDIER` reader"] pub type R = crate::R<TIMCDIER_SPEC>; #[doc = "Register `TIMCDIER` writer"] pub type W = crate::W<TIMCDIER_SPEC>; #[doc = "Field `CMP1IE` reader - CMP1IE"] pub type CMP1IE_R = crate::BitReader<CMP1IE_A>; #[doc = "CMP1IE\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq,...
//! Base stats // IMports use crate::{Ability, BodyColor, EggGroup, GrowthRate, Item, Type}; /// Stats #[derive(PartialEq, Clone, Copy, Debug)] #[derive(serde::Serialize, serde::Deserialize)] pub struct Stats { /// Hp pub hp: u8, /// Attack pub atk: u8, /// Defense pub def: u8, /// Speed pub speed: u8, /...
use sdl2::pixels::PixelFormatEnum; use ted_interface::*; use self::rand::Rng; use *; const TERRAIN_IMAGE_ROWS:u32=10; const TERRAIN_WIDTH: u32=40; const CHUNK_WIDTH_SQUARES: u32=10; const CHUNK_WIDTH_PIXELS: u32=CHUNK_WIDTH_SQUARES*TERRAIN_WIDTH; const PARTICLE_COUNT: usize=10; const PARTICLE_TURN_SPEED: f64=0.1; cons...
/* * 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 */ /// HostListResponse : Response with Host information from Datadog. #[derive(Clone, Debug, PartialEq,...
// Copyright 2016 The Fancy Regex Authors. // // 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, modify, merge, p...
pub struct IsClosed { pub in_arrow: bool, pub in_cond: bool, recent: Vec<TOCLOSE>, } #[derive(PartialEq, Debug, Clone, Copy)] pub enum TOCLOSE { BRACKETS, PARENS, QUOTES, } impl IsClosed { pub fn new() -> IsClosed { IsClosed { recent: Vec::new(), in_arrow: f...
use std::ops::{Index, IndexMut}; fn main() { let mut puzzle = input(); println!("First solution: {}", puzzle.solve()); let mut puzzle = input(); puzzle.expand(); println!("Second solution: {}", puzzle.solve()); } type Position = (usize, usize); #[derive(Debug, Clone)] struct Node { visited: b...
use std::error::Error; use std::fs; #[derive(Debug)] pub struct Conf { pub cpn: String, pub asno: String, pub tag: String, } impl Conf { pub fn new(args: Vec<&str>) -> Result<Conf, &'static str> { if args.len() < 2 { return Err("not enough arguments"); } let tag = i...
#[doc = "Register `AHB2SMENR` reader"] pub type R = crate::R<AHB2SMENR_SPEC>; #[doc = "Register `AHB2SMENR` writer"] pub type W = crate::W<AHB2SMENR_SPEC>; #[doc = "Field `GPIOASMEN` reader - IO port A clocks enable during Sleep and Stop modes"] pub type GPIOASMEN_R = crate::BitReader; #[doc = "Field `GPIOASMEN` writer...
use std::io::stdin; pub fn get_name() -> String { let mut name = String::new(); println!("Please enter your name"); stdin().read_line(&mut name).unwrap(); name }
fn main() { let input: &str = include_str!("input.txt"); let mut sections = input.split("\n\n"); let grid_string = sections.next().unwrap(); let fold_instructions = sections.next().unwrap(); let highest_coords = get_highest_coord(grid_string); let mut grid = vec![vec![false; highest_coords.x as ...
use clockwork::Modules; use clockwork::routes::{self, Routes, UriParams, BodyParams, RouteModel}; use clockwork_handlebars::ViewRenderer; use models::NewSubmit; pub fn register(routes: &mut Routes) { routes.get("/projects/new", new); routes.post("/projects/new", routes::model_handler(new_submit)); } fn new(mo...
// Copyright 2015-2016 Joe Neeman. // // 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 distributed // except accordin...
use image; use image::{GenericImage, Rgb, Rgba}; use texture::{Pixel, Texture}; impl<P: Pixel + image::Pixel, I: GenericImage<Pixel = P>> Texture for I { type Pixel = I::Pixel; fn width(&self) -> u32 { self.dimensions().0 } fn height(&self) -> u32 { self.dimensions().1 } fn ...
use crate::{ grid::{ config::{ColoredConfig, Entity}, dimension::CompleteDimensionVecRecords, records::{ExactRecords, PeekableRecords, Records, RecordsMut}, util::string::{count_lines, get_lines}, }, settings::{measurement::Measurement, peaker::Peaker, CellOption, Height, Tab...
use nom::types::CompleteStr; use uuid::Uuid; use std::fmt; use std::str::FromStr; use topic::{Reversible, Topic}; use version::Version; named!(pub topic<CompleteStr, Topic>, do_parse!( tag_s!("agents/") >> agent_id: map_res!(take_until_s!("/"), |s: CompleteStr| FromStr::from_str(s.0)) >> ...
pub struct PasswordEncoder {} impl PasswordEncoder { pub fn encode(raw_password: &str) -> String { let digest = md5::compute(raw_password); format!("{:x}", digest) } pub fn verify(password: &str, raw_password: &str) -> bool { if password.eq(raw_password) { return true; ...
use std::time::Duration; use actix::prelude::*; use actix_broker::{BrokerIssue, SystemBroker}; use actix_web::client::Client; use futures::{compat::Future01CompatExt, FutureExt, TryFutureExt}; use crate::caltrain_status::CaltrainStatus; use crate::station::Station; pub struct CStatusFetcher { station: Station, ...
extern crate rocket_contrib; extern crate sl_lib; extern crate tera; use diesel::prelude::*; use rocket_contrib::Template; use tera::Context; // use sl_lib::models::{Post, User}; use sl_lib::models::Post; use sl_lib::*; // use sl_lib::markdown::markdown_to_html; // use it for filter later instead of writing html to ...
use crate::{prelude::*, utils::*}; use arrow::record_batch::RecordBatch; use itertools::Itertools; use log::debug; use owning_ref::OwningHandle; use rayon::prelude::*; use std::marker::PhantomData; type SourceParserHandle<'a, S> = OwningHandle< Box<<S as Source>::Partition>, DummyBox<<<S as Source>::Partition ...
#[doc = "Register `DMAMR` reader"] pub type R = crate::R<DMAMR_SPEC>; #[doc = "Register `DMAMR` writer"] pub type W = crate::W<DMAMR_SPEC>; #[doc = "Field `SWR` reader - Software Reset When this bit is set, the MAC and the DMA controller reset the logic and all internal registers of the DMA, MTL, and MAC. This bit is a...
use std::cell::RefCell; use std::collections::{HashMap, HashSet}; use std::mem; use std::ptr::null_mut; use bincode; use flate2; use libc::c_void; use bw; use entity_serialize::{self, deserialize_entity, entity_serializable, EntitySerializable}; use units::{unit_to_id, unit_from_id}; use save::{fread, fwrite, fread_n...
#[doc = "Prunes branches of the document tree that contain no documentation"]; export mk_pass; fn mk_pass() -> pass { run } type ctxt = { mutable have_docs: bool }; fn run( _srv: astsrv::srv, doc: doc::cratedoc ) -> doc::cratedoc { let ctxt = { mutable have_docs: true }; let fold...
use std::pin::Pin; use std::task::{Context, Poll}; use crate::{ state_machine::{Core, Ended, InGame}, Connection, }; use futures::{future::Either, ready, sink::Sink, stream::Stream}; use rsc2_pb::protocol::{self, Status}; pub struct InGameLoop<'sm, 'b> { state: Option<InGame<'sm>>, framed: Pin<&'b mu...
//! A module that provides task synchronisation primitives. #[doc(inline)] pub use tokio::sync::oneshot; pub mod mpsc;
fn main() { let (flashes, sync) = solve(); println!("First solution: {}", flashes); println!("Second solution: {}", sync); } fn solve() -> (usize, usize) { let mut field = input(); let mut flashes = 0; let mut i = 0; loop { i += 1; // Add one to each octopus field....
cfg_if::cfg_if! { if #[cfg(feature = "sha1")] { use std::io::Write; use encoding::hex; use cryptographer::{sha1, Hash}; fn main() { let mut h = sha1::new(); h.write(b"His money is twice tainted:") .expect("failed to consume"); h.write(b" 'taint yours and 'taint mine.") .expect("fai...
extern crate homotopy; use homotopy::*; fn main() { let a = Circle {center: [0.0, 0.0], radius: 1.0}; let b = Lerp(0.0, 10.0); let c = Square::new(a, b); assert!(check2(&c, Default::default())); let d = c.map(|(xy, z)| [xy[0], xy[1], z]); assert!(check2(&d, Default::default())); let lef...
use jsonrpc_core::{MetaIoHandler, Metadata}; use std::sync::mpsc::Sender; use messages::{EnvelopeSubject, Notification}; use rpc::agent::Rpc as AgentRpc; use rpc::ping::Rpc as PingRpc; use rpc::room::Rpc as RoomRpc; use rpc::subscription::Rpc as SubscriptionRpc; use rpc::track::Rpc as TrackRpc; use rpc::webrtc::Rpc a...
use tui::layout::{Constraint, Direction, Layout as TUILayout, Rect}; pub struct Layout { pub help_bar: Rect, pub formulae_list: Rect, pub info: Rect, } impl Layout { pub fn new(size: Rect) -> Layout { let main_chunks = TUILayout::default() .direction(Direction::Vertical) ...
use rustberry::effects::http_player::HttpPlayer; use rustberry::player::PlaybackHandle; #[tokio::main] async fn main() -> Result<(), failure::Error> { let player = HttpPlayer::new().unwrap(); println!("starting..."); let handle = player .start_playback( "https://tortoise.silverratio.net...
use juice_sdk_rs::{client, transports, types, Result}; #[tokio::main] async fn main() -> Result<()> { let transport = transports::http::Http::new("http://10.1.1.40:7009")?; let client = client::Client::new(transport, true); //let number = client.block_number(String::from("sys")).await?; let block = cl...
#![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 Blueprint { #[serde(flatten)] pub azure_resource_base: AzureResourceBase, pub properties: BlueprintProp...
use super::*; use add_generator::*; use bitop_generator::*; use mathic::*; impl<'a> JIT<'a> { pub fn emit_op_bitand(&mut self, op: &Ins) { if let Ins::BitAnd(dest, op1, op2) = op { let left_reg = T1; let right_reg = T2; let result_reg = T0; let scratch_gpr = T...
use uuid::Uuid; #[derive(juniper::GraphQLInputObject)] pub struct NewUser { pub username: String, pub password: String, pub email: String, } #[derive(juniper::GraphQLObject)] pub struct User { pub uuid: Uuid, pub first_name: String, pub last_name: String, pub username: String, pub emai...
// -------------------------------------------------------------------------------// // Cryptopals, Set 2, Challenge 11: https://cryptopals.com/sets/2/challenges/11 // Impl by Frodo45127 // -------------------------------------------------------------------------------// use crate::utils::*; const DATA: &[u8; 164] = ...
/* ---New Cashier No Space or Shift--- Some new cashiers started to work at your restaurant. They are good at taking orders, but they don't know how to capitalize words, or use a space bar! All the orders they create look something like this: "milkshakepizzachickenfriescokeburgerpizzasandwichmilkshakepizza" The kit...
use once_cell::sync::Lazy; use parking_lot::{Mutex, MutexGuard}; use std::sync::Arc; #[derive(Clone)] pub struct Atom<T> { value: Arc<Mutex<T>>, subscribers: Arc<Mutex<Vec<Subscriber>>>, } impl<T> Atom<T> { pub fn new(initial: T) -> Self { Self { value: Arc::new(Mutex::new(initial)), ...
use crate::access_control; use fund::{ accounts::{ fund::{Fund, FundType}, vault::TokenVault, }, error::{FundError, FundErrorCode}, }; use serum_common::pack::Pack; use solana_program::{ account_info::{next_account_info, AccountInfo}, msg, program, pubkey::Pubkey, }; use spl_toke...
use crate::PopReceipt; use azure_core::headers::{utc_date_from_rfc2822, CommonStorageResponseHeaders}; use azure_storage::core::xml::read_xml; use bytes::Bytes; use chrono::{DateTime, Utc}; use http::response::Response; use std::convert::TryInto; #[derive(Debug, Clone)] pub struct GetMessagesResponse { pub common_...
#[doc = "Register `FRCR` reader"] pub type R = crate::R<FRCR_SPEC>; #[doc = "Register `FRCR` writer"] pub type W = crate::W<FRCR_SPEC>; #[doc = "Field `FRL` reader - Frame length"] pub type FRL_R = crate::FieldReader; #[doc = "Field `FRL` writer - Frame length"] pub type FRL_W<'a, REG, const O: u8> = crate::FieldWriter...
// https://projecteuler.net/problem=15 /* Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner. rrdd - right right down down rdrd rddr drrd drdr ddrr How many such routes are there through a 20×20 grid? */ fn main...
//! Log module use byteorder::{BigEndian, ByteOrder}; use super::types::*; /// As log trait for how primitive types are represented as indexed arguments /// of the event log pub trait AsLog { /// Convert type to hash representation for the event log. fn as_log(&self) -> H256; } impl AsLog for u32 { fn as_log(&sel...
extern crate tui; extern crate termion; extern crate chrono; extern crate xdg; use std::io; use termion::event; use termion::input::TermRead; use termion::screen::AlternateScreen; use tui::Terminal; use tui::backend::TermionBackend; use tui::layout::{Group, Size}; use tui::widgets::Widget; use chrono::offset::local...
use std::collections::{HashMap, HashSet}; use hymns::runner::timed_run; const INPUT: &str = include_str!("../input.txt"); type Graph = HashMap<Cave, Vec<Cave>>; #[derive(Debug, Hash, Eq, PartialEq, Copy, Clone)] enum Cave { Start, End, Big(&'static str), Small(&'static str), } impl TryFrom<&'static...
//! # InfluxDB Client //! InfluxDB is an open source time series database with no external dependencies. //! It's useful for recording metrics, events, and performing analytics. //! //! ## Usage //! //! ```Rust //! extern crate influx_db_client; //! //! use influx_db_client::{InfluxdbClient, Point, Points, Value, Influ...
#[cfg(feature="wav")] extern crate hound; extern crate instrument; extern crate pitch_calc as pitch; extern crate sample; extern crate time_calc as time; pub use map::{Audio, Map, Sample}; pub use mode::Mode; pub use sampler::{Frames, Sampler}; pub mod dynamic; pub mod map; mod mode; mod sampler; #[cfg(feature="serd...
mod data_types; mod deb; mod extractor; #[cfg(test)] mod deb_test; pub use data_types::*; pub use deb::*; pub use extractor::*;
use crate::ast; use crate::{Parse, Spanned, ToTokens}; /// An is expression. #[derive(Debug, Clone, ToTokens, Parse, Spanned)] pub struct ExprIs { /// The left-hand side of a is operation. pub lhs: Box<ast::Expr>, /// The `is` keyword. pub is: ast::Is, /// The right-hand side of a is operation. ...
// file: pheno.rs // // Copyright 2015-2017 The RsGenetic Developers // // 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 require...