text
stringlengths
8
4.13M
use core::ffi::c_void; use core::ptr::null_mut; use crate::syscalls::*; pub struct RegionWalker { ptr: *mut c_void, } impl RegionWalker { pub fn new() -> Self { RegionWalker { ptr: null_mut(), } } } impl Iterator for RegionWalker { type Item = MEMORY_BASIC...
// This file contains data structures to store notes and helper functions to manipulate them. // We have different representations for notes in DB and notes not yet in DB. use chrono::{DateTime, Utc, Local}; use serde::{Serialize, Deserialize}; use sha3::{Shake128, digest::{Update, ExtendableOutput, XofReader}}; use th...
// Copyright (C) 2015-2021 Swift Navigation Inc. // Contact: https://support.swiftnav.com // // This source is subject to the license found in the file 'LICENSE' which must // be be distributed together with this source. All other rights reserved. // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ...
pub fn sort(numbers: Vec<i32>, reversed: bool) -> Vec<i32> { let mut result = numbers; for i in 1..result.len() { let key = result[i]; let mut j: i32 = i as i32 - 1; while (!reversed && j >= 0 && key < result[j as usize]) || (reversed && j >= 0 && key > result[j as usize]) ...
use clap::{Args, IntoApp, Parser, Subcommand}; #[test] fn arg_help_heading_applied() { #[derive(Debug, Clone, Parser)] struct CliOptions { #[clap(long)] #[clap(help_heading = Some("HEADING A"))] should_be_in_section_a: Option<u32>, #[clap(long)] no_section: Option<u32>,...
/* * Rust BareBones OS * - By John Hodge (Mutabah/thePowersGang) * * arch/x86/x86_io.rs * - Support for the x86 IO bus * * == LICENCE == * This code has been put into the public domain, there are no restrictions on * its use, and the author takes no liability. */ #[inline(always)] pub unsafe fn inb(port: u1...
use serde_json; use std::cmp::Ordering; #[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Hash)] #[serde(rename_all = "camelCase")] pub struct SharedLibrary { pub start: u64, pub end: u64, pub offset: u64, pub name: String, pub path: String, pub debug_name: String, pub debug_path: Stri...
use std::collections::HashSet; fn create_string(s: &str, v: Vec<Option<usize>>) -> String { let mut idx = s.len(); let mut slice_vec = vec![]; while let Some(prev) = v[idx] { slice_vec.push(&s[prev..idx]); idx = prev; } slice_vec.reverse(); slice_vec.join(" ") } fn word_br...
// generic function to get both floats and integers pub fn get_number<T>(message: &str) -> T // restricts the function to only work with types that implement // the from str function. where T: std::str::FromStr, { let number: T = loop { println!("{}", message); let mut input = String::new(); ...
fn hand_back() { fn foo(v1: Vec<i32>, v2: Vec<i32>) -> (Vec<i32>, Vec<i32>, i32) { // do stuff with _v1 and _v2 // hand back ownership, and the result of our function (v1, v2, 42) } let v1 = vec![1, 2, 3]; let v2 = vec![1, 2, 3]; let (_v1, _v2, _answer) = foo(v1, v2); // can't use _v1 / _v2 here! }...
//! # Model builder //! //! `model_builder` defines a basic class to create models from //! an initializer and an optimizer. extern crate ndarray; use ndarray::{ArrayBase, Data, Ix1, Ix2}; use crate::regression::{Initialize as RegInit, Optimize as RegOpt, Regression}; use crate::classification::{ Clas...
// This file is part of dpdk. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/dpdk/master/COPYRIGHT. No part of dpdk, including this file, may be copied, modified, propagated, or distributed except accordin...
use super::{View, ViewMut}; #[derive(Clone, Debug)] pub struct Frame { pub page: Vec<u8>, pub transparent: Option<u8>, pub width: usize, pub height: usize, } impl Frame { pub fn new(width: usize, height: usize) -> Self { Self { page: vec![0; width * height], transpa...
#[derive(Debug, PartialEq)] pub struct Info { pub i: u64, pub j: u64, } pub type InfoList = Vec<Info>; pub trait InfoListMethod { fn get_from_i(&self, i: u64) -> Info; } impl InfoListMethod for InfoList { fn get_from_i(&self, i: u64) -> Info { let res = self.iter().find(|&e| (e.i == i)).unwra...
use wasm_bindgen_test::*; include!(concat!(env!("OUT_DIR"), "/no_interface.rs")); #[wasm_bindgen_test] fn smoke() { let obj = GetNoInterfaceObject::get(); assert_eq!(obj.number(), 3.0); obj.foo(); }
#[derive(Copy, Clone, Debug)] pub struct Color { r: u8, g: u8, b: u8, } impl Color { pub fn new(r: u8, g: u8, b: u8) -> Self { Color {r, g, b} } pub fn black() -> Self { Self::new(0, 0, 0) } pub fn gray() -> Self { Self::new(120, 120, 120) } pub fn whi...
#[doc = "Register `TZC_REGION_TOP_LOW0` reader"] pub type R = crate::R<TZC_REGION_TOP_LOW0_SPEC>; #[doc = "Field `TOP_ADDRESS_LOW` reader - TOP_ADDRESS_LOW"] pub type TOP_ADDRESS_LOW_R = crate::FieldReader<u32>; impl R { #[doc = "Bits 12:31 - TOP_ADDRESS_LOW"] #[inline(always)] pub fn top_address_low(&self)...
use http::header::{ ACCESS_CONTROL_ALLOW_HEADERS, ACCESS_CONTROL_ALLOW_METHODS, ACCESS_CONTROL_ALLOW_ORIGIN, ACCESS_CONTROL_REQUEST_HEADERS, ACCESS_CONTROL_REQUEST_METHOD, ORIGIN, }; use http::Method; use crate::http_tests::{Header, TestRequest, TestServer}; /// A simple cors request test. pub async fn test_cors_...
use std::{env, path::PathBuf}; use glob::glob; fn main() -> Result<(), std::io::Error> { println!("cargo:rerun-if-changed=../../../common"); let files = glob("../../../common/*.fbs") .unwrap() .into_iter() .filter_map(|e| e.ok()) .collect::<Vec<_>>(); let files = files.ite...
use std::env; use std::io::{stdin, stdout, Write}; use std::path::Path; use std::process::{Child, Command, Stdio}; fn main() { loop { print!("Let me > "); stdout().flush().unwrap(); let mut input = String::new(); stdin() .read_line(&mut input) .expect("Someth...
use exonum::{ api::node::public::explorer::{TransactionQuery, TransactionResponse}, crypto::{self, Hash, PublicKey, SecretKey}, messages::{self, RawTransaction, Signed}, }; use exonum_testkit::{ApiKind, TestKit, TestKitApi, TestKitBuilder}; // Import data types used in tests from the crate where the servi...
use crate::blockchain::BlockchainR; use actix_web::error::{Error, ErrorBadRequest, ErrorNotFound}; use actix_web::{App, Json, Path, Responder, State}; use chain_crypto::PublicKey; use chain_impl_mockchain::account::{AccountAlg, Identifier}; use jormungandr_lib::interfaces::AccountState; use std::str::FromStr; pub fn c...
/// Be careful when using that function pub fn create_universe() {} pub struct Builder {} impl Builder { /// Do not try at home fn build_rocket(&self) {} fn build_shuttle(&self) {} }
use serde::{Deserialize, Serialize}; use serde_json; mod rand_num_gen; use std::env; use std::fs::{self, OpenOptions}; use std::path::Path; use std::io::prelude::*; #[allow(non_snake_case)] #[derive(Serialize, Deserialize)] struct Tenant { id: String, numPods: u32, } fn main() { let args: Vec<String> = e...
#![cfg(feature = "std")] use tabled::settings::{ object::{Columns, Segment}, Alignment, Format, Height, Modify, Style, }; use crate::matrix::Matrix; use testing_table::test_table; #[cfg(feature = "color")] use owo_colors::OwoColorize; test_table!( cell_height_increase, Matrix::new(3, 3) .wit...
use crate::*; #[near_bindgen] impl Contract { pub fn nft_tokens( &self, from_index: U64, limit: u64, ) -> Vec<JsonToken> { let mut tmp = vec![]; let keys = self.tokens_by_id.keys_as_vector(); let start = u64::from(from_index); let end = min(start + limit...
// This file is part of Substrate. // Copyright (C) 2020 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free S...
// print 'Hello,world!' on the screen // To run this program: // $ rustc main.rs // $ ./main fn main() { println!("Hello, world!"); }
fn main() -> Result<(), Box<dyn std::error::Error>> { // セレクターをパース (このセレクターは記事のアンカーノード群(タイトル)を指す。 <a href="link">Title</a>) let selector = scraper::Selector::parse("h-simple-product-page").unwrap(); /* let doc = scraper::Html::parse_document(html); for node in doc.select(&selector) { println...
use assert_fs::prelude::{FileTouch, FileWriteStr, PathChild, PathCreateDir}; use assert_fs::TempDir; use chef::Skeleton; #[test] pub fn no_workspace() { // Arrange let content = r#" [package] name = "test-dummy" version = "0.1.0" edition = "2018" [[bin]] name = "test-dummy" path = "src/main.rs" [dependencies...
mod learning; use learning::variable as n_variable; use learning::datatype; fn main() { n_variable::start(); datatype::datatype(); // println!("Hello, worlda!"); }
use anyhow::Result; use itertools::Itertools; use ndarray::{parallel::prelude::*, Array2, ArrayBase, Axis}; use num_traits::Float; use ordered_float::OrderedFloat; use superslice::*; pub fn hrr<T: Ord>(a: T, b: T) -> T { std::cmp::max(a, b) } pub fn mr<T: Float>(a: T, b: T) -> T { (a * b).sqrt() } #[allow(de...
#[doc = "Register `ICR` writer"] pub type W = crate::W<ICR_SPEC>; #[doc = "Field `CCF` writer - Computation complete flag clear Setting this bit clears the CCF status bit of the AES_SR and AES_ISR registers."] pub type CCF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `RWEIF` writer - Read or w...
use std::rc::Rc; use crate::binary::chunk::*; #[derive(Debug, Clone)] pub struct Writer { data: Vec<u8>, } impl Writer { #[inline] pub fn new() -> Self { Self { data: Vec::with_capacity(1024) } } #[inline] pub fn write_byte(&mut self, b: u8) { self.data.push(b); } #[...
use aoc::read_data; use std::cmp::min; use std::convert::Infallible; use std::error::Error; use std::str::FromStr; #[derive(Debug, Clone, PartialEq)] enum Cell { Floor, /// free seat L, /// taken seat Seat, } impl std::fmt::Display for Cell { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> s...
pub fn is_power_of_four(n: i32) -> bool { match n { n if n <= 0 => false, 1 => true, n if n % 4 == 0 => Self::is_power_of_four(n / 4), _ => false, } }
// 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. pub mod psk; use self::psk::Psk; use Error; use eapol; use failure; use key::exchange::Key; use rsna::SecAssocResult; pub enum Method { Psk(psk::Psk)...
/* * 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 */ /// Organization : Create, edit, and manage organizations. #[derive(Clone, Debug, PartialEq, Serializ...
use std::fmt::Write; use eyre::Report; use hashbrown::HashMap; use rosu_v2::prelude::{Beatmapset, GameMode, Score, User}; use crate::{ commands::osu::TopOrder, core::Context, embeds::{osu, Author, Footer}, pp::PpCalculator, util::{ constants::OSU_BASE, datetime::how_long_ago_dynamic, numbe...
use ::test_utils::load_db_from_json; use std::env; fn main() { let args: Vec<String> = env::args().collect(); if args.len() < 4 { panic!("Expected 3 arguments: an input path, a splits file path, and a gridstore path") } load_db_from_json(&args[1], &args[2], &args[3]); }
#![allow(clippy::forget_non_drop)] // This example exists to allow for profiling // applications to provide details about // the criterion benchmarks use ress::Tokenizer; static REGEX: &[&str] = &[ r#"x/"#, r#"|/"#, r#"|||/"#, r#"^$\b\B/"#, r#"(?=(?!(?:(.))))/"#, r#"a.\f\n\r\t\v\0\[\-\/\\\x00\u...
use rusqlite::Transaction; /// This schema migration creates a missing index that is used to join blocks /// and transactions when we're querying for all transactions in a block. /// /// According to load tests this improves block query performance significantly. pub(crate) fn migrate(transaction: &Transaction<'_>) ->...
use iron::mime::Mime; use iron::{Iron, Request, Response, IronResult, status}; use router::Router; use mount::Mount; use staticfile::Static; use std::io::Read; use std::sync::mpsc::Sender; use std::fs::File; use std::path::Path; use std::io::Error as IoError; use client_api; use webhooks; use types::HandledGithub...
use crate::days::day21::{FoodLine, parse_input, default_input}; use std::collections::{HashMap, HashSet}; pub fn run() { println!("{}", food_str(default_input()).unwrap()) } pub fn food_str(input : &str) -> Result<usize, ()> { food(parse_input(input)) } pub fn food(input : Vec<FoodLine>) -> Result<usize, ()>...
fn main() { let mut x = 5; println!("The valueof x is: {}", x); x = 5; println!("The valueof x is: {}", x); let _signed:i8 = 1; let _unsigned:u8 = 1; let _x = 2.0; // f64 let _y : f32 = 3.0; let tup: (i32, f64, u8) = (500, 4.6, 1); //tuple println!("this is a tuple ({}, {}, {...
pub mod comma; pub mod json_array; pub mod json_object; pub mod name; pub mod property_assignment; pub mod value; pub mod visitor; pub mod whitespace; use visitor::ExpressionVisitor; pub trait Expression: std::fmt::Debug { fn accept(&mut self, visitor: &mut dyn ExpressionVisitor); } #[derive(Debug)] pub enum Json...
//! A Lambertian diffuse material. use crate::{ hittable::HitRecord, material::{Scatter, ScatterType}, pdf::PDF, ray::Ray, texture::Texture, }; use rand::Rng; /// A Lambertian diffuse material. Attenuation is adjustable via the `abedo` /// property. #[derive(Clone, Debug)] pub struct Lambertian { ...
use crate::container::incomplete_vector_from_container_response; use crate::container::responses::ListContainersResponse; use crate::core::prelude::*; use azure_core::errors::AzureError; use azure_core::headers::request_id_from_headers; use azure_core::prelude::*; use hyper::{Method, StatusCode}; #[derive(Debug, Clone...
use std::str::from_utf8; use chrono::prelude::*; use serde::{Deserialize, Serialize}; use sled::transaction; use sled::Transactional; use transaction::{ConflictableTransactionError, TransactionalTree}; use uuid::Uuid; use crate::base32; #[derive(Debug, Hash, PartialEq, Eq)] pub enum TreeNames { DataTr...
pub use super::parity_bit::add_parity_bit; pub use super::parity_bit::compute_parity_bit; pub use super::parity_bit::compute_parity_bit_opt; pub use super::parity_bit::has_parity; pub use super::parity_bit::remove_parity_bit; #[test] fn test_compute_parity_bit() { // out of range assert_eq!(compute_parity_bit...
pub fn roman_to_int(s: String) -> i32 { s.replace("IV", "IIII") .replace("CM", "DCCCC") .replace("XC", "LXXXX") .replace("IX", "VIIII") .replace("CD", "CCCC") .replace("XL", "XXXX") .chars() .fold(0, |mut acc, el| { match el { 'I' =...
// for command line input use std::io::stdin; use std::fs::File; use std::io::prelude::*; use std::str; use std::io::BufReader; use std::io::Result; // for update from form? &str for remote data such as form, which can't take ownership pub fn none_if_empty_or_str<'a>(input: &'a String) -> Option<&'a str> { if in...
// Wicci Shim Module // PostgreSQL Interface // fn foo(db: &Connection) { // let f:() = Connection::connect("", &SslMode::None); // let g:() = db.prepare(""); // core::result::Result<postgres::Statement<'_>, postgres::error::Error> // } // * need to define database connection pool structures!! use std::process; ...
use sgx_types::*; use sgx_urts::SgxEnclave; static ENCLAVE_FILE: &'static str = "libenclave1.signed.so"; extern "C" { fn say_something( eid: sgx_enclave_id_t, retval: *mut sgx_status_t, some_string: *const u8, len: usize, ) -> sgx_status_t; } pub struct Enclave(SgxEnclave); i...
use ::core; use ::core::cell::{RefCell, RefMut}; use mantle::concurrency::SingleThreaded; use mantle::KError; use kobject::*; use memory::LinkedList; static AVAILABLE_CAPS: SingleThreaded<RefCell<LinkedList<CapRange>>> = SingleThreaded(RefCell::new(LinkedList::empty())); fn get_avail_caps_list() -> RefMut<'static...
use serde_json::Value; use serde_json as json; use test_transaction; pub fn run_test(name: &str, test: &str) { let test: Value = json::from_str(test).unwrap(); assert_eq!(test_transaction(name, &test, true), Ok(true)); } #[cfg(feature = "bench")] use test::Bencher; #[cfg(feature = "bench")] pub fn run_bench(...
use crate::slack; use crate::{EventDetails, SlackConfig, Standup, StandupList, User, UserList, UserState}; use chrono::Local; pub fn challenge(c: String) -> String { c } pub fn event( evt: EventDetails, standups: &mut StandupList, users: &mut UserList, ) -> (String, String) { let user = users.find...
extern crate permutohedron; extern crate atty; static WORDLIST : &str = include_str!("wordlist"); use std::io::Write; use std::collections::BTreeSet; fn main() { let stdout = std::io::stdout(); let mut out = stdout.lock(); let mut words = BTreeSet::new(); for word in WORDLIST.split('\n') { w...
use pkcs_padding; fn main() { let unpadded = "YELLOW SUBMARINE"; let result = pkcs_padding::pad_to_str(&unpadded, 20); println!("Found result: {}", result); }
use crate::peek::Peekable; use crate::{AsyncRead, AsyncWrite, LolbResult}; use std::future::Future; use std::io::{Read, Write}; pub trait Socket: Read + Write + AsyncRead + AsyncWrite + Unpin {} /// Trait for providing incoming connections to LoadBalancer::handle_incoming() pub trait ConnectionProvider<S, F> where ...
use crate::lib::environment::Environment; use crate::lib::error::DfxResult; use crate::lib::identity::Identity; use crate::lib::provider::{create_agent_environment, get_network_descriptor}; use crate::lib::root_key::fetch_root_key_if_needed; use clap::Clap; use tokio::runtime::Runtime; /// Gets the canister ID for th...
use crate::history::{self}; use crate::Alphabet; use crate::TestSpaceFile; use crate::{LineModification, TestSpace, TestSpaceTextFile, TextModifier}; use rand::{self, Rng}; use std::fs; use std::path; impl TestSpace { const SUFFIX: &'static str = "_ts"; /// Creates a test space that represents a directory in t...
mod animation; mod input; mod transformation; pub use self::animation::*; pub use self::input::*; pub use self::transformation::*;
// TODO : move to metadata use crate::core::spotify_id::SpotifyId; use crate::protocol::spirc::TrackRef; use serde::{ de::{Error, Unexpected}, Deserialize, }; #[derive(Deserialize, Debug, Default, Clone)] pub struct StationContext { pub uri: String, pub title: String, #[serde(rename = "titleUri")...
use preexplorer::prelude::*; fn main() -> anyhow::Result<()> { comparing_many()?; increasing_comparison()?; Ok(()) } fn comparing_many() -> anyhow::Result<()> { // Computing the data let data_1 = vec![0. as f32, 1., 2., 3., 4., 5.]; let data_2 = vec![0., 1.4, 10., 4.]; // Define plotab...
extern crate libc; pub mod benchmark_utilities { use std::os::raw::c_void; type Handle = *mut c_void; type Dword = libc::c_uint; const REALTIME_PRIORITY_CLASS: Dword = 0x100; pub fn set_realtime() { unsafe { let current = GetCurrentProcess(); SetPriorityClass(current, REALTIME_PRIORITY_CLASS); } } ...
use super::utils::{error::BadgeError, BadgeOptions, QueryInfo}; use actix_web::{http, middleware, web, HttpRequest, HttpResponse}; use awc::Client; use badgeland::{Badge, BadgeData, Icon, Size, Style}; use serde::Deserialize; use std::{ collections::hash_map::DefaultHasher, convert::TryFrom, hash::{Hash, Ha...
#[doc = "Register `DR` reader"] pub type R = crate::R<DR_SPEC>; #[doc = "Register `DR` writer"] pub type W = crate::W<DR_SPEC>; #[doc = "Field `BYTE0` reader - Data byte 0"] pub type BYTE0_R = crate::FieldReader; #[doc = "Field `BYTE0` writer - Data byte 0"] pub type BYTE0_W<'a, REG, const O: u8> = crate::FieldWriter<'...
use std::ffi::CStr; use esp_idf_bindgen::{ esp_err_t, nvs_get_i8, nvs_set_i8, nvs_get_u8, nvs_set_u8, nvs_get_i16, nvs_set_i16, nvs_get_u16, nvs_set_u16, nvs_get_i32, nvs_set_i32, nvs_get_u32, nvs_set_u32, nvs_get_i64, nvs_set_i64, nvs_get_u64, nvs_set_u64, nvs_get_blob, nvs_set_b...
#[doc = "Register `ITLINE7` reader"] pub type R = crate::R<ITLINE7_SPEC>; #[doc = "Field `EXTI4` reader - EXTI4"] pub type EXTI4_R = crate::BitReader; #[doc = "Field `EXTI5` reader - EXTI5"] pub type EXTI5_R = crate::BitReader; #[doc = "Field `EXTI6` reader - EXTI6"] pub type EXTI6_R = crate::BitReader; #[doc = "Field ...
mod hr; mod faisalabad { #[derive(Debug)] pub struct Food { pub name : String, pub price : u16, } #[derive(Debug)] pub enum Direction { Right, Left, Up, Down, } pub fn abc (){ println!("Welcoe in abc"); } } use faisalabad::Foo...
extern crate ralloc; #[test] fn minimal() { let a = Box::new(1); let b = Box::new(2); let c = Box::new(3); assert_eq!(*a, 1); assert_eq!(*b, 2); assert_eq!(*c, 3); }
use std::sync::Arc; use vulkano::descriptor::descriptor_set::{DescriptorSet, PersistentDescriptorSet}; use vulkano::descriptor::pipeline_layout::PipelineLayoutAbstract; use vulkano::format::Format; use vulkano::image::{ImmutableImage, ImageDimensions, MipmapsCount}; use vulkano::image::view::ImageView; use vulkano::sa...
mod chat; mod util;
use core::cmp::{max, min}; /// Solves the Day 16 Part 1 puzzle with respect to the given input. pub fn part_1(input: String) { for line in input.split("\n") { let bits = parse_line(line); let mut sum = 0; let mut beg = 0; let end = bits.len(); while beg < end - 10 { ...
use crate::context::Context; use crate::errors::ShellError; use crate::parser::{hir, RawToken, Token}; use crate::TaggedItem; use crate::Text; use std::path::PathBuf; pub fn baseline_parse_single_token( token: &Token, source: &Text, ) -> Result<hir::Expression, ShellError> { Ok(match *token.item() { ...
use std::{ thread, time::{Duration, Instant}, }; use exgui_core::{controller, Color, Comp, KeyboardController, MouseController, Real, Render, SystemMessage}; pub use gl; pub use glutin; use glutin::{ event::{ElementState, Event, KeyboardInput, MouseButton, MouseScrollDelta, VirtualKeyCode, WindowEvent}, ...
// --- Day 3: Toboggan Trajectory --- // With the toboggan login problems resolved, you set off toward the // airport. While travel by toboggan might be easy, it's certainly not // safe: there's very minimal steering and the area is covered in // trees. You'll need to see which angles will take you near the // fewest ...
#[cfg(all(test, feature = "md5"))] mod test { use std::io::Write; use cryptographer::md5::{self, Hash}; use encoding::hex; #[test] fn md5() { let mut h = md5::new(); let hello = "hello".as_bytes(); h.write(&hello).expect("failed to consume 'hello'"); let world = "...
use iron::prelude::*; use iron::status; use rss::{Channel}; use common::lazy_static::PATH; use services::topic::get_rss_topic_list; pub fn render_rss(_: &mut Request) -> IronResult<Response> { let items = get_rss_topic_list(); let channel = Channel { title: "Rust社区".to_owned(), description: ...
use crate::image_data::ImageData; use crate::rect::Rect; use std; use std::fmt::Debug; use std::sync::atomic::Ordering; use std::any::Any; use std::sync::{Arc, Mutex}; use std::sync::atomic::AtomicUsize; use std::cell::{RefCell, Ref, RefMut}; use std::ops::{Deref, DerefMut}; use lazy_static::lazy_static; static NEXT_...
use crate::parser::Error; use crate::schedule_at; use crate::time_domain::RuleKind::*; #[test] fn basic_timespan() -> Result<(), Error> { assert_eq!( schedule_at!("14:00-19:00", "2020-06-01"), schedule! { 14,00 => Open => 19,00 } ); assert_eq!( schedule_at!("10:00-12:00,14:00-16:00...
pub mod apps;
use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; use hydroflow::{assert_graphvis_snapshots, hydroflow_syntax}; use multiplatform_test::multiplatform_test; macro_rules! assert_contains_each_by_tick { ($results:expr, $tick:expr, &[]) => {{ assert_eq!($results.borrow().get(&$tick), Non...
#[doc = "Register `SR` reader"] pub type R = crate::R<SR_SPEC>; #[doc = "Field `TEF` reader - Transfer error flag This bit is set in Indirect mode when an invalid address is being accessed in Indirect mode. It is cleared by writing 1 to CTEF."] pub type TEF_R = crate::BitReader; #[doc = "Field `TCF` reader - Transfer c...
use actix_identity::Identity; use actix_web::{client::Client, error, http, web, Error, HttpResponse}; use futures::Future; use tera::{Context, Tera}; use crate::model; use crate::utils; use crate::utils::HandlerErrors; pub fn index_view( client: web::Data<Client>, api_key: web::Data<model::APIKey>, pool: ...
use flux::ast::walk; use lspower::lsp; #[derive(Clone, Debug)] pub struct NodeFinderNode<'a> { pub node: walk::Node<'a>, pub parent: Option<Box<NodeFinderNode<'a>>>, } #[derive(Clone)] pub struct NodeFinderVisitor<'a> { pub node: Option<NodeFinderNode<'a>>, pub position: lsp::Position, } impl<'a> Nod...
pub(crate) mod errors; pub(crate) mod fulfillment_checker; pub(crate) mod packet; pub use self::errors::ParseError; pub use self::fulfillment_checker::IlpFulfillmentChecker; pub use self::packet::{ parse_f08_error, IlpFulfill, IlpPacket, IlpPrepare, IlpReject, PacketType, Serializable, };
/* * QuickCheck testing for the linear algebra library against * the Nalgebra rust library. */ extern crate nalgebra; extern crate quickcheck; use hacspec_lib::prelude::*; use hacspec_linalg::*; use nalgebra::DMatrix; use quickcheck::*; type IntSize = i32; // === Helper functions === fn assert_matrices(x: Matrix,...
use crate::data::COORDINATES; use crate::Location; #[allow(dead_code)] pub fn get_locations() -> Vec<Location> { COORDINATES .iter() .fold(Vec::new(), |mut acc: Vec<Location>, x| { acc.push(Location { longitude: x[0], altitude: x[2], latit...
use crate::util::time; pub fn day20() { println!("== Day 20 =="); let input = "src/day20/input.txt"; time(part_a, input, "A"); time(part_b, input, "B"); } #[derive(Debug)] struct Message { msg: Vec<i32>, } impl Message { fn parse(input: &str) -> Self { let mut msg = Vec::new(); ...
use std::fs; use std::f32::consts::PI; struct Vector2D { x: isize, y: isize, } impl Vector2D { fn rotate(&mut self, radian: f32) { let newx = self.x * radian.cos() as isize - self.y * radian.sin() as isize; let newy = self.x * radian.sin() as isize + self.y * radian.cos() as isize; ...
use super::Cache as InnerCache; use std::{borrow::Borrow, hash::Hash, sync::Arc, time::Duration}; use tokio::{sync::Mutex, task, time}; /// Async version of Cache with LRU eviction strategy pub struct Cache<K, V>(Mutex<InnerCache<K, V>>); #[allow(clippy::needless_doctest_main)] impl<K: 'static + Hash + Eq + Sync + Se...
use crate::prelude::*; pub mod sharable { use crate::prelude::*; #[derive( Clone, From, Deref, DerefMut, Debug, Collectable, Finalize, Send, Sync, Unpin, NoTrace, )] #[from(forward)] pub struct DataFrame(pub Gc<ConcreteDataFrame>); #[derive(Debug, Collectable, NoTrace, Finalize, Send,...
/// Parent visitor implementation pub mod parent; #[cfg(target_arch = "wasm32")] extern crate console_error_panic_hook; use crate::token::{ByteValue, ControlOperator, RangeValue, SocketPlug, Token, Value}; use std::{ fmt::{self, Write}, marker::PhantomData, }; #[cfg(feature = "std")] use std::borrow::Cow; #[cf...
use crate::{AGENT_NUM_UPPER_BOUND, STEP_SG_SIDE, LAST_UNTAGGED_DISPLAY_LENGTH}; use crate::action::*; use crate::display::RenderObject; use crate::grid::{Grid, Position, PositionChange}; use rand::rngs::StdRng; use rand::{Rng, SeedableRng}; use rayon::prelude::*; use std::collections::HashMap; pub type Id = u32; #[...
use bevy::prelude::*; use bevy::window::WindowMode; use bevy_tmx::TmxPlugin; fn main() { App::build() .insert_resource(WindowDescriptor { title: "Ortho".to_string(), width: 1024., height: 720., vsync: false, resizable: true, ...
use crate::{ cmd::oui::*, traits::{TxnEnvelope, TxnFee, TxnSign, TxnStakingFee, B64}, }; use helium_api::{models::transactions::PendingTxnStatus, ouis}; use serde_json::json; use structopt::StructOpt; /// Updates an organizational OUI. The transaction is not /// submitted to the system unless the '--commit' op...
use super::*; use rdisk_shared::{AsByteSlice, AsByteSliceMut, StructBuffer}; #[repr(C, packed)] #[derive(Copy, Clone)] struct VhdDiskGeometry { cylinders: u16, heads: u8, sectors_per_track: u8, } #[repr(C, packed)] #[derive(Copy, Clone)] pub(crate) struct VhdFooterRecord { cookie_id: u64, features...
#[derive(Debug, Clone, Copy)] pub enum Parenthesis { LParen, RParen, LBracket, RBracket, LCurly, RCurly, } #[derive(Debug, Clone, Copy)] pub enum Operator { Equals, Plus, Minus, Star, StarStar, Slash, Percent, Colon, Semicolon, Exclam...