text
stringlengths
8
4.13M
// Copyright 2020-2021, The Tremor Team // // 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 agr...
use std::io::Read; fn read<T: std::str::FromStr>() -> T { let token: String = std::io::stdin() .bytes() .map(|c| c.ok().unwrap() as char) .skip_while(|c| c.is_whitespace()) .take_while(|c| !c.is_whitespace()) .collect(); token.parse().ok().unwrap() } fn main() { let...
// Copyright 2021 Datafuse Labs. // // 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 ...
///Name: Hangchen Qu ///ID: hq5na use std::rand::random; use std::os; use std::io::File; fn main() { let args = os::args(); let fname1: &str = args[1]; let fname2: &str = args[2]; let path1 = Path::new(fname1.clone()); let msg_file1 = File::open(&path1); let path2 = Path::new(fname...
/*! A very simple application that show your name in a message box. Unlike `basic_d`, this example use layout to position the controls in the window */ extern crate native_windows_gui as nwg; extern crate native_windows_derive as nwd; use nwd::NwgUi; use nwg::NativeUi; #[derive(Default, NwgUi)] pub struct ...
extern crate rand; use rand::Rng; use std::fmt::Debug; use crate::room::RoomType; use crate::sound::{AudioEvent, Effect}; use crate::state::State; use crate::timer::{Timer, TimerType}; use crate::{Action, GameEventType}; #[derive(Debug, Copy, Clone)] pub enum EnemyType { Rat, Roomba, } pub trait Enemy: Deb...
pub use VkCompositeAlphaFlagsKHR::*; #[repr(u32)] #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum VkCompositeAlphaFlagsKHR { VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR = 0x00000001, VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR = 0x00000002, VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR = 0x00000004, VK_COMPOSIT...
//<prefix>-<event-type>/<day>/<seconds>/<serialization>/<compression>-<capability> use std::time::{ SystemTime, UNIX_EPOCH, }; pub trait KeyGenerator { fn generate_key(&mut self, capability: u64) -> String; } pub struct S3KeyGenerator { bucket: String, serialization: String, compression: Stri...
#![cfg_attr(feature = "cargo-clippy", allow( cast_lossless, transmute_ptr_to_ref))] //! A simple copy-free ELF parser. //! //! This parser is limited, and parses only the specific kind of ELF files we expect to run. //! //! `Elf32::parse` can be used to parse a byte array into structs that reference the origin...
/*! HyperLogLog相关的命令定义、解析 所有涉及到的命令参考[Redis Command Reference] [Redis Command Reference]: https://redis.io/commands#hyperloglog */ use std::slice::Iter; #[derive(Debug)] pub struct PFADD<'a> { pub key: &'a [u8], pub elements: Vec<&'a [u8]>, } pub(crate) fn parse_pfadd(mut iter: Iter<Vec<u8>>) -> PFADD { ...
use crate::mock_server::bare_server::BareMockServer; use crate::MockServer; use async_trait::async_trait; use deadpool::managed::{Object, Pool}; use once_cell::sync::Lazy; use std::convert::Infallible; /// A pool of `BareMockServer`s. /// /// ## Design constraints /// /// `wiremock`'s pooling is designed to be an invi...
impl From<&metrics::Label> for crate::metric_message::Label { fn from(label: &metrics::Label) -> Self { Self { key: label.key().to_owned(), value: label.value().to_owned(), } } }
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distri...
/// This module contains implementations of `ToLua` and `FromLua` traits for /// Vector data types pub mod event; pub mod log; pub mod metric; pub mod util; pub mod value;
use super::NEEDLESS_COLLECT; use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_hir_and_then}; use clippy_utils::source::{snippet, snippet_with_applicability}; use clippy_utils::sugg::Sugg; use clippy_utils::ty::is_type_diagnostic_item; use clippy_utils::{can_move_expr_to_closure, is_trait_method, path_to_lo...
use crate::config::{CompressionType, TypeExtension}; use bzip2::{read::BzDecoder, write::BzEncoder}; use csv::{Writer as CsvWriter, WriterBuilder}; use flate2::{read::GzDecoder, write::GzEncoder}; use snafu::{ensure, ErrorCompat, ResultExt, Snafu}; use std::{ fs::File, io::{Read, Result as IoResult, Seek, SeekF...
// > Database internal calls (try to separate CDRS from Rustler) // Copyright 2020 Roland Metivier // // 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...
use test_structs::Windows::Win32::{Foundation::HWND, UI::WindowsAndMessaging::CWPSTRUCT}; #[test] fn test_struct_formatting_parameters_debug_trait() { let mut cwp = CWPSTRUCT::default(); cwp.hwnd = HWND(5678); assert_eq!("CWPSTRUCT { lParam: LPARAM(0), wParam: WPARAM(0), message: 0, hwnd: HWND(5678) }", f...
use ruduino::Pin; use ruduino::cores::current::*; use ruduino::modules::HardwareSpi; pub fn setup() { // Set up SPI pin directions <Spi as HardwareSpi>::MasterInSlaveOut::set_input(); <Spi as HardwareSpi>::MasterOutSlaveIn::set_output(); <Spi as HardwareSpi>::Clock::set_output(); // Turn on SPI ...
#[derive(Serialize, Deserialize, Debug,)] pub struct NewBookDto { pub title: String, pub author: String, #[serde(default)] pub is_published: bool, } #[derive(Serialize, Deserialize, Debug,)] pub struct IdDto { id: i32 }
#[doc = "Reader of register DR_10"] pub type R = crate::R<u32, super::DR_10>; #[doc = "Reader of field `DRNL1`"] pub type DRNL1_R = crate::R<u16, u16>; #[doc = "Reader of field `DRNL2`"] pub type DRNL2_R = crate::R<u16, u16>; impl R { #[doc = "Bits 0:15 - Data value"] #[inline(always)] pub fn drnl1(&self) -...
// Stamping The Sequence // https://leetcode.com/explore/challenge/card/march-leetcoding-challenge-2021/592/week-5-march-29th-march-31st/3691/ pub struct Solution; impl Solution { pub fn moves_to_stamp(stamp: String, target: String) -> Vec<i32> { let stamp = stamp.as_bytes(); let s_len = stamp.len...
extern crate futures; extern crate tokio_core; extern crate telegram_bot; use telegram_bot::prelude::*; extern crate json; extern crate afterparty_ng as afterparty; use afterparty::{Delivery, Hub}; extern crate hyper; use hyper::{Client, Server}; use hyper::net::HttpsConnector; use hyper_native_tls::NativeTlsClie...
use std::fs::File; use std::io::prelude::*; use std::fmt; use crate::memory::Memory; pub struct SnesCartridge { memory: Vec<u8>, title: String, rom_makeup: u8, chipset: u8, rom_size: usize, ram_size: usize, country: u8, developer_id: u8, rom_version: u8, checksum_complement: u16...
use ggez::{ self, graphics::{self, spritebatch::SpriteBatch, Rect}, }; use util; pub struct SpriteDrawContext<'a> { sprite: &'a mut Sprite, comp: &'a (SpriteComponent + 'a), } impl<'a> graphics::Drawable for SpriteDrawContext<'a> { fn draw_ex(&self, ctx: &mut ggez::Context, param: graphics::DrawP...
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::collections::HashMap; use std::collections::HashSet; use std::fs; use std::io; use std::os::unix::io::AsRawFd; use std::path; use std::sync::Arc; ...
//! The trait that should be implemented for every variant in the `Modes` //! enum. These define what to do on each wlc callback. //! //! If any are left unspecified, they execute the `Default` operation. use rustwlc::*; use super::{Default}; /// Trait that defines callbacks that occur when in that mode. /// /// NOTE...
// Exec use num_derive::FromPrimitive; #[derive(Encode, Decode, FromPrimitive, Debug, Clone, Copy)] #[repr(u8)] pub enum ExecMessageType { CapsetReq = 0x00, // TODO: ExecMessageType enum }
extern crate surface; extern crate netpbm; use surface::{Surface, ColorRGBA}; use std::io::{self, Write}; static SAMPLE_IMAGE: &'static [u8] = include_bytes!("../sample_image2.ppm"); const IMAGE_WIDTH: usize = 896; const IMAGE_HEIGHT: usize = 600; const TAKE_PIXELS: usize = 1024 * 4 + 219; fn write_out( wr: &mut W...
pub trait Iterable<R> { fn at(&self, uint) -> R; fn at_sq(&self, uint, uint) -> R; fn each(&self) -> ElemIterator<R>; fn each_with_square(&self) -> ElemSquareIterator<R>; fn each_with_row_col(&self) -> ElemRowColIterator<R>; } pub struct ElemIterator<'a, R> { chess_board: &'a (Iterable<R> + 'a), idx: uin...
use crate::bounds::Bounds3; use crate::interaction::Interaction; use crate::interaction::SurfaceInteraction; use crate::intersect::Intersect; use crate::light::Light; use crate::primitive::Primitive; use crate::ray::Ray; use crate::sampler::Sampler; use crate::spectrum::Spectrum; use crate::types::Float; use std::rc::R...
#[cfg(feature = "Win32_UI_Shell_Common")] pub mod Common; #[cfg(feature = "Win32_UI_Shell_PropertiesSystem")] pub mod PropertiesSystem; ::windows_targets::link ! ( "shlwapi.dll""system" #[doc = "*Required features: `\"Win32_UI_Shell\"`*"] fn AssocCreate ( clsid : ::windows_sys::core::GUID , riid : *const ::windows_sys:...
use core::ops::ControlFlow; use std::collections::btree_map::Entry; use firefly_diagnostics::*; use firefly_intern::symbols; use firefly_syntax_base::*; use crate::ast::*; use crate::visit::VisitMut; pub fn analyze_function(reporter: &Reporter, module: &mut Module, mut function: Function) { let resolved_name = F...
pub mod passport_processing_part_1; pub mod passport_processing_part_2;
use crate::algebra::{AssociativeMagma, InvertibleMagma, UnitalMagma}; /// A group. /// /// This trait is an alias of [`AssociativeMagma`] + [`UnitalMagma`] + [`InvertibleMagma`]. /// /// [`AssociativeMagma`]: ./trait.AssociativeMagma.html /// [`UnitalMagma`]: ./trait.UnitalMagma.html /// [`InvertibleMagma`]: ./trait.I...
/// ERROR packet can be the acknowledgment of any other type of packet. /// The error code is an integer indicating the nature of the error. A /// table of values and meanings is given in the appendix. (Note that /// several error codes have been added to this version of this /// document.) The error message is inten...
extern crate bindgen; extern crate pkg_config; use std::env; use std::path::PathBuf; use cmake; fn update_submodules(modules: &[&str], dir: &str) { let mut args = vec![ "submodule", "update", "--init", "--depth", "1", "--recommend-shallow", ]; args.extend_from_sli...
use super::context::{ downcast_ctx, Context, ContextType, Ctx, PineRuntimeError, Runner, VarOperate, }; // use super::ctxid_parser::CtxIdParser; use super::output::{InputSrc, InputVal, SymbolInfo}; use super::{AnySeries, AnySeriesType}; use crate::ast::stat_expr_types::{Block, VarIndex}; use crate::types::{ Dat...
use input_i_scanner::{scan_with, InputIScanner}; fn dfs(i: usize, p: usize, g: &Vec<Vec<usize>>, size: &mut Vec<usize>, dp: &mut Vec<u64>) { size[i] = 1; for &j in &g[i] { if j == p { continue; } dfs(j, i, g, size, dp); size[i] += size[j]; dp[i] += dp[j] + si...
//! [![Banner](https://raw.githubusercontent.com/nvzqz/static-assertions-rs/assets/Banner.png)](https://github.com/nvzqz/static-assertions-rs) //! //! Compile-time assertions to ensure that invariants are met. //! //! _All_ assertions within this crate are performed at [compile-time]. This //! allows for finding errors...
use grapl_service::decoder::NdjsonDecoder; use sqs_executor::event_decoder::PayloadDecoder; use tokio::fs; #[cfg(test)] pub(crate) async fn read_osquery_test_data(path: &str) -> Vec<crate::parsers::OSQueryEvent> { let file_data = fs::read(format!("sample_data/{}", path)) .await .expect(&format!("Fa...
use itertools::Itertools; use std::env; use std::io::{self, BufRead}; fn format_layer(layer: &str, width: usize) { for line in &layer.chars().chunks(width) { print!(" "); for c in line { if c == '1' { print!("🎅") } else { print!(" "); ...
use ::smallvec::SmallVec; use ::std::fmt; use crate::util::{CoordType, Minimum, Point}; #[derive(Debug)] struct BoundingBox { min_x: CoordType, length_x: CoordType, min_y: CoordType, length_y: CoordType, min_z: CoordType, length_z: CoordType, } #[derive(Debug, Clone)] struct PointCubeXAssignm...
macro_rules! byte_array_to_rust { ($ptr:ident, $len:expr) => { if $ptr.is_null() || $len == 0 { Vec::new() } else { unsafe { std::slice::from_raw_parts($ptr, $len as usize).to_vec() } } } } macro_rules! buffer_to_vec { ($buffer:ident) => { if $buffer....
use std::cell::RefCell; use std::collections::HashMap; use std::fs; use crate::context::{Build, CloneSafe}; use crate::error::{Result, TensorNodeError}; use crate::nodes::NodeRoot; pub struct NodeCache<T: Build> { paths: RefCell<HashMap<String, String>>, caches_source: RefCell<HashMap<String, String>>, ca...
use std::sync::Mutex; use std::time::{SystemTime, UNIX_EPOCH}; use actix_web::{web, App, HttpServer, HttpRequest, HttpResponse}; extern crate reqwest; extern crate getopts; use getopts::Options; use std::env; static URL: &str = "http://127.0.0.1:8080/"; // URL веб-сервера по умолчанию static BIND: &str = "127.0.0.1:80...
extern crate psutil; #[test] fn uptime() { assert!(psutil::system::uptime() > 0); } #[test] fn virtual_memory() { let vm = psutil::system::virtual_memory().unwrap(); // simple sanity checking assert!(vm.total != 0); assert!(vm.free <= vm.total); assert!(vm.percent > 0.0); } #[test] fn swap_me...
use serde::*; use crate::util; pub type UserId = i32; #[derive(Debug, Serialize, Deserialize)] pub struct User { pub user_id: UserId, user_secret: String, } impl User { pub fn new(id: UserId) -> Self { User { user_id: id, user_secret: util::generate_random_string(10), ...
//! Example program drawing some text on a page. #[macro_use] extern crate simple_pdf; use simple_pdf::graphicsstate::Color; use simple_pdf::units::{Millimeters, Points, UserSpace}; use simple_pdf::{BuiltinFont, Pdf}; use std::io; /// Create a `text.pdf` file, with a single page containg some /// text lines positione...
//! Same as guessing game from the book but over TCP rather than standard IO. //! //! https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html //! //! To communicate with this server do: //! ```sh //! $ nc localhost 8080 //! ``` use futures::prelude::*; use rand::Rng; use runtime::net::{TcpListener, TcpStrea...
// This file was generated by gir (https://github.com/gtk-rs/gir) // from ../gir-files // DO NOT EDIT use crate::Encoding; use crate::Expectation; use crate::MessageHeadersType; use glib::translate::*; #[cfg(any(feature = "v2_26", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_26")))] use std::me...
// Copyright (c) 2017 Martijn Rijkeboer <mrr@sru-systems.com> // // 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 dis...
#![feature(test)] extern crate test; use std::fs; use std::path::Path; use test::{black_box, Bencher}; use datasets::image::mnist; #[bench] fn mnist_load_from_scratch(b: &mut Bencher) { let path = Path::new("./tmp/mnist"); match path.metadata() { Ok(d) => { if d.is_dir() { ...
#![feature(attr_literals)] #[macro_use] extern crate validator_derive; extern crate validator; use validator::Validate; #[derive(Validate)] #[validate(schema(function = "hey"))] struct Test { s: String, } fn hey(_: &Test) -> Option<(String, String)> { None } #[derive(Validate)] #[validate(schema(function = ...
//! CLI config for request authorization. /// Env var providing authz address pub const CONFIG_AUTHZ_ENV_NAME: &str = "INFLUXDB_IOX_AUTHZ_ADDR"; /// CLI flag for authz address pub const CONFIG_AUTHZ_FLAG: &str = "authz-addr"; /// Env var for single tenancy deployments pub const CONFIG_CST_ENV_NAME: &str = "INFLUXDB_I...
#![allow(unused_imports)] #![allow(unused_must_use)] #![allow(unused_macros)] #![allow(non_snake_case)] #![allow(clippy::too_many_arguments)] #![allow(clippy::many_single_char_names)] #![allow(clippy::needless_range_loop)] #![allow(clippy::comparison_chain)] use std::cmp::{max, min, Reverse}; use std::collections::{Bi...
use serde::{Serialize, Deserialize}; #[derive(Serialize, Deserialize)] pub struct CustomerCreatedEvent { pub name : String, pub credit_limit: i64 }
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}, std::io, }; #[derive(Clone, Copy, Debug)] pub enum EtherType { Ipv4 = 0x0800, } ...
use crate::constants::*; use cvar::{INode, IVisit}; use std::sync::{Arc, RwLock}; pub use orb::Config as OrbConfig; pub fn set_cli_cvars(config: &mut dyn IVisit, cmd: &clap::ArgMatches) { if let Some(values) = cmd.values_of("set") { for chunk in values.collect::<Vec<_>>().chunks_exact(2) { let...
#[allow(non_snake_case)] pub mod ProgramAssetSchema { use crate::render::shader::ShaderStage; use serde::{Deserialize}; #[derive(Deserialize)] #[serde(rename = "Program")] pub struct ProgramDef { pub id: String, #[serde(default = "ProgramDef::default_includes")] pub includes: Vec<String>, pub shaders...
extern crate rustplot; use rustplot::chart_builder; use rustplot::chart_builder::Chart; use rustplot::data_parser; #[test] fn window_size_tests() { let data_1 = data_parser::get_str_col(0, 0, 5, "./resources/bar_chart_tests.csv"); let data_2 = data_parser::get_num_col(1, 0, 5, "./resources/bar_chart_tests.csv...
use std::fmt::Debug; use std::marker::Unsize; use std::mem::transmute; use std::ops::CoerceUnsized; use std::ops::Deref; use futures::future::{self, BoxFuture}; use futures::prelude::*; use inherit_methods_macro::inherit_methods; use crate::event::{Events, Pollee, Poller}; use crate::file::{AccessMode, StatusFlags}; ...
#[derive(Debug, Copy, Clone, Default, Ord, PartialOrd, Eq, PartialEq)] pub struct Range { pub start: usize, pub end: usize, } impl std::ops::Add for Range { type Output = Self; /// will become the full range represented across self and other fn add(self, other: Self) -> Self { Self { ...
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use fdio::{fdio_sys, ioctl_raw, make_ioctl}; use std::fs::File; use std::os::unix::io::AsRawFd; use std::os::raw; use fuchsia_zircon as zx; pub fn connect...
//! An interface to the BED track format file as specified in //! https://genome.ucsc.edu/FAQ/FAQformat.html#format1 use crate::util::{get_buf, Strand}; use math::{ partition::integer_interval_map::IntegerIntervalMap, set::{ contiguous_integer_set::ContiguousIntegerSet, ordered_integer_set::Ord...
use log::warn; use regex::Regex; use serenity::model::channel::{Channel, Message}; use serenity::model::user::User; use serenity::prelude::*; use serenity::Result as SerenityResult; pub struct Utils; impl Utils { pub fn check_msg(result: SerenityResult<Message>) { if let Err(why) = result { ...
#![warn(missing_docs)] #![warn(missing_doc_code_examples)] //! Keep your files in sync! //! //! Synchronize your files in differents machines on the same network use serde::{Deserialize, Serialize}; use std::{error::Error, fmt::Display}; pub mod config; mod crypto; mod deletion_tracker; mod fs; mod network; pub mod ...
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distri...
#![desc = "Constraint Satisfaction in Rust"] #![license = "MIT"] #![crate_id = "csar#0.2"] #![crate_type = "lib"] #![feature(struct_inherit)] #![feature(globs)] use std::fmt; use std::cell::RefCell; use std::collections::hashmap::HashMap; use std::rc::{Rc, Weak}; pub use ltxy::{LtXY, LtXYC, LeXY, LeXYC, GtXY, GtXYC,...
use std::ops; #[derive(Copy, Clone)] pub struct Point { pub x: f64, pub y: f64 } impl Point { pub fn new(x: f64, y: f64) -> Self { Point { x, y } } } impl ops::Add for Point { type Output = Point; fn add(self, other: Self) -> Self { Point::new(self.x + other.x, self.y + othe...
use std::cmp; use std::io::Read; fn main() { let mut buf = String::new(); // 標準入力から全部bufに読み込む std::io::stdin().read_to_string(&mut buf).unwrap(); // 行ごとのiterが取れる let mut iter = buf.split_whitespace(); let days: usize = iter.next().unwrap().parse().unwrap(); let hapinesses: Vec<(u32, u32, ...
use itertools::Itertools; use std::str::FromStr; #[derive(Debug, Clone, PartialEq, Eq)] pub struct Grid<T> { rows: usize, cols: usize, g: Vec<T>, } type GridPos = (usize, usize); #[derive(Debug, Clone, Copy)] pub enum Direction { UpLeft, Up, UpRight, Right, DownRight, Down, Dow...
/* * hurl (https://hurl.dev) * Copyright (C) 2020 Orange * * 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 ...
#[derive(Debug, Serialize, Clone)] pub struct GraphQlErrorLocation { line: i32, column: i32, } #[derive(Debug, Serialize, Clone)] pub struct GraphQLError { message: String, locations: Vec<GraphQlErrorLocation>, } #[derive(Debug, Serialize, Clone)] pub struct GraphQLErrors { errors:...
use crate::{ builtins::{PyBytes, PyBytesRef, PyStrRef}, convert::{IntoPyException, ToPyObject}, function::PyStr, protocol::PyBuffer, PyObjectRef, PyResult, TryFromObject, VirtualMachine, }; use std::{ffi::OsStr, path::PathBuf}; #[derive(Clone)] pub enum FsPath { Str(PyStrRef), Bytes(PyBytes...
extern crate regex; pub mod irc;
use super::state_prelude::*; const UI_TIMER_DISPLAY_RON_PATH: &str = "ui/timer_display.ron"; pub struct Ingame { level: Level, ui_data: UiData, } impl Ingame { pub fn new(level: Level) -> Self { Self { level, ui_data: Default::default(), } } } impl<'a, 'b> S...
use bytes::{Buf, BytesMut}; use hex_literal::hex; use serde::Deserialize; use std::io::Read; use zenith_utils::bin_ser::LeSer; #[derive(Debug, PartialEq, Deserialize)] pub struct HeaderData { magic: u16, info: u16, tli: u32, pageaddr: u64, len: u32, } // A manual implementation using BytesMut, jus...
extern crate rand; extern crate piston_window; extern crate find_folder; mod draw; mod snake; mod game; use piston_window::*; use piston_window::types::Color; use game::Game; use draw::to_coord_u32; const BACK_COLOR: Color = [0.8, 0.8, 0.8, 1.0]; fn main() { let opengl = OpenGL::V3_2; let (width, height) ...
use std::collections::HashMap; fn main() { const INPUT: &str = include_str!("../input.txt"); let checksum = compute_checksum(INPUT.lines().collect()); println!("{}", checksum); println!("{}", day2_part2(INPUT.lines().collect())); } fn compute_checksum(ids: Vec<&str>) -> i64 { let mut two_matches =...
use std::fs::File; use std::io::{Read, Write}; use std::path::Path; use super::apt::{apt_install, service_start}; use super::juju; /// Write the samba configuration file out to disk pub fn render_samba_configuration<T: Write>(f: &mut T, volume_name: &str) ...
#[cfg(test)] mod tests { type ParseResult<'a, Output> = Result<(&'a str, Output), &'a str>; trait Parser<'a, Output> { fn parse(&self, input:&'a str) -> ParseResult<'a, Output>; fn map<F, NewOutput>(self, map_fn: F) -> BoxedParser<'a, NewOutput> where Self: Sized + 'a, ...
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! Utilities for filtering events. use fidl::encoding::Decodable; use fidl_fuchsia_media_sessions2::*; /// A filter accepts or rejects filter applicants...
/* * Integration tests for vsv. * * Author: Dave Eddy <dave@daveeddy.com> * Date: February 19, 2022 * License: MIT */ use std::fs; use std::fs::File; use std::io::Write; use std::path::{Path, PathBuf}; use std::str; use anyhow::{anyhow, Result}; use assert_cmd::Command; mod common; struct Config { proc_pa...
use async_std::net::{TcpListener, TcpStream, ToSocketAddrs}; use async_std::prelude::*; use async_std::task; use futures::{ future::FutureExt, io::{AsyncRead, AsyncWrite}, }; use std::net::{IpAddr, SocketAddr}; async fn handshake<Reader, Writer>( mut reader: Reader, mut writer: Writer, ) -> anyhow::Res...
#![feature(proc_macro_hygiene, decl_macro)] #[macro_use] extern crate diesel; #[macro_use] extern crate rocket; extern crate rocket_contrib; extern crate serde; use rocket::response::NamedFile; use rocket_contrib::serve::StaticFiles; use std::io; mod api; mod init; mod todos; pub type Connection = std::sync::Mutex<...
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub fn serialize_operation_activate_gateway( input: &crate::input::ActivateGatewayInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonO...
use clap::Parser; use std::io::{self, BufRead}; #[derive(Parser)] #[command(about = "Split input strings and extract certain columns", long_about = None)] #[command(version = "1.0")] struct Cli { /// Keep empty split-elements, if delimiter is repeated. Ignored, if no Delimiter is given. #[arg(short, long)] ...
use rltk::RGB; use specs::prelude::*; #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Component)] pub struct Position { pub x: i32, pub y: i32, } impl Position { pub fn new(x: i32, y: i32) -> Position { Self { x, y } } } #[derive(Copy, Clone, Debug, Component)] pub struct R...
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)]...
mod message_receiver; mod place_runner; mod plugin; mod place; mod core; use std::{ fs::{read_to_string}, path::Path, process, }; use log::error; use clap::{App, Arg}; use colored::Colorize; use crate::{ place_runner::PlaceRunnerOptions, message_receiver::{RobloxMessage, OutputLevel}, core::{...
pub use VkPipelineInputAssemblyStateCreateFlags::*; #[repr(u32)] #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum VkPipelineInputAssemblyStateCreateFlags { VK_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_NULL_BIT = 0, } use crate::SetupVkFlags; #[repr(C)] #[derive(Clone, Copy, Eq, PartialEq, Hash)] pub struct VkPip...
pub mod allocationcallback; pub mod applicationinfo; pub mod attachmentdescription; pub mod attachmentreference; pub mod bindsparseinfo; pub mod buffercopy; pub mod buffercreateinfo; pub mod bufferdeviceaddresscreateinfoext; pub mod bufferimagecopy; pub mod buffermemorybarrier; pub mod bufferviewcreateinfo; pub mod cle...
use mixer::*; use std::num::Wrapping; const PBITS: u32 = 8; // Bits of fixed-point precision for phase. pub struct Mixer<C> { srate: u32, samp_count: Wrapping<u32>, // sample count; used for ticking next_tick: Wrapping<u32>, // will tick again when sample count reaches this chan: Vec<Chann...
use rocket::Route; use super::db::Pool; use juniper::RootNode; use rocket::response::content; use rocket::State; use super::schema::{Database, MutationRoot, QueryRoot}; use super::db::DbConn; use super::db::models::User; use diesel::*; use super::auth::AuthInfo; pub type Schema = RootNode<'static, QueryRoot, Muta...
extern crate syntax; use self::syntax::ptr::{B}; use self::syntax::ast::*; use self::syntax::parse::parser::{Parser}; use self::syntax::visit::*; use self::syntax::visitor_impl::{TypeChecker}; //#[test] //fn test_parse_and_typecheck_var_decl(){ // let mut p = Parser::new("let var a : int := 1 in end".to_string());...
use anyhow::Result; use clap::Parser; use qapi::qmp; use super::{GlobalArgs, QmpStream}; #[derive(Parser, Debug)] pub(crate) struct StopCommand { } impl StopCommand { pub async fn run(self, qmp: QmpStream, _args: GlobalArgs) -> Result<i32> { qmp.execute(qmp::stop { }).await?; Ok(0) } } #[derive(Parser, Debug)]...
extern crate clap; extern crate env_logger; extern crate piccolo; extern crate rustyline; use clap::{App, Arg}; use piccolo::prelude::*; use rustyline::error::ReadlineError; use rustyline::Editor; use std::path::{Path, PathBuf}; fn main() { #[cfg(feature = "pc-debug")] env_logger::init(); let matches ...
#[macro_use] extern crate criterion; extern crate rs_poker; use criterion::Criterion; use rs_poker::core::Hand; use rs_poker::holdem::MonteCarloGame; fn simulate_one_game(c: &mut Criterion) { let hands = ["AdAh", "2c2s"] .iter() .map(|s| Hand::new_from_str(s).expect("Should be able to create a han...
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #![feature(async_await, await_macro, futures_api)] #![deny(warnings)] use failure::{Error, ResultExt}; use fidl::endpoints::ServiceMarker; use fidl_fuchsi...