text
stringlengths
8
4.13M
//! Reading `.hltas` files. use std::{ fmt::{self, Display, Formatter}, num::NonZeroU32, str::FromStr, }; use nom::{ self, bytes::complete::tag, character::complete::{digit0, line_ending, multispace0, one_of, space1}, combinator::{all_consuming, map_res, opt, recognize, verify}, error:...
mod item; mod repository; pub use item::*; pub use repository::*; use common::error::Error; use common::model::{AggregateRoot, StringId}; use common::result::Result; use shared::event::CollectionEvent; use crate::domain::author::AuthorId; use crate::domain::publication::{Header, Publication, PublicationId}; pub type...
pub(crate) mod network_manager;
extern crate oxygengine_core as core; pub mod device; pub mod resource; pub mod system; pub mod prelude { pub use crate::{device::*, resource::*, system::*}; } use crate::{ resource::InputController, system::{input_system, InputSystemResources}, }; use core::{ app::AppBuilder, ecs::pipeline::{Pip...
use hacspec_dev::prelude::*; use hacspec_lib::prelude::*; use unsafe_hacspec_examples::aes_gcm::*; struct AeadTestVector<'a> { key: &'a str, nonce: &'a str, msg: &'a str, aad: &'a str, exp_cipher: &'a str, exp_mac: &'a str, } const KAT: [AeadTestVector; 4] = [ AeadTestVector { key...
mod header; mod packet; mod parser; mod reader; mod writer; pub use header::*; pub use packet::*; pub use parser::*; pub use reader::*; pub use writer::*;
use std::collections::HashMap; fn get_new_freq(freq: i32, line: &str) -> i32 { let mut chars = line.chars(); let operation = chars.next(); let delta_str: String = chars.collect(); let delta: i32 = delta_str.parse().unwrap(); if operation == Some('+') { freq + delta } else { freq - delta } } fn part1(lines...
// Copyright 2020 lencx // license that can be found in the LICENSE file or at // https://opensource.org/licenses/MIT. use std::{thread::sleep, time::Duration}; enum UpdateResult { None, QuitApplication, } struct App { client: Box<dyn Client>, state: AppState, } struct AppState { title: String, } trait C...
use crate::{ gui::{BuildContext, Ui, UiMessage, UiNode}, scene::commands::{ particle_system::{ EmitterNumericParameter, SetEmitterNumericParameterCommand, SetEmitterPositionCommand, SetEmitterResurrectParticlesCommand, }, SceneCommand, }, send_sync_message...
// since our policy is tabs, we want to stop clippy from warning about that #![allow(clippy::tabs_in_doc_comments)] extern crate graphite_proc_macros; mod communication; #[macro_use] pub mod misc; mod document; mod frontend; mod global; pub mod input; pub mod tool; pub mod consts; #[doc(inline)] pub use misc::Edito...
use std::ops::{Deref, Range}; use std::marker::PhantomData; use errors::*; pub trait BlockDevice { fn block_size(&self) -> usize; fn num_blocks(&self) -> usize; fn get_block(&mut self, num: usize) -> Result<Block>; fn push(&mut self, block: &[u8]) -> Result<()>; fn pop(&mut self) -> Result<()>; ...
//! Tests auto-converted from "sass-spec/spec/libsass-closed-issues" #[allow(unused)] use super::rsass; mod t47_str_slice; // From "sass-spec/spec/libsass-closed-issues/issue-2640.hrx" #[test] fn issue_2640() { assert_eq!( rsass( ".theme1, .theme2 {\ \n .something {\ \...
use std::mem; use linalg::{Layout, Mat, Matrix, Scalar, Square, Vect, Vector}; use typehack::data::*; use typehack::dim::*; pub trait GaussianNullspaceExt<X>: Matrix where X: Vector<Scalar = Self::Scalar, Dims = Self::Cols> { fn ge_null_elem(self) -> X; } #[cfg_attr(rustfmt, rustfmt_skip)] impl<T: Clone + ...
#![no_std] use zoon::*; blocks!{ #[s_var] fn watching_enabled() -> bool { false } #[update] fn toggle_watching() { watching_enabled().update(not); } // -- mouse -- #[s_var] fn mouse_position() -> Point { Point::new(0, 0) } #[update] fn updat...
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. mod authenticator; mod supplicant; use self::authenticator::Authenticator; use self::supplicant::Supplicant; use Error; use akm::Akm; use bytes::BytesMut;...
use super::*; pub(crate) fn buffer_command(ctx: &Context) -> CommandResult { assume_args(&ctx, "try: /buffer N")?; // TODO get rid of this string let buf = ctx.parts[0] .parse::<usize>() .map_err(|_e| Error::InvalidArgument("try: /buffer N (a number this time)".into()))?; ctx.request(...
extern crate bytes; extern crate hex; extern crate rsocket_rust; use bytes::{Bytes, BytesMut}; use rsocket_rust::frame::*; use rsocket_rust::utils::Writeable; #[test] fn test_setup() { let f = Setup::builder(1234, 0) .set_mime_data("application/binary") .set_mime_metadata("text/plain") .se...
pub const BUFFER_HEIGHT: usize = 25; pub const BUFFER_WIDTH: usize = 80; pub fn halt_cpu() -> ! { unsafe { asm!("hlt"); } loop {} // Never reach here } pub fn out_byte(dst: u16, value: u8) { unsafe { asm!( "mov $0, %dx mov $1, %al out %al, %dx" ...
/// A basic trie, used to associate patterns to their hyphenation scores. #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Patterns { pub tally: Option<Vec<(u8, u8)>>, pub descendants: HashMap<u8, Patterns, BuildHasherDefault<FnvHasher>> } /// A specialized hash map of pattern-score pairs. #[derive(C...
#[doc = "Register `ADC2_OR` reader"] pub type R = crate::R<ADC2_OR_SPEC>; #[doc = "Register `ADC2_OR` writer"] pub type W = crate::W<ADC2_OR_SPEC>; #[doc = "Field `VDDCOREEN` reader - VDDCOREEN"] pub type VDDCOREEN_R = crate::BitReader; #[doc = "Field `VDDCOREEN` writer - VDDCOREEN"] pub type VDDCOREEN_W<'a, REG, const...
fn main() { println!("Hello, World!"); another_function(5,6); } fn another_function(x: i32,y: i32) { println!("The value of x and y are: {} and {}",x,y); }
// Here it goes all the stuff related with "Settings" and "My Mod" windows. extern crate gtk; extern crate pango; extern crate url; use std::cell::RefCell; use std::rc::Rc; use std::path::{ Path, PathBuf }; use url::Url; use gtk::prelude::*; use gtk::{ Entry, Button, Frame, ComboBoxText, ApplicationWindow, Win...
#[macro_use] extern crate criterion; extern crate hamming; use criterion::{Criterion, Bencher, ParameterizedBenchmark, PlotConfiguration, AxisScale}; const SIZES: [usize; 7] = [1, 10, 100, 1000, 10_000, 100_000, 1_000_000]; macro_rules! create_benchmarks { ($( fn $group_id: ident($input: expr) { ...
use crate::coord::CoordTranslate; use crate::drawing::DrawingArea; use crate::drawing::DrawingBackend; /// The trait indicates that the type has a dimension info pub trait HasDimension { fn dim(&self) -> (u32, u32); } impl<T: DrawingBackend> HasDimension for T { fn dim(&self) -> (u32, u32) { self.get_...
type Result<T> = std::result::Result<T, String>; fn main() { let result = iter_result(); println!("{}", result.unwrap()); } fn iter_result() -> Result<i32> { (0..5).map(|x| if x > 2 { Err("greater than 2") } else { Ok(1) }); Ok(1) }
use super::{ChatServer, ClientPacket}; use crate::chat::{InternalId, SuccessReason}; use crate::error::*; use log::*; use uuid::Uuid; impl ChatServer { pub(super) fn ban_user(&mut self, user_id: InternalId, to_ban: &Uuid) { self.handle_user(user_id, to_ban, true); } pub(super) fn unban_user(&mut ...
use std::os::raw::c_char; use bioenpro4to_channel_manager::channels::ChannelInfo as ChInfo; use std::ffi::{CString, CStr}; use anyhow::Result; use bioenpro4to_channel_manager::utils::{create_encryption_key, create_encryption_nonce}; #[repr(C)] pub struct ChannelInfo{ pub channel_id: *const c_char, pub announce...
mod info; mod validate; use crate::info::Info; use crate::validate::Validate; use crossterm::style::Stylize; use solp::Consume; extern crate humantime; extern crate solp; #[macro_use] extern crate prettytable; extern crate crossterm; pub trait ConsumeDisplay: Consume + std::fmt::Display { fn as_consume(&mut self...
// This file is part of Substrate. // Copyright (C) 2019-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 // // ht...
//! Implements `StdSearchNode`. use std::cmp::min; use std::cell::UnsafeCell; use std::hash::Hasher; use std::collections::hash_map::DefaultHasher; use uci::{SetOption, OptionDescription}; use board::{Board, IllegalBoard}; use value::*; use depth::*; use qsearch::{Qsearch, QsearchParams, QsearchResult}; use moves::{Mo...
use franklin_crypto::plonk::circuit::allocated_num::Num; use franklin_crypto::bellman::pairing::Engine; use franklin_crypto::bellman::plonk::better_better_cs::cs::ConstraintSystem; use super::cipher_tools::{ CipherParams, mds::{MdsMatrix, construct_mds_matrix, construct_inverse_matrix, dot_product, add_vectors,...
#[test] fn test_hello_world() {}
use std::fs::read_to_string; type Program<'a> = Vec<(&'a str, i32)>; fn parse(input: &str) -> Program { input.lines() .map(|line| line.split_whitespace().collect::<Vec<_>>()) .map(|line| (line[0], line[1].parse().unwrap())) .collect() } pub fn run(program: &Program) -> (bool, i32) { l...
fn print_one<'a>(x: &'a i32) { println!("`print_one`: x is {}", x); } fn add_one<'a>(x: &'a mut i32) { *x += 1; } fn print_multi<'a, 'b>(x: &'a i32, y: &'b i32) { println!("`print_multi`: x is {}, y is {}", x, y); } fn pass_x<'a, 'b>(x: &'a i32, _: &'b i32) -> &'a i32 { x } // fn invalid_output<'a>() ->...
#![no_std] #![feature(once_cell)] #![feature(map_try_insert)] pub mod inode; pub mod ramdisk; pub mod file_table;
use super::types; use crate::common::types as common; use crate::common::types::ParsingContext; use crate::execution; use crate::logical::types::Named; use crate::syntax::ast; use crate::syntax::ast::{PathExpr, PathSegment, TableReference}; use hashbrown::HashSet; #[derive(Fail, Debug, Clone, PartialEq, Eq)] pub enum ...
#![allow(dead_code)] mod tl_client; fn main() { }
use std; import state::{state, outcome, cont, died, won, cmd, move, wait, score}; import geom::{left, down, up, right}; import std::list; import std::list::{list, nil, cons}; import result::{result, ok, err}; type posn = { state: state, outcome: outcome, trail: @list<cmd>, score: score }; type shell = { mut best: posn...
use crate::error::Error; use gfx_hal::adapter::Adapter; use gfx_hal::window::Extent2D; use gfx_hal::{ adapter::PhysicalDevice, device::Device, format::Swizzle, format::{Aspects, Format}, image::{SubresourceRange, ViewKind}, memory::{Properties, Requirements}, Backend, MemoryTypeId, }; use st...
use cpython::{NoArgs, ObjectProtocol, PyResult, Python}; use std::collections::{BTreeMap, HashMap}; use std::fmt::Debug; use std::hash::Hash; use std::time::{Duration, Instant}; pub fn run_benchmark<T: Debug + Copy + Hash + Ord, U: Debug + PartialEq>( reps: usize, range: impl Iterator<Item = T>, benchees: ...
use std::{net::SocketAddr, ops::Deref, sync::Arc}; use actionable::Permissions; use bonsaidb_core::{custodian_password::ServerLogin, custom_api::CustomApi}; use flume::Sender; use tokio::sync::{Mutex, RwLock}; use crate::{Backend, CustomServer}; /// The ways a client can be connected to the server. #[derive(Debug, P...
use std::thread; use std::time::{Duration, SystemTime}; use serde::Deserialize; use warmy::{Res, SimpleKey, Store, StoreOpt}; use warmy::json::Json; #[derive(Debug, Deserialize)] #[serde(rename_all = "snake_case")] struct Dog { name: String, gender: Gender } impl Default for Dog { fn default() -> Self { ...
#![feature(nll, underscore_imports)] extern crate cgmath; extern crate pbrt; use std::sync::{ Arc, Mutex }; use cgmath::{ Deg, Matrix4 }; use pbrt::aggregate::{ BvhAccel, SplitMethod }; use pbrt::camera::{ OrthographicCamera, PerspectiveCamera }; use pbrt::film::Film; use pbrt::filter::TriangleFilter; use pbrt::inte...
//! File attribute wrappers use fuse; use std::cell::RefCell; use std::path::{Path, PathBuf}; use std::usize; use time::{self, Timespec}; /// Describes a type that can be attributed pub trait Content { fn name(&self) -> &str; fn size(&self) -> usize; } /// Tags content as being either a file or a directory. ...
use core::pos::BiPos; #[repr(u8)] #[derive(Debug, PartialEq, Clone, Copy, Hash, Eq)] pub enum TokenType { LParen, RParen, LCurly, RCurly, LBracket, RBracket, QMark, Hyphen, Comma, Dot, Semicolon, Pipe, Plus, Minus, Star, Slash, Backslash, Unders...
#![allow(dead_code,unused_variables, unused_mut)] extern crate x11; extern crate libc; extern crate futures; mod display; pub use display::Display; mod error; pub use error::XError; mod window; pub use window::Window; pub use x11::xlib::{ XMapEvent, XDestroyWindowEvent, XConfigureEvent, XUnmapEvent, XPropertyEve...
use std::io::{Write}; use parser::html; use parser::html::Expression as Expr; use parser::html::Statement as Stmt; use parser::html::{Fmt}; use parser::html::Statement::{Element, Store, Condition, Output}; use parser::{Ast, Block}; use super::ast::{Code, Statement, Param, Expression}; use super::Generator; fn key_...
//! For making notable symbols and words out of text. #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum Operator { Plus, Minus, Star, Slash, Percent, Caret, LParen, RParen, Pipe, Equals, Factorial, } use self::Operator::*; #[derive(Debug, Clone, PartialEq)] pub enum Tok...
#![allow( clippy::len_without_is_empty, // Types that are non-empty by construction do not need is_empty method )] pub mod encoder; pub mod headers; pub mod frame; pub mod rice; mod writer; pub use writer::{FrameWriter, HeaderWriter}; pub const SMALL: bool = true; pub const BLOCK_SIZE: u16 = if SMALL { 192 } els...
use ckb_chain_spec::consensus::Consensus; use ckb_core::block::Block; use ckb_core::cell::{CellProvider, CellStatus}; use ckb_core::extras::{BlockExt, EpochExt}; use ckb_core::header::{BlockNumber, Header}; use ckb_core::transaction::{OutPoint, ProposalShortId, Transaction}; use ckb_core::uncle::UncleBlock; use ckb_db:...
use super::*; use crate::error::{NodeError, NodeErrorKind}; use poa::engines::authority_round::RollingFinality; use rand::Rng; use sha2::{Digest, Sha256}; use std::collections::HashSet; use std::fs::{create_dir_all, File}; use std::io::{ErrorKind, Read, Seek, Write}; use std::path::PathBuf; use ton_block::{InMsg, OutMs...
/* chapter 4 syntax and semantics */ fn main() { let mut a = vec![1, 2, 3]; for b in &a { println!("{}", b); } // because a is mutable we will see the warning: // // warning: variable does not need to be mutable, // #[warn(unused_mut)] on by default // // let mut a = vec![1...
mod cli; mod errors; mod config; mod container; mod ipc; mod child; mod hostname; mod mounts; mod namespaces; mod capabilities; mod syscalls; mod resources; #[macro_use] extern crate scan_fmt; use errors::exit_with_retcode; fn main() { match cli::parse_args() { Ok(args) => { log::info!("{:?}"...
use nm_dbus::NmError; use crate::{ErrorKind, NmstateError}; pub(crate) fn nm_error_to_nmstate(nm_error: &NmError) -> NmstateError { NmstateError::new( ErrorKind::Bug, format!( "{}: {} dbus: {:?}", nm_error.kind, nm_error.msg, nm_error.dbus_error ), ) }
use std::io; fn main() { loop { println!("Insert the position of the fibonacci series (x to exit):"); let mut value = String::new(); io::stdin().read_line(&mut value) .expect("Failed to read line"); match value.trim().parse() { Ok(num) => println!("Fibonacci...
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize}; use near_sdk::collections::LookupMap; use near_sdk::json_types::{U128, U64}; use near_sdk::serde::{Deserialize, Serialize}; use near_sdk::serde_json::{self, json}; use near_sdk::wee_alloc::WeeAlloc; use near_sdk::{env, ext_contract, near_bindgen, AccountId,...
use std::env; use tcalc_rustyline::error::ReadlineError; use tcalc_rustyline::Editor; #[macro_use] mod macros; mod ast; mod buffered_iterator; mod parsing; mod running; mod scanning; use crate::ast::*; use crate::running::*; fn print_usage() { println!("Usage: {} [OPTION] EXPRESSIONS", env!("CARGO_PKG_NAME")); } ...
fn main() { println!("a"); }
#[doc = "Register `VVACCR` reader"] pub type R = crate::R<VVACCR_SPEC>; #[doc = "Field `VA` reader - Vertical Active duration"] pub type VA_R = crate::FieldReader<u16>; impl R { #[doc = "Bits 0:13 - Vertical Active duration"] #[inline(always)] pub fn va(&self) -> VA_R { VA_R::new((self.bits & 0x3fff...
#[no_mangle] pub extern fn physics_single_chain_ideal_thermodynamics_isometric_force(number_of_links: u8, link_length: f64, end_to_end_length: f64, temperature: f64) -> f64 { super::force(&number_of_links, &link_length, &end_to_end_length, &temperature) } #[no_mangle] pub extern fn physics_single_chain_ideal_...
use std::{io::BufReader, sync::Arc}; use arrow::csv::reader; use wasm_bindgen::prelude::*; use crate::{schema::Schema, utils::StringReader}; #[wasm_bindgen] pub fn infer_schema_from_csv( content: String, // max_records: usize, // returns the schema as a jsvalue ) -> Result<JsValue, JsValue> { // let ...
fn round_to_next_5(n: i32) -> i32 { let abs_remain = (n % 5).abs(); let to_add_on = if n < 0 { abs_remain } else { 5 - abs_remain }; return if abs_remain > 0 { n + to_add_on } else { n }; } fn main() { println!("0 {}", round_to_next_5(0)); println!("5 {}", round_to_next_5(2)); println!("5 {}", round_to_next_5...
impl Solution { pub fn contains_duplicate(nums: Vec<i32>) -> bool { use std::collections::HashMap; let mut numMap = HashMap::new(); for n in nums { let count = numMap.entry(n).or_insert(0); *count += 1; } for (key, count) in ...
extern crate rand; use std::io; use rand::Rng; use std::cmp::Ordering; #[allow(non_snake_case)] fn main() { let randomNum = rand::thread_rng().gen_range(0, 101); loop { println!("Guess the correct number\n>>>"); let mut guess = String::new(); io::stdin().read_line(&mut guess) ...
use std::process; mod instruction; pub mod interrupt_handler; mod registers; use crate::cpu::instruction::*; use crate::cpu::interrupt_handler::*; use crate::cpu::registers::*; use crate::gb; use crate::memory::Memory; use crate::timer::Cycles; pub struct Cpu { registers: Registers, pc: u16, sp: u16, ...
use crate::runtime::Runtime; use crate::variable::Variable; use std::collections::HashSet; use std::fmt::Write; use std::ops::{Index, IndexMut}; use std::option::Option; use std::vec::Vec; #[derive(Debug, Clone, PartialEq, Eq)] pub struct StackFrame { exception_handlers: HashSet<Variable>, variables: Vec<Varia...
//! This crate provides a framework for writing chess engines. //! //! # Why chess engines? //! //! Simple! Chess is the greatest thing humans have //! invented. Computers follow closely ;) //! //! # Why a framework? //! //! There is lots of knowledge out there about how to write a chess //! engine, and there is a lot ...
/* * *const T型 不変の生ポインタ * *mut T型 可変の生ポインタ */ fn main(){ let c1 = 'A'; // &で参照を作り、型強制で生ポインタに変換する let c1_ptr: *const char = &c1; println!("c1: {:?}", c1); println!("*c1_ptr: {:?}", unsafe{*c1_ptr}); let c2 = 'B'; // ""じゃない let c2_ptr: *const char = &c2; println!("c2: {:...
//! Implements `Multipv`. use super::{bogus_params, contains_dups}; use super::aspiration::Aspiration; use std::cmp::{min, max}; use std::time::Duration; use std::sync::Arc; use std::sync::mpsc::TryRecvError; use uci::{SetOption, OptionDescription}; use moves::Move; use value::*; use depth::*; use ttable::*; use evalu...
extern crate sevent; extern crate mio; extern crate bytes; use bytes::Buf; use bytes::BufMut; use sevent::iobuf::IoBuffer; use mio::net::TcpStream; struct Echo; impl sevent::ConnectionHandler for Echo { fn on_read(&mut self, id: usize, buf: &mut IoBuffer) { sevent::connection_write(id, |wbuf| { ...
use std::io; use std::rand; struct Property { name : String, price : int, } fn get_numeric_input() -> int { let input = io::stdin().read_line() .ok().expect("Failed to getline\n"); let input_num: Option<int> = from_str(input.as_slice().trim()); let num = match i...
use clap::{App, AppSettings, Arg}; /// readlink [OPTION]... FILE... /// /// -f, --canonicalize /// canonicalize by following every symlink in every component of the given name recursively; all but the last component must exist /// /// -e, --canonicalize-existing /// can...
use ethabi::{Function, Param, ParamType}; pub struct ContractBuilder {} impl ContractBuilder { pub fn create_send_fn() -> Function { let interface = Function { name: "send".to_owned(), inputs: vec![ Param { name: "to".to_owned(), ...
#[macro_export] macro_rules! impl_from { ($trait:ident : [$($from:ty => $to:ident ),*] ) => { $( impl From<$from> for $trait { fn from(f: $from) -> $trait { $trait::$to(f) } } )* } } mod canvas; mod clipboard; mod edit;...
#[doc = "Register `APB3ENR` reader"] pub type R = crate::R<APB3ENR_SPEC>; #[doc = "Register `APB3ENR` writer"] pub type W = crate::W<APB3ENR_SPEC>; #[doc = "Field `SBSEN` reader - SBS clock enable Set and reset by software."] pub type SBSEN_R = crate::BitReader; #[doc = "Field `SBSEN` writer - SBS clock enable Set and ...
use parenchyma::error::Result; use parenchyma::tensor::SharedTensor; /// Extends IBlas with Axpby pub trait Axpby: super::Vector { /// Performs the operation y := a*x + b*y . /// /// Consists of a scal(b, y) followed by a axpby(a,x,y). fn axpby(&self, a: &SharedTensor, x: &SharedTensor, b: &SharedTenso...
use bigint::uint::U256; #[derive(Debug, Copy, Clone)] struct Point { x: U256, y: U256 } impl Point { fn new(x: U256, y: U256) -> Point { Point { x: x, y: y } } fn new_small(x: u64, y: u64) -> Point { Point::new(U256{0: [x, 0, 0, 0]}, U256{0: [y, 0, ...
#![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 Tags { #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, } #[...
// See https://rocket.rs/v0.4/guide/testing/#local-dispatching #[cfg(test)] mod test { use rocket::http::{ContentType, Status}; use rocket::local::Client; use rustlang_rocket_mongodb::rocket; #[test] fn get_heroes() { let client = Client::new(rocket()).expect("valid rocket instance"); let response = ...
//! Provides common appearance presets. use iced::{button, container, pane_grid, text_input, Background, Color, Vector}; /// Represents the currently in-use theme. This provides a way to get colours semantically, as in by their purpose. #[derive(Debug, Clone)] pub enum Theme { Dark, } impl Theme { /// To be ...
use py27_marshal::read::errors::ErrorKind; use pydis::{opcode::py27::{self, Mnemonic}, prelude::Opcode}; use thiserror::Error; #[derive(Error, Debug)] pub enum Error<O: 'static + Opcode<Mnemonic = py27::Mnemonic>> { #[error("unexpected data type while processing `{0}`: {1:?}")] ObjectError(&'static str, py27_m...
use std::fs::File; use std::io::Cursor; use std::io::{self, BufRead, BufReader, Read, Stdin}; use std::path::PathBuf; pub enum Input { Console(BufReader<Stdin>), File(BufReader<File>), Mem(Cursor<Vec<u8>>), } impl Input { pub fn console() -> Input { Input::Console(io::BufReader::new(std::io::s...
//! UDS (unified diagnostic protocol) example for reading a data by identifer. //! Run the following server for testing. //! https://github.com/zombieCraig/uds-server use socketcan_isotp::{self, IsoTpSocket, StandardId}; use std::sync::mpsc; fn main() -> Result<(), socketcan_isotp::Error> { let (tx, rx) = mpsc::c...
use log::info; use std::fs::File; use std::io::BufReader; use super::butterfly_collector::{ButterflyCollector, ButterflyJSON}; use super::errors::ButterflyError::{self, *}; use super::webpage_parser::WebpageParser; /// Client used to retrieve butterfly data /// /// You can retrieve data from the Website using `new` t...
//! Driver for the MEMS Lis3dshSpi motion sensor, 3 axis digital output //! accelerometer and temperature sensor. //! //! May be used with NineDof and Temperature //! //! SPI Interface //! //! <https://www.st.com/resource/en/datasheet/lis3dsh.pdf> //! //! //! Syscall Interface //! ----------------- //! //! ### Command ...
/// Represents a token string #[derive(Clone, Debug, Eq, PartialEq)] pub enum SearchToken<'a> { Value(&'a str), StartsWith(&'a str), } enum SearchTokenizerState { StartWith, Char, Hunting, } #[derive(PartialEq, Debug, Clone)] enum SearchGroupState { None, Grouping, } pub fn search_tokeni...
#![allow(dead_code)] #![allow(unused_variables)] #[allow(unused_imports)] use handlegraph::{ handle::{Direction, Handle, NodeId}, handlegraph::*, mutablehandlegraph::*, packed::*, pathhandlegraph::*, }; #[allow(unused_imports)] use handlegraph::packedgraph::PackedGraph; use crate::geometry::*; #...
// unihernandez22 // https://codeforces.com/contest/1324/problem/D // math, binary search use std::io; fn main() { let mut n = String::new(); io::stdin().read_line(&mut n).unwrap(); let n: i64 = n.trim().parse().unwrap(); let mut a = String::new(); io::stdin().read_line(&mut a).unwrap(); le...
//! Compact block implementation. use crate::utils::NetworkPeerHandle; use crate::{ProtocolBackend, ProtocolClient, ProtocolServer, RelayError, Resolved, LOG_TARGET}; use async_trait::async_trait; use codec::{Decode, Encode}; use std::collections::BTreeMap; use std::num::NonZeroUsize; use std::sync::Arc; use tracing::...
//! `package cannyls_rpc.protobuf;` //! //! メッセージ定義は[cannyls_rpc.proto]を参照のこと. //! //! [cannyls_rpc.proto]: https://github.com/frugalos/cannyls_rpc/blob/master/protobuf/cannyls_rpc.proto #![cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))] use ::trackable::error::{ErrorKindExt, TrackableError}; use by...
mod server; extern crate log; extern crate pretty_env_logger; #[tokio::main] async fn main() { // Init logger pretty_env_logger::init(); // Start the API server to handle requests. server::start(([127, 0, 0, 1], 3030)).await; }
use std::sync::{mpsc, Arc, Barrier}; use std::time::Duration; use std::collections::HashMap; use std::thread; use super::common::{Instruction, Value}; fn get_value(map: &HashMap<char, isize>, value: &Value) -> isize { match value { &Value::Raw(ref val) => *val, &Value::Register(register) => *map.g...
use crate::segment::SegmentType; use alloc::collections::VecDeque; use alloc::string::ToString; use alloc::vec; use core::cmp::min; use core::mem; use memchr::memrchr; use seshat::unicode::Segmentation; pub const MAX_BLOCK_SIZE: usize = 1024; pub const MIN_BLOCK_SIZE: usize = 512; pub struct Splitter<'a> { buffer...
struct Data { name:String, no1:u32, no2:u32, } fn main() { let Data = Data{ name : String::from("Mike"), no1 : 55, no2 : 55, }; let result:u32 = add(&Data); println!("The name is :: {}",Data.name); println!("the result is :: {}",result); }// main ends here fn add(Data : &Data)->u32{ Data.no1+ D...
pub mod game_state; pub mod user_state; pub use game_state::GameState; pub use user_state::{UserState, UserStateDb};
pub(crate) fn parse_uds_addr(addr: impl AsRef<str>) -> String { let addr = addr.as_ref(); if addr.starts_with("unix://") || addr.starts_with("UNIX://") { addr.chars().skip(7).collect::<String>() } else { addr.to_owned() } } pub(crate) fn parse_tcp_addr(addr: impl AsRef<str>) -> String {...
//! Renders selected features from the input archive as svg. //! //! For supported features check `Category` enum and `classify` function. //! //! For each feature, we retrieve the coordinates lazily from osm nodes, and //! then produce polylines styled based on the category, cf. `render_svg` //! function. The coordina...
#[doc = "Reader of register HWCFGR12"] pub type R = crate::R<u32, super::HWCFGR12>; #[doc = "Reader of field `TZ`"] pub type TZ_R = crate::R<u32, u32>; impl R { #[doc = "Bits 0:31 - TZ"] #[inline(always)] pub fn tz(&self) -> TZ_R { TZ_R::new((self.bits & 0xffff_ffff) as u32) } }
#[allow(unused_macros)] macro_rules! gen_all_symbols { () => { let market_types = get_market_types(EXCHANGE_NAME); assert!(!market_types.is_empty()); for market_type in market_types .into_iter() .filter(|m| m != &MarketType::Unknown) { let symbols...
use crate::egml::{Component, Node, Comp}; use super::InputEvent; pub struct MouseInput { last_mouse_pos: Option<(f64, f64)>, last_offset: Option<(f64, f64)>, } #[derive(Default, Debug, Clone, Copy, PartialEq)] pub struct MousePos { pub x: f32, pub y: f32, } impl MouseInput { pub fn new() -> Self ...