text
stringlengths
8
4.13M
use rayon_core::ThreadPoolBuilder; use std::error::Error; #[test] #[cfg_attr(any(target_os = "emscripten", target_family = "wasm"), ignore)] fn double_init_fail() { let result1 = ThreadPoolBuilder::new().build_global(); assert!(result1.is_ok()); let err = ThreadPoolBuilder::new().build_global().unwrap_err(...
use std::io; use std::sync::Arc; use actix_web::{middleware, web, App, Error, HttpResponse, HttpServer}; use juniper::http::playground::playground_source; use juniper::http::GraphQLRequest; mod schema; use crate::schema::{create_schema, Schema}; // Setup a playground request handler async fn playground() -> HttpRes...
use nimiq_blockchain_interface::BlockchainError; use nimiq_collections::BitSet; use nimiq_database::TransactionProxy; use nimiq_primitives::{ policy::Policy, slots_allocation::{Validator, Validators}, }; use nimiq_vrf::{Rng, VrfEntropy, VrfSeed, VrfUseCase}; use crate::Blockchain; pub struct Slot { pub nu...
use std::{ sync::{ Arc } }; use derive_more::{ Constructor }; use super::{ config::{ TelegramClientConfig }, responses::{ TelegramMessageData }, }; #[derive(Debug, Constructor)] pub struct TelegramMessage{ config: Arc<TelegramClientConfig>, data: TelegramMes...
pub use self::ai_component::AIComponent; pub use self::action_component::{Action, ActionComponent}; pub use self::actor_component::ActorComponent; pub use self::physics_component::PhysicsComponent; pub use self::render_component::RenderComponent; mod ai_component; pub mod action_component; mod actor_component;...
use std::sync::Arc; use std::collections::HashMap; use std::default::Default; use error_chain::ChainedError; use util::errors::*; use catalog::CatalogManager; use storage::Storage; use storage::storage_factory::StorageFactory; use server::config::ZeusConfig; pub struct StorageManager { tables: HashMap<i32, Arc<Sto...
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT extern crate webkit2gtk_sys; extern crate shell_words; extern crate tempdir; use std::env; use std::error::Error; use std::path::Path; use std::mem::{align_of, size_of}; use std::pro...
pub fn is_key_pressed(x: u8) -> bool { unimplemented!(); } pub fn wait_for_key_press() -> u8 { unimplemented!(); }
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct CConfig<'a> { pub format: &'a str, pub version_format: &'a str, pub style: &'a str, ...
pub use {swc_common, swc_ecma_transforms, swc_ecma_parser};
use std::{ fs::File, io::{BufReader, Seek, SeekFrom}, }; use anyhow::Result; use rustls::{Certificate, PrivateKey}; use rustls_pemfile::{pkcs8_private_keys, rsa_private_keys}; #[tracing::instrument] fn read_keys() -> Result<(PrivateKey, Vec<Certificate>)> { let privkey_path = std::env::var("PRIVKEY_PATH")...
use crate::common::reedsolomon::generic_gf::GenericGF; use crate::common::reedsolomon::generic_gf_poly::GenericGFPoly; use crate::common::reedsolomon::reedsolomon_error::ReedSolomonError; pub struct ReedSolomonDecoder { field: GenericGF, } impl ReedSolomonDecoder { pub fn new(field: GenericGF) -> ReedSolomonD...
mod basic_break_test; mod break_with_multiple_locations; mod interval_break_test; mod multi_break_test; mod relation_break_test; mod skip_break_test;
// Copyright 2020 WHTCORPS INC. Licensed under Apache-2.0. use std::sync::Arc; use std::thread; use std::time::*; use crossbeam::channel; use ekvproto::violetabft_server_timeshare::{PeerState, VioletaBftMessage, BraneLocalState, StoreIdent}; use protobuf::Message; use violetabft::evioletabft_timeshare::MessageType; u...
use amethyst_core::cgmath::{Matrix4, SquareMatrix}; use amethyst_core::specs::prelude::{ BitSet, InsertedFlag, Join, ModifiedFlag, ReadStorage, ReaderId, Resources, System, WriteStorage, }; use amethyst_core::GlobalTransform; use amethyst_renderer::JointTransforms; use super::resources::*; /// System for perf...
use std::env; use std::path::PathBuf; use std::process::exit; use protobuf_parse::Parser; fn main() { let args = env::args_os() .skip(1) .map(PathBuf::from) .collect::<Vec<_>>(); if args.len() != 2 { eprintln!( "usage: {} <input.proto> <include>", env::...
pub mod file_watcher; mod tsc_processor; use indicatif::{HumanDuration, ProgressBar, ProgressStyle}; use walkdir::WalkDir; use std::fs::{copy, create_dir_all, File}; use std::io::prelude::*; use std::path::{Path, PathBuf}; use std::time::Instant; const COMPILE_EXTS: [&str; 3] = ["ts", "tsx", "jsx"]; pub const TARGET...
fn main(){ let number = 6; if number % 4 == 0 { println!("number is divisible by 4"); }else if number % 3 == 0 { println!("number is divisible by 3"); }else if number % 2 == 0 { println!("number is divisible by 2"); }else{ println!("number is not divisible by 4, 3 or...
pub struct Animation{ x : i32, y : i32, length : i32, width : i32, height : i32, speed : i32, cmpt : i32, negativeCmpt : i32, animationOnY : bool } impl Animation{ pub fn new (posX : i32, posY : i32, animationLength : i32, spriteSize : i32, animationSpeed : i32, decalage : i32) ...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use crossbeam::utils::CachePadded; use dashmap::DashMap; use std::{ collections::btree_map::BTreeMap, hash::Hash, sync::{ atomic::{AtomicUsize, Ordering}, Arc, }, }; #[cfg(test)] mod unit_tests; // T...
use chrono::{NaiveDate, NaiveDateTime, NaiveTime, ParseResult, Utc}; use diesel::{dsl::sum, result::Error, sql_types::{Double, Integer}}; use ferrous_finance::move_month_forward; use std::fmt; use super::*; fn parse_date(src: &str) -> ParseResult<NaiveDateTime> { let full_date = format!("01/{}",src); Ok(Naive...
//! Clock abstraction use crate::rtw_core::datetimew::DateTimeW; /// Time (absolute or relative) #[derive(Debug, Clone, Copy, PartialEq)] pub enum Time { /// Now, can be converted to `DateTimeW` using `Clock.date_time` Now, DateTime(DateTimeW), } /// Clock Abstraction pub trait Clock { /// Get curren...
use chrono::{DateTime, Utc}; use juniper::graphql_object; use sqlx::FromRow; use uuid::Uuid; /// Represents a user in the "users" table. #[derive(Debug, Clone, FromRow)] pub struct User { /// The unique ID of the user. pub id: Uuid, /// Auto-generated timestamp specifying when this user was created. pu...
/* * @lc app=leetcode.cn id=434 lang=rust * * [434] 字符串中的单词数 */ // @lc code=start impl Solution { pub fn count_segments(s: String) -> i32 { return s.split_whitespace().count() as i32; } } // @lc code=end
use blake2::{Blake2b, Digest}; fn main() { let mut data: Vec<u8> = b"test".to_vec(); for i in 0.. { let mut hasher = Blake2b::new(); hasher.input(&data); let out = hasher.result(); data = out.to_vec(); if i % 1000000 == 0 { println!("Round {}: {:?}", i, dat...
//! Various utility types that are helpful in constructing Sylphie modules. #[macro_use] extern crate tracing; pub mod cache; pub mod disambiguate; pub mod locks; pub mod scopes; pub mod strings;
// RED \x1b[0;31m // GREEN \x1b[0;32m // YELLOW \x1b[0;33m // CYAN \x1b[0;36m // NC \x1b[0m macro_rules! info { ($($arg:tt)*) => ({ println!("\x1b[0;36m [INFO]\x1b[0m {}", format!($($arg)*)); }) } macro_rules! error { ($($arg:tt)*) => ({ println!("\x1b[0;31m [ERROR]\x1b[0m {}", format!($($arg...
use reqwest::Client; use ckb_jsonrpc_types::{ BlockNumber, BlockView, HeaderView, OutputsValidator, Transaction, TransactionWithStatus, }; use ckb_jsonrpc_types_43::{BlockView as OldBlockView, HeaderView as OldHeaderView}; use ckb_types::{prelude::*, H256}; use futures::FutureExt; use std::{ future::Future, ...
use super::gateway::Gateway; use futures::{future, Future, Poll}; use linkerd2_app_core::proxy::api_resolve::Metadata; use linkerd2_app_core::proxy::identity; use linkerd2_app_core::{dns, transport::tls, Error, NameAddr}; use linkerd2_app_inbound::endpoint as inbound; use linkerd2_app_outbound::endpoint as outbound; us...
fn main() { for x in 0..10 { println!("{}", x); } let mut range = 0..10; loop { match range.next() { Some(x) => { println!("{}", x); }, None => { break } } } let _one_to_one_hundred = (1..101).collect::<Vec<_>>(); ...
use crate::hittable::HitRecord; use crate::vec3::{Color, Vector3, dot_product, unit_vector, random_in_unit_sphere}; use crate::ray::Ray; use rand::Rng; pub struct MaterialInfo { pub attenuation: Color, pub scattered: Ray } pub trait Material { fn scatter (&self, ray: &Ray, hit_record: &HitRecord) -> Optio...
use std::io; #[derive(Debug)] pub enum DeserializeError { UnknownError, UnimplementedVisit, IncompatibleNumericType, UnexpectedEof, UnknownEnumVariant, UnknownUnionVariant, ParsingError, MissingField(&'static str), UnknownField, IoError(io::Error), } pub trait SeqBuilder { ...
use crate::feature::{Feature, Landmark}; use crate::number::Number; use nalgebra::Isometry3; pub trait KeyFrame { type Number: 'static + Number; type Feature: 'static + Feature<Number = Self::Number>; fn for_landmarks<F>(&self, f: F) where Self::Feature: 'static + Landmark, F: FnMut(&...
extern crate proc_macro; extern crate syn; extern crate quote; use proc_macro::TokenStream; use syn::{parse_macro_input, DeriveInput}; use syn::export::ToTokens; use quote::quote; use std::process::exit; #[proc_macro_derive(Builder)] pub fn derive(input: TokenStream) -> TokenStream { let syntax_tree = parse_macro...
#[allow(unused_imports)] use serde_json::Value; #[derive(Debug, Serialize, Deserialize)] pub struct DrivesDriveFirmwareUpdateNodeStatus { /// The number of drives that did not successfully complete firmware updates update on the node. #[serde(rename = "failed")] pub failed: Option<i32>, /// Time when d...
use super::prelude::*; use serenity::framework::standard::{help_commands, CommandGroup, HelpOptions}; use std::{collections::HashSet, hash::BuildHasher}; #[help] #[individual_command_tip = "Hello! Hallo! こんにちは!Hola! Bonjour! 您好!\n\ If you want more information about a specific command, just enter it as an argument."] ...
use template_rs; fn main() { template_rs::run().unwrap(); }
use std::path::PathBuf; #[derive(Clone, Copy, serde::Deserialize, PartialEq, PartialOrd)] pub enum ConvertType { All, None, IfNotSame, OnlyLossless } #[derive(Clone, serde::Deserialize)] pub struct Config { pub storage_path: PathBuf, pub music_files_template: String, pub conversion_format:...
use std::fs::{File, OpenOptions}; use std::io::Result as IOResult; use std::path::Path; use std::io; use zip::ZipArchive; use hyper::Client; pub fn download_file<'a>(url: &str, path: &'a str) -> IOResult<&'a str> { let client = Client::new(); let mut res = client.get(url).send().unwrap(); let mut file = OpenOpt...
use std::iter; impl Solution { pub fn num_distinct(s: String, t: String) -> i32 { let mut dp: Vec<Vec<i32>> = iter::repeat( iter::repeat(-1).take(t.len()).collect() ).take(s.len()).collect(); return helper(0, 0, &mut dp, &s.chars().collect(), &t.chars().collect()); } } fn h...
//! offline reinforcement learning (q learning after match is over) #![allow(dead_code)] extern crate rand; extern crate nn; use std::fs::File; use std::io::{BufReader, BufWriter}; use std::io::prelude::*; use self::rand::Rng; use self::nn::{NN, HaltCondition, Activation}; use super::Player; use super::super::field::...
use crate::algorithm::samples_tree::checkpoints::Checkpoints; use crate::algorithm::samples_tree::node::{ Children, InsertResult, Node, Nodes, RecordResult, Root, }; use crate::algorithm::samples_tree::{Checkpoint, CHILDREN_CAPACITY}; use arrayvec::ArrayVec; /// Represents a non-leaf node in the B-tree sample stru...
use super::{Peer, TrackerResponse}; use crate::bencoding; use crate::bencoding::{BDict, BInt, BString}; use crate::utility::{PeerId, PORT}; use url::form_urlencoded; use std::borrow::Cow; use std::convert::TryInto; use std::net::Ipv4Addr; pub fn announce( announce_url: &str, info_hash: &Vec<u8>, peer_id...
// use crate::{BindEvent, Context, Display, Entity, Event, FontOrId, Propagation, State, Tree, TreeExt, Visibility, WindowEvent, entity}; use femtovg::{ renderer::OpenGl, Canvas, }; use crate::{Context, Event, Propagation, Tree, TreeExt}; /// Dispatches events to widgets. /// /// The [EventManager] is respo...
mod brainfuck; mod shell; use indicatif::{ProgressBar, ProgressStyle}; use std::time::{Instant}; use clap::{Arg, App}; use crate::brainfuck::{ execute_directly_to_vec, }; use crate::shell::run_shell; fn main() { let matches = App::new("bfrs") .version("3.0") .author("Ian Kim. <ian@ianmkim.com...
#[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::ICR { #[doc = r" Writes to the register"] #[inline] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w.b...
// Copyright 2019 WHTCORPS INC Project Authors. Licensed under Apache-2.0. use lmdb::{ ReadOptions as RawReadOptions, BlockFilter, BlockProperties, WriteOptions as RawWriteOptions, }; use violetabftstore::interlock::::codec::number; pub struct LmdbReadOptions(RawReadOptions); impl LmdbReadOptions { pub fn in...
use treemap; use treemap::{MapItem, Mappable, Rect, TreemapLayout}; #[test] fn layout_items() { let bounds = Rect::from_points(0.0, 0.0, 6.0, 4.0); let mut items: Vec<Box<dyn Mappable>> = vec![ Box::new(MapItem::with_size(6.0)), Box::new(MapItem::with_size(6.0)), Box::new(MapItem::with...
use std::result::Result; use std::vec::Vec; use super::error::Error; use regex::Regex; pub fn extract_tags(note: &str) -> Result<Vec<&str>, Error> { let re = Regex::new(r"((^|\s)#[^\s\t\.\?#,]+)").unwrap(); let mut tags = Vec::<&str>::new(); for m in re.find_iter(note) { let start = match note[m.st...
use std::fmt; use bytes::Bytes; use chrono::{NaiveDate, NaiveDateTime}; use crate::helpers::string_of_slice_opt; use crate::{errors::CIFParseError, helpers::ddmmyy_from_slice}; #[derive(Debug, Clone, Eq, PartialEq)] pub enum FullOrUpdate { Full, Update, } #[derive(Clone, Eq, PartialEq)] pub struct Header { ...
pub mod cudastereo { //! # Stereo Correspondence use crate::{mod_prelude::*, core, sys, types}; pub mod prelude { pub use { super::CUDA_StereoBMTraitConst, super::CUDA_StereoBMTrait, super::CUDA_StereoBeliefPropagationTraitConst, super::CUDA_StereoBeliefPropagationTrait, super::CUDA_StereoConstantSpaceBPTraitConst...
mod color; mod hittable; mod hittable_list; mod ray; mod rtweekend; mod sphere; mod vec3; use std::sync::Arc; use std::thread; fn ray_color(r: &ray::Ray, world: &dyn hittable::Hittable) -> color::Color { let mut hit_record = hittable::HitRecord::default(); if world.hit(r, 0.0, rtweekend::INFINITY, &mut hit_re...
use ezgame::ecs::*; use ezgame::gfx::*; use super::super:: { ChunkPosition, ChunkVertex, RGraphicsShared, RGraphicsChunk, SGraphicsShared, }; /// system that initializes the RGraphicsChunk /// resource pub struct SGraphicsChunk; impl System for SGraphicsChunk { const EVENT: Event = evt::RE...
mod model; mod texture; use crate::{ mesh::{Material, Mesh}, mesh_data::MeshData, texture::{ImmutableTexture, Texture}, threads::FILE_THREAD, }; use atom::AtomSetOnce; use futures::{future::lazy, task::SpawnExt}; use std::{ collections::HashMap, path::{Path, PathBuf}, sync::Arc, }; use vulkano::{ descriptor::P...
#![no_std] #![deny(unsafe_code)] #[macro_use] extern crate static_assertions; use core::ops::Range; trait Tri<A: ?Sized, B: ?Sized, C: ?Sized> {} impl<T, A: ?Sized, B: ?Sized, C: ?Sized> Tri<A, B, C> for T {} assert_impl_all!(u64: Tri<[&'static u8], dyn Tri<dyn Send, dyn Sync, str>, (u16, u16)>); assert_impl_all!(...
fn main() { let s = String::new(); // to string let a = "some string"; let b = a.to_string(); // from let c = String::from("some string"); // edit let mut d = String::from("x"); d.push_str("y"); let k = String::from("k"); d.push_str(&k); d.push('z'); d += &k; ...
// Copyright 2012 Derek A. Rhodes. All rights reserved. // This library is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as // published by the Free Software Foundation; either version 2 of the // licence, or (at your option) any later version. // ...
use serialisation::f1_2018::packets::PacketHeader; #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] pub struct PacketParticipantsInfo { pub m_header: PacketHeader, pub m_numCars: u8, // Number of cars in the data pub m_participants: [ParticipantInfoItem; 20], } #[derive(Serialize, Deserialize, ...
#![deny(clippy::all)] //! High level Node.js [N-API](https://nodejs.org/api/n-api.html) binding //! //! **napi-rs** provides minimal overhead to write N-API modules in `Rust`. //! //! ## Feature flags //! //! ### napi1 ~ napi8 //! //! Because `Node.js` N-API has versions. So there are feature flags to choose what vers...
use error::SRLError; use super::*; // splits string into tokens, fix_whitespaces has to be called prior. Defined behaviour only for chars in VALID_CHARS without \n \t and . pub fn tokenize(mut string : String) -> Result<Vec<String>, SRLError> { let mut tokens : Vec<String> = Vec::new(); #[allow(non_camel_case_types...
use core::time::Duration; use emit_core::{ ambient::Ambient, ctxt::Ctxt, emitter::{self, Emitter}, empty::Empty, filter::Filter, }; use crate::platform::{DefaultCtxt, Platform}; pub fn setup() -> Setup { Setup::default() } type DefaultEmitter = Empty; type DefaultFilter = Empty; pub struct ...
// * Daily Coding Problem August 5th 2020 // * [Medium] -- StitchFix // * Pascal's triangle is a triangular array of integers constructed with the following formula: // * The first row consists of the number 1. // * For each subsequent row, each element is the sum of the numbers directly above it, on either side. /...
use crate::descriptions::SampleDesc; use crate::enums::Format; use checked_enum::UncheckedEnum; use winapi::shared::dxgi::DXGI_SURFACE_DESC; #[repr(C)] #[derive(Copy, Clone)] pub struct SurfaceDesc { pub width: u32, pub height: u32, pub format: UncheckedEnum<Format>, pub sample_desc: SampleDesc, } im...
// vim: tw=80 use crate::common::*; use futures; /// Future representing an operation on a vdev. pub type VdevFut = dyn futures::Future<Item = (), Error = Error>; /// Boxed `VdevFut` pub type BoxVdevFut = Box<dyn futures::Future<Item = (), Error = Error>>; /// Vdev: Virtual Device /// /// This is directly analogous...
extern crate hyper; extern crate module_interface; use module_interface::ModuleResponse; #[no_mangle] pub extern "Rust" fn compute(request: &hyper::server::Request) -> ModuleResponse { println!("incoming query: {:?} - {:?}", request.path(), request.headers()); ModuleResponse::Noop }
use std::{cmp, mem}; use nimiq_block::{Block, BlockError}; use nimiq_blockchain_interface::{ AbstractBlockchain, BlockchainEvent, ChainInfo, PushError, PushResult, }; use nimiq_database::traits::{ReadTransaction, WriteTransaction}; use nimiq_primitives::policy::Policy; use nimiq_zkp::{verify::verify, NanoProof, ZK...
#![feature(is_sorted)] #![allow(non_snake_case)] use algo::strings::{Quick3String, Quick3Way, TrieST, LSD, MSD}; use std::collections::HashMap; const WORDS3: &'static str = include_str!("../res/strings/words3.txt"); const SHELLS: &'static str = include_str!("../res/strings/shells.txt"); const SHELLS_ST: &'static str =...
use crate::parsing::{Parser, ExprKind, Precedence}; use crate::typechecking::Ty; use regexlexer::{Token, TokenKind}; use crate::error::Error; pub(crate) fn parse_let<'a>(parser: &mut Parser<'a>, _token: Token<'a>) -> Result<(ExprKind, Option<Ty>), Error> { let binder = parser.parse_binder()?; parser.expect(Tok...
#[allow(unused_imports)] use serde_json::Value; #[derive(Debug, Serialize, Deserialize)] pub struct SettingsMappings { #[serde(rename = "mappings")] pub mappings: Option<Vec <crate::models::SettingsMappingExtendedExtended>>, }
extern crate ordered_float; // Required by thrift pub extern crate thrift; extern crate try_from; // Required by thrift pub mod common; pub mod completion_hints; pub mod extension_functions; #[allow(deprecated)] // lots of deprecated warnings from the thrift-generated code pub mod omnisci; pub mod serialized_result_se...
// Copyright 2022 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 ...
// Copyright 2020 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 std::sync::{Arc, Mutex}; use std::thread; #[allow(dead_code)] pub fn run() { println!("We cannot share just mutex. We need to make copy of this, multiple owners ->Rc"); let counter = Arc::new(Mutex::new(0)); //Arc is atomic version of Rc //counter is immutable but ...
pub fn rotate(input: &str, key: i8) -> String { let mut rel = String::new(); for c in input.chars() { if c.is_ascii_alphabetic() { let mut temp = if c.is_uppercase() { (c as u8 - b'A') as i8 + key } else { (c as u8 - b'a') as i8 + key }...
/* * Copyright 2020 Fluence Labs Limited * * 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 a...
struct Solution; use std::collections::HashMap; impl Solution { fn rearrange_barcodes(barcodes: Vec<i32>) -> Vec<i32> { let n = barcodes.len(); if n == 1 { return barcodes; } let mut hm: HashMap<i32, usize> = HashMap::new(); let mut max: (usize, i32) = (0, 0); ...
use core::fmt; use core::ops::{Add, AddAssign}; macro_rules! addr_common { ( $t:ty, $e:expr ) => { impl Add<usize> for $t { type Output = Self; fn add(self, _rhs: usize) -> Self { Self::from(self.into(): usize + _rhs) } } impl AddAssign<...
#[doc = "Register `TSZ` reader"] pub struct R(crate::R<TSZ_SPEC>); impl core::ops::Deref for R { type Target = crate::R<TSZ_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<TSZ_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<TSZ_SPEC>) ...
use cgmath::{InnerSpace, Vector3}; use rand::prelude::*; use crate::ray::Ray; use crate::scene::Scene; use crate::util; pub struct Canvas { x_size: u32, y_size: u32, camera_distance: f64, location: Vector3<f64>, direction: Vector3<f64>, // This is a unit vector } // Pixels are 2 units wide so tha...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::cli_state::CliState; use crate::StarcoinOpt; use anyhow::Result; use clap::Parser; use scmd::{CommandAction, ExecContext}; use starcoin_crypto::HashValue; use starcoin_rpc_api::chain::GetTransactionOption; use starcoin_rp...
use postgres::{Connection, types::ToSql}; use log::*; use ndarray::Array2; use crate::config::Config; use crate::error::{GeneratorError, Result}; pub fn load_data(config: &Config, data_file: Option<&str>) -> Result<Array2<f64>> { // Build the connection to the DB let conn = config.connect_db()?; ...
use std::fmt; use serde_json; #[derive(Debug, Serialize)] pub struct LogMessage { details: String, url: Option<String>, } impl LogMessage { pub fn new(details: &str) -> LogMessage { LogMessage { details: details.to_string(), url: None, } } } impl fmt::Display f...
// https://leetcode.com/problems/detonate-the-maximum-bombs/ // You are given a list of bombs. The range of a bomb is defined as the area where its effect // can be felt. This area is in the shape of a circle with the center as the location of the bomb. // The bombs are represented by a 0-indexed 2D integer array bomb...
use std::path::{Path, PathBuf}; use structopt::StructOpt; use std::str::FromStr; use url::Url; #[derive(Debug, Eq, PartialEq)] pub enum AddKind { Local(PathBuf), Git(String), } impl FromStr for AddKind { type Err = failure::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { let path = P...
#[no_mangle] pub extern "C" fn fact(mut n: u32) -> u32 { let mut result = 1; while n > 0 { result = result * n; n = n - 1; } result }
use boxercrab::{Connection, Event}; use log::LevelFilter; use log4rs::{ append::console::{ConsoleAppender, Target}, config::{Appender, Config, Root}, Handle, }; use std::fs::File; use std::io::prelude::*; use structopt::{clap::arg_enum, StructOpt}; use tokio::runtime::Runtime; #[derive(Debug, StructOpt)] #...
#![feature(total_cmp)] #![feature(bool_to_option)] pub mod chart; pub mod math;
use std::io; use std::net::SocketAddr; use umio::external::Sender; use server::dispatcher::DispatchMessage; use server::handler::ServerHandler; mod dispatcher; pub mod handler; /// Tracker server that executes responses asynchronously. /// /// Server will shutdown on drop. pub struct TrackerServer { send: Sende...
use cgmath::{ Angle, Deg, InnerSpace, Matrix4, Point3, SquareMatrix, Vector3, Vector4, }; use collision::{ Ray3, }; #[derive(Copy, Clone, Debug)] pub struct Camera { /// The distance from the eye to the near clipping plane. pub near: f32, /// The distance from the eye t...
use crate::geometry_utilities::point_inside_tetrahedron; use array_init::array_init; use itertools::Itertools; #[feature(array_map)] use kiss3d::nalgebra::Point3; use nalgebra::{Isometry3, Vector3}; use ncollide3d::query::{Ray, RayCast}; use ncollide3d::shape::{Tetrahedron, Triangle}; use slotmap::{new_key_type, SlotMa...
#![warn(clippy::disallowed_methods)] use clap::crate_authors; use std::io; use std::path::PathBuf; use std::thread::available_parallelism; use std::time::SystemTime; use clap::{CommandFactory, Parser, Subcommand}; use clap_complete::{generate, Shell as CompletionShell}; use rand::distributions::Alphanumeric; use rand...
// 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 agre...
#[macro_use] extern crate serde_derive; extern crate docopt; extern crate cmd; use std::process; use docopt::Docopt; const USAGE: &'static str = "\ Note Usage: note add <book> note add <book> -c <note> note edit <book> <note-index> note edit <book> <note-index> -c <note> note ls [--all] note ...
use rand::prelude::IteratorRandom; use std::env; const HIRA: &str = "あいうえおかきくけこがぎぐげごさしすせそざじずぜぞたちつてとだぢづでどなにぬねのはひふへほばびぶべぼぱぴぷぺぽまみむめもやゆよらりるれろわをん"; const HIRA_GOJUU: &str = "あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらりるれろわをん"; const KATA: &str = "アイウエオカキクケコガギグゲゴサシスセソザジズゼゾタチツテトダヂヅデドナニヌネノハヒフヘホバビブベボパピプペポマミムメモヤユヨラリルレロワヲン"; c...
// TODO(gib): Good rust coverage checker (tarpaulin?) // TODO(gib): Set up Travis (including tests, building binaries, and coverage). // Run: `cargo test -- --ignored` // https://github.com/japaric/trust #![feature(external_doc)] #![doc(include = "../README.md")] use std::env; use anyhow::Result; use log::trace; fn...
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 pub mod harness; #[cfg(feature = "openssl")] pub mod openssl; #[cfg(feature = "rustls")] pub mod rustls; pub mod s2n_tls; #[cfg(feature = "openssl")] pub use crate::openssl::OpenSslConnection; #[cfg(feature = ...
use nom::*; use std::str; use std::str::FromStr; use std::ascii::AsciiExt; use types::*; named!(i64_digit<i64>, map_res!( map_res!(digit, str::from_utf8), FromStr::from_str ) ); fn parse_bulk(input: &[u8]) -> IResult<&[u8], Reply> { let (i1, command) = try_parse!( inp...
use clap::Parser; /// Creates a new user and login credentials on the authentication server #[derive(Parser)] pub struct CreateUser { /// Email address of the user to be created #[clap(index = 1)] pub email: Option<String>, /// New password to be associated with this account #[clap(index = 2)] ...
use super::*; use std::convert::TryInto; #[derive(Serialize, Deserialize)] pub(crate) struct RawFbas(pub(crate) Vec<RawNode>); #[derive(Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub(crate) struct RawNode { pub(crate) public_key: PublicKey, #[serde(default)] pub(crate) quorum_set: RawQuoru...
//! Utility for testing crates with [`wasm-mt`](https://crates.io/crates/wasm-mt). #![feature(async_closure)] use wasm_mt::WasmMt; // use wasm_mt::console_ln; use wasm_mt::utils::{ab_from_text, fetch_as_arraybuffer, fetch_as_text, run_js}; use wasm_bindgen::prelude::*; use js_sys::ArrayBuffer; mod transform; use tra...