text
stringlengths
8
4.13M
use lodepng::*; fn encode<T: rgb::Pod>(pixels: &[T], in_type: ColorType, out_type: ColorType) -> Result<Vec<u8>, Error> { let mut state = Encoder::new(); state.set_auto_convert(true); state.info_raw_mut().colortype = in_type; state.info_raw_mut().set_bitdepth(8); state.info_png_mut().color.colortyp...
extern crate hlua; use hlua::Lua; extern crate rustyline; use rustyline::error::ReadlineError; use std::rc::Rc; use std::io; use std::io::BufRead; mod snail; use snail::*; use std::io::prelude::*; use std::error::Error; use std::fs; use std::fs::File; use std::fs::metadata; use std::env; use std::path::Path; use...
pub struct Rect { } impl Rect { pub fn new() -> Rect { Rect { } } } pub struct Collision { cell_size: u32, rects: HashMap<string, Rect>, } impl Collision { pub fn new(cell_size: u32) -> Collision { Collision { cell_size: cell_size, rects: HashMap:...
extern crate rustogram; const HIGHEST_TRACKABLE_VALUE: i64 = 3600 * 1000 * 1000; const NUMBER_OF_SIGNIFICANT_VALUE_DIGITS: i32 = 3; use rustogram::histogram::*; use rustogram::iter::*; #[test] fn test_get_total_count() { let histogram = get_histogram(); let raw_histogram = get_raw_histogram(); assert_eq!(...
use reqwest; use std::error::Error; use std::fs::File; use std::io::BufReader; use std::io::Read; use std::result::Result; pub trait SiteDownloader { fn get_radar_meta(&self) -> Result<String, Box<dyn Error>>; fn get_radar_image(&self, rel_path: &str) -> Result<Vec<u8>, Box<dyn Error>>; } pub struct MeteoArso...
extern crate bincode; extern crate serde; extern crate serde_derive; use libc as c; use serde::{Deserialize, Serialize}; use serde::de::DeserializeOwned; use std::path::Path; use std::io::Read; use std::io::Write; use std::io::BufWriter; use std::io::BufReader; use unix_socket::*; use std::marker::PhantomData; use std...
#![no_std] #![feature(const_fn)] #![feature(alloc)] #![allow(safe_packed_borrows)] #[macro_use] extern crate vga; extern crate device; #[macro_use] extern crate alloc; #[macro_use] extern crate bitflags; mod fat32; mod file; use alloc::Vec; use device::ata::ATA; use device::disk::Disk; use file::{File, FileMode, Fi...
// Copyright 2020 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 ...
extern crate ansi_term; extern crate rand; extern crate ndarray; extern crate itertools; extern crate termion; use rand::Rng; use rand::prelude::SliceRandom; use crate::grid::rgb::RGB; use crate::grid::grid::colored_char; use super::tile::{Tile, OUTLINED_SQUARE}; #[derive(Clone, Debug)] pub struct Tetrad { pub ...
// // zhtta.rs // // Running on Rust 0.8 // // Starting code for PS3 // // Note: it would be very unwise to run this server on a machine that is // on the Internet and contains any sensitive files! // // University of Virginia - cs4414 Fall 2013 // Weilin Xu and David Evans // Version 0.3 extern mod extra; use std::...
mod board; pub mod digit; use crate::board::{Board, GameOver, PLAYERS}; use anyhow::Result; use std::{ io::{self, Write}, iter, }; fn main() -> Result<()> { let mut board = Board::new(); println!("Tic Tac Toe"); println!("==========="); println!(); println!("Squares are numbered 1 through...
//! アガリ形を保持する牌集合を定義する。 use crate::context::Context; use crate::tile::{Order, Tile}; use crate::tiles::Tiles; use crate::tilesets::Tilesets; use std::collections::HashSet; use std::fmt; use std::ops::Range; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum MachiKind { /// 両面待ち。 /// /// 例: 23 に対して...
use std::future::Future; use aws_lambda_events::event::alb::{ AlbTargetGroupRequest, AlbTargetGroupResponse }; use mu_runtime::{Context, Error}; use crate::deserializer::AlbDeserialize; use crate::{response, AlbSerialize}; /// Listen to ALB events. Unlike [mu_runtime::listen_events], this method /// expects you...
use std::fmt::Debug; use std::fmt::Display; use std::fmt; use std::io::Error as IoError; use std::marker::PhantomData; use bytes::BytesMut; use log::trace; use kf_protocol::Encoder; use kf_protocol::Decoder; use kf_protocol::Version; use kf_protocol::derive::Decode; use kf_protocol::derive::Encode; use kf_protocol::a...
/* 서버를 싱글 스레드에서 멀티 스레드로 바꾸기 */ use std::net::{TcpListener, TcpStream}; use std::io::{Read, Write}; use std::fs; use std::thread; use std::time::Duration; // fn main() { // let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); //80번 포트는 관리자 권한이 필요, 비 관리자는 1024 이상의 포트번호 사용 // // for stream in listener...
pub fn crc(buff: &[u8]) -> u32 { crc_seed(buff, 0) } pub fn crc_seed(buff: &[u8], seed: u32) -> u32 { let mut r = seed; for byte in buff { r = (r + *byte as u32) & 0xffffffff; } r }
//! //! Exposes a [Virtual File Systems (VFS)](https://docs.rs/vfs/) via HTTPS. //! //! The [HttpsFSServer] exposes a VFS (implementing [FileSystem](vfs::filesystem::FileSystem)) via HTTPS. //! [HttpsFS] can be uses to access a [FileSystem](vfs::filesystem::FileSystem) exposed by a [HttpsFSServer]. //! //! # Example //...
#![allow(unused_imports)] use num_integer::{div_ceil, div_floor}; use proconio::{fastout, input, marker::*}; #[fastout] fn main() { input! { a: usize, b: usize, w: usize, }; let w = w * 1000; let ans1 = div_floor(w, a); let ans2 = div_ceil(w, b); if ans1 < ans2 { ...
use iced::{button, Button, Container, Row, Text}; use iced_native::{Align, Length}; use crate::messages::Message; use crate::styles; #[derive(Default)] pub struct ToolBar { study_button: button::State, ranges_button: button::State, } impl ToolBar { pub fn view(&mut self) -> Container<Message> { ...
extern crate lazy_static; extern crate girigiri; use std::time::Instant; // use engine::first_engine::*; // use engine::random_engine::*; use girigiri::engine::alphabeta::controller::*; use girigiri::shogi::state::*; use girigiri::shogi::hash::*; use std::io::{self, Write}; const LOOP_MAX: i32 = 2000; const NORMALIZ...
pub mod rccell;
//! A module that containers the core of the arena allocator #![allow(clippy::new_without_default)] #![allow(unused)] use std::mem; use std::num::NonZeroUsize; use crate::token::Token; #[derive(Clone, Debug)] pub struct Allocator<T> { data: Vec<Cell<T>>, head: Option<NonZeroUsize>, len: usize } #[derive(...
#[cfg(test)] mod tests { #[test] fn it_works() { assert_eq!(2 + 2, 4); } #[test] fn test_other(){ println!("tt"); } } #[derive(Debug)] struct point{ x:i32, y:i32, } impl Point { fn compaire }
use super::{ error::Result, table_column::{TableColumn, TableOptions, TableOrder}, }; use crate::styles::table::StyleSheet; use iced_graphics::Primitive; use iced_native::{ event::{self, Event}, layout::{Limits, Node}, mouse, text, scrollable, container, Color, Element, Hasher, Clipboard, Vector, Point, Re...
fn main() { let x = 5u32; let y = { let x_squared = x * x; let x_cubed = x_squared * x; // without ;, this is "returned" and assigned to y. x_cubed + x_squared + x }; let z = { // with ;, this is not returned. z is nil // compiler warns unused :') ...
// This file is part of Substrate. // Copyright (C) 2020 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // 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://...
use glob::{glob_with, MatchOptions}; use std::cmp::Ordering; use std::fs; use yaml_rust::YamlLoader; use super::*; use crate::metrics::L2; use crate::DefaultLabeledCloud; /// Given a yaml file on disk, it builds a point cloud. Minimal example below. /// ```yaml /// --- /// data_path: DATAMEMMAP /// labels_path: LABEL...
use std::convert::TryFrom; use std::fmt; use itertools::Itertools; use crate::error::{self, LuaError}; use crate::token::{self, Token}; #[derive(Clone, Debug)] pub struct Name(pub String); impl Name { pub fn as_str(&self) -> &str { self.0.as_str() } } impl fmt::Display for Name { fn fmt(&self, ...
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 use libra_secure_push_metrics::{register_int_counter_vec, IntCounterVec}; use once_cell::sync::Lazy; static STATE_COUNTER: Lazy<IntCounterVec> = Lazy::new(|| { register_int_counter_vec!( "libra_key_manager_state", ...
use std::iter::Iterator; use std::option::Option; use std::option::Option::{None, Some}; use std::prelude::v1::Vec; use nalgebra::{distance, Isometry3, Point3, Vector3}; use crate::geometry_utilities::bounding_tetrahedron; use crate::tetrahedral_mesh::{TetrahedralMesh, VertexKey}; fn build_tetrahedral_mesh(points: &...
#![cfg(not(tarpaulin_include))] /// LevelCacheStore trees have significant differences, so we use separate integration tests /// for their evaluation. Fortunately, only 'with-config' constructors (and couple of specific /// replica-constructors) can be used for instantiation of LevelCacheStore trees, so we group /// t...
use super::super::core::cpu::ArmCpu; use super::super::core::memory::*; use glutin::VirtualKeyCode; #[derive(RustcEncodable, RustcDecodable)] pub struct GbaJoypad { key_input: u16, dirty: bool } // 4000130h - KEYINPUT - Key Status (R) // Bit Expl. // 0 Button A (0=Pressed, 1=Released) // 1 Bu...
mod prompt_nonzero_len; mod prompt_exact_len; mod prompt_multiline; mod prompt_any_len;
#[doc = "Register `SINGLEFIFOCOUNT` reader"] pub struct R(crate::R<SINGLEFIFOCOUNT_SPEC>); impl core::ops::Deref for R { type Target = crate::R<SINGLEFIFOCOUNT_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<SINGLEFIFOCOUNT_SPEC>> for R { #[inline(a...
use std::io::{self, Read}; #[macro_use] extern crate lazy_static; use regex::Regex; const REQUIRED_FIELD: [&str; 7] = ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"]; fn valid_hgt(byr: &str) -> bool { if byr.len() == 5 { let (height, unit) = byr.split_at(3); (150..194).contains(&height.parse::<u...
use super::{Entity, Disposable}; struct Disposables { name: String, image: &'static str, shape: &'static str, freshness: (u8, u8), //current, total weight: i32, }
use crate::init; use crate::interrupt; use core::sync::atomic::{AtomicBool, AtomicU32, Ordering}; static NUM_HARTS: AtomicU32 = AtomicU32::new(1); // boot core static CURRENT_BOOTING: AtomicU32 = AtomicU32::new(0); static CURRENT_BOOT_DONE: AtomicBool = AtomicBool::new(false); pub fn num_harts() -> u32 { NUM_HART...
// This file is part of Substrate. // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // 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.a...
use crate::mat::mat3::Mat3f; use crate::vec::vec3::Vec3; use serde_derive::{Deserialize, Serialize}; use wasm_bindgen::prelude::*; /// Collection of 3d float vectors #[wasm_bindgen(js_name=Array3f, inspectable)] #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Array3f { #[wasm_bindgen(skip)] pub data...
// Copyright 2017 ETH Zurich. All rights reserved. // // 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 //...
use crate::float_near; use crate::vector::{Vec2, Vec3}; use std::cmp; use std::ops; #[repr(C)] #[derive(Debug, Default, Clone, Copy)] pub struct Vec4 { pub x: f32, pub y: f32, pub z: f32, pub w: f32, } impl Vec4 { pub fn new(x: f32, y: f32, z: f32, w: f32) -> Vec4 { Vec4 { x, y, z, w } ...
// Copyright 2017 Mozilla Foundation // Copyright 2017 Google Inc. // // 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 requir...
pub mod disaster; pub mod game; use disaster::Disaster; use disastle_castle_rust::Room; pub use ron; use std::{ fs::File, io::{self, Read}, path::Path, result, }; pub fn load_disasters(path: &Path) -> result::Result<Vec<Disaster>, io::Error> { let mut file = File::open(path)?; let mut content ...
use std::fs; use std::cmp::Ordering; #[derive(Debug)] struct Wire { points: Vec<Point>, } impl Wire { fn add_point(&mut self, point: &Point) { self.points.push(*point); } fn point_exists(&self, point: &Point) -> Result<usize, usize> { self.points.binary_search(&point) } fn ad...
#[derive(Eq, Copy, Clone)] pub struct ID(u32); const GENERATION_SHIFT: u32 = 24; const GENERATION_MASK: u32 = (u8::max_value() as u32) << GENERATION_SHIFT; const MAX_INDEX: u32 = (1 << GENERATION_SHIFT) - 1; impl ID { pub fn new(index: u32, generation: u8) -> ID { if index > MAX_INDEX { panic!...
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // // Portions Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the THIRD-PARTY file. mod gdt; pub mod inte...
use serde::{Deserialize, Serialize}; use crate::schema::users; use crate::utils::regexs; use validator_derive::*; #[derive(Debug, Clone, Queryable, Identifiable, Deserialize)] pub struct User { pub id: i32, pub name: String, pub password: String, pub created_at: chrono::NaiveDateTime, } #[derive(Debu...
use std::ops::Deref; use winapi::{ um::handleapi::{CloseHandle, INVALID_HANDLE_VALUE}, um::winnt::HANDLE }; /// Wraps a windows [HANDLE]. #[derive(Debug, Eq, PartialEq, Clone)] pub struct Handle(RawHandle); /// Wraps the actual [HANDLE] and drop if owned. #[derive(Debug, Eq, PartialEq, Copy, Clone)] struct Ra...
pub mod img_hash { //! # The module brings implementations of different image hashing algorithms. //! //! Provide algorithms to extract the hash of images and fast way to figure out most similar images in //! huge data set. //! //! Namespace for all functions is cv::img_hash. //! //! ### Supported Algorithms...
use std::sync::atomic::{Ordering, AtomicIsize}; use std::ffi::CStr; use std::os::raw::c_char; use std::slice; static FD: AtomicIsize = AtomicIsize::new(0); const TARGET_FILE: &[u8] = b"/dev/i2c-5"; fn timestamp_ms() -> u64 { use std::time::{SystemTime, UNIX_EPOCH}; let now = SystemTime::now(); let elapsed = now...
#![warn(clippy::all)] struct List<T> { element: T, next: Option<Box<Self>>, } impl<T> List<T> { fn push(self, element: T) -> Self { List { element, next: Some(Box::new(self)), } } fn pop(self) -> (T, Option<Self>) { let element = self.element; ...
#[derive(Debug)] struct Point { x: f32, y: f32, } #[derive(Debug)] struct Rectangle { top_left: Point, bottom_right: Point, } fn rect_area(rect: &Rectangle) -> f32 { let Rectangle { top_left: Point { x: x1, y: y1 }, bottom_right: Point { x: x2, y: y2 }, } = rect; (y1 - y2)...
//@revisions: stack tree //@[tree]compile-flags: -Zmiri-tree-borrows // Test what happens when we read parts of a pointer. // Related to <https://github.com/rust-lang/rust/issues/69488>. fn ptr_partial_read() { let x = 13; let y = &x; let z = &y as *const &i32 as *const u8; // This just strips provenan...
use std::convert::From; use std::string::String; #[derive(Debug)] pub struct ParserError { pub message: String, } impl From<std::ffi::OsString> for ParserError { fn from(_: std::ffi::OsString) -> ParserError { ParserError { message: "Invalid data type".to_string(), } } } impl From<std::num::ParseIntError> ...
pub use home_controller::*; mod home_controller;
use serde::{Serialize, Deserialize}; #[derive(Serialize, Deserialize)] pub struct Role { #[serde(rename = "_id")] pub id: String, pub name: String, pub permissions: Vec<String>, }
use ring::aead::{seal_in_place, open_in_place, Algorithm, AES_256_GCM, Nonce, Aad}; use ring::aead::{OpeningKey, SealingKey}; use ring::rand::{SecureRandom, SystemRandom}; use base64; // Keep following in sync with ring configuration static ALGO: &'static Algorithm = &AES_256_GCM; const NONCE_LEN: usize = 12; pub cons...
/*! Units used by CSS */ #[deriving_eq] pub enum Length { Em(float), // normalized to 'em' Px(float), // normalized to 'px' Pt(float) } impl Length { pure fn rel(self) -> float { match self { Em(x) => x, _ => fail!(~"attempted to access relative unit of an absolute leng...
use std::sync::mpsc::Receiver; use std::thread::{spawn, JoinHandle}; pub struct Progression { total: usize, actual: usize, } //reads worth 10 //joins worth 1 //compares worth 2 pub enum Action { Read, Join, Compare, } fn value(a: Action) -> usize { match a { Action::Read => 5, ...
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Pin Control Register n"] pub pcr: [PCR; 32], #[doc = "0x80 - Global Pin Control Low Register"] pub gpclr: GPCLR, #[doc = "0x84 - Global Pin Control High Register"] pub gpchr: GPCHR, _reserved3: [u8; 24usize], ...
/// # vlive-rs /// /// Unofficial Rust crate for VLive API /// /// VLive does not have a public API so some actions may not be be ideal, /// such as having to scape a video page in order to retrieve video data. /// Some functions will make multiple API requests in order to fetch required data. /// use async_trait::asyn...
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use criterion::*; mod yatp_callback { use criterion::*; use std::sync::atomic::*; use std::sync::*; use yatp::task::callback::Handle; pub fn ping_pong(b: &mut Bencher<'_>, ping_count: usize) { let pool = yatp::Builder::new...
use rustc::mir::Local; use rustc::hir::def_id::DefId; use rustc::session::config::Input; use rsmt2::parse::IdentParser; use rsmt2::parse::ModelParser; use crate::exec::driver::analysis_passes::sir::Sir; use rsmt2::Solver; use super::sir::NodeId; use std::collections::HashMap; use rsmt2::errors::SmtRes; use rsmt2::prin...
use crate::rt::{Read, ReadBufCursor, Write}; use bytes::{Buf, Bytes}; use h2::{Reason, RecvStream, SendStream}; use http::header::{HeaderName, CONNECTION, TE, TRAILER, TRANSFER_ENCODING, UPGRADE}; use http::HeaderMap; use pin_project_lite::pin_project; use std::error::Error as StdError; use std::io::{Cursor, IoSlice}; ...
use std::thread; use std::time::Duration; struct ThreadPool { th: std::thread::JoinHandle<()>, } impl ThreadPool { fn start() -> Self { let th = thread::spawn(|| { for i in 0 .. 10 { println!("hi! I'm {}", i); thread::sleep(Duration::from_millis(1)); ...
use tokio::runtime::Runtime; use async_trait::async_trait; #[async_trait] trait Converter { async fn process(&mut self); } struct ConverterA {} #[async_trait] impl Converter for ConverterA { async fn process(&mut self) { println!("process for ConverterA"); //<Self as Converter>::static_common...
#[derive(Debug)] enum FS { Dir(String, Vec<FS>), File(String, usize), } use crate::FS::*; impl FS { fn weight(&self) -> u64 { match self { Dir(_, v) => v.iter().map(|e| e.weight()).sum(), File(_, w) => *w as u64 } } fn find_min(&self, min : u64, current : u...
fn part1(input: &Vec<u64>, preamble_size: usize) -> Option<u64> { let start = std::time::Instant::now(); let window_size = preamble_size; let mut min = 0; let mut max = min + window_size; let mut found_needle; let mut invalid_number: Option<u64> = None; for needle in input[(window_size + 1)....
use cgmath::{ElementWise, Vector2, Vector3}; #[derive(Copy, Clone, Debug)] pub struct RigidBody2D { pub current: Vector3<f32>, pub velocity: Vector3<f32>, pub acceleration: Vector3<f32>, pub drag: Vector3<f32>, pub mass: f32, } impl RigidBody2D { pub fn new() -> Self { RigidBody2D { ...
use crate::secret::Secret; use crate::{KeyId, PublicKey}; use ockam_core::Result; use ockam_core::{async_trait, compat::boxed::Box}; /// Key id related vault functionality #[async_trait] pub trait KeyIdVault { /// Return [`Secret`] for given key id async fn get_secret_by_key_id(&mut self, key_id: &str) -> Resu...
/* * Ory APIs * * Documentation for all public and administrative Ory APIs. Administrative APIs can only be accessed with a valid Personal Access Token. Public APIs are mostly used in browsers. * * The version of the OpenAPI document: v0.0.1-alpha.21 * Contact: support@ory.sh * Generated by: https://openapi-gen...
use crate::errors::{AppErrorType::*, AppError}; use crate::models::{Article, Rest, Ciamis}; use select::document::Document; use select::predicate::{Attr, Class, Name}; use slog::{crit, o, Logger}; pub async fn get_article_asy_syariah(log: Logger) -> Result<Rest, AppError> { let body = reqwest::get("https://asysy...
use std::collections::HashMap; use async_std::stream; use async_trait::async_trait; use serde_derive::{Deserialize, Serialize}; use svc_agent::{ mqtt::{IncomingRequestProperties, ResponseStatus}, Addressable, AgentId, }; use uuid::Uuid; use crate::app::context::Context; use crate::app::endpoint::prelude::*; u...
use intertrait::*; struct Data; #[cast_to] impl Data { fn hello() { println!("hello!"); } } fn main() { let _ = Data; }
/// In the original, this is an enum, (automatically) narrowed down to u8 on assignment. #[repr(u8)] pub enum thinktype { gunthinks = 10, gunthinke = 9, explode = 8, fade = 7, idle = 6, straight = 5, ramdiag = 4, ramstraight = 3, dragoncmd = 2, gargcmd = 1, playercmd = 0, }
use super::super::interconnect::Interconnect; pub struct Ppu; impl Ppu { pub fn new() -> Self { Ppu } pub fn step(&mut self, mem: &mut Interconnect) { } }
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use starcoin_logger::prelude::*; use starcoin_vm_types::account_config::G_ACCOUNT_MODULE; use starcoin_vm_types::errors::VMError; use starcoin_vm_types::vm_status::{AbortLocation, StatusCode, VMStatus}; //should be consistent with Erro...
// Copyright 2021 Contributors to the Parsec project. // SPDX-License-Identifier: Apache-2.0 mod test_create { use crate::common::{create_ctx_with_session, decryption_key_pub}; use std::convert::TryFrom; use tss_esapi::{interface_types::resource_handles::Hierarchy, structures::Auth}; #[test] fn tes...
use i_comparable::IComparableError; use i_shape::IShape; use mat::Mat3x1; use ray::Ray3; #[test] fn test_intersect_ray_ray() { //parallel rays, no intersection { let a = Ray3::init(&[20f64, 0f64, 0f64], &[1f64, 1f64, 1f64]); let b = Ray3::init(&[25f64, 0f64, 0f64], &[1f64, 1f64, 1f64]); ...
pub mod abac; pub mod adapter; pub mod enforcer; pub mod management_api; pub mod rbac_api_test; pub mod rpc_calls;
//! Public-key Authenticated encryption. use std::io; use std::convert::TryFrom; use ::aead::{ AeadCipher, DecryptFail }; use ::kex::KeyExchange; /// `SealedBox` trait. /// /// ``` /// # extern crate rand; /// # #[macro_use] extern crate sarkara; /// # fn main() { /// # use sarkara::aead::{ Ascon, AeadCipher }; /// ...
use thiserror::Error; #[derive(Debug, Error)] pub enum ConsensusError { #[error("insufficient participation")] InsufficientParticipation, #[error("invalid timestamp")] InvalidTimestamp, #[error("invalid sync committee period")] InvalidPeriod, #[error("update not relevant")] NotRelevant,...
use entity_store::*; use entity_id_allocator::EntityIdAllocator; use direction::Direction; use content::actions; use straight_line::InfiniteAbsoluteLineTraverse; #[derive(Debug, Clone, Copy)] pub enum ActionType { Null, Walk(EntityId, Direction), CloseDoor(EntityId), OpenDoor(EntityId), FireBullet(...
use crate::util::helper::{cubic_pulse, length, max, min}; use std::mem::swap; use crate::boundary::SolidBody; use crate::util::occupancy::occupancy; pub struct FluidQuantity { pub src: Vec<f64>, pub dst: Vec<f64>, pub normal_x: Vec<f64>, pub normal_y: Vec<f64>, pub phi: Vec<f64>, pub vo...
use wasm_bindgen::prelude::*; use crate::modules::*; #[wasm_bindgen] pub struct Context{ buffer: Option<Buffer>, frame: Frame, } #[wasm_bindgen] impl Context{ pub fn new(canvas_width:usize,canvas_height:usize)->Context{ Context{ buffer:None, frame: Frame::new(canvas_width...
#[test] fn test_is_positive() { assert 42i8.is_positive(); assert 42i16.is_positive(); assert 42i32.is_positive(); assert 42i64.is_positive(); assert 42i.is_positive(); assert 4.2f32.is_positive(); assert 4.2f64.is_positive(); assert 4.2f.is_positive(); assert (1f32 / 0f32).is_p...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::module::map_err; use futures::future::TryFutureExt; use futures::FutureExt; use network_api::PeerStrategy; use network_p2p_types::peer_id::PeerId; use starcoin_rpc_api::sync_manager::SyncManagerApi; use starcoin_rpc_api::...
use rust_fsm::*; use crate::utils::*; use log::info; #[cfg(target_arch = "x86_64")] use core::arch::x86_64::*; use std::io::BufWriter; use std::fs::File; use std::io::Write; state_machine! { derive(Debug) FSM(initial) start => { next => violation, hasnext => safe, }, safe => { next => st...
// Copyright 2020 WHTCORPS INC. Licensed under Apache-2.0. use std::cmp::Ordering; use fidel_timeshare::ExprType; use milevadb_query_common::Result; use milevadb_query_datatype::codec::mysql::Decimal; use milevadb_query_datatype::codec::Datum; use milevadb_query_datatype::expr::EvalContext; use milevadb_query_normal...
//! # Inlucde NPM //! //! Include Static `npm build` ouput in your rust binary //! When you compile in debug mode the File contents will just be read from disk and not embedded. This can manually be overriden with the `embed` feautere. //! //! The argument path is the ouput directory of the npm build. The parent direct...
use libnl::error::{Error, NetlinkError}; #[derive(Debug)] pub struct NlSock { pub nl_sock: *const nl::nl_sock, } impl NlSock { pub fn new() -> Result<NlSock, Error> { let nl_sock = try!(nl_socket_alloc()); match nl_connect(nl_sock) { Ok(_) => Ok(NlSock { nl_sock: nl_sock }), ...
// aarch64 pub const KERNEL_HEAP_SIZE: usize = 16 * 1024 * 1024; // 32 MB #[inline] pub fn phys_memory_base() -> usize { kernel_hal::arch::config::PHYS_MEMORY_BASE }
/* * Copyright (c) 2020 - 2021. Shoyo Inokuchi. * Please refer to github.com/shoyo/jindb for more information about this project and its license. */ use crate::buffer::{BufferError, BufferManager}; use crate::constants::RelationIdT; use crate::relation::heap::Heap; use crate::relation::Relation; use crate::relatio...
use std::collections::HashMap; #[test] fn test_default_hash_map() { let mut map = HashMap::<u32, u32>::new(); let generate_value = |x: u32| -> u32 { x * 8 / 5 }; let key_limit = 2_000u32; for i in 0..key_limit { map.insert(i, generate_value(i)); } assert_eq!(key_limit as usize, map.le...
use core::marker::PhantomData; use super::io::Io; #[derive(Copy, Clone)] pub struct PortIO<T> { port: u16, //IO Port number value: PhantomData<T>, // Do not hold this value yourself, only hint for the compiler } impl<T> PortIO<T> { pub const fn new(port: u16) -> Self { PortIO::<T> { p...
use parity_scale_codec::Encode; use parity_scale_codec_derive::{Encode, Decode}; use super::{build_solidity, first_error, no_errors}; use solang::{parse_and_resolve, Target}; #[test] fn various_constants() { #[derive(Debug, PartialEq, Encode, Decode)] struct FooReturn(u32); #[derive(Debug, PartialEq, Enc...
extern crate docopt; extern crate sidekiq; extern crate rustc_serialize; extern crate env_logger; #[cfg(feature="flame_it")] extern crate flame; use sidekiq::*; use docopt::Docopt; #[cfg(feature="flame_it")] use std::fs::File; const USAGE: &'static str = r#"Sidekiq Usage: sidekiq [-r <redis>] [-n <namespace>] [-...
use nom::IResult; use failure::Error; use nom; use nom::digit; use crate::filter::{Filter, FilterArg, SizeUnit}; use std::str::{self, FromStr}; fn url(input: &str) -> IResult<&str, FilterArg> { let mut result = String::new(); let mut remaining = input; let mut stack = 0; while let Some(n) = remaining.f...
use std::env; use std::fs::File; use std::io::{BufRead, BufReader, Result}; fn input(filename: &str) -> Result<Vec<Vec<char>>> { let mut result: Vec<Vec<char>> = Vec::new(); let file = File::open(filename)?; let reader = BufReader::new(file); for (i, line) in reader.lines().enumerate() { resul...
pub mod generator;