text
stringlengths
8
4.13M
fn main() { for x in 1 .. 10 { println!("x == {}", x); } //println!("{}", 1..10); }
use syntax::ptr::P; use syntax::ast; /// A test as a description and associated block. #[derive(Clone)] pub struct Test { pub description: String, pub block: P<ast::Block>, pub test_config: TestConfig } #[derive(Clone)] pub struct TestConfig { pub ignored: bool, pub failing: bool } impl TestConfi...
fn main() { let adult = true; let age = if adult {"+18"} else { "-18"}; println!("Age is {}", age); }
use std::convert::TryFrom; use std::result; use std::fmt::Debug; use std::slice::Iter; #[derive(PartialEq, Eq, PartialOrd, Debug)] pub struct NonEmpty<T>(Vec<T>); impl<T> NonEmpty<T> { pub fn try_new(v: Vec<T>) -> result::Result<Self, Vec<T>> { if v.is_empty() { Err(v) } else { ...
/// https://blog.hamayanhamayan.com/entry/2021/03/14/001917 /// 解説を見た /// みかんの個数は最大W*1000個 = 10^6 /// O(n)で計算できるらしい fn main() { proconio::input! { A: u32, B: u32, W: u32 } let W = 1000 * W; let mut min: u32 = std::u32::MAX; let mut max: u32 = 0; for i in 1..W+1 { ...
use opentype::glyph_positioning::{GlyphPositioning, PairAdjustment, Table}; use opentype::layout::script::{Language, Script}; use truetype::Value; #[test] fn features() { let GlyphPositioning { features, .. } = ok!(Value::read(&mut setup!(CFF, "GPOS"))); let tags = features.headers.iter().map(|header| header.t...
use addr; use bytes::{Bytes, ByteStr, ToBytes}; use mio::{tcp, Socket}; use eio::{Reactor, Pair, Future}; use eio::frame::{self, Frame}; use eventual::{self, Async}; use std::sync::mpsc; #[test] pub fn test_tcp_echo() { ::env_logger::init().unwrap(); let addr = addr::localhost(); let reactor = Reactor::s...
use std::fmt; fn main() {} #[derive(Debug)] struct Segment(i32, char); impl fmt::Display for Segment { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}{}", self.0, self.1) } } #[derive(Debug)] struct Segments(pub Vec<Segment>); impl fmt::Display for Segments { fn fmt(&se...
type BitBoard = u64; #[derive(Copy, Clone)] struct Pieces { pawns: BitBoard, rooks: BitBoard, knights: BitBoard, bishops: BitBoard, queens: BitBoard, king: BitBoard, can_king_side_castle: bool, can_queen_side_castle: bool, } #[derive(Debug, PartialEq, Copy, Clone)] pub enum Color { ...
use crate::crawler::CrawlConfig; use regex::Regex; use tokio::macros::support::Pin; use std::future::Future; pub struct DefaultConfig { starting_url: String } impl DefaultConfig { pub fn new(starting_url: &str) -> Self { DefaultConfig { starting_url: starting_url.to_string() } } } impl CrawlConfi...
use std::mem; use std::ptr; use messages::Message; use storage::StorageValue; use libc::{c_char, size_t}; use assets::TradeAsset; use capi::common::*; use transactions::components::Intermediary; use transactions::trade_intermediary::{TradeIntermediaryWrapper, TradeOfferIntermediaryWrapper}; use error::{Error, ErrorK...
use std::sync::{Arc, Mutex}; use std::task::Poll; use std::time::Duration; use futures::stream::SplitSink; use futures_util::{SinkExt, StreamExt}; use log::*; use tokio::net::{TcpListener, TcpStream}; use tokio_tungstenite::tungstenite::Message; use tokio_tungstenite::{accept_async, WebSocketStream}; use crate::event...
#[cfg(feature = "postgres_default")] use crate::base::pg::RealmConnection; #[cfg(feature = "sqlite_default")] use crate::base::sqlite::RealmConnection; use crate::base::*; use chrono::prelude::*; use std::cell::Ref; pub struct In<'a, UD> where UD: crate::UserData, { pub ctx: &'a crate::Context, pub lang: L...
#[doc = "Reader of register RCC_MC_MLAHBLPENCLRR"] pub type R = crate::R<u32, super::RCC_MC_MLAHBLPENCLRR>; #[doc = "Writer for register RCC_MC_MLAHBLPENCLRR"] pub type W = crate::W<u32, super::RCC_MC_MLAHBLPENCLRR>; #[doc = "Register RCC_MC_MLAHBLPENCLRR `reset()`'s with value 0x17"] impl crate::ResetValue for super::...
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::CTRL4 { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut...
use crate::BenchStr; use std::ops::Deref; use std::sync::Arc; /// a not very optimized version - just using `Arc<str>`. #[derive(Clone)] pub struct StdLibArcStrOnly(Arc<str>); impl BenchStr for StdLibArcStrOnly { fn from_str(slice: &str) -> Self { Self(Arc::from(slice)) } fn from_static(slice: &'...
pub mod builder; pub mod prelude; mod css; mod state; use glib::clone; use glib::source::Continue; use gtk::Inhibit; use std::time::{Duration, SystemTime}; use super::Msg; use crate::config::Config; use prelude::*; use state::{Message, State}; use crate::x11::X11; const XCB_EWMH_CLIENT_SOURCE_TYPE_OTHER: u32 = 2; ...
use std::os; use std::io::fs; fn main() { let p = Path::new(os::args()[0].clone()); println!("YOLO!"); fs::unlink(&p); }
extern crate intcode_vm; use std::error::Error; use std::io::{self, Read, Write}; use intcode_vm::*; type Result<T> = ::std::result::Result<T, Box<dyn Error>>; fn main() -> Result<()> { let mut input = String::new(); io::stdin().read_to_string(&mut input)?; part_1(&input)?; part_2(&input)?; Ok((...
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ use bytes::BytesMut; use crate::gdbstub::commands::*; #[derive(PartialEq, Debug)] pub struct qC {...
use mandelbrot_set::buffer::Buffer; use mandelbrot_set::MandelbrotSet; const WIDTH: usize = 1400; const HEIGHT: usize = 800; fn main() { let mut buffer = Buffer::new(WIDTH, HEIGHT); let mandelbrot_set = MandelbrotSet::default(); mandelbrot_set.generate(WIDTH, HEIGHT, |x, y, color| { buffer.set_pi...
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::INT0STAT { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w ...
mod crates; mod godbolt; mod misc; mod moderation; mod playground; mod prefixes; mod showcase; use poise::serenity_prelude as serenity; pub type Error = Box<dyn std::error::Error + Send + Sync>; pub type Context<'a> = poise::Context<'a, Data, Error>; pub type PrefixContext<'a> = poise::PrefixContext<'a, Data, Error>;...
/* * 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 */ /// DeletedMonitor : Response from the delete monitor call. #[derive(Clone, Debug, PartialEq, Seriali...
use std::fs; use regex::Regex; #[derive(Debug)] struct Passport { byr: String, iyr: String, eyr: String, hgt: String, hcl: String, ecl: String, pid: String, cid: String } impl Passport{ fn is_valid(&self) -> bool{ if self.byr == "" || self.iyr == "" || self.eyr == "" ...
use std::fs::File; use std::net::Ipv4Addr; use std::time::{SystemTime, UNIX_EPOCH}; use dhcp; use netcfg; struct Dhcpd { verbose: bool, hwaddr: [u8; 6], ipaddr: Option<Ipv4Addr>, subnet: Option<Ipv4Addr>, router: Option<Ipv4Addr>, dns_server: Option<Ipv4Addr>, dhcp_server: Option<Ipv4Addr>...
use crate::{helpers::Writer, IntoResponse, Response}; use bytes::BytesMut; use hyper::{header, Body, StatusCode}; use std::{ error, fmt, io::{self, Write}, result, }; pub type Result<T = Response, E = Error> = result::Result<T, E>; pub struct Error { e: Box<dyn ErrorResponse + Send + Sync>, } impl Er...
extern crate glfw; use std::mem::{transmute, size_of}; use std::slice; use std::slice::IterMut; pub struct Control { pub last_frame: bool, pub this_frame: bool } impl Control { pub fn down(&self) -> bool { self.this_frame } pub fn up(&self) -> bool { !self.this_frame } pub fn just_dow...
#![feature(result_map_or_else)] use runner::run; use std::time::SystemTime; pub fn timestamp() -> f64 { SystemTime::now() .duration_since(SystemTime::UNIX_EPOCH) .unwrap() .as_millis() as f64 } fn main() { run(&|message| println!("{}", message), &timestamp); }
// Copyright (c) 2019 Intel Corporation. All rights reserved. // Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // 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 LICENSE-BSD-3-Clause file....
mod component; pub use component::{FiringComponent, FiringSet, FiringSubset, FiringSequence};
use std::thread; use std::sync::{Arc, Mutex}; use std::sync::mpsc; use websocket::sync::Server; use websocket::server::NoTlsAcceptor; mod client; mod dispatcher; pub struct WsServer { server: Server<NoTlsAcceptor>, } impl WsServer { pub fn run(self, dispatcher_rx: mpsc::Receiver<Vec<u8>>) { let client_senders: ...
use crate::{ config::InitConfig, constants::{BCRYPT_COST, JWT_SECRET_LENGTH}, }; use super::predefined; use err_derive::Error; use log::{info, error}; use tokio_postgres::{ Client, Error as PostgresError, NoTls, }; use unzip_n::unzip_n; #[derive(Debug, Error)] pub enum InitError { #[error(displ...
use futures::sync::oneshot; use futures::future; use futures::Future; use hyper; use hyper::{Response, Request, Uri}; use hyper::client::Client; use hyper::server::Service; use hyper_tls::HttpsConnector; use mktemp::Temp; use std::io::prelude::*; use std::marker::PhantomData; use std::path::Path; use std::process::Comm...
use std::ffi::OsString; use vec_map::VecMap; #[doc(hidden)] #[derive(Debug, Clone)] pub struct MatchedArg { #[doc(hidden)] pub occurs: u64, #[doc(hidden)] pub vals: VecMap<OsString>, } impl Default for MatchedArg { fn default() -> Self { MatchedArg { occurs: 1, val...
extern crate image; use std::process::exit; use std::env; use std::cmp::min; const TONE:u32 = 4; const TONE_STEP:u32 = 256 / TONE; fn usage(args: &Vec<String>) { println!("{} {}\n", args[0], "[image-file] [tile-size]"); exit(1); } fn mosaic(img: &image::RgbImage, x: u32, tile_x:u32, y: u32, tile_y: u32) -> ...
use http::HeaderMap; use http::header; /// An HTTP content length pub struct ContentLength { val: u64, } pub struct Error { _p: (), } impl ContentLength { pub fn get(map: &HeaderMap) -> Result<Option<Self>, Error> { match map.get(header::CONTENT_LENGTH) { Some(_) => unimplemented!(), ...
use std::{collections::HashMap, str::FromStr}; use problem::{Problem, solve}; enum Direction { East, SouthEast, SouthWest, West, NorthWest, NorthEast, } impl Direction { fn step(&self, pos: (i32, i32)) -> (i32, i32) { let (x, y) = pos; match self { Direction::E...
/// Defines a new control, creating a Rust wrapper, a `Deref` implementation, and a destructor. /// An example of use: /// ```ignore /// define_control!{ /// /// Some documentation /// #[attribute(whatever="something")] /// rust_type: Slider, /// sys_type: uiSlider, /// } /// ``...
use std::collections::HashMap; use super::super::super::{Coordinates, Location, Portal}; pub fn make<'a>() -> Location<'a> { let portal_to_house_left: Portal = Portal::new(0, 2); let portal_to_house_right: Portal = Portal::new(0, 3); let portal_to_laboratory: Portal = Portal::new(0, 1); let portal_to_r...
fn main() { let hexadecimal = 0x10; let octal = 0o10; let binary = 0b10; let mut n = 10; print!("{} ", n); n = hexadecimal; print!("{} ", n); n = octal; print!("{} ", n); n = binary; println!("{} ", n); }
#[doc = "Register `M5IER` reader"] pub type R = crate::R<M5IER_SPEC>; #[doc = "Register `M5IER` writer"] pub type W = crate::W<M5IER_SPEC>; #[doc = "Field `SEIE` reader - ECC single error interrupt enable"] pub type SEIE_R = crate::BitReader; #[doc = "Field `SEIE` writer - ECC single error interrupt enable"] pub type S...
// This file was generated mod ip_addr_private { pub trait Sealed { } } /// Extension for [`Ipv6Addr`](std::net::Ipv6Addr) pub trait IsntIpAddrExt: ip_addr_private::Sealed { /// The negation of [`is_unspecified`](std::net::Ipv6Addr::is_unspecified) #[must_use] fn is_not_unspecified(&self) -> bool; ///...
use std::ops::Deref; fn main() { let x = 5; // let y = &x; // assert_eq!(5, y); // error: no implementation for `{integer} == &{integer}` // let y = Box::new(x); // assert_eq!(5, y); // error: no implementation for `{integer} == std::boxed::Box<{integer}>` assert_eq!(5, x); // must use t...
use actix_web::{ body::{BoxBody, MessageBody}, dev::{ResponseHead, Service, ServiceRequest, ServiceResponse}, http::{header, StatusCode}, HttpRequest, HttpResponse, ResponseError, }; use futures::prelude::*; use std::str::FromStr; use thiserror::Error; use crate::{renderer::render_error, MiniserveConfi...
// Copyright (c) 2018-2020 Jeron Aldaron Lau // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0>, the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, or the ZLib // license <LICENSE-ZLIB or https://www.zlib.net/zlib_license.html> at ...
/* Copyright (c) 2017 The swc Project Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, ...
use super::*; impl Graph { /// Set the name of the graph. /// /// # Arguments /// /// * name: String - Name of the graph. pub fn set_name(&mut self, name: String) { self.name = name; } /// Set the embedding of the graph. /// /// # Arguments /// /// * embedding: ...
#[doc = "Reader of register BIST_CTL"] pub type R = crate::R<u32, super::BIST_CTL>; #[doc = "Writer for register BIST_CTL"] pub type W = crate::W<u32, super::BIST_CTL>; #[doc = "Register BIST_CTL `reset()`'s with value 0"] impl crate::ResetValue for super::BIST_CTL { type Type = u32; #[inline(always)] fn re...
#[allow(non_snake_case)] mod App; use App::decode_pixel; use self::decode_pixel::DecodePixel; use self::decode_pixel::DecodePixelFuncs; fn main() { #![allow(non_snake_case)] // git rid of warnings match DecodePixel::new_decoder("images/image.png".to_string()) { Ok(mut t) => { match t.begin...
use futures::StreamExt; use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::error::Error; use subspace_core_primitives::{SegmentHeader, SegmentIndex}; use subspace_networking::libp2p::PeerId; use subspace_networking::{Node, SegmentHeaderRequest, SegmentHeaderResponse}; use tracing::{debug, error, trace, warn}...
use super::{parse_args, ModifierTrait}; use crate::BoxSource; use nom::{branch::alt, bytes::complete::tag, IResult}; use rodio::Source; #[derive(Debug, PartialEq)] pub struct VolumeModifier { pub volume: f32, } impl Default for VolumeModifier { fn default() -> Self { Self { volume: 1.0 } } } impl...
use std::io; use std::io::BufRead; use std::io::BufReader; struct Instruction { opcode: String, op1: String, op2: Option<String>, } struct CPU { regs: [i64; 8], pc: i64, mul_count: usize, } impl CPU { fn new() -> Self { CPU { regs: [0; 8], pc: 0, ...
use crate::model::{Post, PostView}; use termion::event::Key; #[derive(Debug)] pub enum Msg { FetchSubreddit(Option<String>), // None fetches homescreen SubredditResponse(Vec<Post>, Option<String>), Error(String), CommentsResponse(PostView), Input(Key), }
extern crate ggez; use ggez::{Context, GameResult}; use ggez::graphics::{self, DrawMode, Point2}; use ggez::conf; use ggez::event; struct State { image: graphics::Image, } impl State { fn new(context: &mut Context) -> GameResult<Self> { let image = graphics::Image::new(context, "/imp.png")?; ...
pub fn max_sum_submatrix(matrix: Vec<Vec<i32>>, k: i32) -> i32 { use std::cmp::*; use std::collections::*; fn add(v1: &mut Vec<i32>, v2: &Vec<i32>) { for i in 0..v1.len() { v1[i] += v2[i]; } } fn max_sum_under(k: i32, arr: &[i32]) -> Option<i32> { let mut set = ...
use pest::iterators::Pair; use pest::iterators::Pairs; use pest::Parser; use pest_derive::Parser; use std::fs; use std::io; use std::io::prelude::*; // you're about to read some awful, hacky, PoC Rust code. // you've been warned. #[derive(Parser)] #[grammar = "recipe.pest"] struct RecipeParser; fn main() { let m...
extern crate sdl2; extern crate gl; extern crate nalgebra as na; use crate::rusty_life::input; use crate::rusty_life::view; use sdl2::*; use std::ffi; use std::ptr; pub struct Renderer { sdl_context : Sdl, sdl_window : sdl2::video::Window, gl_context : sdl2::video::GLContext, shader_program : gl::ty...
use error_chain::ChainedError; use serde_json; use std::thread; use std::time::Duration; use client; use client::from_string; use errors::*; use stops; #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] struct PredictionsList { pub predictions: Vec<Predictions>, } #[derive(Serialize, De...
use crate::vec3::*; pub struct Ray { pub pos: Vec3, pub dir: Vec3, } impl Ray { pub fn point_at_t(&self, t: f64) -> Vec3 { self.pos + self.dir * t } } #[cfg(test)] mod tests { use super::*; #[test] fn ray_struct() { let r = Ray { pos: Vec3(0.0, 0.0, 0.0), ...
mod repository; mod status; pub use repository::*; pub use status::*; use common::error::Error; use common::event::Event; use common::model::{AggregateRoot, StatusHistory, StringId}; use common::result::Result; use crate::domain::admin::Admin; use crate::domain::publication::Publication; pub type ContractId = String...
#![doc = "generated by AutoRust 0.1.0"] #![allow(unused_mut)] #![allow(unused_variables)] #![allow(unused_imports)] use crate::models::*; use reqwest::StatusCode; use snafu::{ResultExt, Snafu}; pub mod billing_accounts { use crate::models::*; use reqwest::StatusCode; use snafu::{ResultExt, Snafu}; pub a...
fn main() { let mut x = 5; { let y = &mut x; //x= 6; //error *y += 1; //y是不可变的,只能是x的可变引用,但是对y取值是可以变的,因为取值后是x,x是可变的 } println!("{}", x); } fn borrow_can_not_change() { let x = 5; let y = &x; //x = 6; //error //*y = 6; //error /************...
extern crate rand; use rand::prelude::*; use std::f64; use std::string::String; use std::fmt::Write; const L: usize = 32; const N: usize = L * L; struct System { cell: [i32; N], temperature: f64, } impl System { fn new() -> System { let t = 10.0; System { cell: [1; N], ...
#[doc = "Reader of register ICENABLER1"] pub type R = crate::R<u32, super::ICENABLER1>; #[doc = "Writer for register ICENABLER1"] pub type W = crate::W<u32, super::ICENABLER1>; #[doc = "Register ICENABLER1 `reset()`'s with value 0"] impl crate::ResetValue for super::ICENABLER1 { type Type = u32; #[inline(always...
use indicatif::{ProgressBar, ProgressIterator, ProgressStyle}; use std::{fs::File, io::prelude::*, io::BufReader}; /// Structure that saves the common parameters for reading csv files. /// /// # Attributes /// * path: String - The of the file to read. E.g. "/tmp/test.csv" /// * verbose: bool - If the progress bars and...
use std::convert::TryInto; use gl::types::*; use glutin::{ContextBuilder, PossiblyCurrent}; use glutin::event::{Event, KeyboardInput, ModifiersState, VirtualKeyCode, WindowEvent}; use glutin::event_loop::{ControlFlow, EventLoop}; use glutin::GlProfile; use glutin::window::WindowBuilder; use glutin::WindowedContext; us...
use neon::prelude::*; use uuid::Uuid; use access::{VaultConfig, WrappedVault}; use emerald_vault::{ Address, hdwallet::{ bip32::HDPath, WManager }, mnemonic::{ generate_key, Language, Mnemonic, MnemonicSize }, storage::error::VaultError, structs::{ ...
fn main() { // borrowing let s1 = String::from("hello") ; let len = calculate_length(&s1) ; println!("The Length of '{}' is {}.", s1, len) ; // mutable references let mut s = String::from("hello") ; change(&mut s) ; println!("{}", s) ; /* cannot have multiple mutable references to a particular piece o...
use std::io; fn main() { println!("Generate the nth Fibonacci number."); loop { println!("Please input the number you want to generate."); let mut n = String::new(); io::stdin().read_line(&mut n) .expect("Failed to read line."); let n: u32 = if let Ok(num) = n.tr...
use std::process::Command; fn main() { let output = Command::new("g++").args(&["src/lib.cpp", "-Wredundant-decls", "-Wcast-align", "-Wmissing-declarations", "-Wmissing-include-dirs", "-Wswitch-enum", "-Wswitch-default", "-Wextra", "-Wall", "-Werror", "-Winvalid-pch", "-Wredundant-decls", "-Wformat=2", "-Wmissing-f...
use std::collections::{HashMap, HashSet}; use std::mem; use std::time::Instant; const INPUT: &str = include_str!("../input.txt"); #[derive(Clone)] enum Rule { Terminal(char), NonTerminal(Vec<usize>), } fn parse_rule(s: &str) -> Vec<Rule> { if s.starts_with('"') { return vec![Rule::Terminal(s.char...
#![feature(start)] #![feature(asm)] #![feature(lang_items)] #![feature(panic_implementation)] #![feature(naked_functions)] #![no_std] /// Makes a syscall with the given arguments. macro_rules! syscall { ($num:expr) => {{ let result: u64; asm!("syscall" : "={rax}"(res...
// 3rd party imports {{{ use clap::Clap; // }}} // Own imports {{{ use crate::aur; use crate::config::Config; use crate::error::Error; // }}} #[derive(Clap)] pub struct CliArgs { packages: Vec<String>, } pub async fn handler(args: CliArgs, config: Config) -> Result<(), Error> { let aur = aur::Handle::from(&...
#[doc = "Reader of register RES_CAUSE2"] pub type R = crate::R<u32, super::RES_CAUSE2>; #[doc = "Writer for register RES_CAUSE2"] pub type W = crate::W<u32, super::RES_CAUSE2>; #[doc = "Register RES_CAUSE2 `reset()`'s with value 0"] impl crate::ResetValue for super::RES_CAUSE2 { type Type = u32; #[inline(always...
use std::fs::File; use std::io::{BufRead, BufReader}; pub fn exercise() { let data = load_data(); let mut total = 1; total *= traverse(1,1,(*data).to_vec()); total *= traverse(3,1,(*data).to_vec()); total *= traverse(5,1,(*data).to_vec()); total *= traverse(7,1,(*data).to_vec()); total *= traverse(1,2,(*data...
use arkecosystem_client::api::models::business::Business; use serde_json::Value; pub fn assert_business_data(actual: &Business, expected: &Value) { assert_eq!(actual.address, expected["address"].as_str().unwrap()); assert_eq!(actual.name, expected["name"].as_str().unwrap()); assert_eq!(actual.public_key, e...
#![allow(dead_code)] pub fn i18n(days: i32) -> String { match days { std::i32::MIN..=-2 => format!("arrived {} days ago", days.abs()), -1 => format!("arrived yesterday !"), 0 => format!("arrives today !"), 1 => format!("arrives tomorrow !"), 2..=std::i32::MAX => format!("arr...
// Copyright 2019 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. //! A simple port manager. use crate::error; use crate::lifmgr::{self, LIFProperties, LifIpAddr}; use failure::{Error, ResultExt}; use fidl_fuchsia_net; u...
use std::ops::Deref; use std::rc::Rc; enum List { Cons(i32, Box<List>), Nil, } fn main() { use crate::List::{Cons, Nil}; let list = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil)))))); test_mybox(); test_rc(); } struct MyBox<T>(T); impl<T> MyBo...
#[doc = "Register `SWPR` writer"] pub type W = crate::W<SWPR_SPEC>; #[doc = "P0WP\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum P0WP_AW { #[doc = "0: Write protection of SRAM2 page x is disabled"] Disabled = 0, #[doc = "1: Write protection of SRAM2 page x is enabled"] Enab...
pub mod asset; pub mod color; pub mod event; pub mod game; pub mod geometry2d; pub mod input; pub mod renderer; pub mod util; pub fn init_logging() { use env_logger::*; let default_log_level = if cfg!(debug_assertions) { "debug" } else { "info" }; Builder::from_env(Env::default().de...
use amethyst::ecs::prelude::{Component, VecStorage}; use crate::entities::tile::TileTypes; /// This component is meant for tiles. #[derive(Debug, Clone, Copy)] pub struct TileBase { pub kind: TileTypes, } impl Component for TileBase { type Storage = VecStorage<Self,>; }
use super::super::shift::*; #[derive(Copy)] pub struct Leaf { pub mask: u64, pub children: [u64; 64], } impl Clone for Leaf { fn clone(&self) -> Leaf { let mut new = Self::new(); new.mask = self.mask; for i in 0..64 { new.children[i] = self.children[i]; } ...
/* * Copyright 2018 Intel Corporation * * 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 agre...
use crate::switch::ToCKBCellDataTuple; use crate::utils::{ config::PLEDGE, transaction::*, types::{Error, ToCKBCellDataView}, }; use ckb_std::{ ckb_constants::Source, debug, high_level::{load_cell_capacity, load_input_out_point}, }; use core::result::Result; use molecule::prelude::Entity; pub f...
trait ShowPoint { fn point_print(&self); } #[derive(Debug)] struct Point{ x: i32, y: i32, } impl ShowPoint for Point{ fn point_print(&self){ println!("({},{})",self.x,self.y); } } fn print_to_me(x: Point)-> Point { x.point_print(); let y =Point{x: 28,y: 17}; y } fn main() { ...
// #![feature(str_split_once)] use common::Result; use db::{Database, Pod}; use event::obj::Listener; use notify::{watcher, DebouncedEvent, RecursiveMode, Watcher}; use std::{ collections::HashMap, sync::{mpsc::channel, Arc, Mutex}, time::Duration, }; use strum::AsRefStr; use walkdir::WalkDir; #[derive(De...
use crate::models; //use postgres::Client; #[derive(Debug)] pub struct Record { _id: i64, sync_ts: i64, origin: String, origin_id: i64, timestamp: i64, ip: i64, category: String, } impl Record { pub fn from(sync_ts: i64, log: models::LogEntry) -> Record { // map origin to strin...
mod checker; mod config; mod config_manipulate; mod debugger; mod deployment; mod generator; mod project_context; mod recipe; mod signal; mod tester; mod util; mod wallet; use std::env; use std::fs; use std::path::PathBuf; use std::process::exit; use std::str::FromStr; use anyhow::{anyhow, Result}; use checker::Check...
use clap::ArgMatches; use colors::*; use ears::{AudioController, Music}; use preprocess; use std::cmp; use std::env; use std::fs::File; use std::io; use std::io::{Read, Write}; use std::path::Path; use std::process::{Command, Stdio}; use std::sync::atomic; use std::thread; use std::time::Duration; use tempdir::TempDir;...
#[doc = "Register `PIR` reader"] pub type R = crate::R<PIR_SPEC>; #[doc = "Register `PIR` writer"] pub type W = crate::W<PIR_SPEC>; #[doc = "Field `INTERVAL` reader - Polling interval Number of CLK cycles between to read during automatic polling phases. This field can be written only when BUSY = 0."] pub type INTERVAL_...
use std::collections::HashMap; pub fn hash_map_reducer(hash_maps: Vec<HashMap<char, usize>>) -> HashMap<char, usize> { let mut result: HashMap<char, usize> = HashMap::new(); for hash_map in hash_maps { for (key, val) in hash_map.iter() { let count = result.entry(*key).or_insert(0); *count += *val;...
#[derive(Clone, Debug)] /// A container for aspects of a Portage Version pub struct Version { pv: String, pr: String, pvr: String, } impl Version { /// Construct a new Version struct pub fn new(pv: String, pr: String, pvr: String) -> Version { Version { pv, pr, pvr } } /// Return...
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under both the MIT license found in the * LICENSE-MIT file in the root directory of this source tree and the Apache * License, Version 2.0 found in the LICENSE-APACHE file in the root directory * of this source tree. */ use s...
use bls12_381::Scalar; use sapvi::{BlsStringConversion, Decodable, Encodable, ZKContract, ZKProof}; use std::fs::File; use std::time::Instant; type Result<T> = std::result::Result<T, failure::Error>; fn main() -> Result<()> { { // Load the contract from file let start = Instant::now(); le...
// array related exercices. mod array; // dynamic programming related exercices. mod dynamic_prog;
#![crate_type = "bin"] #![feature(globs)] pub mod lexer; mod tcp; mod irc; mod parse; mod actions;
extern crate libc; extern crate libqmlbind_sys as ffi; use libc::c_char; use libc::c_int; use std::ffi::CString; fn main() { println!("libqmlbind-sys example"); // Port of https://github.com/seanchas116/libqmlbind/blob/master/examples/hello_world_window/main.c // http://stackoverflow.com/a/34379937/17...
// Copyright 2015-2018 Capital One Services, LLC // // 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 o...