text
stringlengths
8
4.13M
use std::ffi::OsStr; use std::io; use anyhow::anyhow; use anyhow::Context; use anyhow::Result; use positioned_io::ReadAt; pub trait BlockDevice: ReadAt + Send + Sync {} impl<T: ReadAt + Send + Sync> BlockDevice for T {} pub fn open_raw_or_first_partition<S: AsRef<OsStr>>(target: S) -> Result<Box<dyn BlockDevice>> { ...
pub mod bytecode; pub mod convert; mod frame; pub mod opcode; use crate::evaluator::builtin; use crate::evaluator::objects; use crate::vm::convert::Read; mod preludes { pub use super::super::preludes::*; pub use crate::vm; } use preludes::*; pub const STACK_SIZE: usize = 2048; pub const GLOBALS_SIZE: usize ...
// --- paritytech --- use pallet_authorship::Config; use pallet_session::FindAccountFromAuthorIndex; // --- darwinia-network --- use crate::*; frame_support::parameter_types! { pub const UncleGenerations: u32 = 0; } impl Config for Runtime { type FindAuthor = FindAccountFromAuthorIndex<Self, Aura>; type UncleGener...
pub struct Bytecode { pub instructions: Vec<Instruction>, } #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)] pub enum Register { Arg(usize), Local(usize), } #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)] pub enum Instruction { // FFI to Rust RustCallMut { rust_fn: usize...
/// A `usize` extension to use `usize`s as constrainable values pub trait UsizeExt { /// Get the constrainable value fn _cv(&self) -> usize; } impl UsizeExt for usize { fn _cv(&self) -> usize { *self } } /// A slice extension to use slice as constrainable values pub trait SliceExt { /// Get the constrainable val...
use core::alloc::{GlobalAlloc, Layout}; use core::cell::Cell; use core::ptr::{NonNull, null_mut}; use core::mem::{align_of, size_of}; use core::slice::{from_raw_parts, from_raw_parts_mut}; use core::ops::{Deref, DerefMut}; pub(crate) use ALLOCATOR as Global; extern { static kernel_phys_end: usize; } fn main_mem_s...
extern crate bitintr; use bitintr::*; #[no_mangle] pub fn pext_u32(x: u32, mask: u32) -> u32 { x.pext(mask) } #[no_mangle] pub fn pext_u64(x: u64, mask: u64) -> u64 { x.pext(mask) }
use rocket::Request; use rocket_contrib::Template; #[derive(Serialize)] struct Context404 { uri: String } #[error(404)] fn not_found(req: &Request) -> Template { let context = Context404 { uri: req.uri().as_str().to_string() }; Template::render("errors/404", &context) }
use crate::headers::*; use crate::AddAsHeader; use http::request::Builder; #[derive(Debug, Clone, Copy)] pub struct ClientRequestId<'a>(&'a str); impl<'a> ClientRequestId<'a> { pub fn new(client_request_id: &'a str) -> Self { Self(client_request_id) } } impl<'a> From<&'a str> for ClientRequestId<'a> ...
pub fn factors(input: u64) -> Vec<u64> { let mut factors = Vec::new(); let mut target = input; let mut factor = 2; while factor <= target { if target % factor == 0 { factors.push(factor); target = target / factor; } else { factor = factor + 1; ...
use std::convert::TryInto; use std::{cmp::Ordering::Greater, cmp::Ordering::Less, io, io::prelude::*, mem}; use vint32::iterator::VintArrayIterator; use vint32::vint_array::VIntArray; const FLUSH_THRESHOLD: usize = 16_384; const VALUE_OFFSET: u32 = 1; #[derive(Debug)] pub struct DocLoader<'a> { blocks: &'a [u8],...
mod login; mod person; mod persons_list; pub use login::*; pub use person::*; pub use persons_list::*;
use target::Target; use {ir, target, support, pass}; /// A compilation builder. pub struct CompilationBuilder<'target> { /// The target to build with. target: &'target Target, /// The target triple. triple: target::Triple, /// The target CPU. cpu: target::CPU, /// The current features. ...
#[macro_use] extern crate error_chain; #[macro_use] extern crate nom; use nom::{le_u8, le_u16, le_u32}; use std::io::Read; use std::fs::File; use std::path::Path; mod errors; use errors::*; pub struct FitFile { bytes: Vec<u8>, header: FitFileHeader, } impl FitFile { pub fn open<P: AsRef<Path>>(path: P)...
// Extract the subset of boards that are strictly reachable from the initial // board. // // Input: 2-analyze's output // // Output: // board depth name // idx: next-name... // ... // ... // // board: hex representation of bit-board (only white boards) // depth: the depth of the board // name: board n...
// Generated by `scripts/generate.js` pub type VkAccelerationStructureType = super::super::khr::VkAccelerationStructureType; #[doc(hidden)] pub type RawVkAccelerationStructureType = super::super::khr::RawVkAccelerationStructureType;
#![cfg(all(test, feature = "test_e2e"))] use azure_core::prelude::*; use azure_storage::blob::container::PublicAccess; use azure_storage::blob::prelude::*; use azure_storage::core::prelude::*; use std::sync::Arc; use std::time::Duration; #[tokio::test] async fn lease() { let container_name: &'static str = "azuresd...
use crate::{ env::Env, render::{RenderContext, VNode}, }; use futures::{ channel::mpsc, // prelude::*, stream::{FusedStream, Stream}, task::{self, Poll}, }; use siro::vdom::Nodes; use std::pin::Pin; use wasm_bindgen::JsCast as _; pub struct App<'env, TMsg: 'static> { env: &'env Env, mou...
type Image = Vec<Vec<u32>>; fn rotate_matrix(image: Image) -> Image { let mut i = image.clone(); for (x, vec) in image.iter().enumerate() { for (y, _) in vec.iter().enumerate() { i[x][y] = image[y][x]; } i[x].reverse(); } i } #[cfg(test)] mod tests { use super:...
use actix_web::{App,HttpServer,web}; extern crate simple_logger; mod executor{ pub mod validate_password; pub mod execute; } #[actix_rt::main] async fn main() ->std::io::Result<()> { simple_logger::SimpleLogger::new().init().unwrap(); HttpServer::new(||{ App::new() .service( ...
use std::collections::HashMap; use amethyst::{ assets::Handle, core::timing::Time, ecs::prelude::*, input::{is_close_requested, is_key_down}, prelude::*, renderer::VirtualKeyCode, ui::{UiEventType, UiPrefab}, }; use crate::{states::ToppaState, ToppaGameData}; #[derive(PartialEq, Eq, Hash,...
use crate::distribution::{Continuous, ContinuousCDF}; use crate::function::gamma; use crate::statistics::*; use crate::{Result, StatsError}; use rand::Rng; use std::f64; /// Implements the [Inverse /// Gamma](https://en.wikipedia.org/wiki/Inverse-gamma_distribution) /// distribution /// /// # Examples /// /// ``` /// ...
use apllodb_shared_components::{ApllodbError, ApllodbResult}; use apllodb_storage_engine_interface::{ ColumnDataType, ColumnDefinition, ColumnName, TableConstraintKind, }; use serde::{Deserialize, Serialize}; /// A constraint parameter that set of record (not each record) must satisfy. #[derive(Clone, Eq, PartialE...
use private::{SealedRequestLineParserState, SealedRequestParserState}; use std::collections::HashMap; use thiserror::Error; #[doc(hidden)] const SPACE: u8 = ' ' as u8; #[doc(hidden)] const COLON: u8 = ':' as u8; #[doc(hidden)] const CR: u8 = '\r' as u8; #[doc(hidden)] const LF: u8 = '\n' as u8; #[doc(hidden)] const TA...
// vim: tw=80 #![cfg_attr(feature = "nightly-docs", feature(doc_cfg))] //! Examples of mock objects and their generated methods. //! //! This crate only exists to document the autogenerated methods of the //! [`Mockall`](https://docs.rs/mockall/latest/mockall) //! crate. You should never depend on this crate. // #[c...
#![feature(rand, old_io, core, collections, hash)] #![allow(unused_features)] #![feature(test)] extern crate url; extern crate openssl; extern crate "rustc-serialize" as rustc_serialize; extern crate "sha1-hasher" as sha1; extern crate rand; #[macro_use] extern crate bitflags; #[cfg(test)] extern crate test; pub us...
/*! ```rudra-poc [target] crate = "concread" version = "0.2.5" indexed_version = "0.1.18" [report] issue_url = "https://github.com/kanidm/concread/issues/48" issue_date = 2020-11-13 rustsec_url = "https://github.com/RustSec/advisory-db/pull/532" rustsec_id = "RUSTSEC-2020-0092" [[bugs]] analyzer = "SendSyncVariance" ...
use diesel::result::{DatabaseErrorKind, Error as DieselError}; use failure::Fail; use hyper::StatusCode; use serde_json; use validator::{ValidationError, ValidationErrors}; use stq_http::errors::{Codeable, PayloadCarrier}; #[derive(Debug, Fail)] pub enum Error { #[fail(display = "Not found")] NotFound, #[...
use std::{collections::hash_map::Entry, fmt}; use ahash::AHashMap as HashMap; #[cfg(feature = "parallel")] use crate::dispatch::dispatcher::ThreadPoolWrapper; use crate::{ dispatch::{ batch::BatchControllerSystem, dispatcher::{SystemId, ThreadLocal}, stage::StagesBuilder, BatchAcce...
// < begin copyright > // Copyright Ryan Marcus 2020 // // See root directory of this project for license terms. // // < end copyright > use crate::models::Model; use crate::models::*; use bytesize::ByteSize; use log::*; use std::collections::HashSet; use std::io::Write; use std::str; use crate::train::Trained...
///// chapter 2 "using variables and types" ///// program section: // fn main() { let x = Box::new(5_i32); println!("{}", x); } ///// output should be: /* */// end of output
use crate::api::*; use std::{ os::raw::c_short, sync::{Arc, Mutex}, }; use vigem_client as vgm; use vigem_client::ClientExt; #[derive(Clone)] pub struct Bus { client: Arc<Mutex<vgm::Client>>, } impl Bus { pub fn new() -> Result<Bus, Error> { let client = vgm::Client::new().map_with_vgp_error...
// Copyright 2018 The Exonum Team // // 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 i...
// Helper macro to test against errors in validate function. #[macro_export] macro_rules! test { ($name:ident, $contents:expr, $expected_errors:expr) => { #[test] fn $name() { // Which errors do we expect? let mut expected_errors: Vec<(&str, usize, usize)> = $expected_errors; // Which is th...
use crate::byte::Byte; use crate::word::Word; use crate::interrupt::{Interrupt, Result}; pub struct MemorySpace { memory: Box<[Byte; MemorySpace::SIZE]>, } macro_rules! box_array { ($val:expr ; $len:expr) => {{ // Use a generic function so that the pointer cast remains type-safe fn vec_to_boxe...
use crate::{inventory::get_inventory_list, prelude::*}; pub const MAP_VIEW_WIDTH: usize = 80; pub const MAP_VIEW_HEIGHT: usize = 43; const TOOLTIP_HORIZONTAL_PADDING: i32 = 1; #[derive(Debug, PartialEq, Copy, Clone)] pub enum ItemMenuResult { Cancel, NoResponse, Selected, } pub fn ui_inventory_use_input...
use std::convert::TryFrom; use anyhow::Result; use crate::evaluator::new_error; use crate::evaluator::objects; #[derive(Debug, Clone, PartialEq, Eq)] pub enum Function { Len, First, Last, Rest, Push, Puts, } static FUNCTIONS: [Function; 6] = [ Function::Len, Function::First, Func...
use std::collections::HashMap; use std::env; use std::fs; #[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)] struct Coordinate { x: i32, y: i32, } fn simulate(curr: Coordinate, op: (char, i32), len: &mut i32) -> Vec<(Coordinate, i32)> { let (dir, dist) = op; let mut coords: Vec<(Coordinate, i32)> = Ve...
#[macro_use] mod xml; mod make_invertible; use cgmath::{Matrix4, One}; use convert::image_namer::ImageNamer; use db::{Database, ModelId}; use skeleton::{Skeleton, Transform, SMatrix}; use primitives::{self, Primitives, DynamicState}; use nitro::Model; use time; use util::BiVec; use connection::Connection; use self::xm...
/// Result type for Error pub type ParseResult<T, E = ParseError> = std::result::Result<T, E>; /// Any kind of error encountered during parsing #[derive(Debug, Error)] #[allow(missing_docs)] pub enum ParseError { #[error("io error: {0}")] Io(#[from] std::io::Error), #[error("missing version header")] ...
pub mod aon; pub use aon::AONDriver; pub mod prci; pub use prci::PRCIDriver; pub mod spi; pub use spi::SPIDriver; pub mod gpio; pub use gpio::GPIODriver; pub mod uart; pub use uart::UartDriver; pub mod clint; pub use clint::CLINTDriver;
#[doc = "Register `CSR` reader"] pub type R = crate::R<CSR_SPEC>; #[doc = "Register `CSR` writer"] pub type W = crate::W<CSR_SPEC>; #[doc = "Field `WUF` reader - Wakeup flag"] pub type WUF_R = crate::BitReader; #[doc = "Field `SBF` reader - Standby flag"] pub type SBF_R = crate::BitReader; #[doc = "Field `EWUP1` reader...
// 数组的大小在编译期间就已经确定,slice的大小在编译期间不确定,数组的类型标记为[T;size],slice的类型标记为&[T] use std::mem; // 借用一个slice fn analyze_slice(slice: &[i32]) { println!("first element of the slice: {}", slice[0]); println!("the slice has {} element", slice.len()); } fn main() { // 固定大小的数组(类型标记是多余的) let xs: [i32; 5] = [1, 2, 3, 4, ...
//! module subtle implements functions that are often useful in cryptographic code but require //! careful thought to use correctly. /// constant_time_byte_eq returns 1 if x == y and 0 otherwise. pub fn constant_time_byte_eq(x: u8, y: u8) -> isize { (((x ^ y) as u32).wrapping_sub(1) >> 31) as isize } /// constant...
mod class; fn main() { let args: Vec<String> = std::env::args().collect(); let class_file = args.get(1).expect("Must specify class file"); let data = &std::fs::read(class_file).expect("Unable to read file"); let c = class::parse(data); c.print(); }
//! An analog of a Python String. //! //! To return to Python you must use ```into_raw``` method and return a raw pointer. //! You can create them using the ```from``` trait method, from both ```&str``` and ```String```. //! //! # Safety //! When passed from Python you can convert from PyString to an owned string //! (...
use anyhow::{anyhow, Result}; use futures::{StreamExt, TryStreamExt}; use imagepullsecret_sync::config::{Config, RegistryAuth}; use k8s_openapi::api::core::v1::{LocalObjectReference, Namespace, Secret, ServiceAccount}; use kube::{ api::{ListParams, Meta, PatchParams, PostParams}, Api, Client, }; use kube_runtim...
fn main() { let mut s = String::from("hello world"); //let word = first_word(&s); let word = first_word_slice(&s); s.clear(); println!("the first word is {}", word); } // without slices fn first_word(s: &String) -> usize { let bytes = s.as_bytes(); //array of bytes for (i, &item) in bytes....
use std::collections::HashMap; pub struct Dictionary { hash_map: HashMap<String, i32>, } impl Dictionary { pub fn new(&self) -> Dictionary { Dictionary { hash_map: Default::default(), } } pub fn add_key(&mut self, key: &str, number: i32) { if !self.hash_map.contain...
/// An enum to represent all characters in the Coptic block. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum Coptic { /// \u{2c80}: 'Ⲁ' CapitalLetterAlfa, /// \u{2c81}: 'ⲁ' SmallLetterAlfa, /// \u{2c82}: 'Ⲃ' CapitalLetterVida, /// \u{2c83}: 'ⲃ' SmallLetterVida, /// \u{2c...
pub mod matrix_test; pub mod opengl_test; pub mod quaternion_test; pub mod ecs_test;
/* * 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 reverie_syscalls::LocalMemory; use reverie_syscalls::Syscall; use syscalls::syscall; use syscal...
use std::ops::Range; use std::ops::RangeTo; use std::ops::RangeFrom; use std::ops::RangeFull; use std::iter::Enumerate; use nom::*; use std::str; use std::str::FromStr; use std::str::Utf8Error; #[derive(Debug, Clone, PartialEq)] pub enum Token { Comment(String), Float(f64), Integer(i64), Char(char), ...
pub fn read_lines(filename: String) -> Vec<String> { let rows = std::fs::read_to_string(filename).expect("Failed to read input"); return rows.split("\n").map(|s| s.to_string()).collect(); }
use metrics::*; use specs::prelude::*; use std::time::Instant; use tokio::prelude::Sink; use types::*; use websocket::OwnedMessage; use std::mem; use std::sync::mpsc::{channel, Receiver}; pub struct PollComplete { channel: Receiver<(ConnectionId, OwnedMessage)>, } impl PollComplete { pub fn new(channel: Receiver<...
use clap::{App, Arg, ArgMatches}; use result::{FdownError, Result}; use std::env; use std::ffi::OsString; const CONFIG: &'static str = "config"; const COUNT: &'static str = "count"; const CATEGORY: &'static str = "category"; const DEFAULT_CONFIG: &'static str = "~/.fdown"; const SUBS: &'static str = "subs"; const UNSA...
use std::io::{BufRead, Write}; use actix::prelude::*; use futures::{future, prelude::*, stream}; use crate::error::CliError; use git_lfs_spec::transfer::custom; #[derive(Debug, Clone)] struct Input(custom::Event); impl Message for Input { type Result = Result<Output, CliError>; } #[derive(Debug, Clone)] struct...
use std::default::Default; use std::from_str; use std::fmt; use types::elements::*; use types::vertexs::*; // Obj file structure pub struct Obj { // Vertex data pub geometric_vertices: Vec<GeometricVertex>, pub texture_vertices: Vec<TextureVertex>, pub vertex_normals: Vec<VertexNormals>, pub paramet...
fn main() { let x = 5; let y = 10; println!("x = {} and y = {}", x, y); }
//! Simple echo websocket server. //! Open `http://localhost:8080/ws/index.html` in browser //! or [python console client](https://github.com/actix/actix-web/blob/master/examples/websocket-client.py) //! could be used for testing. #![allow(unused_variables)] extern crate actix; extern crate actix_web; extern crate env...
extern crate gtk; extern crate gio; use gtk::{ WidgetExt, WindowExt, ContainerExt, TextViewExt, TextBufferExt, GtkApplicationExt, DialogExt, FileChooserExt, BinExt, Cast }; use gio::{ ApplicationExt, SimpleActionExt, ActionMapExt, MenuExt, FileExt }; fn main() { match gtk::Application::new("co...
use ::Provider; use ::Temperature; use ::TemperatureUnits; pub struct FakeProvider; impl Provider for FakeProvider { fn get_temperature(&self) -> Option<Temperature> { Some(Temperature { digit: 23, milli: 500, unit: TemperatureUnits::Celsius, }) } }
use crate::connection::{ConnectionError, Credentials, Request as EthaneRequest}; use reqwest::blocking::Client; use reqwest::header::HeaderMap; /// Wraps a blocking http client pub struct Http { /// The domain where requests are sent address: String, credentials: Option<Credentials>, client: Client, }...
//! OpenLibrary work schemas. use friendly::scalar; use crate::arrow::*; use crate::ids::index::IdIndex; use crate::prelude::*; pub use super::source::OLWorkRecord; use super::source::Row; /// Work row in extracted Parquet. #[derive(Debug, Clone, ArrowField, ArrowSerialize, ArrowDeserialize)] pub struct WorkRec { ...
use std::{env, fs}; fn main() { let args: Vec<String> = env::args().collect(); if args.get(1).is_none() { panic!("Supply a file to run against"); } let content = fs::read_to_string(args.get(1).unwrap()).expect("Reading file went wrong"); let mut plays: Vec<(char, char)> = Vec::new(); ...
// 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 http://mozilla.org/MPL/2.0/. use core::ops::{Index, IndexMut, Range, RangeFrom, RangeTo, RangeFull}; use crate::string::{ByteStr}; impl Index<usi...
use crate::{ pipeline::{ render_mesh::RenderMesh, light::IsLight, material::IsMaterial, }, camera::{ IsCamera, } }; use glow::HasContext; use luminance::{ context::GraphicsContext, pipeline::PipelineState, render_state::RenderState, tess::TessSliceIndex,...
pub trait Mapper<T> { fn map(&self) -> T; fn map_to(&self, destination: T) -> T { destination } }
use crate::eval::LNum; struct HexStrComp<'a> { whole_part: &'a str, fractional_part: Option<&'a str>, exponent_part: Option<&'a str>, } fn get_componenets(s: &str) -> Result<HexStrComp, String> { // let's get the exponent first let exponent_splitter = if s.contains("p") { "p" } else { "P" }; l...
use self::Msg::*; use gtk::prelude::*; use gtk::Orientation::Vertical; use img_dedup::SimilarPair; use log::debug; use relm::{connect, Relm, Widget}; use relm_attributes::widget; use relm_derive::Msg; use std::collections::BinaryHeap; pub struct Model { files: BinaryHeap<SimilarPair>, current_pair: Option<Simi...
#[async_trait] impl < R > FromReader < crate :: ERROR, R > for Connect where Self : Sized, R : Read + std :: marker :: Unpin + std :: marker :: Send { async fn from_reader(reader : & mut R) -> Result < Self, crate :: ERROR > { let c_flags : ConnectFlags ; Ok(Connect(< Protocol > :: ...
extern crate rand; use std::sync::{Arc, Mutex}; use std::sync::atomic::{AtomicBool, Ordering}; use std::thread; use std::time; #[derive(Clone)] struct Item { score: i32, is_unique: bool } impl Item { pub fn new(score: i32) -> Item { Item { score: score, is_unique: true ...
use crypto::Secret; use parameters::{ClientTransportParameters, ServerTransportParameters, TransportParameters}; use types::Side; use super::{QuicError, QuicResult}; use codec::Codec; use std::str; use std::io::Cursor; use super::QUIC_VERSION; use hex; use ring::aead::AES_256_GCM; use ring::digest::SHA256; use snow...
// Multiples of 3 and 5 // 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. fn main() { let mut sum = 0; for num in 1..1001 { if num % 3 == 0 || num % 5 == 0 { ...
pub use super::models::Session; pub use super::models::new::Session as NewSession; use db::{DatabaseConnection, SelectError}; generate_crud_fns!(sessions, NewSession, Session); /// Fetches a session from the database along with whether it's the current session. pub fn get_session(conn: &DatabaseConnection, id: i32) ...
use std::fs::File; use std::io::{BufReader, BufWriter}; use crate::cartridge::{MirrorMode, Rom, RomMapper}; use crate::savable::Savable; use super::Mapper; pub struct Mapper4 { rom: Rom, target: u8, prg_mode: bool, chr_invert: bool, mirror_mode: MirrorMode, registers: [u8; 8], prg_banks...
#[derive(Clone, Copy)] pub struct Color { pub r: f64, pub g: f64, pub b: f64, } impl Color { pub fn grey(c: f64) -> Self { Self { r: c, g: c, b: c } } pub fn black() -> Self { Self { r: 0.0, g: 0.0, b: 0.0, } } } impl std::ops::A...
/* * Copyright (C) 2019-2021 TON Labs. All Rights Reserved. * * Licensed under the SOFTWARE EVALUATION License (the "License"); you may not use * this file except in compliance with the License. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ...
#![allow(dead_code)] /// # Render engine middlware /// Currently only `HandlebarsEngine` support /// /// ## Features /// * Init Tempalte engine /// * Adding Template paths /// * useful additional helpers with strong params checking /// * helpers logger for critical situations /// /// ## Helpers /// * `link` - css link ...
pub fn reverse_endian_u32 (hash: u32) -> u32 { ( ((hash & 0x000000FF) << 24) | ((hash & 0xFF000000) >> 24) | ((hash & 0x00FF0000) >> 8) | ((hash & 0x0000FF00) << 8) ) }
/* * 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 */ /// SyntheticsVariableParser : Details of the parser to use for the global variable. #[derive(Clone, ...
// `match` is a valid method for handling `Option`. However, you may // eventually find heavy usage tedious, especially with operations only // valid with an input. In these cases, combinators can be used to // manage control flow in a modular fashion. // // `Option` has a buil in method called `map()`, a vombinator...
// loop, while & for fn main() { // loop loop_fn(); // while while_fn(); // for for_fn(); } fn for_fn() { // this is FAST { println!("Iteration through array: for"); let array = [1, 2, 3, 4, 5, 6, 7, 8]; for i in array.iter() { println!("{}", i); ...
extern crate futures; extern crate tokio; extern crate tokio_stomp; use std::time::Duration; use tokio_stomp::*; use tokio::executor::current_thread::{run, spawn}; use futures::future::ok; use futures::prelude::*; // Stream data from the UK national rail datafeed. // See http://nrodwiki.rockshore.net/index.php/Darwi...
extern crate env_logger; extern crate fuse; #[macro_use] extern crate lazy_static; #[macro_use] extern crate jsonfs; #[macro_use] extern crate serde_json; mod setup; use std::fs::OpenOptions; use std::io::prelude::*; #[test] fn bad_write_does_nothing() { let _fs = setup::get_fs(); let path = setup::from_mntp...
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ mod nullbuf; pub use nullbuf::NullTerminatedBuf; #[macro_use] #[allow(unused_macros)] pub mod str_enum; pub mod case; pub mod con...
use core::task::{Context, Poll, Waker}; use std::collections::BTreeMap; use std::collections::HashMap; use std::collections::VecDeque; use std::net::SocketAddr; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; use std::time::Duration; use futures::executor::block_on; use futures::future::Future; use...
use crate::{Context, Error}; use poise::serenity_prelude as serenity; fn create_embed<'a>( f: &'a mut serenity::CreateEmbed, author: &serenity::User, name: &str, description: &str, links: &str, ) -> &'a mut serenity::CreateEmbed { f.title(&name) .description(&description) .field...
use surf::http::Method; use crate::endpoints::load_balancing::LoadBalancer; use crate::framework::endpoint::Endpoint; use crate::framework::ApiResultTraits; /// List Load Balancers /// https://api.cloudflare.com/#load-balancers-list-load-balancers #[derive(Debug)] pub struct ListLoadBalancers<'a> { /// The Zone t...
// Copyright 2015-2016 Joe Neeman. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except accordin...
#[doc = "Reader of register SCAN_PARAM"] pub type R = crate::R<u32, super::SCAN_PARAM>; #[doc = "Writer for register SCAN_PARAM"] pub type W = crate::W<u32, super::SCAN_PARAM>; #[doc = "Register SCAN_PARAM `reset()`'s with value 0"] impl crate::ResetValue for super::SCAN_PARAM { type Type = u32; #[inline(always...
pub mod cr1 { pub mod bidimode { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0x40003800u32 as *const u32) >> 15) & 0x1 } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0x40003800u32 as...
//! An attribute-like macro to implement traits for `Either` //! (defined in [`either`](https://crates.io/crates/either) crate). //! If your trait is implemented for both type `A` and `B`, //! then it is automatically implemented for `Either<A, B>`. //! //! # Usage //! //! When defining a trait, wrap it with the macro ...
use git2::Repository; use autorel_chlg::ChangeLog; pub struct Release<V> { pub prev_version: Option<V>, pub version: V, pub changelog: ChangeLog, pub repo: Repository, }
use crate::error::Error; use crate::{CoordDimensions, CoordSeq, Geometry as GGeometry}; use geo_types::{ Coordinate, LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon, }; use std; use std::borrow::Borrow; use std::convert::{TryFrom, TryInto}; #[allow(clippy::needless_lifetimes)] fn create_coor...
use std::process; pub fn part_one(input: &str) -> String { let numbers = parse_input(input); let mut val: Option<(i32, i32)> = None; for n in numbers.iter() { for m in numbers.iter() { if n + m == 2020 { val = Some((*n, *m)) } } } match val { ...
// Copyright (C) 2017 1aim GmbH // // 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 wr...
#![allow(missing_docs)] // TODO(mingwei) use std::collections::HashMap; pub use hydroflow_cli_integration::*; use crate::scheduled::graph::Hydroflow; pub async fn launch_flow(mut flow: Hydroflow) { let stop = tokio::sync::oneshot::channel(); tokio::task::spawn_blocking(|| { let mut line = String::ne...
#[doc = "Reader of register RCC_APB5RSTCLRR"] pub type R = crate::R<u32, super::RCC_APB5RSTCLRR>; #[doc = "Writer for register RCC_APB5RSTCLRR"] pub type W = crate::W<u32, super::RCC_APB5RSTCLRR>; #[doc = "Register RCC_APB5RSTCLRR `reset()`'s with value 0"] impl crate::ResetValue for super::RCC_APB5RSTCLRR { type T...
#[doc = "Register `CKGAENR` reader"] pub type R = crate::R<CKGAENR_SPEC>; #[doc = "Register `CKGAENR` writer"] pub type W = crate::W<CKGAENR_SPEC>; #[doc = "Field `AXICKG` reader - AXI interconnect matrix clock gating This bit is set and reset by software."] pub type AXICKG_R = crate::BitReader; #[doc = "Field `AXICKG`...