text
stringlengths
8
4.13M
use crate::distribution::Discrete; use crate::function::factorial; use crate::statistics::*; use crate::{Result, StatsError}; use ::nalgebra::{DMatrix, DVector}; use rand::Rng; /// Implements the /// [Multinomial](https://en.wikipedia.org/wiki/Multinomial_distribution) /// distribution which is a generalization of the...
use std::boxed::Box; use diesel::prelude::*; use diesel::pg::PgConnection; use rocket::request::{self, FromRequest, Request}; use rocket::response::{Failure, status}; use rocket::http::Status; use rocket::Outcome; use dbtools::s3; use fields::Authentication; use models::traits::passwordable::Passwordable; use DbConn;...
// variables5.rs // Make me compile! Execute the command `rustlings hint variables5` if you want a hint :) fn main() { let number = "holy molly this is crazy"; // don't change this line println!("Number {}", number); let number = number.len(); println!("Number {}", number); }
// RGB Rust Library // Written in 2019 by // Dr. Maxim Orlovsky <dr.orlovsky@gmail.com> // basing on ideas from the original RGB rust library by // Alekos Filini <alekos.filini@gmail.com> // // To the extent possible under law, the author(s) have dedicated all // copyright and related and neighboring rights to ...
//! Predicate existential types. //! //! Provides newtypes `Pet` and `PetRef` //! for providing predicate accepted //! values and references respectively. #![warn(missing_docs)] #![cfg_attr(not(feature = "std"), no_std)] extern crate no_std_compat as std; #[macro_use] macro_rules! std_prelude { () => { #[...
//! The `NAME LIST (NLST)` command // // This command causes a directory listing to be sent from // server to user site. The pathname should specify a // directory or other system-specific file group descriptor; a // null argument implies the current directory. The server // will return a stream of names of files and...
///! Handle the color theme use crate::options::SkimOptions; use tuikit::prelude::*; #[rustfmt::skip] lazy_static! { pub static ref DEFAULT_THEME: ColorTheme = ColorTheme::dark256(); } /// The color scheme of skim's UI /// /// <pre> /// +----------------+ /// | >selected line | --> selected & normal(fg/bg) & ma...
//! Provides functionality of adding inherent extrinsics to the Domain. //! Unlike Primary chain where inherent data is first derived the block author //! and the data is verified by the on primary runtime, domains inherents //! short circuit the derivation and verification of inherent data //! as the inherent data is ...
use crate::{DomainId, SealedBundleHeader}; use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; use sp_consensus_slots::Slot; use sp_core::H256; use sp_runtime::traits::{BlakeTwo256, Hash as HashT, Header as HeaderT}; use sp_std::vec::Vec; use sp_trie::StorageProof; use subspace_core_primitives::BlockNum...
#![doc = "generated by AutoRust 0.1.0"] #![allow(unused_mut)] #![allow(unused_variables)] #![allow(unused_imports)] use super::{models, API_VERSION}; #[non_exhaustive] #[derive(Debug, thiserror :: Error)] #[allow(non_camel_case_types)] pub enum Error { #[error(transparent)] Registries_ImportImage(#[from] regist...
use std::io::{self, Read, Write}; // mod rsa; mod ed25519; // pub use self::rsa::RSA; pub use self::ed25519::ED25519; pub trait KeyPair: Sync + Send { fn system(&self) -> &'static CryptoSystem; fn has_private(&self) -> bool; fn verify(&self, data: &[u8], signature: &[u8]) -> Result<bool, ()>; fn s...
extern crate postgres; extern crate serde; extern crate serde_json; extern crate curl; extern crate rand; extern crate chrono; extern crate num; extern crate toml; extern crate clap; #[macro_use] extern crate serde_derive; #[macro_use] extern crate prettytable; use std::fs::File; use std::io::prelude::*; use std::{io,...
use super::{Ipv4Addr, Ipv4Net, OsRng}; use rand::seq::SliceRandom; pub fn enum_port_range(val: &str, randomize: bool) -> Result<Vec<u16>, String> { let ports: Vec<&str> = val.split('-').collect(); if ports.len() == 2 { let low_port: u16 = match ports[0].parse() { Ok(p) => p, Er...
#[cfg(test)] use crate::model::Group; use crate::solutions::i; use crate::tests::samples; #[test] fn should_return_none_if_groups_is_empty() { let groups = Vec::new(); let result = i::find_largest_group(&groups); assert!(result.is_none()); } #[test] fn should_return_group_if_groups_has_only_one_element() ...
pub mod json; pub mod md; use std::io; use super::engine::CheckSuiteResult; use self::json::JsonReport; use self::md::MarkdownReport; pub enum ReportType { Json, Markdown, } pub struct Reporter<'a> { check_suite_result: &'a CheckSuiteResult<'a>, report_type: ReportType, filename: Option<&'a str>...
use nom::IResult; use std::time::SystemTime; use crypto::SessionKey; use data::{Certificate, Hash, I2PDate, LeaseSet, RouterInfo, SessionTag, TunnelId}; pub mod frame; // // Common structures // pub struct BuildRequestRecord { to_peer: Hash, receive_tid: TunnelId, our_ident: Hash, next_tid: TunnelId...
use crate::matrix::{Matrix, MatrixOps}; #[derive(Debug)] pub struct Layer { input_size: usize, output_size: usize, pub(crate) weights_matrix: Matrix, } impl Layer { pub fn new(data: Matrix) -> Layer { Layer { input_size: data.rows, output_size: data.cols, we...
#![allow(missing_docs)] use currency::assets::{Fee, Fees}; use decimal::UFract64; pub struct Builder { trade: Option<Fee>, exchange: Option<Fee>, transfer: Option<Fee>, } impl Builder { pub fn new() -> Self { Builder { trade: None, exchange: None, transfer:...
use std::collections::HashMap; use std::fs; use std::io; #[derive(Eq, PartialEq, Hash, Clone, Copy, Debug)] struct Point { x: isize, y: isize, } impl std::ops::Sub for Point { type Output = Point; fn sub(self, other: Point) -> Point { Point {x: self.x - other.x, y: self.y - other.y} } } impl...
use log::{SetLoggerError, LevelFilter, Record, Level, Metadata, Log, set_logger, set_max_level, max_level}; use std::env; static LOGGER: SimpleLogger = SimpleLogger; pub struct SimpleLogger; impl Log for SimpleLogger { fn enabled(&self, metadata: &Metadata) -> bool { metadata.level() <= max_level() }...
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::SUBMODCTRL { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'...
use crate::color::{color, Color}; use crate::hittable::HitRecord; use crate::material::{Material, MaterialType}; use crate::ray::Ray; use crate::texture::{Texture, TextureColor}; use crate::vec::Vec3; use std::sync::Arc; // Diffuse #[derive(Debug, Clone)] pub struct Diffuse { pub emit: Texture, } impl Diffuse { ...
use std::env; use std::fs; use std::process; fn main() { let args: Vec<String> = env::args().collect(); if args.len() < 2 { eprintln!("{:?}: no arguments", &args[0]); process::exit(1); } for i in 1..args.len() { if let Err(why) = fs::remove_file(&args[i]) { eprintl...
use crate::{ order::{output::OutputStream, parameters::ParameterValue}, tools, }; use ffmpeg_sys_next::*; #[derive(Debug)] pub struct SubtitleEncoder { pub identifier: String, pub stream_index: isize, pub codec_context: *mut AVCodecContext, } impl SubtitleEncoder { pub fn new( identifier: String, ...
// Copyright 2021 The Matrix.org Foundation C.I.C. // // 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...
extern crate serial; mod msg_gen; use cm_com::serial::prelude::*; use std::io::prelude::*; use self::msg_gen::OpCodes; use std::{thread, time}; pub fn connect(port: String) -> Result<(), serial::Error> { //Try to open connection to serial port let sp = serial::open(&port); let mut sp = match sp { Ok(serial...
mod actions; mod checker; mod keys; mod operator; mod splitter; pub use self::keys::Primitive; pub(crate) use self::{ actions::{Action, AssignmentActions, AssignmentError}, checker::{is_array, value_check}, keys::{Key, KeyBuf, KeyIterator, TypeError}, operator::Operator, splitter::split_assignment, }; use typ...
//! Solutions to the Cryptopals crypto challenges. //! //! https://cryptopals.com/ extern crate ansi_term; extern crate rand; pub mod attacks; pub mod challenges; pub mod utils; pub mod victims; fn main() { // Run the challenges in Set 1. println!("{}", challenges::set1::challenge01()); println!("{}", c...
#![feature(lang_items, asm)] #![no_std] #[macro_use] extern crate lazy_static; pub mod vga;
use std::io::BufRead; use std::io::BufReader; use std::io::BufWriter; use std::io::Write; use std::net::TcpStream; use output; use output::Output; use ::zbackup::repository::*; use ::misc::*; pub fn handle_client ( repository: & Repository, stream: TcpStream, ) { let peer_address = stream.peer_addr ().unwrap (...
use crate::{qjs, Actual, Artifact, ArtifactStore, Input, Output, Ref, Result}; use relative_path::{RelativePath, RelativePathBuf}; pub struct Internal { artifacts: ArtifactStore, path: RelativePathBuf, } #[derive(Clone)] #[repr(transparent)] pub struct Directory(Ref<Internal>); impl AsRef<ArtifactStore> for ...
//! Node Implemation //! use std::{ fmt::Display, rc::Rc, }; use crate::hash::*; #[derive(Clone, Debug)] pub enum Node<T: ToString + Display> { Mid { left: Box<Node<T>>, right: Box<Node<T>>, hash: String, }, Leaf { data: Rc<T>, hash: String, }, Emp...
use core::marker::PhantomPinned; use std::mem; use std::pin::Pin; fn main() { let mut heap_value = Box::pin(SelfReferential { self_ptr: 0 as *const _, _pin: PhantomPinned, }); let ptr = &*heap_value as *const SelfReferential; // safe because modifying a field doesn't move the whole str...
use std::collections::HashMap; use std::fmt; const COMPLETED_SEGMENT_SIZE: i32 = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9; const WIDTH: usize = 9; const HEIGHT: usize = 9; const SQUARE_SIZE: usize = 3; fn segment_valid(segment: &Vec<i32>) -> bool { let segment_copy = segment.clone(); let segment_no_zeroes = segment_...
use std::env; use serenity::prelude::*; use toaster_core::{ toaster_framework::ToasterFramework, dynamic_loading::{ PluginManager, }, handler, share_map_hack::{ ToasterHack, } }; fn main() { println!("Hello, world!"); let mut client = Client::new(...
use ethers::{ providers::Middleware, types::{Address, BlockId, Bytes, H256, U256}, }; use tokio::runtime::Runtime; #[derive(Debug)] /// Blocking wrapper around an Ethers middleware, for use in synchronous contexts /// (powered by a tokio runtime) pub struct BlockingProvider<M> { provider: M, runtime: R...
use serde::{Deserialize, Serialize}; use strum_macros::Display; use utility_types::{omit, partial, pick}; #[derive(Debug, Serialize, Deserialize, Display, Clone)] #[serde(tag = "type")] // to flatten the enum to the parent struct pub enum AccountType { Admin { first_name: String, last_name: String, }, In...
#[macro_use] extern crate lazy_static; extern crate regex; use pyo3::prelude::*; use pyo3::wrap_pyfunction; use regex::Regex; lazy_static! { static ref DOLLAR_SEARCH: Regex = Regex::new(r"DOLLAR|USD|\$").unwrap(); } /// Finds the multiplier within a couple of lines that dollar is mentioned #[pyfunction] pub fn fi...
pub fn process_part1(input: &str) -> String { let cols = input.lines().last().unwrap().chars().map(|_| 1).sum::<usize>(); let lines = input.lines().map(|_| 1).sum::<usize>(); let input_rows = input .lines() .map(|row| row.chars().map(|num| num.to_digit(10).unwrap() as usize) .colle...
mod dynamics; mod properties; pub use self::{dynamics::Dynamics, properties::PhysicalProperties};
use criterion::{criterion_group, criterion_main, Criterion}; use scc::HashIndex; fn read(c: &mut Criterion) { let hashindex: HashIndex<usize, usize> = HashIndex::default(); assert!(hashindex.insert(1, 1).is_ok()); c.bench_function("HashIndex: read", |b| { b.iter(|| { hashindex.read(&1,...
pub mod app_config; pub mod log;
#[doc = "Register `OTG_DOEPMSK` reader"] pub type R = crate::R<OTG_DOEPMSK_SPEC>; #[doc = "Register `OTG_DOEPMSK` writer"] pub type W = crate::W<OTG_DOEPMSK_SPEC>; #[doc = "Field `XFRCM` reader - XFRCM"] pub type XFRCM_R = crate::BitReader; #[doc = "Field `XFRCM` writer - XFRCM"] pub type XFRCM_W<'a, REG, const O: u8> ...
// This file is part of dpdk. 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/dpdk/master/COPYRIGHT. No part of dpdk, including this file, may be copied, modified, propagated, or distributed except accordin...
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
use std::ops::{Add, Sub, Mul, Div, Index}; use std::cmp::{PartialEq}; #[derive(Copy, Clone)] struct Vector3 { x: f32, y: f32, z: f32, } impl Vector3 { // // Constructor // fn new(x: f32, y: f32, z: f32) -> Vector3 { Vector3 { x: x, y: y, z: z } } // // Basic Forms // fn ba...
#![allow(clippy::reversed_empty_ranges)] use crate::pattern::Pattern; use crate::{Offsets, Result}; use std::ops::{Bound, RangeBounds}; use unicode_normalization_alignments::UnicodeNormalization; /// The possible offsets referential pub enum OffsetReferential { Original, Normalized, } /// Represents a Range ...
use byteorder::*; use crate::midi::MidiHandler; use std::error::Error; use std::fs::*; use std::io::{Cursor, Write}; use std::path::*; use serde_derive::{Serialize, Deserialize}; use serde_json; mod command; pub mod instruments; mod seqtree; mod track; use self::command::*; use self::seqtree::*; use self::track::*; ...
use std::cmp::Ordering; use std::collections::BinaryHeap; use std::collections::HashMap; use colored::*; /// Solves the Day 23 Part 1 puzzle with respect to the given input. pub fn part_1(input: String) { let mut lines = input.lines().skip(2); let top = lines.next().unwrap(); let bot = lines.next().unwrap...
use std::collections::{HashMap, HashSet}; use std::hash::{Hash, Hasher}; #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] pub struct Point(pub usize, pub usize); impl Point { fn line(&self, other: &Point) -> Line { let m = (other.1 as f64 - self.1 as f64) / (other.0 as f64 - self.0 as f...
extern crate smpl; extern crate find_folder; extern crate toml; #[macro_use] extern crate serde_derive; #[macro_use] extern crate irmatch; #[macro_use] extern crate failure; mod input; mod script_lib; mod library; mod game; mod assets; mod display; mod game_screen; mod title_screen; use failure::Error; fn main() { ...
pub mod channel; pub mod gateway; pub mod guild; pub mod user; pub mod voice; use std::hash::Hash; /// Efficient cachable entities mapping to the models returned from Discord's /// API. /// /// For example, the [`EmojiEntity`] does not contain the user data within it, /// but contains only the ID of the user. This ca...
use pnet::packet::Packet; use pnet::packet::ethernet::{EtherTypes, EthernetPacket}; use pnet::packet::ethernet::EtherType; pub fn handler(interface_name: &str, ethernet: &EthernetPacket) -> EtherType { let ether_type: EtherType = match ethernet.get_ethertype() { //EtherTypes::Ipv4 => handle_ipv4_packet(in...
//! //! This crate can be used for tests that accompany hacspecs. //! pub mod prelude; pub mod rand; pub mod test_vectors; /// Convert a hex string to a byte vector. pub fn hex_to_bytes(hex: &str) -> Vec<u8> { assert!(hex.len() % 2 == 0); let mut bytes = Vec::new(); for i in 0..(hex.len() / 2) { b...
/* * 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. */ // reinject stat* as fstatat unittest use reverie::Tool; #[derive(Debug, Default, Clone)] struct ...
#[doc = "Reader of register TEMP_SR"] pub type R = crate::R<u32, super::TEMP_SR>; #[doc = "Reader of field `TS1_ITEF`"] pub type TS1_ITEF_R = crate::R<bool, bool>; #[doc = "Reader of field `TS1_ITLF`"] pub type TS1_ITLF_R = crate::R<bool, bool>; #[doc = "Reader of field `TS1_ITHF`"] pub type TS1_ITHF_R = crate::R<bool,...
use anyhow::{anyhow, Result}; use chrono::{DateTime, Local}; use itertools::{Itertools, MinMaxResult}; use log::debug; use sun::Position; use crate::{ geo::{Coords, Hemisphere}, wallpaper::properties::SolarItem, }; /// Get the index of the image which should be displayed for given datetime and location. pub f...
use crate::io::{Load, Save}; use crate::layers::loss_layer::*; use crate::layers::time_layers::*; use crate::layers::Dropout; use crate::math::Norm; use crate::optimizer::*; use crate::params::*; use crate::types::*; use crate::util::{randarr2d, remove_axis}; use ndarray::{Array, Array2, Axis, Ix2, Ix3, RemoveAxis}; us...
// ************************************** // 多线程 // ************************************** use std::process; use std::thread; use std::time::Duration; fn main() { simple_spawn(); join_spawn(); } // thread::spawn创建一个子线程闭包. fn simple_spawn() { println!("pid from main thread {}", process::id()); threa...
mod compress; mod decompress; mod file_io; use std::time::Instant; fn main() { const FILE_NAME: &str = "testFile.hps"; const BLOCK_SIZE: usize = 5; { let mut to_compress: Vec<u8> = file_io::read_from_file("EnglishShortened.txt"); // let mut to_compress: Vec<u8> = String::from("H...
//! This module contains resources specific to a game. //! They should be set up/added to the world when creating a new game, or loading a savegame, //! and be removed when the player exits to the MainMenu or ends the application. mod game_session; mod savegame_path; pub mod game_world; //pub mod planet; pub use self:...
#[derive(Debug)] pub enum Transport { Udp, Tcp, Invalid, } impl From<&str> for Transport { fn from(transport: &str) -> Self { match transport { "UDP" => Self::Udp, "TCP" => Self::Tcp, _ => Self::Invalid, } } }
// 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. //! Stream-based Fuchsia VFS directory watcher #![deny(warnings)] #![deny(missing_docs)] #[macro_use] extern crate fdio; extern crate fuchsia_async as as...
//! Streaming SIMD Extensions 2 (SSE2) pub use arch::_mm_stream_si64; use mem::transmute; use simd::*; /// Convert the lower double-precision (64-bit) floating-point element in a to /// a 64-bit integer. #[inline] #[target_feature(enable = "sse2")] pub unsafe fn _mm_cvtsd_si64(a: f64x2) -> i64 { ::arch::_mm_cvtsd...
pub fn gcd(a:u64, b:u64) -> u64 { if b < a { return gcd(b, a); } let remainder = b % a; if remainder == 0 { return a; } return gcd(remainder, a); } pub fn lcm(a:u64, b:u64) -> u64 { return (a * b) / gcd(a, b); }
use std::{fs, io}; fn check_passport(passport: &str) -> bool { let passport = passport .split(|c| c == ' ' || c == '\n') .map(|s| s.split(':').next().unwrap()) .collect::<Vec<_>>(); for required in &["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"] { if !passport.contains(&requi...
mod common; use std::sync::mpsc::Receiver; use std::sync::mpsc::Sender; #[derive(PartialEq, Eq, Copy, Clone)] enum Op { Add, Mul, } #[derive(PartialEq, Eq, Copy, Clone)] enum Cnd { True, False, } #[derive(PartialEq, Eq, Copy, Clone)] enum Cmp { LessThan, Equal, } #[derive(PartialEq, Eq, Copy, C...
fn order(sentence: &str) -> String { let mut str_vec: Vec<&str> = sentence.split_whitespace().collect(); str_vec.sort_by_key(|s| s.trim_matches(char::is_alphabetic)); str_vec.join(" ") } #[test] fn returns_expected() { assert_eq!(order("is2 Thi1s T4est 3a"), "Thi1s is2 3a T4est"); assert_eq!(order("is200 T...
pub fn create_generator<'a>( pos: ::na::Vector3<f32>, generated_entity: ::component::GeneratedEntity, salvo: usize, time_between_salvo: f32, eraser_probability: f32, generators: &mut ::specs::WriteStorage<'a, ::component::Generator>, entities: &::specs::Entities, ) { let entity = entitie...
use actix_web::{guard, web, App, HttpResponse, HttpServer}; use async_graphql::http::{playground_source, GraphQLPlaygroundConfig, MultipartOptions}; use async_graphql::{EmptySubscription, Schema}; use async_graphql_actix_web::{Request, Response}; use files::{FilesSchema, MutationRoot, QueryRoot, Storage}; async fn ind...
use std::fmt; use std::error::{self, Error}; /////////////////////////////////////////// // Aux Macro for creating the error type /////////////////////////////////////////// macro_rules! new_error_type { ($Error: ident) => ( new_error_type!($Error, stringify!($Error)); ); ($Error: ident, $Descrip...
use std::fmt::Debug; use crate::Fingerprint; /// An alias for [`Result`](std::result::Result)'s with [`StorageError`]. pub type Result<T> = std::result::Result<T, StorageError>; /// A sum type for all error conditions that can arise in this crate. #[derive(Debug, thiserror::Error)] pub enum StorageError { /// Th...
//! `Context` is a top level module contains static context and dynamic context for each request use std::sync::Arc; use diesel::connection::AnsiTransactionManager; use diesel::pg::Pg; use diesel::Connection; use futures_cpupool::CpuPool; use r2d2::{ManageConnection, Pool}; use stq_http::client::ClientHandle; use stq...
mod covid19; mod config; use actix_web::{HttpServer, App, get, Responder, HttpResponse}; #[get("/health-check")] async fn health_check() -> impl Responder { HttpResponse::Ok() } #[actix_web::main] async fn main() -> std::io::Result<()> { HttpServer::new(|| { App::new() .service(health_ch...
use core::*; pub trait Frame { fn frame<F: Framer>(self, framer: F) -> Stream<Bytes>; fn frame_one<F: Framer>(self, framer: F) -> Stream<Bytes>; } impl Frame for Stream<Bytes> { fn frame<F: Framer>(self, framer: F) -> Stream<Bytes> { let (tx, rx) = Stream::pair(); tx.receive(move |res| {...
#[doc = "Register `SMPR2` reader"] pub type R = crate::R<SMPR2_SPEC>; #[doc = "Register `SMPR2` writer"] pub type W = crate::W<SMPR2_SPEC>; #[doc = "Field `SMP0` reader - Channel 0 sampling time selection"] pub type SMP0_R = crate::FieldReader<SMP0_A>; #[doc = "Channel 0 sampling time selection\n\nValue on reset: 0"] #...
// RGB Rust Library // Written in 2019 by // Dr. Maxim Orlovsky <dr.orlovsky@gmail.com> // basing on ideas from the original RGB rust library by // Alekos Filini <alekos.filini@gmail.com> // // To the extent possible under law, the author(s) have dedicated all // copyright and related and neighboring rights to ...
use super::helpers::{allocations, fixtures::get_language}; use tree_sitter::Parser; #[test] fn test_pathological_example_1() { let language = "cpp"; let source = r#"*ss<s"ss<sqXqss<s._<s<sq<(qqX<sqss<s.ss<sqsssq<(qss<qssqXqss<s._<s<sq<(qqX<sqss<s.ss<sqsssq<(qss<sqss<sqss<s._<s<sq>(qqX<sqss<s.ss<sqsssq<(qss<sq&...
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Control Register 1"] pub cr1: CR1, #[doc = "0x04 - Control Register 2"] pub cr2: CR2, #[doc = "0x08 - Interrupt Status Register"] pub isr: ISR, #[doc = "0x0c - Interrupt Clear Register"] pub icr: ICR, #[...
/* borrow */ /* use reference(&Vec<i32>) as arguments */ /*&T ← reference type is a type which borrows ownership; 1 or more references to resource*/ /* &mut T ← mutable reference; only one mutable reference */ fn foo(v1: &mut Vec<i32>,v2: &mut Vec<i32>) -> Option<i32> { let v1_max: Option<i32> = v1.pop(); let v2_m...
use crate::blob::blob::requests::*; use crate::blob::prelude::*; use crate::core::prelude::*; use azure_core::prelude::*; use azure_core::HttpClient; use bytes::Bytes; use http::method::Method; use http::request::{Builder, Request}; use std::sync::Arc; pub trait AsBlobLeaseClient { fn as_blob_lease_client(&self, l...
extern crate wingui; use ::window::WindowBuilder; use super::Backend as AbsBackend; mod window; pub struct Backend; impl AbsBackend for Backend { type Window = window::Window; fn start(builder: WindowBuilder) { } }
#[doc = "Register `DAC_DHR8R2` reader"] pub type R = crate::R<DAC_DHR8R2_SPEC>; #[doc = "Register `DAC_DHR8R2` writer"] pub type W = crate::W<DAC_DHR8R2_SPEC>; #[doc = "Field `DACC2DHR` reader - DACC2DHR"] pub type DACC2DHR_R = crate::FieldReader; #[doc = "Field `DACC2DHR` writer - DACC2DHR"] pub type DACC2DHR_W<'a, RE...
extern crate winit; /// an integer 2d position #[allow(missing_docs)] #[derive(PartialEq, Clone, Copy, Debug)] pub struct Position { pub x: i64, pub y: i64, } /// an integer 2d delta pub type Delta = Position; /// an integer 2d size #[allow(missing_docs)] #[derive(PartialEq, Clone, Copy)] pub struct Size { ...
use std::{collections::HashMap, io::ErrorKind, net::SocketAddr, rc::Rc, time::Instant}; use bytes::BytesMut; use mio::{event::Event, net::UdpSocket, Poll, Token}; use rustls::ClientSession; use crate::{ config::Opts, proto::{ TrojanRequest, UdpAssociate, UdpParseResult, MAX_BUFFER_SIZE, MAX_PACKET_SIZ...
use ggez::{ GameResult, Context, graphics::Color, nalgebra::Point2, input::mouse::MouseButton }; use crate::utils::loading_screen; use crate::text::Text; use crate::button::Button; use std::collections::HashMap; use serde::Deserialize; use urlencoding::encode; use std:: { fs, env }; #[derive(Deserializ...
use std::fmt; use std::iter::Fuse; use std::ops::RangeInclusive; use std::vec; use serde_derive::Serialize; use super::ihex16::{IHex16File, IHex16Word}; #[derive(Copy, Clone, Serialize)] #[serde(tag = "type")] pub enum IHex16Diff { #[serde(rename(serialize = "single"))] Single { address: u32, ...
extern crate clap; extern crate fuse; extern crate secstr; extern crate colorhash256; extern crate interactor; extern crate rusterpassword; extern crate ansi_term; extern crate rustc_serialize; extern crate cbor; extern crate freepass_core; mod util; mod openfile; mod interact; mod mergein; use std::{env, fs}; use cl...
use aoc_runner_derive::{aoc, aoc_generator}; use std::num::ParseIntError; #[aoc_generator(day10)] fn parse_input_day10(input: &str) -> Result<Vec<usize>, ParseIntError> { let mut adapters = input .lines() .map(|n| n.parse().unwrap_or(0)) .collect::<Vec<_>>(); adapters.sort_unstable(); ...
use fs::Resource; use alloc::boxed::Box; use system::error::Result; pub fn resource() -> Result<Box<Resource>> { Ok(Box::new(SyslogResource { pos: 0 })) } /// The kernel log resource. pub struct SyslogResource { pos: usize } impl Resource for SyslogResource { fn dup(&self) -> Result<Box<Resou...
fn gcd(mut n: u64, mut m: u64) -> u64 { assert!(n != 0 && m != 0); while m != 0 { if m < n { let t = m; m = n; n = t; } m = m % n; } n } fn main() { let n = gcd(12, 16); println!("greatest common divisor of 12 and 16 is {}", n); }
use support::{decl_storage, decl_module, StorageValue, dispatch::Result, StorageMap}; use system::ensure_signed; use parity_codec::{Encode, Decode}; use runtime_primitives::traits::{As, Hash}; pub trait Trait: balances::Trait {} #[derive(Encode, Decode, Default, Clone, PartialEq)] #[cfg_attr(feature = "std", derive(...
extern crate log; extern crate png; extern crate vk_sys as vk; extern crate vulkano; pub mod debug; pub mod engine; pub mod figure; pub mod frame; pub mod scene;
use bytes::Bytes; use crate::error::Result; use crate::node::NodeCollection; use crate::node_types::StandardType; use crate::reader::Reader; pub struct Printer; impl Printer { pub fn run(input: impl Into<Bytes>) -> Result<()> { let mut reader = Reader::new(input.into())?; let mut nodes = Vec::new...
pub fn process(input: String) -> String { return input.chars().rev().collect::<String>(); }
use std::ptr; pub struct FrameBuffer { frame_buffer: u32, render_buffer: u32, texture_color_buffer: u32, } impl FrameBuffer { pub fn new(width: u32, height: u32) -> FrameBuffer { let mut frame_buffer: u32 = 0; let mut render_buffer: u32 = 0; let mut texture_color_bu...
fn main() { let n = read::<i32>(); let str = match n % 10 { 2 | 4 | 5 | 7 | 9 => "hon", 0 | 1 | 6 | 8 => "pon", 3 => "bon", _ => panic!("unreachable") }; println!("{}", str); } fn read<T: std::str::FromStr>() -> T { let mut s = String::new(); std::io::stdin...
pub struct GuiSettings { pub(crate) show_fps: bool, pub(crate) show_graph_stats: bool, } impl std::default::Default for GuiSettings { fn default() -> Self { Self { show_fps: false, show_graph_stats: false, } } } impl GuiSettings { pub fn ui(&mut self, ui: &m...
use std::hash::Hash; use serde::{Deserialize, Serialize}; use crate::evaluation::Evaluation; #[derive(Serialize, Deserialize, Debug)] pub struct Blunder { pub position: String, pub move_: String, pub eval_before: Evaluation, pub eval_after: Evaluation, } impl PartialEq for Blunder { fn eq(&self,...
use std::fs; use test_case::test_case; use fnv::FnvHashMap; use std::collections::{HashMap, HashSet}; use tf_demo_parser::demo::packet::datatable::{ParseSendTable, SendTableName, ServerClass}; use tf_demo_parser::demo::parser::MessageHandler; use tf_demo_parser::demo::sendprop::{SendPropIdentifier, SendPropName}; use ...