text
stringlengths
8
4.13M
use {Request, Response}; use super::codec::{Codec, Encoder, Decode, Encode}; use {http, h2}; use futures::{Future, Stream, Poll, Async}; use tower::Service; use tower_h2::RecvBody; /// A bidirectional streaming gRPC service. #[derive(Debug, Clone)] pub struct Grpc<T, C> { inner: T, codec: C, } #[derive(Debug...
/* Copyright (c) 2015, 2016 Saurav Sachidanand 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, di...
// Neg The unary negation operator -. use crate::integer::Integer; use core::ops::Neg; impl Neg for Integer { type Output = Integer; fn neg(self) -> Self::Output { self.negate() } } impl Neg for &Integer { type Output = Integer; fn neg(self) -> Self::Output { self.negat...
use super::*; use serde::Deserialize; #[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)] struct MyData { id: u32, data: u32, } impl Entity<u32> for MyData { fn get_id(&self) -> u32 { self.id } } #[test] fn should_be_able_to_save_and_read() { // given let mut storage = Sqli...
use crate::widget::{soft_label, titled_panel}; use druid::{ widget::{CrossAxisAlignment, Flex, MainAxisAlignment, TextBox, Controller}, Data, Lens, Widget, WidgetExt, Env, EventCtx, Event, }; #[derive(Clone, Data, Lens, Default)] pub struct Base64State { plaintext: String, base64: String, mode: usi...
pub mod config_define; pub use self::config_define::{Config, Metadata}; use serde_json; use serde_yaml; use std::fs::File; use std::io::BufReader; use std::io::Read; pub fn load(path: &str, op: &str) -> Config { assert!(!path.is_empty()); assert!(!op.is_empty()); let file = File::open(path).expect("Unabl...
use proc_macro2::{Span, TokenStream}; use quote::{quote, ToTokens}; use syn::token::{Colon, Pub}; use syn::{ parenthesized, parse::{Parse, ParseStream, Result}, parse_quote, Expr, Field, Fields, Ident, ItemStruct, Token, Type, VisPublic, Visibility, }; #[derive(Clone, Debug, PartialEq)] pub(crate) struct M...
use cw::{Crosswords, Range}; use cw::PointIter; /// An iterator over the characters in a particular range in a crosswords grid. pub struct RangeIter<'a> { pi: PointIter, cw: &'a Crosswords, } impl<'a> RangeIter<'a> { /// Creates an iterator over the characters in the given range. pub fn new(range: Ran...
extern crate ggez; extern crate rustic; extern crate tiled; use ggez::graphics::Rect; use rustic::application::*; use rustic::resources::*; use rustic::sop::*; use rustic::storyboard::*; fn main() { let mut builder = ApplicationBuilder::new("map", "rustic"); builder.stories(vec![ Story::Setup(Box::ne...
// Copyright 2019. The Tari Project // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following // disclai...
#![allow(clippy::comparison_chain)] #![allow(clippy::collapsible_if)] use std::borrow::Borrow; use std::cmp::Reverse; use std::cmp::{max, min}; use std::collections::{BTreeSet, HashMap, HashSet}; use itertools::Itertools; use whiteread::parse_line; const ten97: usize = 1000_000_007; /// 2ใฎ้€†ๅ…ƒ mod ten97๏ผŽๅ‰ฒใ‚ŠใŸใ„ใจใใซไฝฟใ† cons...
//! Synchronization primitives and utilities based on intrusive collections. //! //! This crate provides a variety of `Futures`-based and `async/await` compatible //! types that are based on the idea of intrusive collections: //! - Channels in a variety of flavors: //! - Oneshot //! - Multi-Producer Multi-Consumer ...
use crate::components; use crate::game::{MAP_HEIGHT, MAP_WIDTH}; pub fn create_entities_from_map( world: &mut legion::World, map: Vec<(components::Position, &str)>, ) -> ggez::GameResult { for (position, val) in map { if position.x >= MAP_WIDTH || position.y > MAP_HEIGHT { return Err(gg...
//! A Quantity has a magnitude and a dimension. use super::*; use std::cmp::{Ordering, PartialOrd}; use std::fmt; use std::ops::{DivAssign, MulAssign}; #[derive(Copy, Clone, Debug, Default, Eq, Hash, PartialEq)] pub struct Quantity<T> { /// The magnitude of this quantity (compared to the base units) magnitude...
fn print_border(size: usize, l: char, m: char, r: char) { print!("{}", l); for _ in 0..(size-1) { print!("โ”€โ”€โ”€โ”€{}", m); } println!("โ”€โ”€โ”€โ”€{}", r); } pub fn print_square(size: usize, data: &[i32]) { print_border(size, 'โ”Œ', 'โ”ฌ', 'โ”'); for y in 0..size { for x in 0..size { let c = dat...
use crate::apis::api_caller::ApiCaller; use crate::apis::flight_provider::flight_provider_request::FlightProviderRequest; use crate::apis::flight_provider::raw_models::flight_raw::FlightRaw; pub struct FlightProvider {} impl FlightProvider { pub fn new() -> Self { FlightProvider {} } pub async fn...
//https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/submissions/ use std::cmp::max; impl Solution { pub fn max_depth(s: String) -> i32 { let mut nesting_depth = 0; let mut tmp = 0; for c in s.chars() { match c { '(' => tmp += 1, ...
// Copyright 2019 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under the MIT license <LICENSE-MIT // http://opensource.org/licenses/MIT> or the Modified BSD license <LICENSE-BSD // https://opensource.org/licenses/BSD-3-Clause>, at your option. This file may not be copied, // modified, or di...
extern crate self as fuzzcheck; use std::ops::{Bound, Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive}; use fuzzcheck_mutators_derive::make_mutator; use crate::mutators::map::MapMutator; use crate::mutators::tuples::{Tuple2, Tuple2Mutator, TupleMutatorWrapper}; use crate::mutators::Wrapper; us...
/* Copyright โ“’ 2017 contributors. Licensed under the MIT license (see LICENSE or <http://opensource.org /licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of <http://www.apache.org/licenses/LICENSE-2.0>), at your option. All files in the project carrying such notice may not be copied, modified, or distribu...
use std::str::FromStr; use std::{error::Error, fmt}; /// Indicates if the concept is invalid. #[derive(Debug, PartialEq, Eq)] pub struct InvalidBoeConcept { concept: String, } impl InvalidBoeConcept { fn new(concept: &str) -> Self { InvalidBoeConcept { concept: concept.to_owned(), ...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use actix::clock::Duration; use starcoin_config::NodeConfig; use starcoin_node::run_dev_node; use std::sync::Arc; use std::thread; #[stest::test] fn test_run_node() { let config = Arc::new(NodeConfig::random_for_test()); le...
use super::SkewTContext; use crate::{ analysis::{Analysis, PrecipTypeAlgorithm}, app::config::{self}, coords::{ScreenCoords, TPCoords, XYCoords}, gui::{ utility::{draw_filled_polygon, plot_curve_from_points}, Drawable, DrawingArgs, PlotContextExt, }, }; use itertools::izip; use log::...
fn main() { println!("I've been updated!"); }
use crate::checks::author_has_permission; use crate::checks::ParsedCommand; use crate::chess_game::render_board; use serenity::{model::channel::Message, prelude::*}; use std::collections::HashMap; use std::future::Future; use std::pin::Pin; pub fn get_commands() -> HashMap< String, fn(Context, Message, ParsedC...
/* * __ __ _ _ _ * | \/ | ___ ___ __ _| | (_)_ __ | | __ * | |\/| |/ _ \/ __|/ _` | | | | '_ \| |/ / * | | | | __/\__ \ (_| | |___| | | | | < * |_| |_|\___||___/\__,_|_____|_|_| |_|_|\_\ * * Copyright (c) 2017-2018, The MesaLink Authors. * All rights reserved. * *...
use juniper::{ graphql_object, graphql_subscription, Context, EmptyMutation, GraphQLObject, RootNode, SubscriptionCoordinator, Variables, }; use juniper::futures::executor; use juniper::futures::stream::{self, Stream, StreamExt}; use juniper::http::GraphQLRequest; use juniper_subscriptions::{Connection,...
mod line_item; pub use line_item::LineItem; mod money; pub use money::Money; mod currency; pub use currency::Currency; mod billing_method; pub use billing_method::BillingMethod; mod foreign_key; pub use foreign_key::ForeignKey; trait HasVariants { fn variants() -> Vec<String>; }
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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 ...
//! Contains many ffi-safe equivalents of standard library types. //! The vast majority of them can be converted to and from std equivalents. //! //! For ffi-safe equivalents/wrappers of types outside the standard library go to //! the [external_types module](../external_types/index.html) pub(crate) mod arc; pub(crate...
use std::f32::consts::PI; use crate::{ angle::{DirectionX, DirectionY}, position::WorldCoords, ray::Ray, util::round, AngleRad, Grid, TilePosition, }; const RAY_PRECISION: usize = 8; pub fn rays_from(center: &TilePosition, grid: &Grid, width: f32, angle: &AngleRad) -> Vec<Ray> { debug_assert!...
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtWidgets/qboxlayout.h // dst-file: /src/widgets/qboxlayout.rs // // header block begin => #![feature(libc)] #![feature(core)] #![feature(collections)] extern crate libc; use self::libc::*; // <= header block end // main block begi...
use serde::Deserialize; #[derive(Deserialize, Debug)] pub struct FlightTrailPositionRaw { pub lat: Option<f64>, pub lng: Option<f64>, pub alt: Option<f64>, pub spd: Option<f64>, pub ts: Option<i64>, pub hd: Option<i64>, }
use juniper::GraphQLEnum; #[derive(GraphQLEnum)] enum Test { Test, #[graphql(name = "TEST")] Test1, } fn main() {}
pub fn range(start: i32, end: i32) -> Vec<i32> { (start..end + 1).collect() } #[cfg(test)] mod tests { use super::*; #[test] fn test_range_4to9() { assert_eq!(range(4, 9), vec![4, 5, 6, 7, 8, 9]); } #[test] fn test_range_neg2to4() { assert_eq!(range(-2, 4), vec![-2, -1, 0, ...
// This file is part of linux-epoll. 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/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distri...
use cargo::core::manifest::TargetSourcePath; use cargo::core::Edition; use failure::Fallible; use maplit::{btreeset, hashset}; use syn::visit::{self, Visit}; use syn::{Item, ItemMod, ItemUse, UseTree}; use std::collections::{BTreeSet, HashSet}; use std::path::Path; pub(crate) fn find_uses_lossy<'a>( src: &TargetS...
mod gbc; mod gui; use gbc::Emu; use gui::{Gui}; use std::env; use anyhow::{Result, bail}; fn main() -> Result<()>{ if env::args().count() != 2 { bail!("Please enter the path to ROM.GB"); } let rom_name = env::args().nth(1).unwrap(); let emu = Emu::new(&rom_name)?; let mut gui = Gui:...
extern crate rand; use std::fs::File; use std::io::{BufRead, BufReader, Seek, SeekFrom}; use rand::distributions::{IndependentSample, Range}; use rand::{thread_rng, Rng}; use std::path::Path; struct RandomLiner { reader: BufReader<File>, positions: Vec<usize>, } impl RandomLiner { fn new<P: AsRef<Path>>(path: ...
fn main() { println!("๐Ÿ”“ Challenge 28"); println!("Code in 'challenges/src/chal28.rs'"); }
use serde::Serialize; use std::error::Error as StdError; use thiserror::Error; use warp::http::StatusCode; use warp::{Rejection, Reply}; #[derive(Serialize)] struct ErrorMessage { code: u16, msg: String, } pub async fn recover(err: Rejection) -> Result<impl Reply, Rejection> { //api errors should be retur...
// Copyright 2023 Datafuse Labs. // // 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 ...
use glutin::dpi::PhysicalSize; use math::{clamp_mut, Mat4, Vec2, Vec3, SAFE_HALF_PI_MAX, SAFE_HALF_PI_MIN}; pub struct Camera { pub f_width: f32, pub f_height: f32, mov: Vec2, pub position: Vec3, pub pointing: Vec3, pub right: Vec3, pub forward: Vec3, pub look_at: Vec3, up: Vec3, ...
use crate::ast; use crate::ast::expr::EagerBrace; use crate::{ParseError, Parser, Spanned, ToTokens}; use runestick::Span; use std::fmt; /// A unary expression. /// /// # Examples /// /// ```rust /// use rune::{testing, ast}; /// /// testing::roundtrip::<ast::ExprUnary>("!0"); /// testing::roundtrip::<ast::ExprUnary>(...
extern crate nalgebra as na; extern crate nalgebra19 as na19; extern crate rand; extern crate tiled; mod assets; mod combat; mod enemies; mod physics; mod player; mod prelude; mod world; use amethyst::{ animation::AnimationBundle, assets::*, audio::{output::init_output, AudioBundle, SourceHandle, WavFormat}...
//! Adaptive radix tree. #![warn(missing_docs)] #![warn(missing_debug_implementations)] #[macro_use] mod utils; mod bst; mod map; pub use bst::Bst; pub use map::{ConcurrentMap, SequentialMap};
use chrono::Local; use rand::{thread_rng, Rng}; #[derive(Eq, PartialEq, Clone, Debug)] pub struct TemporaryKey { unix_timestamp_secs: u64, unix_timestamp_millis: u16, random_part: u16, } impl TemporaryKey { /// generate a somewhat unique key for temporary tables /// /// The time when the key h...
use async_trait::async_trait; use candy_frontend::{ ast_to_hir::{AstToHir, HirResult}, cst_to_ast::{AstResult, CstToAst}, hir_to_mir::{HirToMir, MirResult}, mir_optimize::{OptimizeMir, OptimizedMirResult}, mir_to_lir::{LirResult, MirToLir}, module::{Module, ModuleKind, PackagesPath}, positio...
use crate::{check_b64_arg, ok, Error, NsmDescription, NsmResponse, NsmResult}; use nsm_driver::nsm_process_request; use nsm_io::{Digest, ErrorCode, Request, Response}; pub fn nsm_get_attestation_doc( fd: i32, n: Option<String>, pk: Option<String>, ud: Option<String>, ) -> NsmResult<NsmResponse> { l...
use object_chain::{Chain, ChainElement, Link}; use crate::{ geometry::{ measurement::{MeasureConstraint, MeasureSpec}, BoundingBox, Position, }, input::event::InputEvent, state::WidgetState, widgets::{ layouts::linear::{ private::{LayoutDirection, LinearLayoutCha...
extern crate limonite; use limonite::syntax::expr::{Expr, ExprWrapper}; use limonite::syntax::op::InfixOp::*; use limonite::syntax::literals::Literals::*; use limonite::semantic::type_checker::TypeChecker; use limonite::semantic::analyzer_trait::ASTAnalyzer; // Type Checker #[test] fn test_type_inference_builtin_type...
use crate::db::HashValueDb; use crate::errors::MerkleTreeError; use crate::hasher::{Arity2Hasher, Arity4Hasher}; use crate::types::LeafIndex; use std::marker::PhantomData; // TODO: Have prehashed versions of the methods below that do not call `hash_leaf_data` but assume // that leaf data being passed is already hashed...
extern crate clap; extern crate falcon; use falcon::analysis; use falcon::il; use falcon::loader::{Elf, Loader}; use std::path::Path; fn main () { let matches = clap::App::new("falcon-example-0") .version("0.2.1") .about("An example of Falcon usage") .arg(clap::Arg::with_name("program") ...
#[cfg(not(target_arch = "wasm32"))] use glutin::MouseCursor as GlMouseCursor; /// Mouse cursor styles #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)] pub enum MouseCursor { /// No cursor None, /// Default cursor Default, /// Crosshair cursor Crosshair, /// Hand cursor Hand, /// ...
use std::io::prelude::*; use std::fs::File; use std::str::from_utf8; enum Dir { N, E, S, W } enum Movement { Right(i32), Left(i32), } struct Map { x: i32, y: i32, dir: Dir } impl Map { fn new() -> Map { Map{x: 0, y: 0, dir: Dir::N} } fn move(&self, i: Movement) -> Map { ...
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[cfg(feature = "ApplicationModel_Appointments_AppointmentsProvider")] pub mod AppointmentsProvider; #[cfg(feature = "ApplicationModel_Appointments_DataProvider")] pub mod DataProvider; #[rep...
use image::ImageBuffer; use rand::rngs::SmallRng; use rand::{Rng, SeedableRng}; // assuming 0.0 <= value <= 1.0 fn brightness(value: f64) -> u8 { (value * 255f64) as u8 } fn rnd(func: fn(i64, i64) -> i64, x: i64, y: i64) -> u8 { brightness(SmallRng::seed_from_u64(func(x, y) as u64).gen()) } fn main() { /...
mod world; mod mouse; mod dot; mod line; pub use self::mouse::Mouse; pub use self::dot::Dot; pub use self::world::World; pub use self::line::Line;
#[doc = "Reader of register CHMAP3"] pub type R = crate::R<u32, super::CHMAP3>; #[doc = "Writer for register CHMAP3"] pub type W = crate::W<u32, super::CHMAP3>; #[doc = "Register CHMAP3 `reset()`'s with value 0"] impl crate::ResetValue for super::CHMAP3 { type Type = u32; #[inline(always)] fn reset_value() ...
mod handle; mod table; // objects mod thread; mod process; mod code; mod mono_copy; mod event; mod channel; pub use self::handle::{Handle, HandleOffset}; pub use self::table::HandleTable; pub use nabi::HandleRights; pub use self::thread::ThreadRef; pub use self::process::ProcessRef; pub use self::code...
pub fn set_cursor_visibility(_visible: bool) {} pub fn set_cursor_bounds(_top: i32, _left: i32, _bottom: i32, _right: i32) {} pub fn clear_cursor_bounds() { }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IPrintManagerInterop(pub ::windows::core::IUnk...
use nalgebra::Vector4; use crate::{LumpData, LumpType, PrimitiveRead}; use std::io::{Read, Result as IOResult}; bitflags! { #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)] pub struct SurfaceFlags: i32 { const LIGHT = 0x1; const SKY2D = 0x2; const SKY = 0x4; const WARP = 0x8; const T...
impl Solution { pub fn is_anagram(s: String, t: String) -> bool { if s.len() != t.len() { return false; } let mut db = std::collections::HashMap::<char, i32>::with_capacity(26); for (x, y) in s.chars().zip(t.chars()) { *db.entry(x).or_default() += 1; ...
//! ะกั‚ะตะฝั‹ use crate::sig::rab_e::openings::*; use crate::sig::rab_e::*; use crate::sig::HasWrite; use nom::{ bytes::complete::take, multi::count, number::complete::{le_f32, le_i16, le_u16, le_u32, le_u8}, IResult, }; use std::fmt; #[derive(Debug)] pub struct Wall { p1: Point, //1-ั ั‚ะพั‡ะบะฐ ัั‚...
// Copyright 2021 Datafuse Labs. // // 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 ...
#[cfg(all(feature = "handlebars", feature = "rustc_version"))] extern crate rustc_version; #[cfg(feature = "handlebars")] extern crate handlebars; #[cfg(feature = "reqwest")] extern crate reqwest; #[macro_use] extern crate serde_derive; #[allow(unused_extern_crates)] extern crate serde; #[macro_use] extern crate qui...
use crate::FileHandle; use std::path::Path; use std::path::PathBuf; #[cfg(feature = "parent")] use raw_window_handle::{HasRawWindowHandle, RawWindowHandle}; pub(crate) struct Filter { pub name: String, pub extensions: Vec<String>, } /// ## Synchronous File Dialog /// #### Supported Platforms: /// - Linux //...
extern crate ingredients_bot; use ingredients_bot::*; fn main() { let food = get_food().unwrap(); println!("{}", food.to_tweets().join("\n---\n")); }
//! linux_raw syscalls supporting `rustix::fs`. //! //! # Safety //! //! See the `rustix::backend` module documentation for details. #![allow(unsafe_code)] #![allow(clippy::undocumented_unsafe_blocks)] use crate::backend::c; use crate::backend::conv::fs::oflags_for_open_how; use crate::backend::conv::{ by_ref, c_i...
use matrix_sdk::{ events::{ room::{ member::MemberEventContent, message::{MessageEventContent, TextMessageEventContent}, }, AnyMessageEventContent, StrippedStateEvent, SyncMessageEvent, }, Client, EventHandler, RoomState, }; use crate::cfg::BotConfig; use tok...
//! Handle damages use amethyst::{ ecs::{ReadStorage, System, WriteStorage, Component, DenseVecStorage, Entities, Write}, }; use specs_physics::events::{ProximityEvent, ProximityEvents}; use amethyst::core::shrev::{ReaderId}; /// Destroys entities which are destroyable. pub struct Destroyer { pub damage: f...
use std::time::Duration; pub const TRAIN_ACCELERATION: u32 = 2; pub trait CurrentMovable { fn accelerate(&mut self, t: Duration) -> i32; fn decelerate(&mut self, t: Duration) -> i32; fn print(&self); } #[derive(Debug)] pub struct CurrentTrain { current_v: i32, } impl CurrentTrain { pub fn new(v:...
mod adventofcode; use adventofcode::load_file; #[cfg(test)] mod tests { use spreadsheet_sum; #[test] fn test1() { let input = r#"5 1 9 5 7 5 3 2 4 6 8"#; assert_eq!(spreadsheet_sum(&input), 18); } } fn spreadsheet_sum(input: &str) -> i32 { let mut sum = 0; for line in inp...
use serde::{de::DeserializeOwned, Deserialize, Serialize}; use crate::{d5_2_hashmap_from_scratch, d7_44_blob_data_file::BlobError}; use std::io; pub fn read_value<V: DeserializeOwned, R: io::Read>(r: &mut R) -> Result<V, BlobError> { let result = bincode::deserialize_from(r)?; Ok(result) } pub fn write_value...
use pattern::*; use haystack::Span; use memchr::{memchr, memrchr}; use std::ops::Range; #[derive(Debug, Clone)] pub struct CharSearcher { // safety invariant: `utf8_size` must be less than 5 utf8_size: usize, /// A utf8 encoded copy of the `needle` utf8_encoded: [u8; 4], } #[derive(Debug, Clone)] pub...
extern crate tuix; use tuix::*; //static THEME: &'static str = include_str!("themes/basic_theme.css"); fn main() { // Create the app let mut app = Application::new(|win_desc, state, window| { match state.insert_stylesheet("examples/themes/basic_theme.css") { Ok(_) => {}, Err(e...
use main_error::MainResult; // You can use plain strings (owned or not) as the error type. // NOTE: Uses the `MainResult` type as a shorthand for `Result<(), MainError>`. fn main() -> MainResult { // NOTE: The try-operator `?` is necessary for implicit conversion to `MainError`. Err("strings can be used as er...
// MinIO Rust Library for Amazon S3 Compatible Cloud Storage // Copyright 2022 MinIO, Inc. // // 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...
#[derive(Debug, Default, Clone)] struct Data { id: String, value: i32, } fn main() { let ds1 = vec![ Data { id: "d1".to_string(), value: 1}, Data { id: "d2".to_string(), value: 2}, ]; let ds2 = [ ds1.clone(), vec![Data { id: "d3".to_string(), value: 3 }] ].con...
use std::ffi::CString; #[cfg(feature = "img")] use image::DynamicImage; use libwebp_sys::*; #[cfg(feature = "img")] use image::*; use crate::{shared::*, Encoder}; pub struct AnimFrame<'a> { image: &'a [u8], layout: PixelLayout, width: u32, height: u32, timestamp: i32, config: Option<&'a WebP...
//! Implementations related to single rules. use crate::types::*; use crate::{ filter::{Filter, Filterable}, tokenizer::{finalize, Tokenizer}, utils, }; use itertools::Itertools; use log::{error, info, warn}; use serde::{Deserialize, Serialize}; use std::collections::HashSet; use std::fmt; pub(crate) mod ...
/* 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/. */ //! Fairly minimal recursive-descent parser helper functions and types. use std::fmt; #[derive(Clone, Debug)] pu...
use super::Schedule; use crate::calendar::{CalendarRequest, LongtermHandling}; use bitflags::bitflags; use chrono::{naive::MIN_DATE, Duration, NaiveDate, TimeZone, Utc}; use icalendar::{Component, Event as IcalEvent}; use std::collections::{BTreeMap, HashSet}; use std::rc::Rc; pub(super) fn generate_events( schedu...
use prost::{ DecodeError, Message, }; use sqs_executor::{ errors::{ CheckedError, Recoverable, }, event_decoder::PayloadDecoder, }; use crate::decoder::decompress::PayloadDecompressionError; #[derive(thiserror::Error, Debug)] pub enum ProtoDecoderError { #[error("DecompressionE...
#[derive(Deserialize)] pub struct ZGUIRepositoryInfo { pub version: String, pub version_type: String }
//! Environment use std::collections::HashMap; use eval::{Function, Value}; use util::interner::{Interner, Name}; /// A stack of environments pub struct Stack<'a> { top: Env, bottom: Option<&'a Stack<'a>>, } impl<'a> Stack<'a> { /// Pushes a new environment into the stack pub fn push(&self, env: Env...
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. mod changer; mod restore; pub use self::changer::{Changer, MapChange, MapChangeType}; pub use self::restore::restore;
// Copyright 2016 Indoc Developers // // 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...
use std::marker::PhantomData; use futures::StreamExt; use openlimits::{ binance::{client::websocket::BinanceWebsocket, Binance}, exchange::Exchange, exchange_ws::OpenLimitsWs, model::websocket::Subscription, }; #[tokio::test] async fn orderbook() { let mut ws = init(); let sub = Subscription::...
#[cfg(feature = "async")] use crate::a_sync::AsyncResultSetCore; #[cfg(feature = "sync")] use crate::{sync::SyncResultSetCore, HdbResult}; use std::sync::Arc; pub(crate) type AmRsCore = Arc<MRsCore>; #[derive(Debug)] pub(crate) enum MRsCore { #[cfg(feature = "sync")] Sync(std::sync::Mutex<SyncResultSetCore>),...
use crate::component_registry::ComponentRegistry; use crate::entities::{EntityId, EntityIds, SpatialEntitiesRes}; use crate::system_commands::{SystemCommandSender, SystemCommandSenderRes}; use spatialos_sdk::worker::connection::{Connection, WorkerConnection}; use spatialos_sdk::worker::op::WorkerOp; use specs::prelude:...
mod symlink; mod downloader; mod archive_reader; mod ls; mod system_node; mod logger; mod node_version; mod commands; mod language; mod home_directory; mod autoselect; mod compiler; extern crate hyper; extern crate regex; extern crate os_type; extern crate rustc_serialize; extern crate semver; extern crate docopt; use...
use ansi_term::Color::{Green, Red, Yellow, Blue, Cyan, White}; use log::*; use chrono::prelude::*; pub fn Info(info: String) -> String { return Green.bold().paint(format!("{}", info)).to_string(); } pub fn printLn(info: String, target: String) -> String { let local: DateTime<Local> = Local::now(); return...
// // Convert //! Convert to LWJGL key and mouse button values. // use terminal::event::{Key, MouseButton}; /// Converts a key to an LWJGL key code. pub fn key_to_lwjgl(key: Key) -> Option<i32> { match key { Key::Q => Some(16), Key::W => Some(17), Key::E => Some(18), Key::R => Some(19), Key::T => Some(...
use super::{access::Access, deserialize_int_opt}; use serde::Deserialize; /// Bit-field properties of a register. #[non_exhaustive] #[derive(Clone, Debug, Default, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Field { /// Define the number of elements in an array. #[serde(default, dese...
/// We want to support a commands like: /// /// cargo push commit -m "hello world" -t feature --story SVC-1111 mod commit; mod git; use commit::{perform_commit, ConventionalCommitType}; #[macro_use] extern crate lazy_static; use structopt::StructOpt; #[derive(Debug, StructOpt)] #[structopt( name = "cargo push",...
use std::convert::TryFrom; use std::fmt; #[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum Level { VeryEasy, Easy, Normal, Hard, Absurd, } impl Level { pub fn iter() -> std::slice::Iter<'static, Level> { [ Level::VeryEasy, Level::Easy, ...
pub fn check_numeric_rules(num: usize) -> Result<bool, &'static str> { let num_list = split_numeric(num)?; let mut found_double = false; for (i, num) in num_list.iter().enumerate() { if i < 5 { if *num > num_list[i + 1] { return Ok(false); } if f...
use nanoserde::{DeBin, SerBin}; use naia_derive::Actor; use naia_shared::{Actor, Property}; use crate::ExampleActor; // Here's an example of a Custom Property #[derive(Default, PartialEq, Clone, DeBin, SerBin)] pub struct Name { pub first: String, pub last: String, } #[derive(Actor)] #[type_name = "ExampleA...