text
stringlengths
8
4.13M
use {Error, Result, Statement}; use types::ToSql; impl<'conn> Statement<'conn> { /// Execute an INSERT and return the ROWID. /// /// # Failure /// Will return `Err` if no row is inserted or many rows are inserted. pub fn insert(&mut self, params: &[&ToSql]) -> Result<i64> { // Some non-inse...
use crate::util::{lines, time, vecs}; pub fn day11_2() { println!("== Day 11 - 2 =="); let input = "src/day11/input.txt"; time(part_a, input, "A"); time(part_b, input, "B"); } fn part_a(input: &str) -> usize { let monkehs = monkehs(input); // let worry_reducer: Box<dyn Fn(i128) -> i128> = Box:...
use std::collections::HashMap; impl Solution { pub fn check_subarray_sum(nums: Vec<i32>, k: i32) -> bool { let n = nums.len(); if n < 2 { return false; } let mut re = 0; let mut mp = HashMap::new(); mp.insert(0, -1 as i32); for i in 0..n{ ...
#[allow(non_camel_case_types,dead_code)] #[derive(Clone,Copy)] pub enum Layer { Background = 0, LayerA = 1, LayerB = 2, LayerC = 3, LayerD = 4, LogoA = 5, LogoB = 6, FrameMask = 7, } #[allow(non_camel_case_types,dead_code)] #[derive(Clone,Copy)] pub enum LayerType { Layer, Backg...
use std::sync::mpsc::channel; pub struct ThreadPool { _handles: Vec<std::thread::JoinHandle<()>>, } impl ThreadPool { pub fn new(num_threads: u8) -> Self { let (sender, receiver) = channel::<Box<dyn Fn()>>(); let _handles = (0..num_threads) .map(|_| { std::t...
use std::collections::HashMap; use amethyst::{ assets::{Completion, Handle, ProgressCounter}, core::timing::Time, ecs::prelude::*, input::{is_close_requested, is_key_down}, prelude::*, renderer::{HiddenPropagate, VirtualKeyCode}, ui::{UiEventType, UiLoader, UiPrefab}, }; use crate::{states...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 pub mod error; mod service; mod store; mod types; mod wallet; pub use service::*; pub use store::*; pub use types::*; pub use wallet::*; #[cfg(any(test, feature = "mock"))] pub mod mock;
use nom::{types::CompleteStr, *}; use crate::ir::{define::Define, FnSig}; #[derive(Clone, Debug, PartialEq)] pub enum Item<'a> { // `@__pre_init = unnamed_addr alias void (), void ()* @DefaultPreInit` Alias(&'a str, &'a str), // `; ModuleID = 'ipv4.e7riqz8u-cgu.0'` Comment, // `source_filename =...
// Copyright 2019 Amar Singh // This file is part of MoloChameleon, licensed with the MIT License #[cfg(test)] use super::*; use runtime_io::with_externalities; use srml_support::{ assert_noop, assert_ok, assert_err, assert_eq_uvec, traits::{Currency, LockableCurrency, ReservableCurrency} // remove unused imports......
use crate::banner; use crate::persistence::pathfinder::Pathfinder; use crate::persistence::pemstore::PemStore; use clap::ArgMatches; use crypto::identity::MixnetIdentityKeyPair; pub fn execute(matches: &ArgMatches) { println!("{}", banner()); println!("Initialising client..."); let id = matches.value_of("...
use criterion::{criterion_group, criterion_main, Criterion, SamplingMode}; use fnv::FnvHashMap; use rand::seq::SliceRandom; use rand::thread_rng; use std::collections::{BTreeMap, HashMap}; use std::fs::File; use std::io::{BufRead, BufReader}; use std::time::Duration; use yada::builder::DoubleArrayBuilder; use yada::Dou...
use crate::kernel_metadata::signal_name; use fmt::Formatter; use io::ErrorKind; use nix::sys::signal::Signal; use std::{convert::TryFrom, fmt, fmt::Display, io}; pub const SIGHUP: Sig = Sig(libc::SIGHUP); pub const SIGINT: Sig = Sig(libc::SIGINT); pub const SIGQUIT: Sig = Sig(libc::SIGQUIT); pub const SIGILL: Sig = Si...
use super::{hash::*, *}; use ckb_crypto::secp::Generator; use ckb_testtool::context::Context; use ckb_tool::ckb_types::{ bytes::Bytes, core::{TransactionBuilder, TransactionView}, packed::*, prelude::*, }; fn gen_tx_for_nft_transfer(context: &mut Context, lock_args: Bytes) -> TransactionView { //lo...
use guion::style::standard::cursor::StdCursor; use super::*; impl Default for Style { #[inline] fn default() -> Self { Self{ font: None, cursor: StdCursor::Arrow, } } }
// 解引用 // “解引用”(Deref)是“取引用”(Ref)的反操作。 // 取引用,有 &、&mut 等操作符,对应的,解引用,有 * 操作符,跟 C 语言是一样的。 use std::ops::Deref; use std::rc::Rc; pub fn first() { fn test1() { let v1 = 1; let p = &v1; // 取引用操作 let v2 = *p; // 解引用操作 println!("{} {}", v1, v2); } test1(); // 自定义解引用 // 解引用...
#[macro_use] extern crate serde_json; use common::{testkit::create_testkit, ALICE_NAME}; mod common; #[test] fn create_contract() { let (mut testkit, api) = create_testkit(); let code = "some code"; let (tx, contract_pub) = api.create_contract(code); testkit.create_block(); api.assert_tx_status(...
#[doc = "Reader of register OBCTL"] pub type R = crate::R<u32, super::OBCTL>; #[doc = "Reader of field `RERR`"] pub type RERR_R = crate::R<bool, bool>; #[doc = "Reader of field `SPC`"] pub type SPC_R = crate::R<bool, bool>; #[doc = "Reader of field `USER`"] pub type USER_R = crate::R<u8, u8>; #[doc = "Reader of field `...
use rustler::{Decoder, Error, NifResult, Term}; pub mod iso_639_1; pub mod iso_639_3; pub mod language; use self::iso_639_1::IsoCode639_1; use self::iso_639_3::IsoCode639_3; use self::language::Language; #[derive(Debug)] pub enum LanguageType { Language(Language), IsoCode639_1(IsoCode639_1), IsoCode639_3...
use derive_builder::Builder; use oauth2::{ basic::BasicClient, AuthUrl, ClientId, ClientSecret, CsrfToken, PkceCodeChallenge, PkceCodeVerifier, RedirectUrl, TokenUrl, }; use urlencoding::encode; #[derive(Debug, Clone)] pub struct OauthClient { pub client: BasicClient, } impl OauthClient { pub fn new<P...
#[doc = "Register `DMAMFBOCR` reader"] pub type R = crate::R<DMAMFBOCR_SPEC>; #[doc = "Register `DMAMFBOCR` writer"] pub type W = crate::W<DMAMFBOCR_SPEC>; #[doc = "Field `MFC` reader - Missed frames by the controller"] pub type MFC_R = crate::FieldReader<u16>; #[doc = "Field `MFC` writer - Missed frames by the control...
use crate::{green::GreenTree, node::TreeNode, root::RootOwnership, Discriminant}; use core::marker::PhantomData; #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum Control { Break, Continue, } pub fn folder<G, R, A>() -> impl CloneableFolder<G, R, Accum = A> where G: GreenTree, R: RootOwnersh...
use async_trait::async_trait; use tonic::transport::Server; use tonic::{Request, Response, Status}; use hello_tf::ImagePreds; use hello_tf::InferRequest; use hello_tf::InferResponse; use hello_tf::PostProcessRequest; use hello_tf::PostProcessResponse; use hello_tf::PreProcessRequest; use hello_tf::PreProcessResponse;...
use lazy_static::lazy_static; use regex::{Regex, RegexBuilder}; #[derive(PartialEq, Debug)] pub enum Token<'a> { If, Else, While, Assignation(&'a str), OpenCBrackets, CloseCBrackets, Expression(&'a str), Print, } fn is_assignation(text: &str) -> bool { lazy_static! { static ...
use crate::util::{eval_source, report_error}; #[cfg(feature = "plugin")] use log::info; use nu_protocol::engine::{EngineState, Stack, StateDelta, StateWorkingSet}; use nu_protocol::{PipelineData, Span}; use std::path::PathBuf; #[cfg(feature = "plugin")] const PLUGIN_FILE: &str = "plugin.nu"; #[cfg(feature = "plugin")...
use super::AppState; use actix_web::{get, web, HttpResponse, Responder}; pub fn init(cfg: &mut web::ServiceConfig) { cfg.service(get_all); } #[get("/data-category")] async fn get_all(app_state: web::Data<AppState<'_>>) -> impl Responder { println!("GET: /data-category"); let data_categories = app_state.d...
use approx; use euclid; use glam; use mint; use rand::{Rng, SeedableRng}; use rand_xoshiro::Xoshiro256Plus; pub trait RandomVec { type Value; fn random_vec(seed: u64, len: usize) -> Vec<Self::Value>; } macro_rules! impl_random_vec { ($t:ty) => { impl RandomVec for $t { type Value = Sel...
use exonum::{ crypto::{Hash, PublicKey}, storage::{Fork, ProofMapIndex, Snapshot}, }; use super::contract::Contract; #[derive(Debug)] pub struct Schema<T> { view: T, } impl<T> AsMut<T> for Schema<T> { fn as_mut(&mut self) -> &mut T { &mut self.view } } impl<T> Schema<T> where T: AsRe...
use auto_impl::auto_impl; #[auto_impl(&)] trait Trait { fn foo(&self) where Self: Clone; } #[derive(Clone)] struct Foo {} impl Trait for Foo { fn foo(&self) where Self: Clone, {} } fn assert_impl<T: Trait>() {} fn main() { assert_impl::<Foo>(); assert_impl::<&Foo>(); }
extern crate iron; #[macro_use] extern crate mime; use iron::prelude::*;
/* * 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 */ /// DowntimeRecurrence : An object defining the recurrence of the downtime. #[derive(Clone, Debug, Pa...
//! Helper for preparing SQL statements. use crate::*; pub use std::fmt::Write; #[derive(Debug, Default)] pub struct SqlWriter { pub(crate) counter: usize, pub(crate) string: String, } pub fn inject_parameters<I>(sql: &str, params: I, query_builder: &dyn QueryBuilder) -> String where I: IntoIterator<Item...
pub enum Level { Info, Warning, Error, Success, } pub struct Alert { pub content: String, pub level: Level, } impl Alert { pub fn new(content: String, level: Level) -> Alert { Alert { content, level } } }
use async_std::sync::Mutex; use rand::seq::SliceRandom; use std::collections::HashSet; use std::net::SocketAddr; use std::sync::Arc; /// Pointer to hosts class. pub type HostsPtr = Arc<Hosts>; /// Manages a store of network addresses. pub struct Hosts { addrs: Mutex<Vec<SocketAddr>>, } impl Hosts { /// Creat...
use std::fs::canonicalize; use error::{CommandError, CommandResult}; #[derive(Debug)] pub enum Source { Fs(String), Temp(String), Http(String), } impl Source { pub fn new(s: String) -> CommandResult<Self> { if s.starts_with("http://") || s.starts_with("https://") { Ok(Source::Http(...
use super::{Expression, visitor::ExpressionVisitor}; #[derive(Debug)] pub struct JsonObjectExpression { pub expressions: Vec<Box<dyn Expression>>, } impl JsonObjectExpression{ pub fn new() -> JsonObjectExpression { JsonObjectExpression{expressions: Vec::new() } } pub fn add_expr(&mut self, exp...
#[doc = "Register `RESP4R` reader"] pub type R = crate::R<RESP4R_SPEC>; #[doc = "Field `CARDSTATUSx` reader - Card status x See ."] pub type CARDSTATUSX_R = crate::FieldReader<u32>; impl R { #[doc = "Bits 0:31 - Card status x See ."] #[inline(always)] pub fn cardstatusx(&self) -> CARDSTATUSX_R { CAR...
pub fn hamming_distance(a: &str, b: &str) -> Result<usize, &'static str> { if a.len() != b.len() { return Err("inputs of different length"); } Ok(a.to_string() .chars() .zip(b.to_string().chars()) .fold(0, |mut diff, (x, y)| { if x != y { diff += 1; ...
extern crate i3themes; extern crate dirs; #[macro_use] extern crate clap; use clap::App; use std::process; use std::path::PathBuf; fn main() { let yml = load_yaml!("cli.yml"); let matches = App::from_yaml(yml).get_matches(); let xdg_location = home_subfile(".config/i3/config"); let i3h_location = h...
use super::*; type Subject = Intersection; mod new { use super::*; #[test] fn it_builds_an_intersection_with_a_rays_parameter_and_surface_normal() { let ray_t = 1.23; let origin = Point3::new(0.1, 0.2, 0.3); let normal = Vector3::new(1.0, 0.0, 0.0); let subject = Subject:...
#![feature(macro_rules)] use std::num::{Int, SignedInt}; use std::fmt::{Show, Formatter, Result}; #[deriving(Copy)] pub struct Checked<T : Int>(pub T); impl<T : Int> Checked<T> { pub fn new(v : T) -> Checked<T> { Checked(v) } } impl<T : Int> Deref<T> for Checked<T> { fn deref(&self) -> &T { ...
use bigneon_api::models::UserDisplayTicketType; use bigneon_db::models::TicketTypeStatus; use support::database::TestDatabase; #[test] fn from_ticket_type() { let database = TestDatabase::new(); let event = database.create_event().with_ticket_pricing().finish(); let ticket_type = event.ticket_types(&databa...
use ast; #[derive(Debug, PartialEq)] pub struct Token { pub val: TokVal, pub span: (usize, usize), } #[derive(Debug, PartialEq, Clone)] pub enum TokVal { Name(String), Num(f64), Op(OpKind), OpenDelim(DelimKind), CloseDelim(DelimKind), AbsDelim } #[derive(Debug, PartialEq, Clone)] pub ...
pub mod about; pub mod amalgamation; pub mod index; pub mod ip; pub mod new_post; pub mod post; pub mod time; pub mod time_root;
pub fn find_longest_common_prefix<T: Clone + Eq>(among: &[Vec<T>]) -> Option<Vec<T>> { if among.len() == 0 { return None; } else if among.len() == 1 { return Some(among[0].clone()); } for s in among { if s.len() == 0 { return None; } } let shortest_w...
use bevy::{ prelude::*, //default bevy input::{keyboard::KeyCode, Input}, }; use crate::{ AppState, SessionResource, }; pub const LIFE_FORM_SIZE: f32 = 150.0; #[derive(Default)] pub struct LifeTag; #[derive(Default)] pub struct LifeSystem {} pub fn create_life_xyz( n:&TetraIndex, x:usize, ...
use crate::read_lines; pub fn run() { let lines = read_lines::read_day(5); let mut ids : Vec<usize> = lines.map(|s| get_id(s.unwrap().as_str())).collect(); ids.sort(); let seat = find_empty_seat(ids).unwrap(); println!("your seat:{}", seat); } fn get_id(seat: &str) -> usize { //First get the row let mut lo...
// 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...
pub(crate) const STRUCTURE_NAME: &str = "__BOLT_STRUCTURE_SERDE_NAME__"; pub(crate) const STRUCTURE_SIG_KEY: &str = "__BOLT_STRUCTURE_SIGNATURE_KEY__"; pub(crate) const STRUCTURE_SIG_KEY_B: &[u8] = b"__BOLT_STRUCTURE_SIGNATURE_KEY__"; pub(crate) const STRUCTURE_FIELDS_KEY: &str = "__BOLT_STRUCTURE_FIELDS_KEY__"; pub(cr...
fn main() { let x:i32 = {let x:i32 = 5; x}; println!("{}", x); }
use ark_bls12_381::Bls12_381; use ark_poly_commit::kzg10::{Powers, VerifierKey}; use super::table::PreProcessedTable; use crate::{ kzg10, multiset::{EqualityProof, MultiSet}, transcript::TranscriptProtocol, }; pub struct LookUpProof { pub multiset_equality_proof: EqualityProof, } impl LookUpProof { ...
#![no_std] #![no_main] use panic_halt as _; use cortex_m::asm; use cortex_m_rt::{entry, exception}; // use cortex_m_semihosting::hprintln; use stm32f1::stm32f103; use stm32f1::stm32f103::Peripherals; static mut SYSTICK_QUEUED: bool = false; // -------------------------------------------------------------------------...
use std::net::SocketAddr; use socket2::{Socket, Domain, Protocol, Type}; use std::io::{Error}; use std::mem::MaybeUninit; use std::slice; fn hex_dump(size: usize, source: &[u8]) { for x in source.iter().take(size) { print!("{:02x} ", x); } println!(""); } fn ip_dump(ip_header: &[u8]) { let ip_...
use crate::prelude::*; pub fn pt1(input: Vec<Ip7>) -> Result<usize> { Ok(input .into_iter() .filter(|ip7| { let mut any_abba = false; for part in ip7 { if !part.has_abba() { continue; } match part.net_type {...
use wasmtime_jit::InstantiationError; use wasmtime_runtime::{Imports, Instance, VMContext, VMFunctionBody, VMMemoryDefinition}; #[allow(clippy::print_stdout)] unsafe extern "C" fn env_println(start: usize, len: usize, vmctx: *mut VMContext) { let definition = FuncContext::new(vmctx).definition(); let memory_de...
pub mod game; pub mod safety;
use quick_xml::Reader; use quick_xml::events::Event; use std::fs::{File, read_dir}; use std::io::*; use std::collections::{HashMap, HashSet}; use regex::Regex; use std::convert::TryInto; // XML parsing state enum ParserState { Idle, ReadingTitle, ReadingBody } pub enum ParserMode { Inc...
use crate::{LCh, Lab}; use approx::{AbsDiffEq, RelativeEq}; impl AbsDiffEq<Lab> for Lab { type Epsilon = f32; fn default_epsilon() -> Self::Epsilon { std::f32::EPSILON } fn abs_diff_eq(&self, other: &Lab, epsilon: Self::Epsilon) -> bool { AbsDiffEq::abs_diff_eq(&self.l, &other.l, epsi...
use iced::{text_input, Column, Element, Length, Row, Text, TextInput}; use serde_json::Value; use crate::jsonrpc::{ExportStatus, ImportStatus, JsonRpc, Method}; pub struct Statuses { statuses: Vec<Status>, } #[derive(Debug, Clone)] pub enum Message { SetName(usize, String), } impl Statuses { pub fn new...
#[macro_use] extern crate log; use azure_storage::core::prelude::*; use azure_storage::queue::prelude::*; use std::error::Error; use std::time::Duration; #[tokio::main] async fn main() -> Result<(), Box<dyn Error>> { // First we retrieve the account name and master key from environment variables. let account =...
// q0014_longest_common_prefix struct Solution; impl Solution { pub fn longest_common_prefix(strs: Vec<String>) -> String { if strs.len() == 0 { return "".to_string(); } else if strs.len() == 1 { return strs[0].to_string(); } let goal = &strs[0]; let...
// HMAC: Keyed-Hashing for Message Authentication // https://tools.ietf.org/html/rfc2104 use crate::hash::{Md2, Md4, Md5, Sha1, Sha224, Sha256, Sha384, Sha512, Sm3}; const IPAD: u8 = 0x36; const OPAD: u8 = 0x5C; macro_rules! impl_hmac_with_hasher { ($name:tt, $hasher:tt) => { #[derive(Clone)] pub ...
use crate::util; use super::{BackendError, BackendStatus, BackendItemStatus}; #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum Status { Initializing, Fetching, NoEntries, Error(Box<str>), Done, } impl Default for Status { fn default() -> Self { Status::Initializing } } impl From<&BackendStatus> for Sta...
fn read_line() -> String { let mut line = String::new(); std::io::stdin().read_line(&mut line).unwrap(); line.trim_end().to_owned() } fn main() { let _n: usize = read_line().parse().unwrap(); let aa = read_line() .split_whitespace() .map(|v| v.parse().unwrap()) .collect(); ...
use super::{chunk_header::*, chunk_type::*, *}; use crate::param::{param_header::*, *}; use crate::util::get_padding_size; use crate::param::param_supported_extensions::ParamSupportedExtensions; use bytes::{Buf, BufMut, Bytes, BytesMut}; use std::fmt; ///chunkInitCommon represents an SCTP Chunk body of type INIT and ...
use std::{error::Error as StdError, fmt::Display}; use duck_dns::{ClearOptions, ClearTxtOptions, Client}; use structopt::StructOpt; use crate::opts::Account; #[derive(StructOpt, Debug)] pub struct Clear { #[structopt(short = "x", long)] pub txt: bool, #[structopt(flatten)] pub account: Account, #...
//! Representation of LV2 plugins. use std::collections::BTreeSet; use crate::rdf_util::{Literal, Iri}; use enumset::EnumSetIter; use crate::bundle_model::constants::{ExtensionData, HostFeature, PluginType, Lv2Option}; use crate::bundle_model::unknowns::{UnknownHostFeature, UnknownExtensionData, UnknownOption, Unknown...
#[doc = "Reader of register INIT_NI_VAL"] pub type R = crate::R<u32, super::INIT_NI_VAL>; #[doc = "Writer for register INIT_NI_VAL"] pub type W = crate::W<u32, super::INIT_NI_VAL>; #[doc = "Register INIT_NI_VAL `reset()`'s with value 0"] impl crate::ResetValue for super::INIT_NI_VAL { type Type = u32; #[inline(...
use glutin; use gfx_window_glutin; use gfx_device_gl; use gfx; use gfx::Factory; use {Dimensions, Input, FileResources, PuckResult}; use super::{Renderer, ColorFormat, DepthFormat}; pub fn get_dimensions(window: &glutin::GlWindow) -> Dimensions { // make this optional at some point Dimensions { pixels: wi...
/* Copyright ⓒ 2016 rust-custom-derive 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, m...
#[derive(Debug, Clone)] #[repr(C)] pub struct ForwardJump { pub at: usize, pub to: usize, } use crate::constants_x64::Register; use crate::dseg::DSeg; use byteorder::{ByteOrder, LittleEndian, WriteBytesExt}; pub type Label = usize; trait Idx { fn index(&self) -> usize; } impl Idx for usize { fn index(...
struct Solution; impl Solution { pub fn longest_mountain(a: Vec<i32>) -> i32 { let mut ans = 0; let mut left = 0; let n = a.len(); while left + 2 < n { // [left, left+1, left+2],至少3个 let mut right = left + 1; // 如果是上升的趋势,用 right 找山顶 if...
mod basic; mod bootstrap; mod fee; mod proposal; mod size_limit; mod tx_select; mod uncle; pub use basic::*; pub use bootstrap::*; pub use fee::*; pub use proposal::*; pub use size_limit::*; pub use tx_select::*; pub use uncle::*;
use common::error::Error; use common::result::Result; use crate::domain::user::{Email, Password, Provider, Username}; #[derive(Debug, Clone)] pub struct Identity { provider: Provider, username: Username, email: Email, password: Option<Password>, } impl Identity { pub fn new( provider: Pro...
// Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // 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>,...
use alloc::{collections::BTreeMap, sync::Arc, vec::Vec}; use spinning_top::Spinlock; use crate::buffer::Buffer; const BUFFER_SIZE: usize = 10485760; struct BufferPoolItem { buffer: Arc<wgpu::Buffer>, allocated: usize, allocations: BTreeMap<usize, usize>, } impl BufferPoolItem { pub fn new(device: &...
use crate::auditwheel::PlatformTag; use crate::target::Arch; use once_cell::sync::Lazy; use serde::Deserialize; use std::cmp::{Ordering, PartialOrd}; use std::collections::{HashMap, HashSet}; use std::fmt; use std::fmt::{Display, Formatter}; /// The policies (allowed symbols) for the different manylinux tags, sorted f...
use cpal::{SampleRate, Stream}; use env_logger::Builder; use ringbuf::{Consumer, RingBuffer}; use stainless_ffmpeg::prelude::*; use std::{collections::HashMap, convert::TryInto, env}; const SAMPLE_RATE: SampleRate = SampleRate(48_000); fn main() { let mut builder = Builder::from_default_env(); builder.init(); ...
#[derive(Debug, Deserialize, Clone)] pub struct MongoSettings { db: String, table: String, uri: String } impl MongoSettings { pub fn get_db_name(&self) -> String { self.db.clone() } pub fn get_table_name(&self) -> String { self.table.clone() } pub fn get_uri(&self) -> String { self.uri.c...
use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; use std::sync::mpsc::{channel, Receiver, Sender}; use std::thread; use uuid::Uuid; #[derive(Debug)] struct ThreadInfo { id: Uuid, busy: AtomicBool, } pub struct PooledThread<F: FnOnce() + Send> { thread: Arc<ThreadInfo...
#![allow(clippy::type_complexity)] #![doc = include_str!("../README.md")] #![cfg_attr(docsrs, feature(doc_cfg))] pub use crate::{ codec::*, cursor::{Cursor, IntoIter, Iter, IterDup}, database::{ Database, DatabaseBuilder, DatabaseKind, Geometry, Info, NoWriteMap, PageSize, Stat, WriteMap, ...
use parity_wasm::elements::Instruction; use std::error; use std::fmt; #[derive(Debug)] pub enum InstructionError { GlobalNotFound, LocalNotFound, UnmatchedInstruction, InvalidOperation(Instruction), } impl fmt::Display for InstructionError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { ...
use bevy::{input::touch::*, prelude::*}; fn main() { App::build() .add_plugins(DefaultPlugins) .add_system(touch_event_system.system()) .run(); } fn touch_event_system(mut touch_events: EventReader<TouchInput>) { for event in touch_events.iter() { match event.phase { ...
extern crate rand; #[macro_use] extern crate serde_derive; extern crate serde_json; #[macro_use] extern crate nom; mod types; pub use types::{Set,Partition,Filter,Run}; mod partition; pub use partition::SumFilteredPartitionIterator; mod distribution; pub use distribution::Distribution; mod filters; pub use filters::{Su...
// This file is part of Substrate. // Copyright (C) 2019-2020 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // 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 // // ht...
use aes::{ cipher::{consts::U16, KeyInit}, cipher::{generic_array::GenericArray, BlockDecrypt, BlockEncrypt}, Aes128, }; use std::collections::HashSet; use crate::pad; use crate::xor::xor_bytes; pub const KEY_SIZE: usize = 16; type Key = GenericArray<u8, U16>; pub type Block = GenericArray<u8, U16>; #[d...
use std::io::test::next_test_unix; use std::io::fs::PathExtensions; use std::time::Duration; use green::task::spawn; use rustuv::{Pipe, PipeListener}; use rustuv::uvll; pub fn smalltest(server: proc(Pipe):Send, client: proc(Pipe):Send) { let path1 = next_test_unix(); let path2 = path1.clone(); let accept...
use frame_support::weights::Weight; use frame_support::{construct_runtime, parameter_types}; use sp_runtime::testing::{Header, H256}; use sp_runtime::traits::{BlakeTwo256, IdentityLookup}; use sp_runtime::Perbill; type AccountId = u64; pub(crate) type ChainId = u64; type Block = frame_system::mocking::MockBlock<TestRu...
use crate::util::Part; use std::collections::HashMap; pub fn solve(input:String, part:Part) -> String { let mut planets:HashMap<String, Vec<String> > = HashMap::new(); // Build up system for pair in input.lines().map(|l| l.trim().to_string()) { let pars:Vec<String> = pair.split(')').map(|p| p.to_...
// Copyright 2020 The VectorDB Authors. // // Code is licensed under Apache License, Version 2.0. pub mod binary_expression; pub mod expression; pub mod scalar_expression; pub use self::binary_expression::BinaryExpressionPlanner; pub use self::scalar_expression::ScalarExpressionPlanner;
extern crate "pkg-config" as pkg_config; fn main() { pkg_config::find_library_opts("uuid", &pkg_config::Options{statik: false, atleast_version: None}).unwrap() }
pub use http_verbs::HttpVerbs; pub use request::Request; pub mod request; pub mod http_verbs;
/// Computes absolute value of a number pub fn abs(number: i32) -> i32 { if number < 0 { number * -1 } else { number } } /// Computes the GCD of 2 numbers using well-known Euclidean Algorithm. /// See: https://en.wikipedia.org/wiki/Euclidean_algorithm pub fn gcd(a: i32, b: i32) -> i32 { ...
//! Google OAuth2 API use crate::env::Env; use serde::{Deserialize, Serialize}; use crate::{Result, unwrap_req_err, unwrap_db_err, unwrap_google_err}; use crate::api::GoogleResponse; /// Login Data pub struct LoginData { /// Refresh token pub refresh_token: Option<String>, /// Access token...
extern crate peroxide; use peroxide::*; fn main() { let a = rand(2, 2); a.print(); }
// 多元赋值 fn main() { let (a, b) = (1, 2); assert_eq!(a, 1); assert_eq!(b, 2); // 解构元祖 let t = (5, "hello".to_string()); let (a, b) = t; assert_eq!(a, 5); assert_eq!(b, "hello".to_string()); }
// MIT License // // Copyright (c) 2021 Miguel Peláez // // 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, modif...
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // // Portions Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the THIRD-PARTY file. #![allow(unused)] #![d...
use self::sort::check_apply_top_n_sort; use crate::{ error::VelociError, highlight_field::*, persistence::{self, Persistence, *}, plan_creator::execution_plan::*, search::{self, result::*, *}, util::{self, StringAdd}, }; use fnv::FnvHashMap; use fst::{automaton::*, raw::Fst, IntoStreamer}; use i...
use super::hsl::{percentage, to_rational2, to_rational_percent}; use super::rgb::values_from_list; use super::{Error, SassFunction}; use crate::css::Value; use crate::value::{Rgba, Unit}; use num_rational::Rational; use num_traits::One; use std::collections::BTreeMap; pub fn register(f: &mut BTreeMap<&'static str, Sas...
use std::io; use thiserror::Error; #[derive(Debug, Error)] pub enum SpdxError { #[error("Error with serde_yaml.")] SerdeYaml { #[from] source: serde_yaml::Error, }, #[error("Error with serde_yaml.")] SerdeJson { #[from] source: serde_json::Error, }, #[error...