text
stringlengths
8
4.13M
//! Source implementation for Postgres database, including the TLS support (client only). mod connection; mod errors; mod typesystem; pub use self::errors::PostgresSourceError; pub use connection::rewrite_tls_args; pub use typesystem::{PostgresTypePairs, PostgresTypeSystem}; use crate::constants::DB_BUFFER_SIZE; use...
use bevy::prelude::*; use big_brain::prelude::*; // First, we define a "Thirst" component and associated system. This is NOT // THE AI. It's a plain old system that just makes an entity "thirstier" over // time. This is what the AI will later interact with. // // There's nothing special here. It's a plain old Bevy com...
use futures_util::StreamExt; use log::{debug, error, info, trace, warn}; use sha1::{Digest, Sha1}; use std::{ env, fs::create_dir_all, ops::RangeInclusive, path::{Path, PathBuf}, pin::Pin, process::exit, str::FromStr, time::{Duration, Instant}, }; use sysinfo::{System, SystemExt}; use th...
use im::HashMap; use rustc_hir::{def::DefKind, definitions::DefPathData, AssocItemKind, ItemKind}; use rustc_metadata::creader::CStore; use rustc_middle::mir::Mutability; use rustc_middle::ty::subst::GenericArgKind; use rustc_middle::ty::{ self, AdtKind, ConstKind, IntTy, PolyFnSig, RegionKind, TyCtxt, TyKind, Uint...
#[doc = "Register `DDRCTRL_ADDRMAP6` reader"] pub type R = crate::R<DDRCTRL_ADDRMAP6_SPEC>; #[doc = "Register `DDRCTRL_ADDRMAP6` writer"] pub type W = crate::W<DDRCTRL_ADDRMAP6_SPEC>; #[doc = "Field `ADDRMAP_ROW_B12` reader - ADDRMAP_ROW_B12"] pub type ADDRMAP_ROW_B12_R = crate::FieldReader; #[doc = "Field `ADDRMAP_ROW...
fn main() { let str1 = "yes"; let str2 = &str1[..]; // 获取 &str 的 slice, 结果类型还是 &str str1 = 3; str2 = 3; // slice 的 slice 还是 slice, 即 &str[..] 的类型还是 &str }
// Copyright 2018 Mohammad Rezaei. // // 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 super::{chunk_header::*, chunk_type::*, *}; use crate::error_cause::*; use bytes::{Bytes, BytesMut}; use std::fmt; ///Abort represents an SCTP Chunk of type ABORT /// ///The ABORT chunk is sent to the peer of an association to close the ///association. The ABORT chunk may contain Cause Parameters to inform ///th...
use std::fs::create_dir_all; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; use std::path::PathBuf; use anyhow::Result; use crate::fixups::urs_utils; fn generate_paths(max_urs: &String, target: &PathBuf) -> Result<Vec<PathBuf>> { let max = urs_utils::urs_to_index(max_urs)?; let paths = (...
pub mod readlink; pub mod settings;
#[doc = "Register `SMCR` reader"] pub type R = crate::R<SMCR_SPEC>; #[doc = "Register `SMCR` writer"] pub type W = crate::W<SMCR_SPEC>; #[doc = "Field `BKPRWDPROT` reader - Backup registers read/write protection offset"] pub type BKPRWDPROT_R = crate::FieldReader; #[doc = "Field `BKPRWDPROT` writer - Backup registers r...
use crate::utils::whitespace_tokenizer; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::cmp::Ordering; use std::ops::Range; use std::result::Result; /// Struct representing the value of an entity to be added to the parser #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Hash)] pub ...
use std::path::PathBuf; use glob::Pattern; use indicatif::ProgressBar; use walkdir::{DirEntry, WalkDir}; use crate::errors::StandardResult; use crate::utils::terminal::alert; use crate::{TEMPLATE_DIR_NAME, TEMPLATE_IGNORE_FILE}; pub fn scan_dir(template_dir: &PathBuf) -> StandardResult<(Vec<DirEntry>, Vec<DirEntry>)...
extern crate shared; use shared::infinity::Infinity; fn main() { let inf = Infinity::new(); let mut first = inf.filter(|x| (1..21).all(|y| x % y == 0) ).take(1); println!("{:?}", first.next().unwrap()); }
// number of CPU cycles between sample output level being adjusted pub const SAMPLE_RATES: [u16; 16] = [428, 380, 340, 320, 286, 254, 226, 214, 190, 160, 142, 128, 106, 84, 72, 54]; #[derive(serde::Serialize, serde::Deserialize, Clone)] pub struct DMC { pub sample: u16, // "output value" that goes to the mixer ...
use std::io::{self, Read}; #[allow(dead_code)] fn read_stdin() -> String{ let mut buffer = String::new(); io::stdin().read_to_string(&mut buffer).expect("did not recieve anything from stdin"); return buffer; } #[derive(Debug)] enum Mode{ Position, Immediate } #[derive(Debug)] enum Operation{ Addit...
use crate::error::Error; impl Error { pub fn not_found<S: Into<String>>(entity: S) -> Error { Error::new(entity.into(), "not_found".to_owned()) .set_status(404) .build() } pub fn unauthorized() -> Error { Error::new("authorization", "unauthorized") .set_...
pub mod backend; pub mod con_back; pub mod init; pub mod memory; pub mod pipeline_2d; pub mod ui_pipeline; use memory::*; use std::sync::Arc; use log::{error, info, warn}; use core::{ marker::PhantomData, mem::{size_of, ManuallyDrop}, ops::Deref, }; use gfx_hal::{ adapter::{Adapter, PhysicalDevice}, ...
//! //! # Sequences //! //! This module implements variable-length sequences and utility functions for it. //! Seq only supports operations that are safe on secret values. //! For use with public values you can use `PublicSeq`. //! use crate::prelude::*; mod bytes; pub use bytes::*; macro_rules! declare_seq { ($...
pub mod module { use crate::types::module::*; use crate::vec3::module::*; use crate::ray::module::*; use crate::hittable::module::*; use crate::camera::module::*; use crate::material::module::*; use crate::rand::module::*; use std::f32; fn get_color( r: &Ray, world: &dyn Hittable, materials: &Vec<Box<dyn Materia...
use rand::Rng; use rand::distributions::{Distribution, Uniform}; fn run_random() { let mut rng = rand::thread_rng(); let n1 : u8 = rng.gen(); let n2 : u16 = rng.gen(); // let n3 = rng.gen(); println!("Random u8: {}", n1); println!("Random u16: {}", n2); println!("Random u32: {}", rng.g...
#[doc = "Register `D2CFGR` reader"] pub type R = crate::R<D2CFGR_SPEC>; #[doc = "Register `D2CFGR` writer"] pub type W = crate::W<D2CFGR_SPEC>; #[doc = "Field `D2PPRE1` reader - D2 domain APB1 prescaler"] pub type D2PPRE1_R = crate::FieldReader<D2PPRE1_A>; #[doc = "D2 domain APB1 prescaler\n\nValue on reset: 0"] #[deri...
pub mod pseudoconic; pub mod pseudocylindric; pub mod conic; pub mod cylindric; pub mod projection_types; pub mod projection_by_name;
fn main() { let x: i32; //warn }
use common::*; use extended::common::*; const BUFFER_CAPACITY: usize = 10; /// A sink that consumes one item every second, but which can buffer up to /// BUFFER_SIZE items pub struct Consumer { buffer: VecDeque<u8>, inner: extended::delayed_series::Consumer, } impl Consumer { pub fn new() -> Consumer { Co...
use crate::interface; use crate::interface::{ BaguaNetError, NCCLNetProperties, Net, SocketHandle, SocketListenCommID, SocketRecvCommID, SocketRequestID, SocketSendCommID, }; use crate::utils; use crate::utils::NCCLSocketDev; use nix::sys::socket::{InetAddr, SockAddr}; use opentelemetry::{ metrics::{BoundVa...
//! ## Error Receipt Binary Format Version 0 //! //! On failure (`is_success = 0`) //! //! ```text //! +-------------------------------------------------------+ //! | | | | | //! | tx type | version | is_success | error code | //! | (1 byte) | (2 bytes...
use super::super::atom::{ btn::{self, Btn}, dropdown::{self, Dropdown}, fa, text::Text, }; use super::{ ChatPalletIndex, ChatPalletSectionIndex, ChatUser, InputingMessage, SharedState, ShowingModal, }; use crate::arena::block; use isaribi::{ style, styled::{Style, Styled}, }; use kagura::pre...
//! Represents the storage trait and example implementation. //! //! The storage trait is used to house and eventually serialize the state of the system. //! Custom implementations of this are normal and this is likely to be a key integration //! point for your distributed storage. // Copyright 2019 EinsteinDB Project...
use crate::{ config::StartConfig, websocket::{ main_subscriber::MainSubscriber, push_messages::{InternalMessage, InnerInternalMessage} }, api::extractors::auth::Auth, }; use actix::{Addr, MailboxError}; use chrono::Utc; use lettre::SmtpTransport; use std::result::Result; pub use crate::...
use std::sync::mpsc::channel; use criterion::{ criterion_main, criterion_group, Criterion, black_box }; use rand::{ Rng, SeedableRng, distributions::Alphanumeric, rngs::SmallRng }; use crossbeam_skiplist::SkipMap; use rayon::prelude::*; #[derive(Clone)] struct DataIter { pid: usize, rng: SmallRng } impl DataI...
#[doc = "Register `FDCAN_TXBTO` reader"] pub type R = crate::R<FDCAN_TXBTO_SPEC>; #[doc = "Field `TO` reader - Transmission Occurred."] pub type TO_R = crate::FieldReader; impl R { #[doc = "Bits 0:2 - Transmission Occurred."] #[inline(always)] pub fn to(&self) -> TO_R { TO_R::new((self.bits & 7) as ...
fn main() { let mut s = String::new(); std::io::stdin().read_line(&mut s).ok(); let mut ia = 0; for c in s.chars() { if c == 'A' { break; } ia += 1; } let mut iz = 0; let mut tmp = 0; for c in s.chars() { if c == 'Z' { iz = tmp; ...
#[path = "support/macros.rs"] #[macro_use] mod macros; #[cfg(target_arch = "wasm32")] wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser); use glam::{ DMat2, DMat3, DMat4, DQuat, DVec2, DVec3, DVec4, Mat2, Mat3, Mat3A, Mat4, Quat, Vec2, Vec3, Vec3A, Vec4, }; pub trait Deg { fn to_radians(self...
//! This module is to test different scenarios and gather timings. //! //! run with `cargo run -p max_load` use chrono::prelude::*; use rand; use rand::prelude::IteratorRandom; use rand::rngs::ThreadRng; use rand::Rng; use std::fmt::Formatter; use std::fs::File; use std::io::Write; use std::ops::Add; use std::thread;...
# [ doc = "Universal synchronous asynchronous receiver transmitter" ] # [ repr ( C ) ] pub struct Usart { # [ doc = "0x00 - Control register 1" ] pub cr1: Cr1, # [ doc = "0x04 - Control register 2" ] pub cr2: Cr2, # [ doc = "0x08 - Control register 3" ] pub cr3: Cr3, # [ doc = "0x0c - Baud r...
use rosu_v2::prelude::User; use crate::embeds::{attachment, Author}; pub struct GraphEmbed { author: Author, image: String, } impl GraphEmbed { pub fn new(user: &User) -> Self { Self { author: author!(user), image: attachment("graph.png"), } } } impl_builder!(...
// You can unpack `Option` by using `match` statements, but it's often // easier ti use the `?` operator. If `x` is an `Option`, then // evaluating `x?` will return the underlying value if `x` is `Some`, // otherwise it will terminate whatever function is being executed and // return `None` #[allow(dead_code)] fn ne...
use std::fs::File; use std::io::Read; #[derive(PartialEq, Debug, Clone)] pub enum GridElement { Ground, Empty, Occupied, } #[derive(PartialEq, Debug, Clone)] pub struct Map { map: Vec<Vec<GridElement>>, } impl Map { pub fn step_part1(&self) -> Map { let mut new_map = self.clone(); ...
use serde_repr::Deserialize_repr; #[derive(Debug, Deserialize_repr)] #[repr(u8)] pub enum LineJoin { Miter = 1, Round = 2, Bevel = 3, } impl Default for LineJoin { fn default() -> Self { Self::Round } }
use crate::dict; use gobble::*; parser! { (Converter ->String) chars_until(Letter, eoi).map(|(a, _b)| a) } parser! { (EnStringPos -> ()) ((Alpha,NumDigit).iplus(),(Alpha,NumDigit,BothAllow).istar()).ig() } parser! { (MiStringPos -> ()) ((MiChar,NumDigit).iplus(),(MiChar,NumDigit,BothAllow).istar()).ig() }...
// 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 crate::models::access::AccessType; use crate::models::access_user::AccessUser; use crate::models::file::File; use crate::models::user::User; use crate::models::DataPoolSqlite; use crate::payloads::requests::{RemoveAccessRequest, UpdateAccessRequest}; use log::{debug, error, info}; const WRITE_ACCESS_ID: i64 = Acce...
use std::env; use std::time::SystemTime; pub fn read_int() -> Result<u64, &'static str> { match env::args().nth(1) { Some(text) => match text.parse::<u64>() { Ok(value) => Ok(value), Err(_) => Err("Invalid number") }, None => { Err("Missing command line a...
pub mod login; pub mod register; pub mod upload;
use std::env; use std::net::IpAddr; use stq_logging; use config_crate::{Config as RawConfig, ConfigError, Environment, File}; use sentry_integration::SentryConfig; /// Service configuration #[derive(Clone, Debug, Deserialize)] pub struct Server { pub host: IpAddr, pub port: u16, pub thread_count: usize, ...
// Copyright 2020. The Tari Project // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following // disclai...
use paras_claim_rewards_contract::ContractContract as ClaimContract; use near_sdk::json_types::U128; use near_sdk::serde_json::json; use near_sdk_sim::{ deploy, init_simulator, to_yocto, ContractAccount, UserAccount, DEFAULT_GAS, STORAGE_AMOUNT, }; // Load in contract bytes at runtime near_sdk_sim::lazy_static_inc...
pub mod eval; pub mod parse; pub mod rust; pub type Value<'a> = eval::value::Value<'a>;
extern crate regex; use std::fs::File; use std::io::BufReader; use std::io::prelude::*; use std::str; use regex::Regex; #[derive(Debug)] struct Rect { id: i32, x: usize, y: usize, width: usize, height: usize, } fn main() -> std::io::Result<()> { println!("day 3"); let mut input_buf = vec!...
use crate::spi::{BinData, FnTable}; use crate::{Bin, IntoUnSyncView, SBin}; /// A binary that's always empty. pub struct EmptyBin; impl EmptyBin { /// Creates a new empty binary. #[inline] pub const fn empty_sbin() -> SBin { SBin(Bin::_const_new(BinData::empty(), &FN_TABLE)) } } const FN_TABL...
/// 用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead , /// 分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead操作返回 -1 ) /// /// 输入: /// ["CQueue","appendTail","deleteHead","deleteHead"] /// [[],[3],[],[]] /// 输出:[null,null,3,-1] /// -----------------------解释----------------------------- /// ["CQueue","appendTail","dele...
use super::config::{BarBuilder, DockDirection}; use super::error::RunnerError; use super::event; pub trait WmScreen { fn dimensions(&self) -> (u32, u32); fn physical_dimensions(&self) -> Option<(f32, f32)>; } pub trait WmAdapter<B: Bar>: Sized { type Error: std::error::Error; type Surface; type Sc...
mod aoc_utils; pub use crate::aoc_utils::*;
#[doc = "Register `CR` reader"] pub type R = crate::R<CR_SPEC>; #[doc = "Register `CR` writer"] pub type W = crate::W<CR_SPEC>; #[doc = "Field `LCDEN` reader - LCD controller enable"] pub type LCDEN_R = crate::BitReader; #[doc = "Field `LCDEN` writer - LCD controller enable"] pub type LCDEN_W<'a, REG, const O: u8> = cr...
fn largest_five_digit_number(num: &str) -> u32 { num.chars() .collect::<Vec<_>>() .windows(5) .map(|t| t.iter().collect::<String>()) .map(|s| s.parse::<_>()) .map(|v| v.unwrap()) .max() .unwrap() } #[cfg(test)] mod tests { use super::*; #[test] f...
#[macro_use] extern crate gfx; extern crate gfx_app; extern crate winit; extern crate rand; mod app; mod state; const BOX_SIZE: usize = 20; fn main() { use gfx_app::Application; use winit::WindowBuilder; let width = ((state::MAIN_WIDTH + state::PREVIEW_WIDTH) * BOX_SIZE) as u32; let height = (state:...
use nalgebra::{ArrayStorage, Vector3}; use rand::Rng; use rand_distr::{Distribution, UnitSphere}; use rand_distr::num_traits::Pow; use crate::object::Intersection; use crate::ray::Ray; use crate::RNG; pub trait Material { fn scatter(&self, int: &Intersection) -> (Ray<f64>, Vector3<f64>); } pub struct Metal { ...
use proc_macro2::{Span, TokenStream as TokenStream2}; use quote::quote; use syn::{parse::ParseBuffer, Error, Fields, Ident, ItemStruct, Type}; const SUPPORTED_TYPES_MSG: &str = "Types supported: \"bytes32\", \"address\", \"uint256\""; pub struct MoebiusState { ast: ItemStruct, } impl MoebiusState { pub fn ex...
// Wicci Shim Module // Manage [u8] latin1 text use std::ascii::AsciiExt; #[cfg(feature = "never")] pub fn make_lower<T: AsciiExt>(bytes: &mut T) { bytes.make_ascii_lowercase(); } pub fn make_lower_vec_u8(bytes: &mut Vec<u8>) { for i in 0 .. bytes.len() { bytes[i] = bytes[i].to_ascii_lowercase(); } } // t...
use block_cipher_trait::generic_array::GenericArray; use block_cipher_trait::generic_array::typenum::U8; use block_cipher_trait::generic_array::typenum::U32; use stream_cipher::NewStreamCipher; use stream_cipher::StreamCipher; use stream_cipher::SyncStreamCipherSeek; #[cfg(cargo_feature = "zeroize")] use zeroize::Zero...
//罗马数字包含以下七种字符: I, V, X, L,C,D 和 M。 // //字符 数值 //I 1 //V 5 //X 10 //L 50 //C 100 //D 500 //M 1000 //例如, 罗马数字 2 写做 II ,即为两个并列的 1。12 写做 XII ,即为 X + II 。 27 写做  XXVII, 即为 XX + V + II 。 // //通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例,例如 4 不写做 ...
include!(concat!(env!("OUT_DIR"), "/greeting.rs"));
use crate::uses::*; use core::slice; use crate::acpi::Rsdt; use crate::mem::PhysRange; use crate::consts; use crate::util::{from_cstr, HwaTag, HwaIter, misc::phys_to_virt}; // multiboot tag type ids const END: u32 = 0; const MODULE: u32 = 3; const MEMORY_MAP: u32 = 6; const RSDP_OLD: u32 = 14; const RSDP_NEW: u32 = 15...
use actix_cors::Cors; use actix_web::{http::header, middleware::Logger, web, App, HttpServer}; extern crate fs_utilities; pub async fn folder_handler(request: web::Json<fs_utilities::Request>) -> web::Json<fs_utilities::Folder> { web::Json(fs_utilities::get_folder_contents(request.0)) } #[actix_rt::main] async f...
use super::id::ObjID; use super::obj::Twzobj; use super::r#const::{ProtFlags, NULLPAGE_SIZE}; use super::tx::Transaction; use crate::TwzErr; crate::bitflags! { pub struct CreateFlags: u64 { const HASH_DATA = 0x1; const DFL_READ = 0x4; const DFL_WRITE = 0x8; const DFL_EXEC = 0x10; const DFL_USE = 0x20; cons...
use super::{ get_cache_file, get_home, error::StateError, }; use std::{ collections::HashMap, path::PathBuf, fs::read_to_string }; use bincode::{deserialize_from, serialize_into}; #[derive(Deserialize, Serialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct Template { pub...
#![recursion_limit = "1024"] extern crate proc_macro; use heck::{CamelCase, KebabCase, MixedCase, ShoutySnakeCase, SnakeCase}; use proc_macro::TokenStream; use proc_macro2::{Ident, Span}; use quote::quote; use syn::*; #[proc_macro_derive(DbEnum, attributes(PgType, DieselType, DbValueStyle, db_rename))] pub fn derive...
pub const INSTANCE_ID_NOT_FOUND: &str = "Instance, associated with given instance id does not found"; pub const SUBPROCESS_TO_LINK_NOT_FOUND: &str = "Subprocess to link does not found in the data structure"; pub const INSTANTIATION_ERROR: &str = "Error occured in the middle of contract instantiation"; pub const...
//! The `entry` module is a fundamental building block of Proof of History. It contains a //! unique ID that is the hash of the Entry before it, plus the hash of the //! transactions within it. Entries cannot be reordered, and its field `num_hashes` //! represents an approximate amount of time since the last Entry was ...
use std::fs::File; use std::io; use std::io::Read; use std::path::Path; use response::*; use request::*; use mime::{extension_to_mime}; const USE_INDEX_HTML: bool = true; pub fn serve(req: &Request, res: &mut Response) { let mut local_path = Path::new("public") .join(Path::new(req.url()).strip_prefix("/...
#![allow(non_snake_case)] //! Warning: this library is programmed as a meme. You should **not** use it. //! Only Linux is supported, because it lets us have the worst ideas the fastest. use std::convert::TryInto; use std::mem; use std::os::raw::*; use std::ptr; use std::slice; use std::sync::atomic::{AtomicBool, Atomi...
extern crate alsa; extern crate libc; use std::ffi::{CStr, CString}; use std::io::{stderr, Write}; use std::mem; use std::thread::{Builder, JoinHandle}; use self::alsa::seq::{Addr, EventType, PortCap, PortInfo, PortSubscribe, PortType, QueueTempo}; use self::alsa::{Direction, Seq}; use errors::*; use {Ignore, MidiMe...
fn main() { { let i = 10; } println!("{} ", i); }
extern crate peroxide; use peroxide::*; fn main() { let a = seq(1, 100, 1); //a.write_single_pickle("example_data/pickle_example_vec.pickle").expect("Can't write pickle"); let mut b = Matrix::from_index(|i, j| (i + j) as f64, (100, 2)); match b.shape { Row => { b = b.change_shape()...
use std::io::{Read, Write}; use bear_vm::device; #[derive(Debug, Clone)] pub struct Register { value: Option<u32>, can_read: bool, can_write: bool, } #[derive(Debug, Clone)] pub struct StdinDevice<T: Read> { state: device::GenericDeviceState, registers: [Register; 0], handle: T, } #[derive(D...
pub mod overview; pub mod vector;
pub fn inorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> { let mut result = vec![]; let mut stack = vec![]; if let Some(root) = root { let mut current = Some(root.clone()); while current.is_some() || !stack.is_empty() { while let Some(node) = current { ...
use crate::Error; use diesel::{ connection::Connection as _, pg::PgConnection, r2d2::{Builder, ConnectionManager, Pool, PooledConnection}, }; #[derive(Clone)] pub struct Postgres { pool: Pool<Manager>, } pub type Manager = ConnectionManager<PgConnection>; pub type Connection = PooledConnection<Manager...
pub mod simple; pub mod generic; pub mod extend; pub mod itertoolslib; pub mod intoiterator_trait; pub mod iter_fn;
use scene::{Rectangle, Tex}; use sdl2::pixels::Color; use sdl2::rect::Rect; pub struct TilePicker { tileset: String, tile_width: u32, tile_height: u32, // XXX: replace with Ratio scale: f32, // widget has total ownership of its position for now rect: Rect, offset: u32, selected: u32...
/// An enum to represent all characters in the InscriptionalPahlavi block. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum InscriptionalPahlavi { /// \u{10b60}: '𐭠' LetterAleph, /// \u{10b61}: '𐭡' LetterBeth, /// \u{10b62}: '𐭢' LetterGimel, /// \u{10b63}: '𐭣' LetterDalet...
use iron::prelude::*; use iron::{BeforeMiddleware, AfterMiddleware, AroundMiddleware, Handler}; use common::http::*; use common::utils::{get_session_obj, is_login, is_admin}; pub struct FlowControl; impl BeforeMiddleware for FlowControl { fn before(&self, _req: &mut Request) -> IronResult<()> { Ok(()) ...
/// Construct a `Resule<rule::Rule, rule::Error>` from a JSON array literal. /// /// ``` /// use ::rule::rule; /// /// let r = rule!["=", "a", 1].unwrap(); /// ``` #[macro_export(local_inner_macros)] macro_rules! rule { ( [$($e:tt)*] ) => { rule![$($e)*] }; ( $($e:tt)* ) => { $crate::Rule::n...
use yew::prelude::*; use yew::virtual_dom::VNode; use yew::{Component, ComponentLink}; use std::fmt::Debug; use stdweb::js; use crate::Entry; #[derive(Properties, PartialEq, Debug, Clone)] pub struct SongListItemProps { pub song: Entry, pub index: usize, } #[allow(dead_code)] pub struct Item { /// State ...
use std::path::PathBuf; pub enum Fixture { CFF, TTF, VariableCFF, VariableTTF, } impl Fixture { pub fn path(&self) -> PathBuf { match *self { Fixture::CFF => "tests/fixtures/SourceSerifPro-Regular.otf".into(), Fixture::TTF => "tests/fixtures/OpenSans-Italic.ttf".int...
// 导出与本文件名同名的 src_a 文件夹下的 a.rs c.rs 中的内容,如果 a.rs 或者 c.rs 不存在,则查找 src_a 目录下的 mod.rs // 优先查找同级的文件夹 src_a 中的 a.rs 文件,符合 1-2) pub mod a; // 优先查找同级的文件夹 src_a 中的 c.rs 文件,符合 1-2) pub mod c; pub use a::*; pub use c::*;
mod change_mapping_response; mod define_action_response; mod define_device_response; mod define_mapping_response; mod define_modifier_response; mod execute_code_response; mod get_defined_actions_response; mod get_defined_mappings_response; mod get_defined_modifiers_response; mod get_devices_response; mod handshake_resp...
use crate::equity::Equity; pub trait ListHolder { fn add_equity(&mut self, ticker: String) -> Cresult; fn remove_equity(&mut self, ticker: String) -> Cresult; fn find_equity(&mut self, ticker: String) -> Cresult; } enum Cresult { Added, Moved, DoesNotExist, Exist, } // Cacher creates and h...
pub mod maze_genotype; pub mod maze_phenotype; pub mod maze_validator; #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum Orientation { Horizontal, Vertical, } #[derive(Debug, Clone, Eq, PartialEq, Copy)] pub enum PathDirection { North, East, South, West, None, } #[derive(Debug, Copy, ...
#![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 ApiServerProfile { #[serde(default, skip_serializing_if = "Option::is_none")] pub visibility: Option<Visibi...
use crate::{ api, model, pb::maine_service_server::MaineServiceServer, service::{db, rpc}, }; use envconfig::Envconfig; #[derive(Debug, Clone, Envconfig)] pub struct Config { #[envconfig(from = "SERVICE_ADDR")] pub addr: String, } pub async fn new_srv( db: db::DB, rpc: rpc::Client, nc...
use std::collections::hash_map::Entry::Vacant; use std::collections::{HashMap, HashSet}; use std::fmt; #[derive(Clone)] pub struct ImportGraph<'a> { pub names_by_id: HashMap<u32, &'a str>, pub ids_by_name: HashMap<&'a str, u32>, pub importers_by_imported: HashMap<u32, HashSet<u32>>, pub importeds_by_im...
use evalexpr::*; fn evaluate_expressions() { assert_eq!(eval("1 + 2 + 3"), Ok(Value::from(6))); // `eval` returns a variant of the `Value` enum, // while `eval_[type]` returns the respective type directly. // Both can be used interchangeably. assert_eq!(eval_int("1 + 2 + 3"), Ok(6)); assert_eq!...
use chrono::TimeZone; pub struct DateTime<'a> { datetime: &'a str, } impl<'a> DateTime<'a> { pub fn new(datetime: &'a str) -> Self { return DateTime { datetime }; } pub fn get_time_duration_to_run(&self) -> chrono::Duration { let mut splited_datetime = self.datetime.split(" "); ...
fn apply<F>(f: F) where F: FnOnce() { //F: Fn() { //F: FnMut() {// error closure `diary` implements `FnOnce` not `FnMut` f(); } fn apply_to_3<F>(f: F) -> i32 where F: Fn(i32) -> i32 { f(3) } fn main() { use std::mem; let greeting = "hello"; let mut farewell = "goodbye".to_owned()...
#![allow(dead_code)] #![allow(unused_variables)] #![allow(unused_mut)] #![feature(macro_rules)] #![feature(globs)] static FOO:u8 = 10; static BAR:f64 = 1.0; static CHR:char = '&'; //static STRIING:String = "Hello"; // Found &'static str expected String //static STR:str = "World"; // Expected str found &'static str //...
use assert_cmd::prelude::*; // Add methods on commands use predicates::prelude::*; // Used for writing assertions use std::process::Command; // Run programs // ================================= // Walk subcommand integration tests // ================================= #[test] fn integration_walk_inpath_doesnt_exist() ...
#![allow(dead_code, unused_imports, unused_variables)] use petgraph::algo::*; use petgraph::graph::NodeIndex; use petgraph::visit::{GraphBase, NodeRef}; use petgraph::Graph; #[derive(Default, Debug)] struct Project { tasks: Graph<Task, Task>, ordered_tasks: Vec<NodeIndex>, } #[derive(Default, Debug)] struct T...
use crate::banner; use crate::node; use crate::node::presence; use crate::node::MixNode; use clap::ArgMatches; use std::net::ToSocketAddrs; use std::thread; fn print_binding_warning(address: &str) { println!("\n##### WARNING #####"); println!( "\nYou are trying to bind to {} - you might not be accessi...