text
stringlengths
8
4.13M
#![cfg_attr(feature = "unstable", feature(unsize))] mod util; mod array; mod vector; mod array_vec; mod small_dst; mod small_vec; pub use array::{Array, ArrayIndex, Addressable}; pub use vector::Vector; pub use small_vec::{SmallVec, Spilled}; pub use array_vec::ArrayVec; pub use small_dst::SmallDST;
pub mod account_creation; pub mod payments; use reusable_fmt::fmt_reuse; // Template for a default Move script fmt_reuse! { TEMPLATE_SCRIPT_MAIN = r#" script {{ {imports} fun main({main_args}) {{ {main_body} }} }} "#; }
extern crate imap; use imap::IMAPStream; fn main() { let mut imapstream = box IMAPStream::new("imap.qq.com", 143); imapstream.connect(); imapstream.login("550532246@qq.com", "xxxxxxx"); imapstream.select("inbox"); }
#[doc = "Register `EMR2` reader"] pub type R = crate::R<EMR2_SPEC>; #[doc = "Register `EMR2` writer"] pub type W = crate::W<EMR2_SPEC>; #[doc = "Field `EM32` reader - CPU wakeup with event mask on event input"] pub type EM32_R = crate::BitReader<EM32_A>; #[doc = "CPU wakeup with event mask on event input\n\nValue on re...
#[doc = "Reader of register GPIO_HI_IN"] pub type R = crate::R<u32, super::GPIO_HI_IN>; #[doc = "Reader of field `GPIO_HI_IN`"] pub type GPIO_HI_IN_R = crate::R<u8, u8>; impl R { #[doc = "Bits 0:5 - Input value on QSPI IO in order 0..5: SCLK, SSn, SD0, SD1, SD2, SD3"] #[inline(always)] pub fn gpio_hi_in(&se...
use bevy::math::{Quat, Vec2, Vec3}; pub fn scale(y: f32, a: f32) -> f32 { y * a } pub fn flip(x: f32) -> f32 { 1.0 - x } pub fn clamp(x: f32) -> f32 { x.abs() } pub fn smooth_start<const N: i32>(x: f32 ) -> f32 { x.powi(N) } pub fn smooth_stop<const N: i32>(x: f32 ) -> f32 { flip(flip(x).powi(N...
#[cfg(test)] mod tests { use crate::aes_ecb::detect_aes_ecb; use std::fs::File; use std::io::{BufRead, BufReader}; // Eighth cryptopals challenge - https://cryptopals.com/sets/1/challenges/8 #[test] fn challenge8() { let mut found: Option<String> = None; for line in BufReader::n...
use std::cell::RefCell; use std::rc::Rc; use futures::{channel::mpsc, future::ready, stream::Stream, StreamExt}; use moxie::{load_once, once, state, Commit}; /// Root a state variable at the callsite, returning a `dispatch` function which may be used to send /// messages to be processed by the provided `reducer` and ...
/* * Slack Web API * * One way to interact with the Slack platform is its HTTP RPC-based Web API, a collection of methods requiring OAuth 2.0-based user, bot, or workspace tokens blessed with related OAuth scopes. * * The version of the OpenAPI document: 1.7.0 * * Generated by: https://openapi-generator.tech *...
use crate::frame::tanh::*; extern "C" { fn fma_tanh_f32(ptr: *mut f32, count: usize); } #[derive(Copy, Clone, Debug)] pub struct TanhF32; impl TanhKer<f32> for TanhF32 { #[inline(always)] fn name() -> &'static str { "fma" } #[inline(always)] fn nr() -> usize { 8 } #[in...
/* Copyright 2020 Mozilla Foundation * * 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 agreed...
// The MD4 Message-Digest Algorithm // <https://tools.ietf.org/html/rfc1320> use core::convert::TryFrom; const INITIAL_STATE: [u32; 4] = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476]; pub fn md4<T: AsRef<[u8]>>(data: T) -> [u8; Md4::DIGEST_LEN] { Md4::oneshot(data) } #[derive(Clone)] pub struct Md4 { buff...
use crate::{FeedId, Runtime}; use codec::{Decode, Encode}; use pallet_feeds::feed_processor::{FeedMetadata, FeedObjectMapping, FeedProcessor}; use pallet_grandpa_finality_verifier::chain::Chain; use scale_info::TypeInfo; use sp_api::HeaderT; use sp_core::Hasher; use sp_runtime::traits::BlakeTwo256; use sp_runtime::{gen...
extern crate hal; extern crate once_cell; use crate::application::Window; use crate::graphics::gfxal::back::Backend; use crate::maths; use once_cell::sync::OnceCell; use std::sync::Mutex; use hal::{ adapter::PhysicalDevice, device::Device, pool::CommandPool, queue::QueueFamily, window::{Presentat...
use nom::number::complete::{le_u8, le_f32}; use serde_derive::{Serialize}; use super::parserHeader::*; #[derive(Debug, PartialEq, Serialize)] pub struct LapData { pub m_lastLapTime: f32, pub m_currentLapTime: f32, pub m_bestLapTime: f32, pub m_sector1Time: f32, pub m_sector2Time: f32, pub m_lap...
#![allow(dead_code)] #![allow(non_camel_case_types)] /// A very small, restricted subset of uinput. Not too much work was done to refine this since /// there exists a uinput crate. /// That crate currently has an issue compiling (05/27) mod key; mod uinput_sys; pub use self::key::Key; use self::uinput_sys as ffi; use ...
//! Bidirectional hashmaps! //! This crate aims to provide a data structure that can take store a 1:1 relation between two //! different types, and provide constant time lookup within this relation. //! //! Unlike a regular hashmap, which provides lookups from "keys" to "values", the two directional //! hashmap provide...
use std::time::Duration; use std::time::Instant; /// /// A container to host a value-instant pair. /// pub(crate) struct TimedData<T> { pub(crate) item: T, pub(crate) time_stored: Instant, } impl<T> TimedData<T> { pub(crate) fn new(item: T) -> TimedData<T> { TimedData { item, ...
extern crate docstrings; use docstrings::parse_md_docblock; fn main() { println!("{:#?}", parse_md_docblock(DOC_STR).unwrap()); } const DOC_STR: &'static str = "\ Lorem ipsum A longer description lorem ipsum dolor sit amet. # Parameters - `param1`: Foo - `param2`: Bar ";
extern crate gcc; use std::env; pub fn main() { let target = env::var("TARGET").unwrap(); let os = if target.contains("linux") { "LINUX" } else if target.contains("darwin") { "DARWIN" } else { "UNKNOWN" }; gcc::Config::new() .file("src/const.c") .file(...
use chrono::{DateTime, FixedOffset, NaiveDate, NaiveDateTime, NaiveTime, Utc}; use std::{borrow::Cow, sync::Arc}; use storm::{Error, Result}; use tiberius::Uuid; pub trait FromSql<'a>: Sized { type Column: tiberius::FromSql<'a>; fn from_sql(col: Option<Self::Column>) -> Result<Self>; } impl<'a, T> FromSql<'a...
use iron::status; use iron::prelude::*; pub fn friendly_greeting(_: &mut Request) -> IronResult<Response> { return Ok(Response::with((status::Ok, "Hello World!"))); }
use std::sync::Arc; use async_trait::async_trait; pub use bonsaidb_core::circulate::Relay; use bonsaidb_core::{ circulate, pubsub::{self, database_topic, PubSub}, schema::Schema, Error, }; #[async_trait] impl<DB> PubSub for super::Database<DB> where DB: Schema, { type Subscriber = Subscriber; ...
use wasm_bindgen::prelude::*; use super::{BufferGeometry, Material, Object3D}; #[wasm_bindgen(module = "three")] extern "C" { #[wasm_bindgen(extends = Object3D)] pub type Group; #[wasm_bindgen(constructor)] pub fn new() -> Group; } #[wasm_bindgen(module = "three")] extern "C" { #[wasm_bindgen(ex...
use regex::Regex; use std::fs::File; use std::io::{BufRead, BufReader}; use struct_lib::Token; // Int match part fn int_match(text: &mut String) -> Token::Token { // <dec int> ::= <number>{<number>} // <number> ::= 0|1|2|3|4|5|6|7|8|9 // Regex for constant integers let int_re = Regex::new(r"(^[0-9][0-9...
pub mod tax_parameters; pub use tax_parameters::TaxParameters;
use crate::{ alloc::Allocator, containers::{Array, String}, }; pub trait Serializer { type Ok; type Err; type ArraySerializer: ArraySerializer<Ok = Self::Ok, Err = Self::Err>; type MapSerializer: MapSerializer<Ok = Self::Ok, Err = Self::Err>; fn serialize_u8(self, value: u8) -> Result<Self...
use super::*; prelude_macros::implement_accessors! { Vec2, Vec3, Vec4, // Uint2, // Uint3, // Uint4, } #[test] fn test_accessors() { let _ = 1.0.vec3().x; 1.0.vec3().xy(); 1.0.vec3().zyx(); }
//! Config module contains the top-level config for the app. use std::env; use sentry_integration::SentryConfig; use config_crate::{Config as RawConfig, ConfigError, Environment, File}; use stq_http; use stq_logging::GrayLogConfig; /// Basic settings - HTTP binding address and database DSN #[derive(Debug, Deserializ...
use inspector::ResultInspector; fn main() { let ok: Result<_, ()> = Ok(42); ok.inspect(|x| println!("ok value is {}", x)).unwrap(); }
use std::process; use std::process::{Command, Stdio}; fn main() { let command = Command::new("cargo") .arg("fmt") .stdout(Stdio::inherit()) .stderr(Stdio::inherit()) .output() .expect("failed to execute cargo fmt"); process::exit(command.status.code().unwrap_...
//! Kube is an umbrella-crate for interacting with [Kubernetes](http://kubernetes.io) in Rust. //! //! # Overview //! //! Kube contains a Kubernetes client, a controller runtime, a custom resource derive, and various tooling //! required for building applications or controllers that interact with Kubernetes. //! //! Th...
use std::fs::File; use std::io::{BufReader, BufWriter}; use bitflags::bitflags; use serde::{Deserialize, Serialize}; use crate::joypad::{Button, JoyPort}; use crate::savable::Savable; pub use addr_modes::AddrMode; pub use instructions::OPTABLE; mod addr_modes; mod instructions; /// Memory page of the cpu stack con...
#[derive(Clone)] pub struct Board { rows: Vec<Vec<i32>>, rows_done: [i32; 5], cols_done: [i32; 5], winner: bool, } pub struct Bingo { moves: Vec<i32>, boards: Vec<Board>, } #[aoc_generator(day4)] pub fn input_generator(input: &str) -> Bingo { let mut input = input.split("\n\n"); let moves = input ...
use std::collections::HashMap; use std::io; use std::str::FromStr; use chrono::{NaiveDateTime, Timelike}; use lazy_static::lazy_static; use regex::Regex; use crate::base::Part; pub fn part1(r: &mut dyn io::Read) -> Result<String, String> { solve(r, Part::One) } pub fn part2(r: &mut dyn io::Read) -> Result<Strin...
use crate::{ instruction::{Instruction, Opcode}, interconnect::Interconnect, io::IO, mmu::Mmu, }; use log::info; use std::fmt::{self, Display}; mod flags; pub use self::flags::ConditionalFlags; mod register; pub use self::register::Register; mod error; use self::error::EmulateError; type Result<T> ...
#[doc = "Register `CCCSR` reader"] pub type R = crate::R<CCCSR_SPEC>; #[doc = "Register `CCCSR` writer"] pub type W = crate::W<CCCSR_SPEC>; #[doc = "Field `EN` reader - enable"] pub type EN_R = crate::BitReader; #[doc = "Field `EN` writer - enable"] pub type EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[...
use super::{ error::{ ErrorMsg, MsgType::{self, *}, }, token::{self, ByteValue, Token, Value}, }; use codespan_reporting::{ diagnostic::{Diagnostic, Label}, files::SimpleFiles, term, }; use std::{ fmt, iter::Peekable, num, result, str::{self, CharIndices}, }; #[cfg(feature = "std")] use std...
#[doc = "Reader of register IC_CLR_INTR"] pub type R = crate::R<u32, super::IC_CLR_INTR>; #[doc = "Reader of field `CLR_INTR`"] pub type CLR_INTR_R = crate::R<bool, bool>; impl R { #[doc = "Bit 0 - Read this register to clear the combined interrupt, all individual interrupts, and the IC_TX_ABRT_SOURCE register. Thi...
use crate::messages::ChainId; use codec::{Decode, Encode}; use frame_support::weights::Weight; use frame_support::Parameter; use scale_info::TypeInfo; use sp_domains::DomainId; use sp_runtime::traits::Member; use sp_runtime::{sp_std, DispatchError, DispatchResult}; use sp_std::vec::Vec; /// Represents a particular end...
use std::path::Path; use std::io::stdin; use inkwell as llvm; use inkwell::targets::{Target, TargetTriple, TargetMachine, RelocMode, CodeModel, InitializationConfig}; use inkwell::OptimizationLevel; use std::process::Command; use diesel_lib::parser::{ lexer::tokens, Parser }; mod compiler; use clap::{App, Ar...
use cgmath::prelude::*; use cgmath::Point3; #[derive(Clone, Copy, Debug)] pub struct BoundingBox { pub min: Point3<f32>, pub max: Point3<f32>, } impl BoundingBox { pub fn neg_infinity_bounds() -> Self { Self { min: [std::f32::INFINITY; 3].into(), max: [std::f32::NEG_INFINIT...
#[rustversion::nightly] const NIGHTLY: bool = true; #[rustversion::not(nightly)] const NIGHTLY: bool = false; fn main() { // Set cfg flags depending on release channel if NIGHTLY { println!("cargo:rustc-cfg=nightly"); } }
use crate::{error::ApllodbResult, validation_helper::short_name::ShortName}; use serde::{Deserialize, Serialize}; /// Database name. #[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)] pub struct DatabaseName(ShortName); impl DatabaseName { /// Constructor. /// /// # Fail...
//! provides init and shutdown functions allowing for entering //! and gracefully exiting alternate screen where program can //! happily perform its shenanigans. //! init function sets up panic hook that will call shutdown() //! preventing messing up the terminal if the program were to panic! //! //! # Usage //! ```no_...
use std::{env, fs}; use ngc::parse::parse; fn main() { let filename = env::args().nth(1).expect("file name required"); let input = fs::read_to_string(&filename).unwrap(); match parse(&filename, &input) { Err(e) => eprintln!("Parse error: {}", e), Ok(prog) => println!("{}", prog), } }
mod twitch_notif; pub use twitch_notif::TwitchNotifEmbed;
extern crate env_logger; extern crate embed_lang; use embed_lang::vm::api; use embed_lang::vm::api::{VMType, Function}; use embed_lang::vm::gc::Traverseable; use embed_lang::vm::vm::{RootedThread, Thread, VMInt, Value, Root, RootStr}; use embed_lang::Compiler; use embed_lang::import::Import; fn load_script(vm: &Thre...
#![no_main] use libfuzzer_sys::fuzz_target; fuzz_target!(|data: &[u8]| { let mut contents = match String::from_utf8(data.to_vec()) { Ok(v) => v, Err(e) => panic!("Invalid UTF-8 sequence: {}", e), }; let replacee: String = "x".to_string(); let replacer: String = "z".to_string(); //p...
use proc_macro2::TokenStream; use quote::format_ident; use syn::{ parse_quote, ExprPath, ItemConst, ItemFn, ItemImpl, ItemMod, ItemStatic, LitByteStr, LitStr, }; use super::context::Context; use crate::parse::process::Process; impl Process { fn gen_wrapper_fn(&self) -> ItemFn { let ident = &self.ident...
#![no_std] #![no_main] extern crate panic_semihosting; pub use cortex_m::{asm::bkpt, iprint, iprintln, peripheral::ITM}; pub use cortex_m_rt::entry; pub use f3::hal::{prelude, serial::Serial, stm32f30x::usart1, time::MonoTimer}; use f3::hal::{ prelude::*, stm32f30x::{self, USART1}, }; use f3::{ led::Led, ...
mod command_counter; mod config; mod invite; mod server_config; pub use self::{ command_counter::CommandCounterEmbed, config::ConfigEmbed, invite::InviteEmbed, server_config::ServerConfigEmbed, };
use std::marker::PhantomData; use crate::{Context, MethodErr, IfaceBuilder,stdimpl}; use crate::ifacedesc::Registry; use std::collections::{BTreeMap, HashSet}; use std::any::Any; const INTROSPECTABLE: usize = 0; const PROPERTIES: usize = 1; #[derive(Debug, Copy, Clone, Eq, Ord, Hash, PartialEq, PartialOrd)] pub struc...
use super::*; use crate::{ components::{self, Resource}, indices::{EntityId, UserId, WorldPosition}, intents::{ check_dropoff_intent, check_melee_intent, check_mine_intent, check_move_intent, CachePathIntent, DropoffIntent, MeleeIntent, MineIntent, MoveIntent, MutPathCacheIntent, Pat...
// Copyright (c) 2020 Jesse Weaver. // // This file is part of secretgarden. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. use anyhow::{anyhow, Context, Result...
use std::result::Result as StdResult; use futures::try_ready; use resol_vbus::BlobBuffer; use tokio::net::TcpStream; use tokio::prelude::*; use crate::error::{Error, Result}; type ReceiveCommandValidatorResult<T> = (&'static str, Option<Result<T>>); type ReceiveCommandValidatorFutureBox<T> = Box<dyn Future<Item ...
static BASE64_CHARS: &'static[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\ abcdefghijklmnopqrstuvwxyz\ 0123456789+/"; pub fn encode(v: &[u8]) -> Vec<u8> { let len = v.len(); let mut split: Vec<u8> = Vec::new(); for i in 0..(len * 4 / 3 + ...
/* * Binary indexed tree test (Rust) * * Copyright (c) 2019 Project Nayuki. (MIT License) * https://www.nayuki.io/page/binary-indexed-tree * * 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 ...
/*! ```rudra-poc [target] crate = "signal-simple" version = "0.1.1" [[target.peer]] crate = "crossbeam-utils" version = "0.8.0" [report] issue_url = "https://github.com/kitsuneninetails/signal-rust/issues/2" issue_date = 2020-11-15 rustsec_url = "https://github.com/RustSec/advisory-db/pull/694" rustsec_id = "RUSTSEC-...
use std::collections::HashMap; use std::path::Path; use std::process::Command; use std::time::SystemTime; // import helper functions from loader module use crate::loader::{get_var_trimmed, read_bracketed_var}; #[derive(Debug, Clone, Eq, PartialEq)] pub(crate) struct FinalRule { target: String, // Every rule in th...
extern crate agg; use agg::Pixel; fn draw_black_frame(pix: &mut agg::Pixfmt<agg::Rgb8>) { let w = pix.width(); let h = pix.height(); println!("w,h: {} {}", w,h); let black = agg::Rgb8::black(); for i in 0 .. h { pix.copy_pixel(0, i, black); pix.copy_pixel(w-1, i, black); } ...
fn main() { let mut input = String::from_utf8(std::fs::read("input/day10").unwrap()) .unwrap() .split_terminator("\n") .map(|n| n.parse().unwrap()) .collect::<Vec<u64>>(); input.push(0); input.sort(); input.push(input.last().unwrap() + 3); let mut ones = 0usize; l...
mod common; use actix_web::{test, web, App}; use drogue_cloud_authentication_service::{endpoints, service, WebData}; use drogue_cloud_service_api::auth::device::authn::{AuthenticationRequest, Credential}; use drogue_cloud_test_common::{client, db}; use serde_json::{json, Value}; use serial_test::serial; fn device1_js...
use crate::core::{ transactions, Account, DbConnection, Money, Permission, Pool, Product, ServiceResult, Transaction, }; use crate::identity_policy::{Action, RetrievedAccount}; use crate::login_required; use crate::web::utils::HbData; use actix_web::{http, web, HttpRequest, HttpResponse}; use chrono::{Duration,...
pub use dir::env_dir; pub use edit::env_edit; pub use envs::envs; pub use generate::generate; pub use init::init; pub use ls::ls; pub use new::env_new; pub use pdir::env_pdir; pub use r#use::r#use; pub use rename::rename; pub use run::run; pub use show::{show, DEFAULT_SHOW_FORMAT}; pub use sync::{env_sync, sync_workflo...
extern crate libc; extern crate libz_sys; extern crate openssl_sys; use libc::{c_int, size_t, c_void, c_char, c_long, c_uchar, c_uint, c_ulong}; use libc::ssize_t; // It seems not to matter that ssh_session is really a struct pub enum ssh_session {} // It seems not to matter that ssh_channel is really a struct pub en...
use hydroflow::hydroflow_syntax; pub fn main() { // An edge in the input data = a pair of `usize` vertex IDs. let (pairs_send, pairs_recv) = hydroflow::util::unbounded_channel::<(usize, usize)>(); let mut flow = hydroflow_syntax! { // inputs: the origin vertex (vertex 0) and stream of input edges ...
//! Maintains a single instance of the FUSE filesystem //! //! The module dolls out shared pointers to the FUSE background //! session. When they all go out of scope, the filesystem shuts //! down. use env_logger; use fuse; use fuse::BackgroundSession; use std::cell::Cell; use std::ffi::OsStr; use std::fs::create_dir;...
pub fn process_stream(string: String) -> u32 { let mut string_iterator = string.chars(); let mut sum = 0; let mut level = 0; let mut garbage_mode = false; let mut contains = string_iterator.next(); while contains != None { let c = contains.unwrap(); if c == '<' { gar...
use crate::provider::client_handling::{ClientProcessingData, ClientRequestProcessor}; use crate::provider::mix_handling::{MixPacketProcessor, MixProcessingData}; use crate::provider::storage::ClientStorage; use crypto::identity::{DummyMixIdentityPrivateKey, DummyMixIdentityPublicKey}; use directory_client::presence::Mi...
// Copyright (c) 2019 Ant Financial // // 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 agreed ...
#[macro_use] extern crate conrod_core; pub mod core;
fn main() { let mut i = 0; while i < 50 { i += 1; if i % 3 == 0 { continue; } if i * i > 400 { break; } print!("{} ", i * i); } println!(""); }
use super::prelude::*; use super::schema::{user, user_auth}; #[derive(Debug, Clone, Validate, Serialize, Deserialize)] pub struct QueryNewUser { #[validate(length(min = 8))] pub(crate) user_name: String, #[validate(length(min = 1))] pub(crate) nick_name: String, #[validate(length(max = 11))] pu...
#[doc = "Reader of register DDRCTRL_DRAMTMG4"] pub type R = crate::R<u32, super::DDRCTRL_DRAMTMG4>; #[doc = "Writer for register DDRCTRL_DRAMTMG4"] pub type W = crate::W<u32, super::DDRCTRL_DRAMTMG4>; #[doc = "Register DDRCTRL_DRAMTMG4 `reset()`'s with value 0x0504_0405"] impl crate::ResetValue for super::DDRCTRL_DRAMT...
#[doc = "BLESS DDFT configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#r...
use std::io; use std::task::Poll; pub(crate) fn async_io<F, T>(mut op: F) -> Poll<io::Result<T>> where F: FnMut() -> io::Result<T> { loop { match op() { Ok(v) => return Poll::Ready(Ok(v)), Err(ref e) if e.kind() == io::ErrorKind::Interrupted => continue, Err(ref e) if e.kind() == io::ErrorKind::WouldBlock...
use std::collections::HashMap; use std::fs::{self, File}; use std::io::{BufRead, BufReader, BufWriter, Write}; use std::path::{Path, PathBuf}; use std::process::Command; use crate::bro_types::Connection; use crate::features::{ DirectionInferenceMethod, FlowFeatures, NormalizedFlowFeatures, PacketFeatures, }; use c...
extern crate rand; extern crate spatialos_gdk; #[macro_use] extern crate spatialos_gdk_derive; use rand::Rng; use schema::Schema; use schema::demogame::Movement; use schema::improbable::Position; use spatialos_gdk::{Connection, ConnectionParameters, Entities, EntityId, System, World, WorldError, Wr...
use crate::typing::Type; use std::fmt; #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct FunType { pub arg: Box<Type>, pub ret: Box<Type>, } impl fmt::Display for FunType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "({} -> {})", self.arg, self.ret) }...
#[doc = "Register `GICD_TYPER` reader"] pub type R = crate::R<GICD_TYPER_SPEC>; #[doc = "Field `ITLINESNUMBER` reader - ITLINESNUMBER"] pub type ITLINESNUMBER_R = crate::FieldReader; #[doc = "Field `CPUNUMBER` reader - CPUNUMBER"] pub type CPUNUMBER_R = crate::FieldReader; #[doc = "Field `SECURITYEXTN` reader - SECURIT...
//! A temporary in-memory database meant to hold us over until the pager and //! B+Tree modules are finalized. //! //! This module will be removed once the pager and B+Tree are functional. use std::borrow::Cow; use std::collections::BTreeSet; use columnvalueops::{ColumnValueOps, ColumnValueOpsExt}; use databaseinfo::...
pub fn problem_045() -> u64 { let n:u64 = 100000000000; let mut triangular = (1..n).map(|i| i * (i + 1)/2 ); let mut pentagonal = (1..n).map(|i| i * (3 * i - 1)/2 ); let hexagonal = (1..n).map(|i| i * (2 * i - 1)); let mut p: u64 = 40756; let mut t: u64 = 40756; for h in hexagonal { ...
use cookie_factory::*; use flate2::Compression; use flate2::read::GzDecoder; use flate2::write::GzEncoder; use nom::{ErrorKind, be_u16, be_u32, be_u8}; use sha2::{Digest, Sha256}; use std::io::{Read, Write}; use crypto::frame::{gen_session_key, session_key}; use data::frame::{certificate, gen_certificate, gen_hash, ge...
//! Retrieve basic data about a protein from a local UniprotKB file //! //! # File format //! //! Files should be tab delimited, with 4 fields: Uniprot Accession, Gene Name, //! Molecular Weight, and Protein Sequence. Each protein appears on it's own //! line in the file, and no header //! should be present //! //! ```...
pub fn raindrops(n: u32) -> String { let factors = [(3, "Pling"), (5, "Plang"), (7, "Plong")]; let mut result = String::new(); for (f, s) in &factors { if n % f == 0 { result.push_str(s); } } if result.is_empty() { return n.to_string(); } result }
// Copyright 2021 Google 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 or agreed to in ...
use crate::{ runtime::Runtimes, watchdog::{ControlCommand, WatchdogQuery}, }; use std::future::Future; use tokio::{ sync::{mpsc, oneshot}, task::JoinHandle, }; pub struct WatchdogMonitor { runtimes: Runtimes, control_command: mpsc::Sender<ControlCommand>, watchdog_finished: oneshot::Receive...
#[macro_use] extern crate cycle_match; fn main() { let data = "1234567890"; let mut data_n_index = 0usize; let mut iter = data.as_bytes().into_iter(); loop_match!((iter.next()) -> || { Some(a) => data_n_index += *a as usize, _ => break, }); assert_eq!(data_n_index, 525); }
use crate::ast; use crate::{ParseError, Parser}; use crate::{Spanned, ToTokens}; /// A literal expression. #[derive(Debug, Clone, ToTokens, Spanned)] pub struct ExprLit { /// Attributes associated with the literal expression. #[rune(iter)] pub attributes: Vec<ast::Attribute>, /// The literal in the exp...
use crate::{ models::money_node::{MoneyNode, NewMoneyNode, UpdateMoneyNode}, schema::{money_nodes, money_nodes::dsl::money_nodes as money_nodes_query}, }; use diesel::prelude::*; use crate::db::finance::FilterQuery; pub fn all(conn: &PgConnection) -> QueryResult<Vec<MoneyNode>> { money_nodes_query ...
use tokio::io::AsyncRead; use crate::error::{TychoError, TychoResult}; use crate::read::async_::func::{read_byte_async, read_bytes_async}; use crate::read::async_::length::read_length_async; pub(crate) async fn read_string_async<R: AsyncRead + Unpin>(reader: &mut R) -> TychoResult<String> { let length = read_leng...
// 参考文档: https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#fully-qualified-syntax-for-disambiguation-calling-methods-with-the-same-name trait Animal { fn baby_name() -> String; } struct Dog; impl Dog { fn baby_name() -> String { String::from("Spot") } } impl Animal for Dog { fn bab...
pub mod models; pub mod operations; #[allow(dead_code)] pub const API_VERSION: &str = "2017-06-01.5.1";
use na::geometry::*; use na::Real; use na::Vector2; type Point = Point2<f32>; type Vector = Vector2<f32>; pub fn get_cross_points_with_sphere( center: &Point, radius: f32, from: &Point, to: &Point, ) -> Vec<Point> { let translate = Vector::new(center.x, center.y); let origin_from = from - tran...
fn main() { println!("Hello, world!"); let s1 = "literal"; // literal, immutable, fixed memory //literal is stored on stack let mut s2 = String::from("string"); //string, mutable //stored on heap s2.push_str("version2"); let s3 = String::from("example"); let x = s3; //value of s3 wa...
use crate::{ alphabet::Alphabet, dfa::standard::StandardDFA, nfa::{ standard::{StandardNFA, Transition}, standard_eps::StandardEpsilonNFA, }, range_set::Range, state::State, }; use core::{ hash::{BuildHasher, BuildHasherDefault, Hash, Hasher}, iter::once, }; use fxhash::F...
use fibers::sync::oneshot::MonitorError; use std::io; use std::sync::mpsc::SendError; use stun_codec::rfc5389::attributes::ErrorCode; use stun_codec::AttributeType; use trackable::error::{self, ErrorKindExt, TrackableError}; /// This crate specific `Error` type. #[derive(Debug, Clone, TrackableError)] pub struct Error...
//! The Splunk HEC generator. mod acknowledgements; use std::{ num::{NonZeroU32, NonZeroUsize}, time::Duration, }; use acknowledgements::Channels; use byte_unit::{Byte, ByteUnit}; use http::{ header::{AUTHORIZATION, CONTENT_LENGTH}, Method, Request, Uri, }; use hyper::{client::HttpConnector, Body, Cl...
use crate::app::application::Application; use crate::app::UpdateResult; use crate::renderer::renderer::Renderer; use crate::ui::*; use rider_config::*; use sdl2::rect::Point; use sdl2::VideoSubsystem as VS; use std::fs::{read_to_string, File}; use std::io::Write; use std::sync::*; pub struct AppState { menu_bar: M...