text
stringlengths
8
4.13M
extern crate rary; fn main() { rary::public_funcion(); rary::indirect_access(); }
mod simple_db { use std::any::{Any, TypeId}; use std::collections::HashMap; use std::fs; use std::fs::{File, OpenOptions}; use std::io::{Read, Seek, SeekFrom}; use std::path::{Path, PathBuf}; use uuid::Uuid; pub enum Errors { NotFound, } struct Table { // GUID -...
use std::io::{Read, Write}; use std::net::{TcpStream, TcpListener}; const LOCAL: &str = "127.0.0.1:6000"; const MSG_SIZE: usize = 16; fn read_message(mut stream: &TcpStream) -> Result<String, &'static str> { let mut buff = vec![0; MSG_SIZE]; match stream.read(&mut buff) { Ok(_) => { l...
use pelite; use pelite::pe64::*; use pelite::pattern as pat; pub fn print(bin: PeFile<'_>, dll_name: &str) { println!("## Miscellaneous\n\n```"); header(bin); game_version(bin); entity_list(bin, dll_name); local_entity_handle(bin, dll_name); global_vars(bin, dll_name); player_resource(bin, dll_name); view_rend...
#![allow(non_snake_case)] fn main() { println!("Salut Rust"); }
// Copyright 2023 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 ...
use cid::Cid; use crate::pb::{FlatUnixFs, PBLink, UnixFs, UnixFsType}; use alloc::borrow::Cow; use core::fmt; use quick_protobuf::{MessageWrite, Writer}; use sha2::{Digest, Sha256}; /// File tree builder. Implements [`core::default::Default`] which tracks the recent defaults. /// /// Custom file tree builder can be ...
use std::{fmt::Display, ops::Deref}; use super::private::Sealed; /// A type-level group of booleans. pub trait Boolean: Sealed {} /// Witnesses a type that is `true`. pub trait Truth: Boolean {} /// Witnesses a type that is `false`. pub trait Falsity: Boolean {} /// Type-level boolean corresponding to `true`. #[de...
#[derive(Debug,Clone,Copy,PartialEq,Eq,Hash)] pub struct Abilities { pub _str: isize, pub _dex: isize, pub _con: isize, pub _int: isize, pub _wis: isize, pub _cha: isize, } #[derive(Debug,Clone,Copy,PartialEq,Eq,Hash)] pub struct AbilityScores(Abilities); #[derive(Debug,Clone,Copy,PartialEq,Eq,...
extern crate crossbeam; use crossbeam::{atomic::AtomicCell, thread}; use std::f64::consts::PI; use std::thread as sthread; use std::time::{Duration, SystemTime}; const TARGET: u32 = 10; const GUESS: u32 = 2500000; fn computer( xr: &AtomicCell<f64>, dr: &AtomicCell<f64>, ticks: &AtomicCell<u32>, tocks...
use binrw::{BinRead, BinWrite, BinReaderExt, BinWriterExt, BinResult, io::Cursor}; pub trait BytesDecodeExt: BinRead where <Self as BinRead>::Args: Default, { fn decode<T: AsRef<[u8]>>(bytes: T) -> BinResult<Self> { let mut reader = Cursor::new(bytes); reader.read_be() } } pub trait BytesE...
mod p1; mod p2; mod p3; fn main() { println!("{}", p1::p1(1_000)); println!("{}", p2::p2(4_000_000)); println!("{}", p3::p3(600_851_475_143)); }
use super::*; use std::io::{BufRead, BufReader}; use std::path::PathBuf; // Notes: // * Particle & constraint vectors are kept private to prevent mismatch between // zero-based and one-based indexing. // * These private vectors are zero-based (no dummy element at zero index). // * Everything here that is called 'num...
//#![allow(warnings, unused_variables, dead_code, improper_ctypes, non_camel_case_types, non_snake_case, non_upper_case_globals)] use core::alloc::{GlobalAlloc, Layout}; use core::fmt; use core::ptr; //use crate::mutex::Mutex; use ::os::kernel_malloc; pub struct FreebsdAllocator; /// `LocalAlloc` is an analogous ...
pub mod scan_sheet_elements; pub mod scan_sheet_layout; use crate::make::scan_sheet_layout::{HighLevelPageDescription, HighLevelField, HighLevelKind}; pub fn dummy() -> HighLevelPageDescription { let page_description = HighLevelPageDescription { document_title: String::from("test1"), fields: vec!...
fn main() { let contents = std::fs::read_to_string("./res/input.txt").expect("Could not read file!"); let lines: Vec<&str> = contents.lines().collect(); let mut x_axis: usize = 0; let mut y_axis: usize = 0; let line_length = lines[0].len(); let mut count = 0; loop { x_axis += 3; ...
//! UDP echo server. //! //! To send messages do: //! ```sh //! $ nc -u localhost 8080 //! ``` use runtime::net::UdpSocket; #[runtime::main] async fn main() -> std::io::Result<()> { let mut socket = UdpSocket::bind("127.0.0.1:8080")?; let mut buf = vec![0u8; 1024]; println!("Listening on {}", socket.loca...
use file_reader; const INPUT_FILENAME: &str = "input.txt"; const ROW_MAX: u32 = 127; const COL_MAX: u32 = 7; const NUM_ROW_CHARS: usize = 7; fn main() { let input_str = match file_reader::file_to_vec(INPUT_FILENAME) { Err(_) => { println!("Couldn't turn file into vec!"); return; ...
/* 给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。 例如: 给定二叉树 [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 返回锯齿形层次遍历如下: [ [3], [20,9], [15,7] ] 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ us...
// Copyright 2020 Jesper de Jong // // 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 ...
// Copyright 2016 functils Developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://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 according t...
test_stdout!( with_positive_start_and_positive_length_returns_subbinary, "<<1>>\n" ); test_stdout!( with_size_start_and_negative_size_length_returns_binary, "<<0,1,2>>\n" ); test_stdout!( with_zero_start_and_size_length_returns_binary, "<<0,1,2>>\n" );
use graph::Graph; use std::hash::Hash; pub fn nodes_by_depth_from<T: Hash + Copy + Eq + Ord>(g: &Graph<T>, start: T) -> Vec<T> { fn traverse<T: Hash + Copy + Eq + Ord>(g: &Graph<T>, v: T, visited: &mut Vec<T>) -> Vec<T> { if !visited.contains(&v) { visited.push(v); } let neighbo...
use rocket::{get, response::NamedFile}; use std::io; #[get("/")] pub(in crate) fn index() -> io::Result<NamedFile> { // failure to read the file is an error, thus we want to return Result, // which in failure translates to HTTP 500. If we returned Option, failures // would result in HTTP 404, which would b...
fn main() { let asdf_fdsa = "<.<"; assert(#concat_idents[asd,f_f,dsa] == "<.<"); assert(#ident_to_str[use_mention_distinction] == "use_mention_distinction"); }
//! This module is just a fake implementation that has the advantages of compiling on every //! architecture. Hence, we can at least check that the code compiles even if we cannot verify it //! functionally. use std::{ffi::CStr, result::Result, sync::RwLock}; static DEVICE: Device = Device {}; pub struct Buffer<T: C...
use std::sync::atomic::AtomicBool; use metrics_exporter_prometheus::PrometheusHandle; use warp::Filter; /// Spawns a server which hosts a `/health` endpoint. pub async fn spawn_server( addr: impl Into<std::net::SocketAddr> + 'static, readiness: std::sync::Arc<AtomicBool>, prometheus_handle: PrometheusHand...
use diesel; use diesel::prelude::*; use diesel::sqlite::SqliteConnection; use iron::typemap::Key; use ruma_identifiers::{RoomId, UserId}; use slog::Logger; use api::{MatrixApi, RocketchatApi}; use config::Config; use errors::*; use handlers::matrix::CommandHandler; use models::schema::{rocketchat_servers, users_on_roc...
use super::UnicodeDots; use unicode_width::UnicodeWidthChar; /// Returns the displayed width in columns of a `text`. fn display_width(text: &str, tabstop: usize) -> usize { let mut w = 0; for ch in text.chars() { w += if ch == '\t' { tabstop - (w % tabstop) } else { ch.w...
use anyhow::{Context, Result}; use std::{env, path::PathBuf}; const PROTO_FILE: &str = "src/kubernetes/cri/proto/api.proto"; fn main() -> Result<()> { tonic_build::configure() .out_dir("src/kubernetes/cri/api") .compile( &[PROTO_FILE], &[&PathBuf::from(PROTO_FILE) ...
pub mod node { tonic::include_proto!("node"); } pub mod client;
use std::process::Command; use std::str; pub fn get_clipboard_image() -> Option<Vec<u8>> { if let Ok(out) = Command::new("xclip") .arg("-o") .arg("-selection") .arg("clipboard") .arg("-t") .arg("TARGETS") .output() { if let Ok(s) = str::from_utf8(&out.std...
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::path::{Path, PathBuf}; use std::fmt; #[derive(Debug, Clone)] pub struct QualifiedId { pub base_id: I...
// 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. /// Constructs a suggestion with common fields. /// Remember to `use crate::models::{Suggestion, DisplayInfo, Intent, AddModInfo};` #[macro_export] macro_r...
use exonum::crypto::{Hash, PublicKey, hash}; use crate::common_structs; // 160, 176, 192 and 208 const A_NUMBER: u8 = 160; const B_NUMBER: u8 = 176; const C_NUMBER: u8 = 192; const D_NUMBER: u8 = 208; pub enum IdType { Account(PublicKey), Token { owner_id: Vec<u8>, symbol: String } } fn gen_id(source: &IdTy...
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" { #[cfg(feature = "Win32_Foundation")] pub fn WSManCloseCommand(commandhandle: *mut WSMAN_COMMAND, flags: u32, r#async: *const WSMAN_SHELL_ASYNC); pub ...
///Contains all states of the UI that we will run through in game which alters the main UI #[derive(Debug, Clone)] pub enum UIState { EscapeMenu, SaveMenu, LoadMenu, OptionsMenu, ShopMenu, UpgradeMenu, InventoryMenu, DialogueMenu, NormalState, } //systems for managing the UI. no...
#![feature(plugin)] #![plugin(rocket_codegen)] #[macro_use] extern crate lazy_static; extern crate reqwest; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate serde_yaml; extern crate log; use log::*; use std::fs::File; use std::path::{Path, PathBuf}; use serde_json::Value; extern crat...
use core::cell::RefCell; use cortex_m::interrupt::{free, Mutex}; use embedded_graphics::{egtext, image::Image, pixelcolor::BinaryColor, prelude::*, text_style}; use heapless::{consts::*, HistoryBuffer, String}; use profont::{ProFont12Point, ProFont9Point}; use ssd1306::{mode::GraphicsMode, prelude::*}; use tinybmp::Bmp...
use k8s_openapi::api::core::v1::Event; use reqwest::Client; use serde::{Deserialize, Serialize}; fn format_message(event: Event) -> TeamsMessage { TeamsMessage { message_type: "MessageCard", context: "http://schema.org/extensions", theme_color: "0076D7", summary: event, } } pub...
use crate::universe::{RsUniverse, Cell}; use super::RsRenderer; use super::consts::*; pub trait RsNoGridRenderer { fn new_filled(width: usize, height: usize) -> Self; fn render(&mut self, universe: &RsUniverse); } impl RsNoGridRenderer for RsRenderer { fn new_filled(width: usize, height: usize) -> RsRen...
use std::time::{SystemTime, Duration, UNIX_EPOCH}; use segment::Metric; #[macro_use] extern crate criterion; use criterion::{Criterion, BatchSize}; #[derive(Metric)] #[segment(measurement="stringtest")] pub struct StringTest { #[segment(time)] timestamp: Duration, #[segment(tag)] tag0: String, ...
/*! Python `property` descriptor class. */ use super::{PyStrRef, PyType, PyTypeRef}; use crate::common::lock::PyRwLock; use crate::function::{IntoFuncArgs, PosArgs}; use crate::{ class::PyClassImpl, function::{FuncArgs, PySetterValue}, types::{Constructor, GetDescriptor, Initializer}, AsObject, Context...
use super::{ boolean::{False, True}, private::Sealed, }; /// Type-level Equality. pub trait Equality<L>: Sealed { /// Whether `Self` equals to `L`. type Output; } /// Syntactic sugar for Equality. pub type Eql<L, R> = <L as Equality<R>>::Output; impl Equality<False> for False { type Output = True...
use crate::system::System; #[derive(Clone, Debug)] pub struct Context<'a, T> { pub value: T, pub system: Option<&'a System>, }
use std::collections::HashMap; use std::ops::Range; #[derive(Debug, Clone)] pub struct Bucket { scale: f32, grids: HashMap<(i32, i32), usize>, min: (i32, i32), max: (i32, i32), } impl Bucket { pub fn new(scale: f32) -> Bucket { Bucket { scale, grids: HashMap::new(),...
#![feature(proc_macro_hygiene, decl_macro)] #[macro_use] extern crate rocket; #[cfg(test)] mod e2e; pub mod jobs; pub mod routes; use routes::root; fn main() { root().launch(); }
use std::ops::Deref; use board::grid::Grid; use board::stats::stone_score::StoneScore; use board::stats::stone_stats::StoneStats; use board::stones::group::GoGroup; use board::stones::grouprc::GoGroupRc; use board::stones::stone::Stone; use graph_lib::topology::Topology; use crate::board::go_state::GoState; pub trai...
//! ### PE-Specific Compilation Checks: //! //! * Binary Type //! * Compiler Runtime //! * Debug Info Stripped //! //! ### Exploit Mitigations: //! //! * Data Execution Prevention (DEP / NX) //! * Dynamic Base //! * Structured Exception Handling (SEH) //! * Code Integrity //! * Control Flow Guard use goblin::pe::chara...
pub trait GeneratorI { /* 需要:seed 1. seed (16bytes)+ seq (4bytes) seq=0 2. SHA512Half 3. 与椭圆最大数比,如果大于,seq+1,重复步骤1 4. 获得private generator 32字节 */ fn private_generator(&self, masterphrase: &Vec<u8>) -> Vec<u8>; /* 需要:private generator,椭圆常数G ...
#[doc = "Writer for register C10IFCR"] pub type W = crate::W<u32, super::C10IFCR>; #[doc = "Register C10IFCR `reset()`'s with value 0"] impl crate::ResetValue for super::C10IFCR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Write proxy for field `CTEIF10`"]...
#![cfg_attr(not(feature = "std"), no_std)] use frame_support::{decl_module, decl_storage, ensure, decl_event, decl_error, dispatch, traits::Get,}; //use frame_system::{self as system, ensure_root, ensure_signed}; use frame_system::{self as system, ensure_signed}; use primitives::{Vpp, ApprovalStatus, Parliament}; use ...
use failure::{Error, Fail}; use log::*; use rand::seq::SliceRandom; use rand::thread_rng; use regex::Regex; use std::borrow::BorrowMut; use std::ffi::OsStr; use std::io::{BufRead, BufReader}; use std::net; use std::process::{Child, Command, Stdio}; use which::which; #[cfg(windows)] use winreg::{enums::HKEY_LOCAL_MACHI...
extern crate pcre; use std::fs::File; use std::io::BufReader; use std::io::BufRead; use std::collections::HashMap; use std::collections::VecDeque; use pcre::Pcre; #[derive(Clone, Debug)] enum Operation { Nop, Not, And, Or, LShift, RShift, } #[derive(Clone, Debug)] struct Gate { inputs: Ve...
// http://devernay.free.fr/hacks/chip8/C8TECH10.HTM extern crate sdl2; extern crate rand; extern crate byteorder; use sdl2::rect::Rect; use sdl2::pixels::Color; use sdl2::event::Event; use sdl2::keyboard::Keycode; use std::time::Instant; use std::fs::File; use std::env; use rand::Rng; use byteorder::{BigEndian, Re...
#![allow(warnings)] use downcast_rs::__std::collections::HashMap; use spacegame::assets::prefab::Prefab; use spacegame::core::animation::{Animation, AnimationController}; use spacegame::core::timer::Timer; use spacegame::core::transform::Transform; use spacegame::gameplay::collision::{BoundingBox, CollisionLayer}; use...
use std; use std::convert::TryFrom; use std::io::{self, BufReader, Write}; use std::marker::PhantomData; use std::net::{Ipv4Addr, SocketAddr}; use crate::Tagged; use async_bincode::{AsyncBincodeStream, AsyncBincodeWriter, AsyncDestination}; use bincode; use bufstream::BufStream; use byteorder::{NetworkEndian, WriteByt...
use input_i_scanner::InputIScanner; macro_rules! chmin { ($a: expr, $b: expr) => { $a = std::cmp::min($a, $b); }; } fn main() { let stdin = std::io::stdin(); let mut _i_i = InputIScanner::from(stdin.lock()); macro_rules! scan { (($($t: ty),+)) => { ($(scan!($t)),+) ...
pub const INPUT: &str = include_str!("../input.txt"); pub fn solve(input: &str) -> (u32, u32) { let mut part_one_sum = 0; let mut part_two_sum = 0; let iter = input.as_bytes().chunks_exact(4); // 4 bytes per line "A X\n" for chunk in iter { let (part_one_score, part_two_score) = match (chunk[0]...
#[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 { ...
//! Macros for logging. use super::symbol; use super::context::Context; use std::ffi::CString; pub enum Level { Debug = 0, Info = 1, Warn = 2, Error = 3, } #[repr(C)] pub(crate) struct Metadata { pub level: Level, pub file: &'static str, pub line: u32, pub column: u32, } pub fn write...
#[derive(Debug,Clone)] pub struct Type { pub name: String, pub category: String, pub qualifier: Vec<String>, pub implements: Vec<String>, pub extends: Option<String>, pub annotation: Vec<String>, pub comment: Vec<String>, pub member: Vec<Member>, } #[derive(Debug,Clone)] pub struct Meth...
use super::writer::Writer; use crate::MkvId; use rand::Rng; use std::io; use std::io::{Error, ErrorKind}; pub const EBML_UNKNOWN_VALUE: u64 = 0x01FFFFFFFFFFFFFF; pub const MAX_BLOCK_TIMECODE: i64 = 0x07FFF; // Date elements are always 8 octets in size. const DATE_ELEMENT_SIZE: i32 = 8; const DOC_TYPE_WEBM: &'static ...
use std::{collections::HashMap, marker::PhantomData}; use super::{ and::And, not::Not, or::Or, passthrough::Passthrough, ActiveFilter, DynamicFilter, FilterResult, }; use crate::internals::{query::view::Fetch, storage::component::Component, world::WorldId}; /// A filter which performs coarse-grained change detect...
use std::{collections::HashMap, hash::Hash}; // TODO: add accuracy to depth cache // TODO: purge cached entries, keep count per depth, and if it reaches zero // TODO: actually cache meshdata #[derive(Debug, Hash, PartialEq, Eq, Clone)] pub struct CacheKey { char: char, mesh_type: MeshType, } impl CacheKey { ...
use common::GiphyGif; use seed::{*, prelude::*}; use crate::state::ModelEvent; /// A card displaying information on a Giphy GIF. pub fn gifcard( gif: &GiphyGif, catg_input: Option<&String>, mut on_save: impl FnMut(String) -> ModelEvent + Clone + 'static, mut on_remove: impl FnMut(String) -> ModelEvent...
use log::debug; use pretty_env_logger::env_logger; use regex::Regex; use serde_derive::Deserialize; use std::env; use std::fs::File; use std::io::prelude::*; use std::io::SeekFrom; #[derive(Deserialize, Debug)] struct Config { extruder_regex: String, replace_comment: String, custom_commands: String, t0...
use libc; extern "C" { #[no_mangle] fn cbor_encoder_close_container( encoder: *mut CborEncoder_0, containerEncoder: *const CborEncoder_0, ) -> CborError_0; } pub type ptrdiff_t = libc::c_long; pub type size_t = libc::c_ulong; pub type uint8_t = libc::c_uchar; /* #define the constants so we c...
// Copyright 2021 rust-ipfs-api Developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://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...
macro_rules! float_eq { ($lhs:expr, $rhs:expr) => { float_eq!($lhs, $rhs, std::f64::EPSILON) }; ($lhs:expr, $rhs:expr, $epsilon:expr) => { ($lhs - $rhs).abs() < $epsilon }; } macro_rules! float_eq_cero { ($lhs:expr) => { float_eq_cero!($lhs, std::f64::EPSILON) }; ($l...
use crate::function::ErlangResult; use crate::term::{OpaqueTerm, Term, TermType}; /// This is an intrinsic expected by the compiler to be defined as part of the runtime, and is used for runtime type checking #[export_name = "__firefly_builtin_typeof"] pub extern "C" fn r#typeof(value: OpaqueTerm) -> TermType { val...
pub mod grid; pub mod out; pub mod process; pub mod trim; #[cfg(feature = "crossterm")] pub mod crossterm;
//! Module provides wrapper for types that cannot be dropped silently. //! Usually such types are required to be returned to their creator. //! `Escape` wrapper help the user to do so by sending underlying value to the `Terminal` when it is dropped. //! Users are encouraged to dispose of the values manually while `Esca...
// Copyright 2016 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::fmt; #[derive(Serialize, Deserialize)] pub struct Todo { id: Option<u32>, name: String, complete: Option<bool>, } impl Todo { pub fn new(id: u32, name: String, complete: bool) -> Self { Self { id: Some(id), name, complete: Some(complete), } ...
use std::env; use minigrep::Config; fn main() { let args: Vec<String> = env::args().collect(); println!("{:?}", args); let config = Config::new(&args); minigrep::run(config); }
mod shared; #[cfg(feature = "local-testing")] #[tokio::test] async fn test_lobbies() { use shared::ds::{self, lobby}; shared::init_logger(); let dual = shared::make_dual_clients(ds::Subscriptions::LOBBY) .await .expect("failed to start clients"); let shared::DualClients { one, two } ...
use tokio::net::TcpStream; use tokio::io::AsyncRead; use tokio::io::AsyncWrite; use tokio_io::io::write_all; use tokio; use failure::Error; use std::net::SocketAddr; use net2::TcpBuilder; mod copy; use std::sync::Arc; use crate::relay::TcpRouter; use bytes::Bytes; use tokio::reactor::Handle; use self::copy::copy_verbo...
#[doc = "Reader of register TEST"] pub type R = crate::R<u8, super::TEST>; #[doc = "Writer for register TEST"] pub type W = crate::W<u8, super::TEST>; #[doc = "Register TEST `reset()`'s with value 0"] impl crate::ResetValue for super::TEST { type Type = u8; #[inline(always)] fn reset_value() -> Self::Type {...
use std::error::Error; use std::fs::File; use std::io::{BufReader, BufWriter}; use compression::{encode, decode}; fn main() -> Result<(), Box<dyn Error>> { let uncompressed_path = "./test/Grimms"; let compressed_path = "./test/Grimms.huffman"; let book = BufReader::new(File::open(uncompressed_path)?); ...
use std::collections::HashMap; use std::fmt; use firefly_diagnostics::SourceSpan; use firefly_intern::Symbol; use crate::lexer::{DelayedSubstitution, LexicalToken, Token}; use crate::lexer::{IdentToken, SymbolToken}; use super::directives::Define; use super::token_reader::{ReadFrom, TokenReader}; use super::types::{...
///! OpenType Variations common tables /// Item Variation Store (used in `MVAR`, etc.) mod itemvariationstore; /// Structs to store locations (user and normalized) mod locations; /// Structs for storing packed deltas within a tuple variation store mod packeddeltas; /// Structs for storing packed points mod packedpoint...
#![cfg(test)] extern crate wabt; extern crate parity_wasm; mod run; macro_rules! run_test { ($label: expr, $test_name: ident) => ( #[test] fn $test_name() { self::run::spec($label) } ); } run_test!("address", wasm_address); run_test!("align", wasm_align); run_test!("binary", wasm_binary); run_test!("bloc...
use super::*; pub enum Tag { A, Abbr, Acronym, Address, Applet, Area, Article, Aside, Audio, B, Base, Basefont, Bdi, Bdo, Big, Blockquote, Body, Br, Button, Canvas, Caption, Center, Cite, Code, Col, Colgroup, Data, Datalist, Dd, D...
use std::net::SocketAddr; use std::path::PathBuf; use clap::Clap; use tracing::warn; use bindle::{ invoice::signature::{KeyRing, SignatureRole}, provider, search, server::{server, TlsConfig}, signature::SecretKeyFile, SecretKeyEntry, }; const DESCRIPTION: &str = r#" The Bindle Server Bindle is a...
use atoms::Location; /// /// A trait that allows one to access the location of any node /// that implements this trait. /// pub trait HasLocation { /// /// Access the start location of this node. /// fn start(&self) -> Location; }
use super::mocks::*; use super::{db_path, pause}; use crate::connector::{AckResponse, EventType, JudgementRequest, JudgementResponse, Message}; use crate::primitives::{Account, AccountType, Challenge, Judgement, NetAccount}; use crate::{test_run, Database}; use matrix_sdk::identifiers::{RoomId, UserId}; use schnorrkel:...
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[repr(transparent)] #[doc(hidden)] pub struct IWindowManagementPreview(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IWindowManagementPreview { type Vtab...
{{~#if is_symmetric}} // The filtered choice is symmetric, so only the lower triangular part needs to be // filtered. if {{>set.id_getter arguments.[0].[1] item=arguments.[0].[0]}} < {{>set.id_getter arguments.[1].[1] item=arguments.[1].[0]}} { {{/if}} let mut values = {{>value_type.full_domain ...
use std::time::Instant; /// 有面值1,5,10,20,50,100的人民币,求问10000有多少种组成方法? fn main() { for i in (1000..=10000).step_by(1000) { println!("n={}", i); func1(i); println!(); func2(i); println!("==="); } } /// 动态规划解法 fn func1(target: usize) { let start = Instant::now(); l...
use std::io::{Read, Result as IOResult}; use crate::PrimitiveRead; pub struct VertexFileFixup { pub lod: i32, pub source_vertex_id: i32, pub vertices_count: i32 } impl VertexFileFixup { pub fn read(read: &mut dyn Read) -> IOResult<Self> { let lod = read.read_i32()?; let source_vertex_id = read.read_i...
pub mod pb { tonic::include_proto!("grpc.examples.echo"); } use http::header::HeaderValue; use pb::{echo_client::EchoClient, EchoRequest}; use tonic::transport::Channel; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let channel = Channel::from_static("http://[::1]:50051") ...
pub const PI: f32 = std::f32::consts::PI; pub const DEG_2_RAD: f32 = PI / 180.0; pub const RAD_2_DEG: f32 = 180.0 / PI; pub const SAFE_F: f32 = 0.0001; pub const SAFE_HALF_PI_MAX: f32 = (PI / 2.0) - SAFE_F; pub const SAFE_HALF_PI_MIN: f32 = (-PI / 2.0) + SAFE_F;
use rand::Rng; /// Generate a [base64url][1] encoded, cryptographically secure, random string. /// /// [1]: https://tools.ietf.org/html/rfc4648#page-7 pub fn generate_random_base64url(length: usize) -> String { let mut rng = rand::thread_rng(); let mut bytes = vec![0; length]; for i in 0..length { ...
extern crate num_cpus; extern crate threadpool; use std::thread; use threadpool::ThreadPool; use std::time::Duration; fn main() { let ncpus = num_cpus::get(); println!("The number of cpus in this machine is: {}", ncpus); let pool = ThreadPool::new(ncpus); for i in 0..ncpus { pool.execute(move || { ...
use std::collections::HashMap; fn main() { let mut input = include_str!("input").split("\r\n\r\n"); let start= input.next().unwrap(); let map: HashMap<_, _> = input.next().unwrap().lines().map( |x| { let mut spl = x.split(" -> "); let mut inp = spl.next().unwrap().chars();...
use libc; use crate::mmapstring::*; use crate::x::*; pub const MAIL_CHARCONV_ERROR_CONV: libc::c_uint = 3; pub const MAIL_CHARCONV_ERROR_MEMORY: libc::c_uint = 2; pub const MAIL_CHARCONV_ERROR_UNKNOWN_CHARSET: libc::c_uint = 1; pub const MAIL_CHARCONV_NO_ERROR: libc::c_uint = 0; /* * * define your own conversion. * ...
pub type CartId = String; pub type ItemCode = String; pub type Quantity = u32; pub type Amount = i32; #[derive(Debug, Clone)] pub enum Item { Product { code: ItemCode, price: Amount }, } #[derive(Debug, Clone)] pub struct CartLine { item: Item, qty: Quantity, } #[derive(Debug, Clone)] pub enum Cart { ...
//! Convert all music in music/ to ogg. use std::env; use std::fs; use std::fs::File; use std::path::Path; use std::process::Command; use tar::Builder; fn main() { let out_dir = env::var("OUT_DIR").unwrap(); let music_dir = Path::new("music"); let music_extensions = vec!["mp3", "opus", "flac", "m4a", "ogg...
use std::{error::Error, fmt, result::Result}; use smartstring::alias::String; use crate::parser::{Lexer, LexerError, Spanning, Token}; /// Error while parsing a GraphQL query #[derive(Debug, Eq, PartialEq)] pub enum ParseError { /// An unexpected token occurred in the source // TODO: Previously was `Token<'a...