text
stringlengths
8
4.13M
use crate::buf_reader::BufIo; use crate::AsyncRead; use futures_util::ready; use http::header::{HeaderName, HeaderValue}; use std::fmt::Debug; use std::io; use std::io::Write; use std::pin::Pin; use std::task::{Context, Poll}; // Request headers today vary in size from ~200 bytes to over 2KB. // As applications use mo...
use super::{data_structure::*, *}; use syntax::ast; // krate is mutable, because we will fill in its NodeId pub fn expand_crate<'a>(krate: &mut LangRust, sess: &'a ParseSess) -> LangHIR { let mut ribcage = ModRibcage {}; let LangRust { module, attrs, span, } = krate; // Step 1:...
use derive_more::{Deref, DerefMut}; use serde::ser::{Serialize, SerializeSeq, Serializer}; use serde_sexpr::to_string; #[derive(Clone, Debug)] pub struct Foo; #[derive(Default, Clone, Debug, Deref, DerefMut)] pub struct Bar(Vec<Foo>); impl Serialize for Foo { fn serialize<S>(&self, serializer: S) -> Result<S::Ok...
pub mod method_call; pub mod notification;
use std::ops::Bound; use chrono::{DateTime, Utc}; type BoundedDatetimeTuple = (Bound<DateTime<Utc>>, Bound<DateTime<Utc>>); pub(crate) mod ts_seconds_bound_tuple { use std::fmt; use std::ops::Bound; use super::BoundedDatetimeTuple; use chrono::{DateTime, NaiveDateTime, Utc}; use serde::{de, ser}...
///// chapter 4 "structuring data and matching patterns" ///// program section: // fn main() { let location = "middle-earth"; let part = &location[7..12]; println!("{}", part); } ///// output should be: /* earth */// end of output
pub mod mds; pub mod sboxes; use rand::Rng; use franklin_crypto::bellman::pairing::Engine; use franklin_crypto::bellman::pairing::ff::Field; use std::marker::PhantomData; use mds::generate_vectors_for_matrix; use sboxes::{QuinticSBox, QuinticInverseSBox}; pub struct CipherParams< E: Engine, const SIZE: usize,...
use crate::kernel::opcode; use crate::kernel::Table_; use crate::statement_iter::{Statement, StatementIter, StatementOwned}; use mmb_parser::{ProofStream, UnifyStream, Visitor}; pub struct UnifyCommands { data: Vec<opcode::Command<opcode::Unify>>, start_offset: usize, } impl UnifyStream for UnifyCommands { ...
use regex::Regex; use std::collections::HashMap; static FILENAME: &str = "input/data"; static BITMASK_LEN: usize = 36; enum Operation { Mask((usize, usize)), Mem(usize, usize), } fn main() { let data = std::fs::read_to_string(FILENAME).expect("could not read file"); let ops = parse(&data); println...
use crate::repr::Literal; use inkwell::values::BasicValueEnum; use super::common::CompileResult; use super::context::CodegenContext; use super::literal::*; fn compile_quoted_symbol(ctx: &mut CodegenContext, name: &String) -> BasicValueEnum { let sym_name_ptr = ctx.str_literal_as_i8_ptr(name.as_str()); let in...
//! Cortex-M7 TCM and Cache access control. use volatile_register::RW; /// Register block #[repr(C)] pub struct RegisterBlock { /// Instruction Tightly-Coupled Memory Control Register pub itcmcr: RW<u32>, /// Data Tightly-Coupled Memory Control Register pub dtcmcr: RW<u32>, /// AHBP Control Regist...
use std::fs::File; use std::mem::size_of; use std::io::Seek; use std::io::SeekFrom; use std::convert::TryInto; use byteorder::{LittleEndian, ReadBytesExt}; use libc::{_SC_PAGESIZE, sysconf}; #[derive(Debug)] pub enum Error { PageMap, Read, Unk, } pub fn virt_to_phys<T>(virt: *const T) -> Result<*const T,...
extern crate termion; use termion::async_stdin; use std::io::{Read, Write}; use std::thread; use std::time::Duration; use crate::util::*; pub struct Input { //will become command ch: Char, position: Pos, } pub type Action = Vec<Input>; pub type Done = Vec<Action>; //will become "Done" stack pub type Undone = Vec...
use azure_core::prelude::*; use azure_storage::blob::prelude::*; use azure_storage::core::prelude::*; use std::error::Error; #[tokio::main] async fn main() -> Result<(), Box<dyn Error + Send + Sync>> { // First we retrieve the account name and master key from environment variables. let account = std::e...
use sudo_test::{Command, Env, User}; use crate::{Result, PASSWORD, USERNAME}; #[test] fn is_limited_to_a_single_user() -> Result<()> { let second_user = "ghost"; let env = Env("ALL ALL=(ALL:ALL) ALL") .user(User(USERNAME).password(PASSWORD)) .user(User(second_user).password(PASSWORD)) ...
use std::io::stdin; fn main() { println!("You enter a dark room with two doors. Do you go through door #1 or door #2?"); let mut door = String::new(); stdin().read_line(&mut door).unwrap(); if door == "1\n".to_owned(){ println!("There is a giant bear here eating a cheese cake."); print...
// Copyright 2014 Christopher Schröder, Johannes Köster. // Licensed under the MIT license (http://opensource.org/licenses/MIT) // This file may not be copied, modified, or distributed // except according to those terms. #![feature(libc)] #![feature(step_by)] #![feature(convert)] #![feature(vec_push_all)] #![feature(...
extern crate timer; extern crate chrono; use timer::Timer; use chrono::Duration; use std::thread; fn x() { println!("hello"); } fn main() { let timer = Timer::new(); let guard = timer.schedule_repeating(Duration::seconds(2), x); // give some time so we can see hello printed // you can execute any...
use actix::prelude::*; use chrono::NaiveTime; use log::warn; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::time::Duration; use std::time::Instant; pub struct RouteFragment { id: String, stop_names: [String; 2], past_trip_duration: Vec<Duration>, last_update_time: Option<...
fn main() { let m = ["This", 4]; let n = [4, 5.]; }
extern crate parser_c; use std::env; use parser_c::parser::exec_parser_simple; use parser_c::parser::lexer::lex; use parser_c::data::input_stream::InputStream; use parser_c::data::position::Position; use parser_c::parser::tokens::CTokEof; fn main() { let mut args = env::args(); let input_file = args.nth(1).u...
mod boxed; mod peek; mod prefixed; mod sensor; pub use self::{ boxed::BoxedIo, peek::{Peek, Peekable}, prefixed::PrefixedIo, sensor::{Sensor, SensorIo}, }; pub use std::io::{Error, ErrorKind, Read, Result, Write}; use std::net::SocketAddr; pub use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncW...
#[allow(unused_imports)] use nom::*; use ast::Ast; use parser::body::body; use std::boxed::Box; use parser::expressions::sexpr; named!(pub if_expression<Ast>, do_parse!( ws!(tag!("if")) >> if_conditional: ws!(sexpr) >> if_body: ws!(body) >> else_body: opt!( complete!( ...
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - TIM3 control register 1"] pub tim3_cr1: TIM3_CR1, _reserved1: [u8; 0x02], #[doc = "0x04 - TIM3 control register 2"] pub tim3_cr2: TIM3_CR2, #[doc = "0x08 - TIM3 slave mode control register"] pub tim3_smcr: TIM3_...
use crate::filter::PostFilters; use bincode::{deserialize, Result}; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize)] pub struct Storage { pub filters: PostFilters, } impl From<PostFilters> for Storage { fn from(filters: PostFilters) -> Self { Storage { filters } } } impl Storage { p...
use std::fmt; #[derive(Debug, PartialEq, Eq, Hash, Clone)] pub struct Feature { name: String, version: Option<String>, } impl Feature { pub fn new(name: String, version: Option<String>) -> Self { Feature { name, version } } } impl fmt::Display for Feature { fn fmt(&self, f: &mut fmt::Form...
// This file is part of Basilisk-node. // Copyright (C) 2020-2021 Intergalactic, Limited (GIB). // 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 // /...
use super::{condition_ready, retry, ConstructContext, ANNOTATION_APP_NAME, LABEL_KAFKA_CLUSTER}; use crate::controller::ControllerConfig; use async_trait::async_trait; use drogue_client::{registry::v1::KafkaAppStatus, Translator}; use drogue_cloud_operator_common::controller::reconciler::{ progress::{self, Operatio...
mod compiler; mod config; mod platform; mod symbols; mod utils; pub use compiler::*; pub use config::*; pub use platform::*; pub use symbols::*; pub use utils::*; pub use compiler::Js as CompilerJs; pub use symbols::Js as SymbolsJs;
use std::io; use std::net::TcpListener; use std::sync::Arc; use std::thread; use connection::{Connection, ConnectionType}; use public_key::KeyPair; pub struct ServerConfig { pub host: String, pub port: u16, pub key: Box<KeyPair>, } pub struct Server { config: Arc<ServerConfig>, } impl Server { p...
use std::io::*; enum Token { Eof, Number(f64), Identifier(String), } fn getToken() { } fn main() { let reader = BufReader::new(stdin()); let buf: [] while (reader.read(buf).is_ok()) { getToken(); } }
// Copyright (c) 2015-2016, Johan Sköld. // License: http://opensource.org/licenses/ISC use std::env; use std::io::Write; use std::path::PathBuf; use std::process::{Command, Stdio}; fn main() { let target = env::var("TARGET").unwrap(); let profile = env::var("PROFILE").unwrap(); let first_div = target.fi...
$NetBSD: patch-vendor_crossbeam-utils_no__atomic.rs,v 1.3 2023/04/08 18:18:11 he Exp $ Add mipsel-unknown-netbsd target as not having 64-bit atomics. Unify with crossbeam-utils-0.8.12 by removing mipsel-sony-psx. --- vendor/crossbeam-utils/no_atomic.rs.orig 2023-01-25 01:49:15.000000000 +0000 +++ vendor/crossbeam-uti...
/// NO. 1: Two Sum pub struct Solution; // ----- submission codes start here ----- use std::collections::HashMap; impl Solution { pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> { // let mut hash_map = HashMap::with_capacity(nums.len()); let mut hash_map = HashMap::with_capacity(nums.len...
use std::sync::Arc; use anyhow::{Context, Result}; use async_trait::async_trait; use chrono::Utc; use serde_derive::Serialize; use serde_json::Value as JsonValue; use sqlx::Acquire; use svc_agent::mqtt::{ IntoPublishableMessage, OutgoingEvent, OutgoingEventProperties, ShortTermTimingProperties, }; use uuid::Uuid; ...
#[doc = "Register `TZC_FAIL_CONTROL0` reader"] pub type R = crate::R<TZC_FAIL_CONTROL0_SPEC>; #[doc = "Field `PRIVILEGE` reader - PRIVILEGE"] pub type PRIVILEGE_R = crate::BitReader; #[doc = "Field `NON_SECURE` reader - NON_SECURE"] pub type NON_SECURE_R = crate::BitReader; #[doc = "Field `DIRECTION` reader - DIRECTION...
use std::io; use std::io::Write; fn main() { println!("This goes to stdout"); println!("ユニコードを作りましょう"); write!(&mut io::stderr(), "This goes to stderr\n").unwrap(); write!(&mut io::stderr(), "ユニコードを作りましょう\n").unwrap(); }
use std::{ ffi::OsStr, process::{ExitStatus, Stdio}, }; #[cfg(feature = "async-std-runtime")] use async_std::process::{Child, Command}; #[cfg(feature = "tokio-runtime")] use tokio::process::{Child, Command}; use crate::error::Result; #[derive(Debug)] pub(crate) struct Process { child: Child, } impl Proc...
use super::c_void; extern "C" { pub fn linearAlloc(size: i32) -> *mut c_void; pub fn linearMemAlign(size: i32, alignment: i32) -> *mut c_void; pub fn linearRealloc(mem: *mut c_void, size: i32) -> *mut c_void; pub fn linearFree(mem: *mut c_void) -> (); pub fn linearSpaceFree() -> u32; }
//! The Tendermock JsonRPC Websocket API. use futures::{SinkExt, StreamExt}; use serde::Serialize; use tendermint_rpc::endpoint::subscribe::{Request, Response}; use warp::ws::{Message, WebSocket, Ws as WarpWs}; use warp::Filter; use super::utils::{JrpcEnvelope, JrpcError, JrpcResponse, JrpcResult, JRPC_VERSION}; use c...
use cpp::{cpp, cpp_class}; use std::{os::raw::{c_char, c_int, c_uint}, ffi::CStr}; cpp! {{ #include <lldb/API/SBDebugger.h> using namespace lldb; }} // pub fn terminate() { // cpp!(unsafe [] { // SBDebugger::Terminate(); // }) // } // pub fn create(source_init_files:...
use std::marker::PhantomData; use std::ops::BitXor; use crate::metric::Metric; use crate::Dist; pub trait CountOnes { #[inline] fn count_ones(self) -> u32; } impl CountOnes for u8 { #[inline] fn count_ones(self) -> u32 { self.count_ones() } } impl CountOnes for u16 { #[inline] fn c...
use std::io::{self, Read, Write}; use vendored_sha3::digest::{ExtendableOutput, Input}; use vendored_sha3::{Sha3XofReader, Shake256}; #[derive(Clone)] enum State { Absorbing(Shake256), Reading(Sha3XofReader), } /// SHAKE256 is the 256-bit SHAKE variable-output-length hash functions defined by FIPS-202 #[deri...
use draw::DrawContext; use std::marker::PhantomData; use std::ptr; use ui_sys::{self, uiDrawBrush}; pub use ui_sys::uiDrawBrushGradientStop as BrushGradientStop; /// Used to determine how a given stroke or fill is drawn. #[derive(Clone, Debug)] pub enum Brush { Solid(SolidBrush), LinearGradient(LinearGradient...
use std::net::SocketAddr; use msg_types::{AnnounceRequest, AnnounceSecret, CallResponse, Disconnect}; use mio::Token; use crate::{client::tui::Tui, common::{debug_message::DebugMessageType, encryption::SymmetricEncryption, lib::read_exact, message_type::{InterthreadMessage, MsgType, msg_types::{self, Call}, Peer}}}; ...
#[derive(Eq, Hash)] pub struct SymbolStatus { name: String, compiled: bool } impl SymbolStatus { pub fn new(name: String) -> SymbolStatus { SymbolStatus { name: name, compiled: false } } pub fn get_name(&self) -> &String { &self.name } pub fn should_compile(&self) -> bool ...
#[doc = "Register `GICD_CIDR2` reader"] pub type R = crate::R<GICD_CIDR2_SPEC>; #[doc = "Field `CIDR2` reader - CIDR2"] pub type CIDR2_R = crate::FieldReader<u32>; impl R { #[doc = "Bits 0:31 - CIDR2"] #[inline(always)] pub fn cidr2(&self) -> CIDR2_R { CIDR2_R::new(self.bits) } } #[doc = "GICD c...
#![allow(dead_code)] #![allow(unreachable_patterns)] fn main() { simple(); } fn simple() { let c = 'c'; match c { 'c' => { println!("Hello"); } _ => { unreachable!(); } } } fn destruct2() { let x = 1; let c = 'c'; match c { ...
use ggez::graphics::Point2; use std; use consts::*; use std::f32::consts::PI; use utils::PointArithmetic; ////////////////////////////////////////////////// pub struct LiveArrow { pub position: Point2, pub angle: f32, pub momentum: Point2, pub height: f32, pub climb_momentum: f32, } impl LiveArro...
pub mod dataset; pub mod layer; pub mod matrix; pub mod nn;
use http; use http::HttpError; #[test] fn test_http_response(){ let dummy_response: http::HttpResponse = http::HttpResponse::builder() .status_code(http::HttpResponseStatusCode::OK) .add_header("Accept", "text/html, application/xhtml+xml") .add_header("Accept-Encoding", "gzip, deflate, sdch") ...
use std::error::Error; use std::io::{self, prelude::*}; /// What is the best beauty score possible, when taking `num_plates` from `stacks`? /// /// `stacks` must be a non-empty square matrix. fn best_beauty_score(stacks: &Vec<Vec<u32>>, num_plates: usize) -> u32 { let n = stacks.len(); assert_ne!(n, 0); le...
#[doc = "Reader of register AIRCR"] pub type R = crate::R<u32, super::AIRCR>; #[doc = "Writer for register AIRCR"] pub type W = crate::W<u32, super::AIRCR>; #[doc = "Register AIRCR `reset()`'s with value 0"] impl crate::ResetValue for super::AIRCR { type Type = u32; #[inline(always)] fn reset_value() -> Sel...
#[cfg(test)] mod tests { use crate::aes_ecb::aes_128_ecb_decrypt; use crate::aes_ecb::aes_128_ecb_encrypt; use crate::util::find_blocksize; use crate::util::generate_random_bytes; use crate::util::parse_key_value; use crate::util::profile_for; use crypto::symmetriccipher::SymmetricCipherErro...
pub mod server; pub mod util; pub mod cache; pub mod authority; pub mod index;
use messages::payloads::*; #[derive(Debug, Clone)] pub enum Payload { Nothing, Unknown(String), Hello(HelloInfo), State(GameStateInfo), Delete(DeleteInfo), PlayerDelete(DeleteInfo), Ping, Pong(PongInfo), PlayerInfo(PlayerInfo), PickupInfo(PickupInfo), PlayerUpdate(PlayerUpda...
fn read<T: std::str::FromStr>() -> T { let mut s = String::new(); std::io::stdin().read_line(&mut s).ok(); s.trim().parse().ok().unwrap() } fn read_vec<T: std::str::FromStr>() -> Vec<T> { read::<String>() .split_whitespace() .map(|e| e.parse().ok().unwrap()) .collect() } fn rea...
fn main() { println!("Project euler problem 1"); println!("Multiples of 3 and 5"); println!("If we list all the natural numbers below 10 that are multiples of 3 or 5, \ we get 3, 5, 6 and 9. The sum of these multiples is 23. \ Find the sum of all the multiples of 3 or 5 below 1000."); let max_...
/* * Datadog API V1 Collection * * Collection of all Datadog Public endpoints. * * The version of the OpenAPI document: 1.0 * Contact: support@datadoghq.com * Generated by: https://openapi-generator.tech */ /// AlertGraphWidgetDefinitionType : Type of the alert graph widget. /// Type of the alert graph widget...
// Enums test #[atrr] pub enum Test { A, B(u32, A /* comment */), /// Doc comment C, } pub enum Foo<'a, Y: Baz> where X: Whatever { A, } enum EmtpyWithComment { // Some comment } // C-style enum enum Bar { A = 1, #[someAttr(test)] B = 2, // comment C, } enum LongVariants...
pub mod application; pub mod container; pub mod domain; pub mod infrastructure; mod mocks;
use super::{Block, BlockId, Field}; use crate::resource::ResourceId; use crate::Promise; use std::collections::HashSet; use std::{cell::RefCell, rc::Rc}; use wasm_bindgen::{prelude::*, JsCast}; #[derive(Clone)] pub struct Texture { element: web_sys::HtmlCanvasElement, context: web_sys::CanvasRenderingContext2d...
/* Okay... one way or another I have a list of per-rect properties, like position. All rects in that list are drawn with the same texture and geometry, however that geometry is specified. Then I have another list of (texture, rect list) pairs. And that gets me batched drawing in a form that's easy to make automatic. T...
use crate::CONFIG_PATH; use crate::{importer::config::Config, Importer}; use log::{debug, error, info}; use std::error::Error; use std::os::unix::prelude::PermissionsExt; use std::path::Path; use crate::{BUFFER_SIZE, SOCKET_PATH}; use std::os::unix::net::UnixListener; use std::os::unix::net::UnixStream; use std::{fs, ...
/// Reaction contain one reaction #[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct Reaction { pub content: Option<String>, pub created_at: Option<String>, pub user: Option<crate::user::User>, } impl Reaction { /// Create a builder for this object. #[inline] pub fn builder() ...
use std::path::PathBuf; use structopt::StructOpt; use super::VarsFormat; #[derive(Debug, StructOpt)] #[structopt( name = "kay", about = "replace ${...} expressions in text", rename_all = "kebab-case" )] pub struct Opt { #[structopt(short = "i", long = "--input-file", parse(from_os_str))] pub inpu...
extern crate sdl2; extern crate rand; extern crate libc; extern crate time; use sdl2::sys; use sdl2::event::{Event}; use sdl2::keyboard::Keycode; use time::PreciseTime; use std::time::Duration; use std::cmp; use rand::Rng; // // Misc /* let a = Point {x: movement.x2 - movement.x1, y: movement.y2 - movement.y1}...
#[cfg(feature = "python")] pub mod py; mod test; /// The freely-jointed chain (FJC) model thermodynamics in the modified canonical ensemble approximated using an asymptotic approach valid for weak potentials. pub mod weak_potential; /// The freely-jointed chain (FJC) model thermodynamics in the modified cano...
use super::{SnapshotsState, StateBuilder}; use crate::error::{Error, UnderlyingError}; use crate::storage::stream::{ReadEggExt, WriteEggExt}; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use std::collections::VecDeque; use std::convert::TryFrom; use std::fs; use std::io; use std::path; // Public inter...
use crate::{ cli::{Command, PecuniaCli, Resource}, client::ApiClient, }; use anyhow::Result; use log::{self, debug, info}; use structopt::StructOpt; mod cli; mod client; mod configuration; mod model; #[tokio::main] async fn main() -> Result<()> { pretty_env_logger::init_custom_env("PECUNIA_LOG"); let ...
mod key_state; mod mouse_state; mod renderer; mod table_tool; use key_state::KeyState; use mouse_state::MouseState; use renderer::Renderer; use table_tool::TableTool; struct ModelessContent { content: State<SelectList<room_modeless::Content>>, page_x: i32, page_y: i32, minimized: bool, } struct Elemen...
struct Solution; impl Solution { pub fn unique_paths_with_obstacles(obstacle_grid: Vec<Vec<i32>>) -> i32 { let (m, n) = (obstacle_grid.len(), obstacle_grid[0].len()); let mut dp = vec![vec![0; n]; m]; for i in 0..m { for j in 0..n { if obstacle_grid[i][j] == 1 { ...
// Copyright 2020 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT use libp2p::gossipsub::Topic; use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(default)] pub struct Libp2pConfig { pub listening_multiaddr: String, pub bootstrap_peers: Vec<String>, #[serde(skip_deserializing)] //...
use std::fmt; use std::io; struct Person { firstname: String, lastname: String, age: u32, } //function to_string() impl fmt::Display for Person { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Your name is: {} {}. Your age is: {}", self.firstname, self.lastname, self.age) ...
#[doc = "Register `FDCAN_TTIR` reader"] pub type R = crate::R<FDCAN_TTIR_SPEC>; #[doc = "Register `FDCAN_TTIR` writer"] pub type W = crate::W<FDCAN_TTIR_SPEC>; #[doc = "Field `SBC` reader - SBC"] pub type SBC_R = crate::BitReader; #[doc = "Field `SBC` writer - SBC"] pub type SBC_W<'a, REG, const O: u8> = crate::BitWrit...
/* Copyright (c) 2023 Uber Technologies, Inc. <p>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 <p>http://www.apache.org/licenses/LICENSE-2.0 <p>Unless required by applicable law or agreed to...
use std::str::Chars; use std::iter::Peekable; use errors::{CalcrResult, CalcrError}; use token::Token; use token::TokVal::*; use token::OpKind::*; use token::DelimKind::*; pub fn lex_equation(eq: &String) -> CalcrResult<Vec<Token>> { let mut lexer = Lexer { pos: 0, iter: eq.chars().peekable(), ...
extern crate mio; extern crate rand; extern crate rustc_serialize; extern crate uuid; extern crate ws; mod models; mod server; mod engine; mod game; mod messages; fn main() { server::start(); }
/// An enum to represent all characters in the Specials block. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum Specials { /// \u{fff9}: '' InterlinearAnnotationAnchor, /// \u{fffa}: '' InterlinearAnnotationSeparator, /// \u{fffb}: '' InterlinearAnnotationTerminator, /// \u{ff...
#[doc = "Register `FDCAN_TTCPT` reader"] pub type R = crate::R<FDCAN_TTCPT_SPEC>; #[doc = "Field `CT` reader - Cycle Count Value"] pub type CT_R = crate::FieldReader; #[doc = "Field `SWV` reader - Stop Watch Value"] pub type SWV_R = crate::FieldReader<u16>; impl R { #[doc = "Bits 0:5 - Cycle Count Value"] #[inl...
use std::cmp::Reverse; use std::collections::BinaryHeap; use std::collections::HashMap; use crate::position::Pos; use crate::position::{neighbors, Dir}; fn make_path(first_middle: Pos, second_middle: Pos, back: &HashMap<Pos, PosData>) -> Vec<Pos> { let mut vec1 = vec![first_middle]; while back[vec1.last().un...
use spectral::prelude::*; use soapier::{self, wsdl}; #[wsdl("./fixtures/iptocountry.wsdl")] #[test] fn test_creates_find_country_as_string() { }
struct FizzBuzzer { next: u32, max: u32, } impl FizzBuzzer { fn new(starting_value: u32, length: u32) -> Self { let max = if length > 0 { starting_value + length - 1 } else { 0 }; // protect from underflow FizzBuzzer { next: starting_value, max } } } impl Iterator for FizzBuzzer { ...
//! Inline Python code directly in your Rust code. //! //! # Example //! //! ``` //! #![feature(proc_macro_hygiene)] //! use inline_python::python; //! //! fn main() { //! let who = "world"; //! let n = 5; //! python! { //! for i in range('n): //! print(i, "Hello", 'who) //! prin...
use std::{cmp, path::PathBuf}; use std::{str::FromStr, sync::Arc}; use druid::{ piet::PietTextLayout, widget::SvgData, Affine, Command, Env, Event, EventCtx, PaintCtx, Point, Rect, RenderContext, Size, Target, TextLayout, Vec2, Widget, WidgetId, WindowId, }; use include_dir::{include_dir, Dir}; use lapce_p...
use crate::crypto::hash::Hashable; use crate::miner::memory_pool::MemoryPool; use crate::network::server::Handle; use crate::transaction::Transaction; use std::sync::Mutex; /// Handler for new transaction // We may want to add the result of memory pool check pub fn new_transaction(transaction: Transaction, mempool: &...
extern crate libc; use libc::{c_void, size_t, pipe, fork, close, write, read}; use std::ffi::CString; fn main() { let mut pp = [0; 2]; let mut qq = [0; 2]; let message = "Hello"; unsafe { pipe(pp.as_mut_ptr()); pipe(qq.as_mut_ptr()); match fork() { 0 => { // 子プロセス close(pp[1]); close(qq[0]...
//! Common Google API types pub mod drive; pub mod oauth; use serde::Deserialize; /// Struct describing a generic response from a Google API #[derive(Deserialize, Debug)] pub struct GoogleResponse<T> { #[serde(flatten)] /// The data returned by Google, if there was no error pub data: Option...
// Import hacspec and all needed definitions. use hacspec_lib::*; const BLOCKSIZE: usize = 16; const IVSIZE: usize = 12; bytes!(Block, BLOCKSIZE); bytes!(Word, 4); bytes!(RoundKey, BLOCKSIZE); bytes!(Nonce, IVSIZE); bytes!(SBox, 256); bytes!(RCon, 15); // for aes128 bytes!(Bytes144, 144); bytes!(Bytes176, 176); // for...
pub mod constant; pub mod cluster;
#[derive(Debug)] pub struct Loan { pub amount: f64, pub periods: u32, pub period_rate: f64, pub payment: f64, } #[derive(Debug)] pub struct Payment { pub amount: f64, pub interest: f64, pub principal: f64, pub balance: f64, } impl Loan { pub fn new(amount: f64, rate: f64, periods: ...
#[doc = "Register `MASK` reader"] pub type R = crate::R<MASK_SPEC>; #[doc = "Register `MASK` writer"] pub type W = crate::W<MASK_SPEC>; #[doc = "Field `CCRCFAILIE` reader - Command CRC fail interrupt enable"] pub type CCRCFAILIE_R = crate::BitReader; #[doc = "Field `CCRCFAILIE` writer - Command CRC fail interrupt enabl...
#[doc = "Register `IDMACTRLR` reader"] pub type R = crate::R<IDMACTRLR_SPEC>; #[doc = "Register `IDMACTRLR` writer"] pub type W = crate::W<IDMACTRLR_SPEC>; #[doc = "Field `IDMAEN` reader - IDMA enable This bit can only be written by firmware when DPSM is inactive (DPSMACT = 0)."] pub type IDMAEN_R = crate::BitReader; #...
use std::collections::HashMap; use regex::Regex; struct TicketValidation { name: String, lower_one: usize, upper_one: usize, lower_two: usize, upper_two: usize } impl From<&str> for TicketValidation { fn from(line: &str) -> Self { let re = Regex::new(r"(\w+): (\d+)-(\d+) or (\d+)-(\d+)...
// TODO Vec should be any iterator // TODO: f64 should just a value that supports Sum and to string pub fn sum(nums: &Vec<f64>) -> f64 { let mut result: f64 = 0.0; // should be first for num in nums { result = result + num; } result } pub fn mean(nums: &Vec<f64>) -> f64 { let nums_sum = sum...
use std::io; fn test_set_1(n: String) -> (String, String) { let mut a = String::new(); let mut b = String::new(); for c in n.trim().chars() { if c == '4' { a.push('3'); b.push('1'); } else { a.push(c); b.push('0'); } } (a, b)...
use crate::Signature; use crate::Tagged; use crate::{CallInfo, ReturnValue, ShellError, Value}; use serde::{Deserialize, Serialize}; use std::io; pub trait Plugin { fn config(&mut self) -> Result<Signature, ShellError>; fn begin_filter(&mut self, _call_info: CallInfo) -> Result<Vec<ReturnValue>, ShellError> {...
fn main() { let tup = (500, 6.4, 1); let (_x, _y, _z) = tup; println!("The value of y is: {}", _y); println!("The value of y is: {}", tup.2); }
#[macro_use] extern crate nom; mod parser; mod entry; mod ledger; fn main() { println!("Hello, world!"); }
#![feature(str_char)] fn return_initial(s: &str) -> char { let string = s.to_string(); let v: Vec<char> = string.chars().collect::<Vec<char>>(); v[0] } fn main() { let s: &str = "apple"; let c = return_initial(s); println!("{}", c); }