text
stringlengths
8
4.13M
// =============================================================================== // Authors: AFRL/RQQA // Organization: Air Force Research Laboratory, Aerospace Systems Directorate, Power and Control Division // // Copyright (c) 2017 Government of the United State of America, as represented by // the Secretary of th...
#![allow(missing_docs)] //! Factory methods for testing use crate::{ BooleanExpression, ComparisonFunction, DatabaseName, Expression, LogicalFunction, NnSqlValue, SqlValue, UnaryOperator, }; use rand::Rng; impl DatabaseName { /// randomly generate a database name pub fn random() -> Self { Sel...
type Block = u32; const BITS_PER_BLOCK : usize = 32; pub struct BitVec { blocks : Vec<Block>, size : usize } struct Index { block : usize, bit : usize } impl BitVec { pub fn new(n : usize) -> BitVec { let nblocks = divceil(n, BITS_PER_BLOCK); let blocks = vec![0 as Block; nblocks]; ...
use crate::*; use rodio::{decoder::Decoder, source::Source, Sink}; use std::{io::Cursor, sync::Arc, time::Duration}; const QUICK_FADE_DURATION_SECONDS: f32 = 0.2; /// Handles playback of a [`Clip`] with support for pausing, resuming, volume adjustment. /// /// Instances can be built using a [`ClipPlayerBuilder`]. //...
fn main() { println!( "{:?}", fixed_xor( &hex::decode("1c0111001f010100061a024b53535009181c").unwrap(), &hex::decode("686974207468652062756c6c277320657965").unwrap() ) ); } fn fixed_xor(one: &[u8], two: &[u8]) -> Vec<u8> { one.iter().zip(two).map(|(a, b)| (a ...
//! Route Component. use super::YewRouterState; use crate::matcher::Matcher; use crate::router_component::render::Render; use crate::router_component::router::Router; use std::fmt::{Debug, Error as FmtError, Formatter}; use yew::{Children, Component, ComponentLink, Properties, ShouldRender}; /// A nested component use...
#![feature(proc_macro)] #![crate_type = "proc-macro"] extern crate proc_macro; #[macro_use] extern crate syn; #[macro_use] extern crate quote; use proc_macro::TokenStream; use syn::{Ident, Type, Expr, WhereClause, TypeSlice, Path}; use syn::synom::Synom; struct MiscSyntax { id: Ident, ty: Type, expr: Expr, ...
// Copyright (c) 2016, <daggerbot@gmail.com> // This software is available under the terms of the zlib license. // See COPYING.md for more information. use winapi; use error::Result; use pixel_format::PixelFormat; use util::GetProvider; use window::Window; /// Windows-specific extensions for `PixelFormat`...
use core::{convert::TryFrom, num::NonZeroU32}; use hashbrown::HashMap; use necsim_core::cogs::Habitat; use crate::{ cogs::habitat::{non_spatial::NonSpatialHabitat, spatially_implicit::SpatiallyImplicitHabitat}, decomposition::Decomposition, }; use super::EqualDecomposition; #[test] fn test_equal_area_decom...
use metrics::config::*; use chrono::{Date, DateTime, Datelike, TimeZone, Utc, Weekday}; use clap::{App, Arg}; use env_logger; use lazy_static::lazy_static; use metrics::asana::*; use regex::Regex; use std::collections::{HashMap, HashSet}; use std::fmt::Write as FmtWrite; use std::fs; use std::fs::File; use std::io::Wr...
use num::traits::{Num, NumCast}; use super::cm::{CM, ToCM}; use super::mm::{MM, ToMM}; use super::m::{M, ToM}; /// ToKM is the canonical trait to use for taking input in kilometers. /// /// For example the millimeters type (MM) implements the ToKM trait and thus /// millimeters can be given as a parameter to any inpu...
use crate::egml::{AnyModel, Real, RealValue, Converter, Fill, Stroke, Transform}; #[derive(Default, Clone)] pub struct Text { pub id: Option<String>, pub x: RealValue, pub y: RealValue, pub font_name: String, pub font_size: RealValue, pub align: (AlignHor, AlignVer), pub stroke: Option<Stro...
#[doc = "Register `MPCBB1_VCTR24` reader"] pub type R = crate::R<MPCBB1_VCTR24_SPEC>; #[doc = "Register `MPCBB1_VCTR24` writer"] pub type W = crate::W<MPCBB1_VCTR24_SPEC>; #[doc = "Field `B768` reader - B768"] pub type B768_R = crate::BitReader; #[doc = "Field `B768` writer - B768"] pub type B768_W<'a, REG, const O: u8...
/// An enum to represent all characters in the NKo block. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum NKo { /// \u{7c0}: '߀' NkoDigitZero, /// \u{7c1}: '߁' NkoDigitOne, /// \u{7c2}: '߂' NkoDigitTwo, /// \u{7c3}: '߃' NkoDigitThree, /// \u{7c4}: '߄' NkoDigitFour, ...
use actix_web::client::SendRequestError; use actix_web::{error, HttpResponse, ResponseError}; use awc; use core::num::ParseIntError; use mysql::Error as MySqlError; use std::fmt; //use std::option::NoneError; type Field = String; #[derive(Debug)] /// An custom error type, that handles convertion to HTTP error code...
use grammers_client::types::Message; use grammers_client::{ClientHandle, InputMessage}; use grammers_mtproto::mtp::RpcError; use grammers_mtsender::InvocationError; use grammers_tl_types as tl; pub async fn resend_message( old_message_id: i32, message: InputMessage, client_handler: &mut ClientHandle, p...
/* Copyright (c) 2023 Uber Technologies, Inc. <p>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 <p>http://www.apache.org/licenses/LICENSE-2.0 <p>Unless required by applicable law or agreed to ...
#[derive(Debug)] struct NestedIterator { int_mode: bool, int: Option<i32>, its: Vec<NestedIterator>, } impl NestedIterator { fn new_from_int(i: i32) -> Self { Self { int_mode: true, int: Some(i), its: vec![], } } fn new(nestedList: Vec<Nested...
use std::sync::Arc; use crate::{ binary::{Encoder, ReadEx}, errors::Result, types::{ column::{ column_data::{ArcColumnData, BoxColumnData}, ArcColumnWrapper, ColumnData, }, SqlType, Value, ValueRef, }, }; use chrono_tz::Tz; use either::Either; pub(crate...
// 通知rust我们要使用外部依赖,这也会调用相应的use rand,所以现在可以使用rand::前缀来调用rand crate中的任何内容 extern crate rand; // 输入输出库,获取用户输入 // io库来自于标准库(也被称为std) use std::io; use std::cmp::Ordering; use rand::Rng; fn main() { println!("Guess the number!"); // 获取1-101之间的随机数 let secret_number = rand::thread_rng().gen_range(1,101); printl...
use crate::rtb_type; rtb_type! { StartDelayMode, 0, PreRoll=0; GenericMidRoll=-1; GenericPostRoll=-3 }
use crate::encryption::{ MixnetEncryptionKeyPair, MixnetEncryptionPrivateKey, MixnetEncryptionPublicKey, }; use crate::PemStorable; use curve25519_dalek::montgomery::MontgomeryPoint; use curve25519_dalek::scalar::Scalar; // TODO: ensure this is a proper name for this considering we are not implementing entire DH h...
use beanstalkd::Beanstalkd; pub fn pop(beanstalkd: &mut Beanstalkd) { let (id, message) = beanstalkd.reserve().unwrap(); println!("{}", message); let _ = beanstalkd.delete(id); }
#[global_allocator] static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc; mod ast; mod evaluator; mod lexer; mod object; mod parser; mod repl; mod token; use crate::lexer::*; use crate::object::*; use crate::parser::*; use std::cell::*; use std::rc::*; fn main() { let input = " let fibonacci = fn(x) { if (x ==...
//! QuotientFilter implementation. use std::collections::hash_map::DefaultHasher; use std::collections::VecDeque; use std::hash::{BuildHasher, BuildHasherDefault, Hash, Hasher}; use std::marker::PhantomData; use fixedbitset::FixedBitSet; use succinct::{IntVec, IntVecMut, IntVector}; use crate::filters::Filter; use cr...
use hacspec_hkdf::*; use hacspec_lib::prelude::*; struct HKDFTestVectors<'a> { ikm: &'a str, salt: &'a str, info: &'a str, l: usize, prk: &'a str, okm: &'a str, } // https://tools.ietf.org/html/rfc5869 const HKDF_KAT: [HKDFTestVectors; 3] = [ HKDFTestVectors { ikm: "0b0b0b0b0b0b0b0...
use pyo3::prelude::*; use rand::distributions::Distribution; use std::convert::TryInto; use ocl::ProQue; use failure::Fallible; /// Simulation parameters /// /// The idea is these are things that would stay the same across invocations /// /// Simulation has two natures. It lives in the Python world and has an impl a...
mod gc_count; mod to_string; mod escaping;
use std::collections::HashMap; use std::io::{BufRead, BufReader}; #[cfg(unix)] use std::os::unix::process::CommandExt; use std::process::{Child, ChildStdout, Command}; use std::sync::{Arc, RwLock}; use anyhow::{bail, Context, Result}; use async_process::Stdio; use serde::{Deserialize, Serialize}; use tempfile::TempDir...
use const_format::{concatcp, formatcp}; use serde::{ de::{self, Unexpected}, Deserialize, Deserializer, }; use serenity::builder::CreateEmbed; use crate::smmo::world_boss::WorldBoss; pub(crate) mod smmo_player; pub(crate) mod world_boss; fn bool_from_int<'de, D>(deserializer: D) -> Result<bool, D::Error> whe...
//! Contains the implementation of the Mac OS X tray icon in the top bar. use std; use cocoa::appkit::{NSApp, NSApplication, NSButton, NSImage, NSStatusBar, NSStatusItem, NSSquareStatusItemLength}; use cocoa::base::{id, nil}; use cocoa::foundation::{NSData, NSSize, NSAutoreleasePool}; use Systray...
mod auth; use tonic::{Request, Response, Status, transport::{Server, server::{RouterService, Unimplemented}}}; use hello_world::greeter_server::{Greeter, GreeterServer}; use hello_world::{HelloReply, HelloRequest}; mod hello_world { tonic::include_proto!("helloworld"); } type Service = RouterService<GreeterServ...
/* chapter 4 syntax and semantics */ use std::cell::RefCell; fn main() { let a = RefCell::new(42); println!("{:?}", a); let b = a.borrow_mut(); // will panic /* let c = a.borrow_mut(); */ println!("{:?}", b); } // output should be: /* */
/// An enum to represent all characters in the Runic block. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum Runic { /// \u{16a0}: 'ᚠ' LetterFehuFeohFeF, /// \u{16a1}: 'ᚡ' LetterV, /// \u{16a2}: 'ᚢ' LetterUruzUrU, /// \u{16a3}: 'ᚣ' LetterYr, /// \u{16a4}: 'ᚤ' LetterY,...
/// An enum to represent all characters in the OldTurkic block. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum OldTurkic { /// \u{10c00}: '𐰀' LetterOrkhonA, /// \u{10c01}: '𐰁' LetterYeniseiA, /// \u{10c02}: '𐰂' LetterYeniseiAe, /// \u{10c03}: '𐰃' LetterOrkhonI, /// ...
fn get_digits(n : i32) -> Vec<u8> { let mut digits : Vec<u8> = vec![0; 6]; digits[0] = ( n / 100000) as u8; digits[1] = ((n / 10000) % 10) as u8; digits[2] = ((n / 1000) % 10) as u8; digits[3] = ((n / 100) % 10) as u8; digits[4] = ((n / 10) % 10) as u8; digits[5] = ( n %...
use core::ops::Deref; use diesel; use diesel::prelude::*; use rand; use ring::{digest, pbkdf2}; use db::ConnectionSource; use db::users; use errors::*; #[derive(Debug, Insertable, Queryable)] #[table_name="users"] pub struct User { pub name: String, pub password_salt: Vec<u8>, pub password_hash: Vec<u8>, pub admi...
use sdl2::keyboard::Keycode; pub struct Keys { key: [bool; 16], } impl Keys { pub fn new() -> Keys { Keys { key: [false; 16] } } pub fn is_down(& self, id: usize) -> bool { self.key[id] } pub fn set_keys(&mut self, option_code: Option<Keycode>, state: bool) { ...
use wallet::Wallet; pub fn run(wallet_path: Path, args: &[String]) { assert!(args.is_empty()); let wallet = Wallet::new(&wallet_path); match wallet.save() { Ok(_) => println!("New wallet saved to {}.", wallet_path.display()), Err(e) => println!("Error saving wallet: {}", e) }; }
use winapi::shared::winerror::ERROR_SUCCESS; use winapi::um::accctrl::*; use winapi::um::aclapi::*; use winapi::um::minwinbase::{LPTR, PSECURITY_ATTRIBUTES, SECURITY_ATTRIBUTES}; use winapi::um::securitybaseapi::*; use winapi::um::winbase::{LocalAlloc, LocalFree}; use winapi::um::winnt::*; use std::io; use std::marker...
use super::*; use std::io; use std::sync::mpsc::channel; use std::sync::mpsc::Receiver; use std::sync::mpsc::Sender; struct FakeReader { receiver: Receiver<String>, } impl FakeReader { fn new() -> (Sender<String>, FakeReader) { let (sender, receiver) = channel(); return (sender, FakeReader { r...
use std::{ convert::TryFrom, fs::File, io::{BufReader, Seek}, pin::Pin, sync::Arc, task::{Context, Poll}, time::SystemTime, }; use rustls::{ client::{ClientConfig, ServerCertVerified, ServerCertVerifier, ServerName}, Certificate, Error as TlsError, OwnedTrustAnchor, Root...
macro_rules! _nums { () => { include_str!("input.txt") .lines() .map(|line| { line.trim() .parse() .expect(&format!("unparsable number {}!", line.trim())) }) .collect() }; } // This hack appears to be the only way to properly export our macro at the proper scope. pub(crate) use _nums as n...
use rhombus_core::hex::coordinates::{ axial::AxialVector, cubic::CubicVector, direction::{HexagonalDirection, NUM_DIRECTIONS}, }; #[derive(Clone, Copy, Debug)] pub struct Range { start: isize, end: isize, } impl Range { pub fn start(&self) -> isize { self.start } pub fn end(&s...
#![no_std] #![no_main] #![feature(abi_x86_interrupt)] #![feature(custom_test_frameworks)] #![test_runner(xagima::testing::runner)] #![reexport_test_harness_main = "test_main"] #![feature(default_alloc_error_handler)] extern crate alloc; use alloc::boxed::Box; use bootloader::BootInfo; use core::panic::PanicInfo; #[...
use Score; use DocId; use docset::{DocSet, SkipResult}; use postings::SegmentPostings; use query::Scorer; use postings::Postings; use fastfield::FastFieldReader; pub struct TermScorer { pub idf: Score, pub fieldnorm_reader_opt: Option<FastFieldReader<u64>>, pub postings: SegmentPostings, } impl TermScorer...
use crate::directories::*; use crate::EditorConfig; use crate::ScrollConfig; use rider_lexers::Language; use rider_themes::Theme; use std::collections::HashMap; use std::fs; pub type LanguageMapping = HashMap<String, Language>; #[derive(Debug, Clone)] pub struct Config { width: u32, height: u32, menu_heig...
/// An enum to represent all characters in the Nushu block. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum Nushu { /// \u{1b170}: '𛅰' CharacterDash1b170, /// \u{1b171}: '𛅱' CharacterDash1b171, /// \u{1b172}: '𛅲' CharacterDash1b172, /// \u{1b173}: '𛅳' CharacterDash1b173,...
use std::collections::HashMap; use super::utils::http_get; use crate::{error::Result, Market, MarketType}; use serde::{Deserialize, Serialize}; use serde_json::Value; pub(crate) fn fetch_symbols(market_type: MarketType) -> Result<Vec<String>> { let instruments = fetch_instruments(market_type)?; Ok(instrument...
//! This module implements the algorithm for constructing a tree-child sequence for a set of trees. //! The function to construct a tree-child sequence is `tree_child_sequence()`. mod channel; mod master; mod search; mod worker; use self::master::Master; use self::search::Search; use tree::Tree; use std::fmt; /// An...
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::f32; use crate::{edge::Edge, point::Point}; const TOLERANCE: f32 = 3.0; const PIXEL_ACCURACY: f32 = 0.25; #[derive(Clone, Debug, Default)] pub ...
fn nth_word(s: &String, nth: u32) -> &str { let bytes = s.as_bytes(); let mut number_of_spaces_to_find = nth - 1; let mut init = 0; for (i, &item) in bytes.iter().enumerate() { if item == b' ' { if number_of_spaces_to_find == 0 { return &s[init..i]; } el...
fn main() { let mut v = vec![10,20,30]; for i in &mut v { *i += 3; } for i in &v { println!("{}", i); } }
use serde::{Deserialize, Serialize}; #[derive(PartialEq, Eq, Clone, Serialize, Deserialize, Debug, Hash, Copy)] pub enum MsgType { Prepare, Commit, Abort, AckP2, End, Ended, Err, } #[derive(PartialEq, Eq, Clone, Serialize, Deserialize, Debug)] pub struct CoordMsg { pub xid: u16, pu...
use anyhop::{Atom, Goal, Method, MethodResult, Task}; use anyhop::MethodResult::{TaskLists}; use anyhop::Task::Operator; use MethodResult::*; use Task::*; use log::{debug, error, info, trace, warn}; use SatelliteMethod::*; use crate::methods::SatelliteMethod::{ScheduleAll, ScheduleOne}; use crate::operators::Satelli...
mod widgets; use crossbeam_channel as channel; use druid::{ commands::{OPEN_FILE, SHOW_OPEN_PANEL}, kurbo::Point, theme, widget::{prelude::*, Flex, Label, Svg}, AppDelegate, AppLauncher, ArcStr, Command, Data, DelegateCtx, Env, FileDialogOptions, FileSpec, Handled, ImageBuf, Lens, Selector, Sin...
use core::ptr::NonNull; use fermium::{SDL_Palette, SDL_PixelFormat}; use crate::{sdl_get_error, Palette, PixelFormatEnum, SdlError}; /// Information about a pixel format. /// /// Internally these are ref counted and usually handed out from a pool that SDL /// manages. As a result, they're generally read-only. The on...
use raycast::Window; use raycast::World; use sdl2::event::Event; use sdl2::keyboard::Keycode; use std::error::Error; use std::time::Duration; const VIEW_FOV_DEGREES: f64 = 60.0; const VIEW_FOV: f64 = VIEW_FOV_DEGREES * std::f64::consts::PI / 180.0; const WORLD_WIDTH: usize = 30; const WORLD_HEIGHT: usize = 30; con...
pub mod app_state; pub mod errors; pub mod handlers; pub mod extractors; pub mod fields; pub mod cursor; use crate::{ websocket::client_subscriber::ClientSubscriber, }; use actix_web::{web, HttpResponse, Error, HttpRequest}; use actix_web_actors::ws; use crate::api::extractors::config::{default_json_config, defaul...
// Copyright 2017, 2020 Parity Technologies // // 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...
use crate::datetime::{get_weekday_val, get_year_len, to_ordinal}; use crate::iter::masks::MASKS; use crate::options::*; use crate::utils::pymod; use chrono::prelude::*; #[derive(Debug)] pub struct YearInfo { pub yearlen: usize, pub nextyearlen: usize, pub yearordinal: isize, pub yearweekday: usize, ...
// Copyright 2021 Protocol Labs. // // 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...
use amethyst::{ core::math, assets::{AssetStorage, Handle, Loader}, core::{Named, Parent, Transform, TransformBundle, math::Vector3}, derive::SystemDesc, ecs::{ Component, Entity, Join, NullStorage, Read, Write, WriteExpect, ReadStorage, System, SystemData, WorldExt, WriteStorage, ...
use std::pin::Pin; use futures::Future; pub type BoxFut<S> = Pin<Box<dyn Future<Output = S> + 'static>>; pub(crate) mod with_db_methods; pub(crate) mod with_tx_methods; pub(crate) mod without_db_methods;
use proc_macro2::TokenStream; use quote::quote; pub(crate) trait Errors { fn result(&self) -> Result<(), TokenStream>; } impl Errors for Vec<TokenStream> { fn result(&self) -> Result<(), TokenStream> { if self.is_empty() { Ok(()) } else { let v = self; Err(q...
mod utils; use wasm_bindgen::prelude::*; use yew::prelude::*; // When the `wee_alloc` feature is enabled, use `wee_alloc` as the global // allocator. #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; #[wasm_bindgen] extern { fn alert(s: &str); } #[w...
#[doc = "Register `MACFCR` reader"] pub type R = crate::R<MACFCR_SPEC>; #[doc = "Register `MACFCR` writer"] pub type W = crate::W<MACFCR_SPEC>; #[doc = "Field `FCB_BPA` reader - Flow control busy/back pressure activate"] pub type FCB_BPA_R = crate::BitReader; #[doc = "Field `FCB_BPA` writer - Flow control busy/back pre...
extern crate clap; extern crate env_logger; #[macro_use] extern crate log; extern crate term_painter; extern crate dirac; use clap::{Arg, App}; use term_painter::ToStyle; use term_painter::Color::*; use term_painter::Attr::*; use std::collections::HashMap; use dirac::checks::CheckSuite; use dirac::engine::CheckSuite...
use game_state::*; use enemy::*; use player::*; use parsing::strings::*; use rand::{thread_rng, Rng}; use std::process; use combat_action::*; pub struct BattleCoordinator { pub player: Player, pub enemy: Option<Enemy>, } impl BattleCoordinator { fn get_gameover_state(player: Player) -> State { Sta...
//! Structured ROTMG packets. #[macro_use] mod macros; pub mod data; pub mod packets;
use super::PageSize; use std::fmt::Debug; use std::cmp::{PartialEq, Eq, Ord, PartialOrd, Ordering}; use alloc::raw_vec::RawVec; use alloc::boxed::Box; use std::mem; use std::fmt; use constants::*; /// Uniform linear address transformation #[derive(Clone)] pub struct Segment { physical_base: u64, virtual_ba...
#[doc = "Register `PLLSAI2CFGR` reader"] pub type R = crate::R<PLLSAI2CFGR_SPEC>; #[doc = "Register `PLLSAI2CFGR` writer"] pub type W = crate::W<PLLSAI2CFGR_SPEC>; #[doc = "Field `PLLSAI2N` reader - SAI2PLL multiplication factor for VCO"] pub type PLLSAI2N_R = crate::FieldReader; #[doc = "Field `PLLSAI2N` writer - SAI2...
pub mod code_generator; pub mod verifier;
mod read; mod write; mod open; mod close; mod mmap; mod mprotect; mod brk; mod ioctl; mod writev; mod mincore; mod getcwd; mod poll; mod arch_prctl; mod exit_group; use super::interrupts::InteruptStack; static mut POS: usize = 0; pub fn handle(vars: &mut InteruptStack) { let syscall_number = vars.rax; // ht...
use super::{schema::schedules, Connection, Postgres}; use artell_domain::{ art::ArtId, scheduler::{Schedule, Scheduler, SchedulerRepository}, }; use chrono::{DateTime, Utc}; use diesel::prelude::*; use uuid::Uuid; pub struct PgSchedulerRepository { pg: Postgres, } impl PgSchedulerRepository { pub fn n...
use indexmap::IndexMap; use serde::{Deserialize, Serialize}; use siro::prelude::*; use siro::{ effects::{DomFocus, Effects}, html::{ self, attr, event::{on_blur, on_click, on_double_click, on_enter, on_input}, }, vdom::class, }; use std::str::FromStr; // ==== model ==== #[derive(Debug,...
use serde::{Deserialize, Serialize}; use crate::column::{column_definition::ColumnDefinition, column_name::ColumnName}; /// Actions to be done by ALTER TABLE statement. #[derive(Clone, Eq, PartialEq, Hash, Debug, Serialize, Deserialize)] pub enum AlterTableAction { /// ALTER TABLE {table_name} ADD COLUMN {column_...
#[derive(Debug)] pub struct Array2<T> { inner: Vec<T>, shape: (usize, usize), }
// Copyright 2017 Google Inc. All rights reserved. // // 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...
use crate::query::search::Search; use group_by::GroupBy; use scan::Scan; use segment_metadata::SegmentMetadata; use serde::{Deserialize, Serialize}; use time_boundary::TimeBoundary; use timeseries::Timeseries; use top_n::TopN; pub mod definitions; pub mod group_by; pub mod response; pub mod scan; pub mod search; pub m...
pub struct TryReader<'l, T> { elements: &'l Vec<T>, needle: usize, } impl<'l, T> TryReader<'l, T> { pub fn new(elements: &'l Vec<T>) -> TryReader<'l, T> { TryReader { elements, needle: 0, } } pub fn next(&mut self) -> Option<&'l T> { if self.has_next...
use super::super::super::super::{awesome, btn, modal}; use super::state::Modal; use super::Msg; use crate::{ block::{self, BlockId}, resource::Data, Resource, }; use kagura::prelude::*; mod common { pub use super::super::common::*; } pub fn render<'a>(block_field: &block::Field, resource: &Resource, w...
/* chapter 4 syntax and semantics */ fn main() { let a: i32 = 3; // implicit fn foo(n: &i32) -> &i32 { n } // explicit fn bar<'a>(n: &'a i32) -> &i32 { n } let c = foo(&a); println!("{}", c); let d = bar(&b); println!("{}", d); } // output should be: /* 3 7 */
//! Utilities for serializing graphs to render using Sigma.js use num::bigint::BigUint; use num::{One, Zero}; use rand::random; use serde_json::map::Map; use serde_json::Value; use crate::hypergraph::DirectedGraph; pub fn to_sigma_json(graph: DirectedGraph) -> Value { // The top-level JSON object. // Should ...
#![allow(unused)] mod dna; mod execute; use std::io::prelude::*; use structopt::StructOpt; use std::path::PathBuf; use std::fs::File; use dna::DNA; use crossbeam_channel::unbounded; // Struct for command line parsing #[derive(StructOpt, Debug)] #[structopt()] struct MyOpt { #[structopt(name = "DNA", default_v...
pub mod first; pub mod second; use first::List; fn main() { let mut l = List::new(); l.push(0); l.push(1); l.push(2); println!("{:?}", l.pop()); println!("{:?}", l.pop()); println!("{:?}", l.pop()); }
#![feature(int_bits_const)] #[warn(unused_variables)] #[warn(non_camel_case_types)] mod loader; mod header; mod programheader; mod sectionheader; fn main() { } #[cfg(test)] mod tests { use super::*; #[test] fn testParserReadData() { let mut parser = loader::Loader::new("/home/kai/Projects/el...
extern crate sdl2; use super::font_renderer; use sdl2::render; use sdl2::ttf; use sdl2::video; pub struct Renderer { ttf_context: ttf::Sdl2TtfContext, texture_creator: render::TextureCreator<video::WindowContext>, } impl Renderer { pub fn from( ttf_context: ttf::Sdl2TtfContext, texture_creator: render::Textur...
use super::{Open, Sink}; use std::io; use libpulse_sys::*; use std::ptr::{null, null_mut}; use std::mem::{transmute}; use std::ffi::CString; pub struct PulseAudioSink(*mut pa_simple); impl Open for PulseAudioSink { fn open() -> PulseAudioSink { info!("Using PulseAudioSink"); let ss = pa_sample_spe...
use core::position::{Size, HasSize, Pos, HasPosition}; use core::cellbuffer::{Cell, CellAccessor}; use ui::core::{ Alignable, HorizontalAlign, VerticalAlign, Widget, Frame, Painter }; /// Logical clone of [Frame](core/frame/struct.Frame.html) that exposes backend /// functionality for users wi...
/// CPU registers, including registers specific to the ALU /// /// The registers on the NES CPU are just like on the 6502. There is the accumulator, 2 indexes, a /// program counter, the stack pointer, and the status register. Unlike many CPU families, members /// do not have generic groups of registers like say, R0 th...
#[macro_use] extern crate lazy_static; extern crate regex; use std::fs; use std::io::{self, BufRead}; use std::path::Path; use std::cmp::max; use std::cmp::Ordering; use regex::Regex; use std::collections::{HashMap, HashSet}; struct Constraint { name: String, intervals: Vec<(u32, u32)> } fn main() { let ...
use crate::openrtb3::bool; use serde::{Deserialize, Serialize}; use super::{ data_asset_format::DataAssetFormat, image_asset_format::ImageAssetFormat, title_asset_format::TitleAssetFormat, video_placement::VideoPlacement, }; #[derive(Serialize, Deserialize, Debug, PartialEq)] pub struct AssetFormat { id: ...
// Line comments are anything after ‘//’ and extend to the end of the line. let x = 5; // This is also a line comment. // If you have a long explanation for something, you can put line comments next // to each other. Put a space between the // and your comment so that it’s // more readable. /// Adds one to the numb...
use chrono::Utc; use taskwarrior_rust::{taskstorage, Operation, Server, DB}; use uuid::Uuid; fn newdb() -> DB { DB::new(Box::new(taskstorage::InMemoryStorage::new())) } #[test] fn test_sync() { let mut server = Server::new(); let mut db1 = newdb(); db1.sync("me", &mut server).unwrap(); let mut d...
use crate::utility; use crate::utility::{random_f64, random_f64_range}; use std::fmt; use std::ops::{Add, AddAssign, Div, DivAssign, Index, IndexMut, Mul, MulAssign, Neg, Sub}; /// Simple vec3 class /// Laid out as x, y, z #[derive(Debug, Default, PartialEq, Clone, Copy)] pub struct Vec3(f64, f64, f64); #[allow(dead_...
//! # Low level reading use super::file::*; use super::parser; use assembly_core::reader::{FileError, FileResult}; use assembly_core::{nom::Finish, reader::ParseAt}; use std::io::prelude::*; use std::{io::SeekFrom, num::NonZeroU32}; /// A low level reader class pub struct LevelReader<T> { inner: T, } impl<T> Le...
// Copyright 2020 The MWC Developers // // 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...
use crate::diagnostics::Diagnostics; use std::fs; use std::io::{self, Read}; use std::path::PathBuf; use std::rc::Rc; use super::error::Error; use super::semantics; use super::syntax::*; pub type Result<T> = ::std::result::Result<T, Error>; pub struct File { pub content: String, pub lines: Vec<String>, } pu...
extern crate openssl; use openssl::rsa::{Rsa, Padding}; use openssl::pkey::Private; use std::io::{Error, ErrorKind}; pub trait CryptoService { fn pubkey_pem(&self) -> String; // fn privkey(&self) -> Vec<u8>; fn encrypt(&self, text: &[u8]) -> Result<Vec<u8>, Error>; fn decrypt(&self, text: &[u8]) -> Res...