text stringlengths 8 4.13M |
|---|
extern crate lazy_static;
pub mod log;
pub mod stream;
pub mod ui;
|
//
use std::fmt;
use vec3::*;
#[derive(Copy, Clone, Debug)]
pub struct Ray {
a: Vec3,
b: Vec3,
}
impl Ray {
pub fn new(ia: Vec3, ib: Vec3) -> Ray { Ray { a:ia, b:ib } }
pub fn origin(&self) -> Vec3 { self.a }
pub fn direction(&self) -> Vec3 { self.b }
pub fn point_at_parameter(&self, t: f32) ... |
use crate::prelude::*;
use byteorder::{LittleEndian, ReadBytesExt};
pub struct X11 {
pub conn: xcb::Connection,
pub preferred_screen: i32,
}
impl X11 {
pub fn connect() -> Self {
let (conn, preferred_screen) = xcb::Connection::connect(None)
.expect("Could not connect to X server");
... |
#[cfg(test)]
mod tests {
use lib::get_missing_number;
#[test]
fn test_get_missing_number() {
let array: [u32; 4] = [4, 2, 1, 5];
assert_eq!(get_missing_number(&array), 3);
}
}
|
mod sequential_allocation;
use std::cmp::Ordering;
#[derive(Debug,PartialEq)]
pub enum LinearListError {
OutOfRange,
MemoryOverflow,
}
pub type LinearListResult<T> = Result<T, LinearListError>;
trait LinearList {
type Item;
fn length(&self) -> usize;
fn get(&self, pos: usize) -> Option<&Self::... |
//! Allocator logging.
//!
//! This allows for detailed logging for `ralloc`.
/// Log to the appropriate source.
///
/// The first argument defines the log level, the rest of the arguments are just `write!`-like
/// formatters.
#[macro_export]
macro_rules! log {
(INTERNAL, $( $x:tt )*) => {
log!(@["INTERNA... |
use wasm_bindgen::prelude::*;
#[wasm_bindgen(module = "/src/imports.js")]
extern {
#[wasm_bindgen]
pub fn log(s: &str);
#[wasm_bindgen]
pub fn now() -> f64;
}
#[wasm_bindgen]
pub fn demo_main(n: u64) -> u64 {
let start = now();
let mut gen = PrimeGenerator::new();
let res = gen.nearest_pr... |
use lib::*;
/// Param type subset generatable by WASM contract
#[derive(Debug, Clone)]
pub enum ParamType {
// Unsigned integer (mapped from u32)
U32,
// Unsigned integer (mapped from u64)
U64,
// Signed integer (mapped from i32)
I32,
// Signed integer (mapped from i64)
I64,
// Address (mapped from H160/Addre... |
struct SomeStruct;
fn uses_it(arg: &SomeStruct) {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test1() {
let val = SomeStruct;
uses_it(&val);
}
}
|
//! Traits for abstracting over different Ethereum 2.0 network protocols.
//!
//! Currently only [`BeaconBlock`]s and beacon [`Attestation`]s can be gossiped, because those are
//! the only types of objects supported by Hobbits. Methods for [other types of objects] will be
//! added later.
//!
//! [`Attestation`]: type... |
#[doc = "Register `ICR` writer"]
pub type W = crate::W<ICR_SPEC>;
#[doc = "Field `SEIF` writer - SEIF"]
pub type SEIF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `XONEIF` writer - Execute-only execute-Never Error Interrupt Flag clear"]
pub type XONEIF_W<'a, REG, const O: u8> = crate::BitWrite... |
pub mod cr {
pub mod en1 {
pub fn get() -> u32 {
unsafe {
core::ptr::read_volatile(0x40007400u32 as *const u32) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40007400u32 as *const u32);
... |
#[doc = "Register `TDH2R` reader"]
pub type R = crate::R<TDH2R_SPEC>;
#[doc = "Register `TDH2R` writer"]
pub type W = crate::W<TDH2R_SPEC>;
#[doc = "Field `DATA4` reader - DATA4"]
pub type DATA4_R = crate::FieldReader;
#[doc = "Field `DATA4` writer - DATA4"]
pub type DATA4_W<'a, REG, const O: u8> = crate::FieldWriter<'... |
extern crate chrono;
use chrono::{DateTime, Datelike, TimeZone, Utc};
use std::cmp;
/// This trait defines functions which allow for year calculations between two dates. As
/// the standard DateTime, Date, and Duration types in chrono are unable to do this (due to
/// complications with leap-years, etc.), a utility ... |
//! Link: https://adventofcode.com/2019/day/6
//! Day 6: Universal Orbit Map
//!
//! You've landed at the Universal Orbit Map facility on Mercury.
//! Because navigation in space often involves transferring between orbits,
//! the orbit maps here are useful for finding efficient routes between,
//! for example, you ... |
//! Inter-Integrated Circuit (I2C) bus
//!
//! This is a master-mode-only implementation of I2C.
//!
//! Take care to note that the `write` and `write_read` methods accept an address argument that is
//! _not shifted on your behalf_.
//!
//! ```
//! use stm32l0x1_hal;
//!
//! let d = stm32l0x1_hal::stm32l0x1::Periphera... |
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Instant;
use futures::channel::mpsc;
use futures::sink::Sink;
use futures::stream::Stream;
use futures::{ready, SinkExt, StreamExt};
use bytes::Bytes;
use failure::Error;
use crate::{Connection, PackChan, SenderSink, SrtCongestCtrl};
type BoxConnStr... |
//! The Equinox stochastic photon mapper, see the README for more information.
#![allow(clippy::module_inception)]
#![forbid(unsafe_code, while_true)]
mod device {
pub mod camera;
pub mod device;
pub mod display;
pub mod environment;
pub mod geometry;
pub mod instance;
pub mod integrator;
... |
// These are for making everything in `src/commands/*`
// available in `src/main.rs` via `mod commands;`.
// (Pssst, don't forget to `use` them as well.)
pub mod about;
pub mod date;
pub mod embed;
pub mod fortune;
pub mod git;
pub mod hmm;
pub mod math;
pub mod noice;
pub mod projects;
pub mod quit;
pub mod rng;
pub m... |
use super::*;
use crate::helpers::SolomonBuilder;
use crate::solomon::{SolomonProblem, SolomonSolution};
use std::sync::Arc;
use vrp_core::construction::heuristics::InsertionContext;
use vrp_core::solver::mutation::{Recreate, RecreateWithCheapest};
use vrp_core::solver::population::Elitism;
use vrp_core::solver::Refine... |
pub use wasm_bindgen::{self, prelude::*, JsCast};
pub mod element;
mod dom;
mod console;
mod futures_signals_ext;
pub use futures_signals_ext::{MutableExt, MutableVecExt};
pub use element::*;
pub use dom::{window, document};
pub use futures_signals::{
self,
map_mut,
map_ref,
signal::{Mutable, Signal,... |
use crate::rvals::{Result, SteelVal};
// TODO
pub const fn _new_void() -> SteelVal {
SteelVal::Void
}
// TODO
pub const fn _new_true() -> SteelVal {
SteelVal::BoolV(true)
}
// TODO
pub const fn _new_false() -> SteelVal {
SteelVal::BoolV(false)
}
#[derive(Debug)]
pub struct Env {
pub(crate) bindings_... |
use crate::http::client::Client;
use std::borrow::Borrow;
use crate::api::models::lock::Lock;
use crate::api::models::transaction::Transaction;
use crate::api::models::wallet::Wallet;
use crate::api::Result;
use std::collections::HashMap;
pub struct Wallets {
client: Client,
}
impl Wallets {
pub fn new(clien... |
use super::*;
use crate::request_options::LeaseId;
use crate::util::HeaderMapExt;
use crate::*;
use crate::{RequestId, SessionToken};
use chrono::{DateTime, FixedOffset, Utc};
use http::header::{DATE, ETAG, LAST_MODIFIED};
#[cfg(feature = "enable_hyper")]
use http::status::StatusCode;
use http::HeaderMap;
#[cfg(feature... |
use regex::Regex;
use std::env;
use std::fs;
use std::fs::File;
use std::fs::OpenOptions;
use std::io::Read;
use std::io::Write;
use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};
fn read_ignoring_utf_errors(path: &PathBuf) -> String {
let mut f =
File::open(path).unwrap_or_else(|_| panic!("M... |
mod asm;
mod bus;
mod cpu;
mod dec;
mod isa;
mod mon;
mod sys;
fn main() {
// syntax brevity for Assembler args
use asm::{branch, label, val, Operand::*};
// assemble a nonsense demo program using diverse instructions
let org: u16 = 0x1234;
let mut asm = asm::Assembler::new();
asm.org(org)
... |
//! Encoding of a binary [`Context`].
//!
//! ```text
//!
//! +------------------+-----------------+-----------------+
//! | | | |
//! | Transaction Id | Current Layer | Current State |
//! | (Hash) | (u64) | (State) |
//! | ... |
use crate::accounts_index::{AccountMapEntry, IsCached, WriteAccountMapEntry};
use solana_sdk::pubkey::Pubkey;
use std::collections::{
hash_map::{Entry, Keys},
HashMap,
};
use std::fmt::Debug;
type K = Pubkey;
// one instance of this represents one bin of the accounts index.
#[derive(Debug, Default)]
pub struc... |
use super::sched::*;
use crate::lib::*;
global_asm!(include_str!("../arch/riscv/kernel/head.S"));
#[repr(C)]
#[derive(Clone, Copy)]
pub struct Context {
pub regs: thread_struct,
pub status: u64,
pub epc: u64,
}
extern "C" {
fn trap_m();
fn trap_s();
}
global_asm!(include_str!("../arch/riscv/kern... |
#[doc = "Register `HSEM_IPIDR` reader"]
pub type R = crate::R<HSEM_IPIDR_SPEC>;
#[doc = "Field `IPID` reader - IPID"]
pub type IPID_R = crate::FieldReader<u32>;
impl R {
#[doc = "Bits 0:31 - IPID"]
#[inline(always)]
pub fn ipid(&self) -> IPID_R {
IPID_R::new(self.bits)
}
}
#[doc = "HSEM IP ident... |
//! Build keyboard events.
mod event;
pub use event::Event;
pub use iced_core::keyboard::{KeyCode, ModifiersState};
|
use super::*;
pub use V8::Private;
impl Private {
pub fn for_api(name: &str) -> Local<Private> {
unsafe {
V8::Private_ForApi(Isolate::raw(), V8::String::new_from_slice(name).into()).into()
}
}
}
|
use htmldsl::attributes;
use htmldsl::elements;
use htmldsl::styles;
use htmldsl::units;
use htmldsl::{TagRenderableIntoElement, TagRenderableStyleSetter};
use crate::models;
pub fn maybe_append<T>(mut vec: Vec<T>, maybe: Option<T>) -> Vec<T> {
match maybe {
Some(v) => {
vec.push(v);
... |
// ===============================================================================
// Authors: AFRL/RQQA
// Organization: Air Force Research Laboratory, Aerospace Systems Directorate, Power and Control Division
//
// Copyright (c) 2017 Government of the United State of America, as represented by
// the Secretary of th... |
use std::sync::{
Arc,
atomic::{
Ordering,
AtomicUsize
}
};
use crossbeam::{
queue::ArrayQueue,
channel::{
self,
Sender,
Receiver
}
};
#[derive(PartialEq, Debug)]
pub enum DonationResult {
Donated,
NotDonated
}
#[derive(Clone)]
pub struct Beggar... |
#[doc = "Register `WTCR` reader"]
pub type R = crate::R<WTCR_SPEC>;
#[doc = "Register `WTCR` writer"]
pub type W = crate::W<WTCR_SPEC>;
#[doc = "Field `IMODE` reader - IMODE"]
pub type IMODE_R = crate::FieldReader;
#[doc = "Field `IMODE` writer - IMODE"]
pub type IMODE_W<'a, REG, const O: u8> = crate::FieldWriter<'a, R... |
use std::fs;
use std::slice;
use tensorflow::Graph;
use tensorflow::SavedModelBundle;
use tensorflow::SessionOptions;
use tensorflow::SessionRunArgs;
use tensorflow::Tensor;
fn main() {
// 加载模型
let export_dir = "pys/resnet50";
let mut graph = Graph::new();
let opts = SessionOptions::new();
let sm =... |
mod add;
mod generate;
mod report;
mod run;
mod update;
pub use add::*;
pub use generate::*;
pub use report::*;
pub use run::*;
pub use update::*;
|
#![no_main]
#![no_std]
extern crate cortex_m_rt;
extern crate panic_halt;
use cortex_m_rt::{entry, interrupt};
#[entry]
fn foo() -> ! {
loop {}
}
#[interrupt] //~ ERROR failed to resolve: use of undeclared crate or module `interrupt`
fn USART1() {}
|
#[doc = "Register `TIM12_CCER` reader"]
pub type R = crate::R<TIM12_CCER_SPEC>;
#[doc = "Register `TIM12_CCER` writer"]
pub type W = crate::W<TIM12_CCER_SPEC>;
#[doc = "Field `CC1E` reader - CC1E"]
pub type CC1E_R = crate::BitReader;
#[doc = "Field `CC1E` writer - CC1E"]
pub type CC1E_W<'a, REG, const O: u8> = crate::B... |
use crate::faucet_config;
use base64::decode;
use faucet_config::{load_faucet_conf, FaucetConf};
use faucet_proto::proto::faucet::{
create_sg_faucet, FaucetRequest as FaucetRequestProto, SgFaucet,
};
use faucet_proto::FaucetRequest;
use grpc_helpers::{provide_grpc_response, spawn_service_thread_with_drop_closure, S... |
use log::error;
use rand::Rng;
use serenity::{
framework::standard::{macros::command, Args, CommandResult},
model::channel::Message,
prelude::*,
};
#[command]
#[description = "Bot will generate a random number between min and max and reply with the result."]
#[usage = "min max"]
#[example = "-999 999"]
fn ... |
fn main() {
let mut line = String::new();
std::io::stdin().read_line(&mut line).unwrap();
let nums = line
.trim()
.split_whitespace()
.into_iter()
.map(|c| c.parse::<f64>().unwrap())
.collect::<Vec<_>>();
println!(
"{}",
((nums[0] - nums[2]).powf(2... |
#[macro_use]
extern crate lazy_static;
extern crate regex;
use regex::Regex;
use std::cmp::{max, min};
const INPUT: &str = include_str!("../input.txt");
struct Reindeer {
name: String,
speed: u32,
duration: u32,
rest: u32,
}
impl Reindeer {
fn from_str(input: &str) -> Self {
lazy_static!... |
use std::fmt;
#[derive(Clone, Copy, Debug)]
pub struct ChunkHeader {
offset: u64,
header_size: u16,
chunk_size: u32,
chunk_type: u16,
}
impl ChunkHeader {
pub fn new(offset: u64, header_size: u16, chunk_size: u32, chunk_type: u16) -> Self {
Self {
offset,
header_siz... |
use SafeWrapper;
use ir::{User, Instruction, Value, TerminatorInst, Block};
use sys;
use std::ptr;
/// A conditional or unconditional branch.
pub struct BranchInst<'ctx>(TerminatorInst<'ctx>);
impl<'ctx> BranchInst<'ctx>
{
/// Creates an unconditional branch.
pub fn unconditional(destination: &Block) -> Self... |
#![deny(
missing_debug_implementations,
trivial_numeric_casts,
unstable_features,
unused_import_braces,
unused_qualifications
)]
extern crate clap;
extern crate notify;
extern crate hyper;
extern crate futures;
extern crate tempdir;
extern crate reqwest;
extern crate pbr;
extern crate libflate;
ext... |
//! Get info on your direct messages.
use rtm::{Cursor, Im, Message, ThreadInfo};
use timestamp::Timestamp;
/// Close a direct message channel.
///
/// Wraps https://api.slack.com/methods/im.close
#[derive(Clone, Debug, Serialize, new)]
pub struct CloseRequest {
/// Direct message channel to close.
pub chann... |
fn revrot(s: &str, c: usize) -> String {
if s.len() < c || s.is_empty() || c == 0 { return "".to_string() }
let (cur, rest) = s.split_at(c);
let sum: u32 = cur.chars().map(|c| c.to_digit(10).unwrap().pow(3)).sum();
let result = match sum % 2 {
0 => cur.chars().rev().collect(),
_ => String::from(&cur[... |
#[doc = "Register `SR` reader"]
pub type R = crate::R<SR_SPEC>;
#[doc = "Field `TAMP1F` reader - TAMP1 detection flag This flag is set by hardware when a tamper detection event is detected on the TAMP1 input."]
pub type TAMP1F_R = crate::BitReader;
#[doc = "Field `TAMP2F` reader - TAMP2 detection flag This flag is set ... |
//! <https://github.com/EOSIO/eosio.cdt/blob/4985359a30da1f883418b7133593f835927b8046/libraries/eosiolib/contracts/eosio/action.hpp#L249-L274>
use alloc::string::{String, ToString};
use alloc::{format, vec};
use alloc::vec::Vec;
use core::str::FromStr;
use codec::{Encode, Decode};
use crate::{
AccountName, ActionNa... |
extern crate failure;
#[macro_use]
extern crate failure_derive;
#[macro_use]
extern crate nom;
#[macro_use]
extern crate log;
pub mod errors;
pub mod keywords;
pub mod parser;
pub mod scc;
pub mod types;
|
//! `StatusReporter` is to expose the necessary operational information
//! to the outside world.
use crate::prelude::*;
use std::convert::TryFrom;
/// # Required features
///
/// This function requires the `status-report` feature of the `delay_timer`
/// crate to be enabled.
#[derive(Debug, Clone)]
pub struct StatusR... |
#[doc = "Register `IOPRSTR` reader"]
pub type R = crate::R<IOPRSTR_SPEC>;
#[doc = "Register `IOPRSTR` writer"]
pub type W = crate::W<IOPRSTR_SPEC>;
#[doc = "Field `GPIOARST` reader - I/O port A reset This bit is set and cleared by software."]
pub type GPIOARST_R = crate::BitReader;
#[doc = "Field `GPIOARST` writer - I/... |
println!("--output--");
if let Some(arg) = std::env::args().skip(1).next() {
println!("Argument: {}", arg);
}
|
use crate::prelude::*;
pub fn visibility_system(world: &mut World) {
let player_entity = world.resource_entity::<Player>().ok();
for (entity, (viewshed, pos)) in world.query::<(&mut Viewshed, &Position)>().into_iter() {
if viewshed.dirty {
if let Some((_, map)) = world.query::<&mut TileMap... |
#[doc = "Register `AHB3RSTR` reader"]
pub type R = crate::R<AHB3RSTR_SPEC>;
#[doc = "Register `AHB3RSTR` writer"]
pub type W = crate::W<AHB3RSTR_SPEC>;
#[doc = "Field `MDMARST` reader - MDMA block reset"]
pub type MDMARST_R = crate::BitReader<MDMARST_A>;
#[doc = "MDMA block reset\n\nValue on reset: 0"]
#[derive(Clone, ... |
#[cfg(target_os = "linux")]
fn are_you_on_linux() {
println!("You are running linux!")
}
#[cfg(not(target_os = "linux"))]
fn are_you_on_linux() {
println!("You are *not* running linux!")
}
mod tests {
use crate::cfg::are_you_on_linux;
#[test]
fn main() {
are_you_on_linux();
print... |
use std::io::{stdout, Read, Write};
use std::fs::File;
use indicatif::{ProgressBar, ProgressStyle};
use curl::easy::{Easy, List};
use memmap::MmapOptions;
use serde_json::Value as JSONValue;
use error::OpenstackError;
use client::Response;
pub fn upload_to_object_store(
file: &mut File,
object_store_url: &s... |
use ndarray::prelude::*;
use ndarray_rand::rand::{thread_rng, Rng};
use ndarray_rand::rand_distr::WeightedIndex;
use ndarray_stats::QuantileExt;
use crate::rl::prelude::*;
/// Allows Agents to be trained using a genetic algorithm
pub trait Evolve {
fn mutate(&mut self, mutation_rate: f64);
fn crossover(&self,... |
#[doc = "Register `BTR` reader"]
pub type R = crate::R<BTR_SPEC>;
#[doc = "Register `BTR` writer"]
pub type W = crate::W<BTR_SPEC>;
#[doc = "Field `BRP` reader - BRP"]
pub type BRP_R = crate::FieldReader<u16>;
#[doc = "Field `BRP` writer - BRP"]
pub type BRP_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 10, O, ... |
pub use generated::*;
use crate::demo::message::bspdecal::*;
use crate::demo::message::classinfo::*;
use crate::demo::message::gameevent::*;
use crate::demo::message::packetentities::*;
use crate::demo::message::setconvar::*;
use crate::demo::message::stringtable::*;
use crate::demo::message::tempentities::*;
use crat... |
#[doc = "Writer for register RPR"]
pub type W = crate::W<u32, super::RPR>;
#[doc = "Register RPR `reset()`'s with value 0xff"]
impl crate::ResetValue for super::RPR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0xff
}
}
#[doc = "Write proxy for field `PRIORITY`"]
pub stru... |
use crate::PyProjectToml;
use anyhow::{bail, format_err, Context, Result};
use fs_err as fs;
use indexmap::IndexMap;
use pep440_rs::{Version, VersionSpecifiers};
use pep508_rs::{MarkerExpression, MarkerOperator, MarkerTree, MarkerValue, Requirement};
use pyproject_toml::License;
use regex::Regex;
use serde::{Deserializ... |
#[allow(unused_imports)]
#[macro_use]
extern crate clap;
#[allow(unused_imports)]
#[macro_use]
extern crate failure;
use failure::Error;
extern crate config;
extern crate serde;
#[allow(unused_imports)]
#[macro_use]
extern crate serde_derive;
extern crate serde_yaml;
extern crate ubackup;
use ubackup::Settings;
use... |
//! This is a platform agnostic Rust driver for the HDC2080, HDC2021 and
//! HDC2010 low-power humidity and temperature digital sensor using
//! the [`embedded-hal`] traits.
//!
//! [`embedded-hal`]: https://github.com/rust-embedded/embedded-hal
//!
//! This driver allows you to:
//! - Set the measurement mode. Tempera... |
use cgmath::Vector2;
pub const SCREEN_SIZE: Vector2<u32> = Vector2 {
x: 1024,
y: 768,
};
pub const GAME_SIZE: Vector2<u32> = Vector2 {
x: 1024,
y: 768,
};
|
use super::*;
/// A planning element.
///
/// # Semantics
///
/// Contains the deadline, scheduled and closed timestamps for a headline. All are optional.
///
/// # Syntax
///
/// Planning lines are context-free.
///
/// ```text
/// KEYWORD: TIMESTAMP
/// ```
///
/// `KEYWORD` is one of `DEADLINE`, `SCHEDULED` or `CLO... |
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::{
convert, fmt, mem,
net::{Ipv4Addr, Ipv6Addr},
str,
sync::Arc,
};
use chrono::prelude::*;
use chrono_tz::Tz;
use either::Either;
use crate::types::{
column::datetime64::to_datetime,
decimal::{Decimal, NoBits},
DateConv... |
/// Tile in the Minesweeper grid, packed into a single byte.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub(super) struct PackedTile(pub(super) u8);
impl Default for PackedTile {
fn default() -> Self {
Tile::default().pack()
}
}
impl PackedTile {
/// Unpacks the `Tile` from a single byte.
... |
use common::error::Error;
use common::result::Result;
#[derive(Debug, Clone)]
pub struct Synopsis {
synopsis: String,
}
impl Synopsis {
pub fn new<S: Into<String>>(synopsis: S) -> Result<Self> {
let synopsis = synopsis.into();
if synopsis.len() < 4 {
return Err(Error::new("synopsi... |
/*
SPDX-License-Identifier: Apache-2.0 OR MIT
Copyright 2020 The arboard contributors
The project to which this file belongs is licensed under either of
the Apache 2.0 or the MIT license at the licensee's choice. The terms
and conditions of the chosen license apply to this file.
*/
use super::common::{Error, ImageDa... |
use crate::{BoxFuture, Result};
pub trait Init<'a, P>: Sized + Send + Sync {
fn init(provider: &'a P) -> BoxFuture<'a, Result<Self>>;
}
|
use crate::{NumBytes, Read, Write};
/// TODO Read, Write, `NumBytes` needs a custom implementation based on `fixed_bytes`
#[derive(Read, Write, NumBytes, Default, Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[eosio_core_root_path = "crate"]
pub struct Checksum160([u8; 20]);
impl Checksum160 {
pub f... |
///// chapter 4 "structuring data and matching patterns"
///// program section:
//
fn main() {
let magic_numbers = vec![7_i32, 42, 47, 45, 54];
///// only the items 42, 47 and 45
//
let slc = &magic_numbers[1..4];
println!("{:?}", slc);
}
///// output should be:
/*
*/// end of output
|
pub fn build_message(opt_name: Option<&str>) -> String {
let name = opt_name.unwrap_or("World");
return format!("Hello {}!", name);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn build_message_none() {
let message = build_message(None);
assert_eq!(message, "Hello World!");
... |
use webrender::api::units::LayoutPixel;
use webrender::api::*;
use rpdf_document::Page;
use rpdf_graphics::{text, GraphicsObject};
use super::text::FontRenderContext;
pub struct PageRenderer<'a> {
page: &'a Page,
}
impl<'a> PageRenderer<'a> {
pub fn new(page: &'a Page) -> Self {
Self { page }
}
... |
#[doc = "Register `CR1` reader"]
pub type R = crate::R<CR1_SPEC>;
#[doc = "Register `CR1` writer"]
pub type W = crate::W<CR1_SPEC>;
#[doc = "Field `LPDS` reader - Low-power deep sleep"]
pub type LPDS_R = crate::BitReader;
#[doc = "Field `LPDS` writer - Low-power deep sleep"]
pub type LPDS_W<'a, REG, const O: u8> = crat... |
#[doc = "Register `TIM7_CR1` reader"]
pub type R = crate::R<TIM7_CR1_SPEC>;
#[doc = "Register `TIM7_CR1` writer"]
pub type W = crate::W<TIM7_CR1_SPEC>;
#[doc = "Field `CEN` reader - Counter enable CEN is cleared automatically in one-pulse mode, when an update event occurs."]
pub type CEN_R = crate::BitReader;
#[doc = "... |
//! Code Expressions.
use std::fmt;
use std::rc::Rc;
// TODO: Use real things instead of scaffolding.
//use crate::ir::immediates::{Imm64, Offset32};
//use crate::ir::{ExternalName, Type};
//use crate::isa::TargetIsa;
#[derive(Clone, Debug, Hash, Eq, PartialEq, Copy)]
pub enum Type {
I32,
I64,
}
pub type Offs... |
extern crate hostname;
extern crate bufstream;
use std::error::Error;
use std::net::TcpStream;
use std::io::{self, Write, BufRead, stderr};
use bufstream::BufStream;
use std::time::{SystemTime, UNIX_EPOCH};
use std::fs::OpenOptions;
enum SmtpState {
INIT,
READY,
MAIL,
RCPT,
DATA,
}
#[derive(Debug... |
use std::fs::File;
use std::io::Write;
fn main() {
// 1バイトずつ書き出す
let path = "sample.txt" ;
let mut file = File::create( path )
.expect("file not found.");
let s = "hello rust world.\n";
for it in s.as_bytes() {
file.write(&[*it])
.expect("cannot write.");
let ch ... |
pub use rusqlite_types::*;
|
use itertools::Itertools;
use std::collections::HashMap;
#[derive(Copy, Clone, Eq, PartialEq)]
pub enum Tile {
Empty,
Wall,
Block,
Paddle,
Ball,
}
impl Tile {
fn new(tile_id: i64) -> Tile {
match tile_id {
0 => Tile::Empty,
1 => Tile::Wall,
2 => Tile... |
use structopt::StructOpt;
use std::path::PathBuf;
#[derive(Debug, StructOpt)]
#[structopt(name = "Pyschedelic image generator", about = "Generate random psychedelic images")]
pub struct Opt {
#[structopt(short = "s", long = "set-wallpaper")]
pub wallpaper: bool,
#[structopt(short = "w", long = "width", de... |
fn main() {
let some_number = Some(5);
let some_string = Some("a string");
// Using none requires telling the compiler the type
let absent_number: Option<i32> = None;
let x: i8 = 5;
let y: Option<i8> = Some(5);
// Can't add an i8 to an Option<i8>
// the trait `std::ops::Add<std::opt... |
#![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 CloudError {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<CloudErrorBody>,
... |
use std::str;
use std::io::BufRead;
use std::collections::HashMap;
use quick_xml::{XmlReader, Element, Event};
use error::Error;
use extension::{Extension, ExtensionMap};
pub trait FromXml: Sized {
fn from_xml<R: ::std::io::BufRead>(mut reader: XmlReader<R>,
element: Elemen... |
use std::{thread, time};
pub use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use std::io::{Cursor, Seek, SeekFrom};
use std::collections::HashMap;
pub use spacepacket::SpacePacket;
extern crate sys_info;
use serde_json;
use Config;
pub enum HkCmds {
ShutdownCommand,
SleepCommand{interval: u16},
... |
use crate::object::*;
use crate::value::*;
use crate::vtable::*;
use crate::*;
pub static ARRAY_VTBL: VTable = VTable {
element_size: 8,
instance_size: 0,
parent: None,
lookup_fn: Some(array_lookup),
index_fn: None,
calc_size_fn: Some(determine_array_size),
apply_fn: None,
destroy_fn: No... |
use std::{mem, ptr};
use std::fs::File;
use std::io::{Read, Seek, SeekFrom, Write};
use super::avl;
use super::block_ptr::BlockPtr;
use super::dvaddr::DVAddr;
use super::from_bytes::FromBytes;
use super::lzjb;
use super::uberblock::Uberblock;
use super::zfs;
pub const NUM_TYPES: usize = 6;
pub const NUM_TASKQ_TYPES: ... |
mod connections;
mod connection;
pub use self::connections::*;
pub use self::connection::*;
|
use crate::binds::BindCount;
use crate::binds::{BindsInternal, CollectBinds};
use crate::from::FromClause;
use crate::{filter::Filter, WriteSql};
use extend::ext;
use std::fmt::{self, Write};
#[derive(Debug, Clone)]
pub enum Join<T> {
Known {
kind: JoinKind,
from: FromClause<T>,
filter: Fil... |
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use fermium::{error::*, events::*, video::*, *};
use gl46::*;
fn main() {
unsafe {
SDL_Init(SDL_INIT_VIDEO);
// 0 for success, negative for error
assert_eq!(0, SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4));
assert_eq!(0, SDL_... |
use scanlex::ScanError;
use std::error::Error;
use std::fmt;
#[derive(Debug)]
pub struct DateError {
details: String,
}
impl fmt::Display for DateError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,"{}",self.details)
}
}
impl Error for DateError {}
pub type DateResult<T> = Re... |
//! Representation of the S-expression tree.
#![deny(missing_docs)]
#![deny(unsafe_code)]
use std::str::FromStr;
use std::fmt::{self, Display, Debug, Formatter};
use std::ops::Deref;
/**
* A single values with symbols represented using `String`.
*
* ```rust
* use atoms::StringValue;
*
* let int = StringValue::... |
//! Toast Box
//!
//! A widget represent a message box
use druid::{
lens::{self, LensExt},
BoxConstraints, Color, Data, Env, Event, EventCtx, LayoutCtx, PaintCtx, Point, Rect,
RenderContext, Size, UnitPoint, UpdateCtx, Widget, WidgetPod,
};
use druid::{
widget::{Align, Label, List, WidgetExt},
Life... |
extern crate regex;
extern crate gtk;
extern crate image;
extern crate imageproc;
extern crate rusttype;
extern crate conv;
extern crate webbrowser;
use regex::Regex;
use gtk::*;
mod decoder;
mod decoder_class;
mod decoder_usecase;
mod gui;
mod visuals;
mod visuals_class;
mod visuals_case;
mod decoding_to_visual;
f... |
use crate::{
document::{PAGE_MAX, PAGE_MIN},
id::Id,
};
use rand::{thread_rng, Rng};
use serde::{Deserialize, Serialize};
use std::cmp::{max, min, Ordering};
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct Position(pub Vec<Id>);
impl Ord for Position {
fn cmp(&self, other: &Self)... |
pub fn reply(message: &str) -> &str {
let trimmed = message.trim();
match trimmed {
trimmed if trimmed.is_empty() => "Fine. Be that way!",
trimmed if is_question(trimmed) && is_yell(trimmed) => "Calm down, I know what I'm doing!",
trimmed if is_question(trimmed) => "Sure.",
trimm... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.