text
stringlengths
8
4.13M
pub mod game; pub mod inning; pub mod inning_half;
use std::sync::Arc; use gltf::texture::{ MagFilter, MinFilter, }; use smallvec::SmallVec; use sourcerenderer_core::graphics::{ AddressMode, AttachmentBlendInfo, AttachmentInfo, Backend, Barrier, BarrierAccess, BarrierSync, BarrierTextureRange, BindingFrequency, BlendInfo...
#[doc = "Reader of register APB2LPENR"] pub type R = crate::R<u32, super::APB2LPENR>; #[doc = "Writer for register APB2LPENR"] pub type W = crate::W<u32, super::APB2LPENR>; #[doc = "Register APB2LPENR `reset()`'s with value 0"] impl crate::ResetValue for super::APB2LPENR { type Type = u32; #[inline(always)] ...
use crate::game_rules::Action; use text_io::read; pub fn select_action(available_actions: Vec<&Action>) -> Option<&Action> { if available_actions.len() > 1 { println!( "Select action by number:\n{}", available_actions .iter() .enumerate() ...
// `with_safe` in unit tests test_stdout!( with_used_with_binary_returns_how_many_bytes_were_consumed_along_with_term, "{hello, 9}\n{hello, 9}\ntrue\nhello\n" );
use super::*; use std::fmt; #[allow(unused_imports)] use core_extensions::SelfOps; use crate::{ abi_stability::PrefixStableAbi, erased_types::{c_functions::adapt_std_fmt, InterfaceType, MakeRequiredTraits}, pointer_trait::{ AsMutPtr, AsPtr, CanTransmuteElement, GetPointerKind, PK_Reference, PK_Sm...
extern crate test; use stringify::Stringify; use std::ffi::{CStr, CString}; use std::borrow::Cow; use self::test::Bencher; #[bench] fn convert_to_cow_str_bench(b: &mut Bencher) { let libc_char = CString::new("something".to_string()).unwrap().as_ptr(); b.iter(|| libc_char.convert_to_cow_str()); } #[bench] fn conv...
use crate::schema::*; use serde_derive::Serialize; #[derive(Queryable, Clone, Debug, Serialize, Deserialize, AsChangeset, Identifiable)] #[table_name = "repositories"] pub struct Repository { pub id: i32, pub name: String, pub url: String, pub ver: String, } #[derive(Insertable, AsChangeset, Debug)] #...
// 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 ...
use tuple::T2; pub type Length = f32; pub type Scale = f32; pub type Point = T2<f32, f32>; pub type Size = T2<f32, f32>; /* pub struct Rect { x: f32, y: f32, width: f32, height: f32, } pub struct Trafo { x: (Length, Scale), y: (Length, Scale) } */
#![no_std] pub const USB_DEVICE_VID: u16 = 0xdead; pub const USB_DEVICE_PID: u16 = 0xbeef; pub const REQ_SELECT: u8 = 0xff; #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum ResetStatus { /// RESET=0 Asserted, /// RESET=1 Deasserted, } #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum Boot0...
use std::i32; pub fn sort(a: &mut Vec<i32>, size: usize) { return merge_sort(a, 0, size - 1); } fn merge_sort(a: &mut Vec<i32>, p: usize, r: usize) { if p < r { let q = (p + r) / 2; merge_sort(a, p, q); merge_sort(a, q + 1, r); return merge(a, p, q, r); } } fn merge(a: &mut Vec<i32>, p: usize, ...
#![allow(clippy::all)] pub const SCENARIO: &str = " SchemaData( activity: { \"A1\": Activity(id: \"A1\", lat: 52.895461, lon: -1.702781), \"A10\": Activity(id: \"A10\", lat: 53.157758, lon: -1.76056), \"A100\": Activity(id: \"A100\", lat: 53.302244, lon: -1.540919), \"A101\": Activity(id: \"A101\", l...
extern crate rltk; use specs::prelude::*; use crate::{Context, get_screen_bounds, Map, State, Viewshed}; use self::rltk::{Algorithm2D, ColorPair, Point, RGB}; #[derive(PartialEq, Copy, Clone)] pub enum RangedTargetResult { Cancel, NoResponse, Selected(Point) } pub fn ranged_target(state: &mut State, context: &mut ...
use std::collections::HashMap; fn main() { let bootstrap = std::fs::read_to_string("input") .unwrap() .split(",") .map(|s| s.parse::<usize>().unwrap()) .collect::<Vec<_>>(); dbg!(part_1(&*bootstrap, 2020)); dbg!(part_1(&*bootstrap, 30000000)); } fn part_1(bootstrap: &[usize...
//! Type wrappers and convenience functions for 2D collision detection pub use collision::algorithm::minkowski::GJK2; pub use collision::primitive::{Circle, ConvexPolygon, Particle2, Rectangle, Square}; use cgmath::{Basis2, Point2}; use collision::algorithm::broad_phase::BruteForce; use collision::primitive::Primitiv...
#![allow(non_upper_case_globals)] use std::any::Any; use std::ffi::{CStr, CString}; use std::mem::ManuallyDrop; use std::os::raw::c_char; use std::ptr::null_mut; pub type CU64 = u64; pub type CBool = u32; pub const CFalse: CBool = 0u32; pub const CTrue: CBool = 1u32; /// call free_c_char to free memory pub fn to_c_...
// Copyright 2012 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 ...
use std::sync::Arc; use base64::encode; use model::*; use utils::*; type Players = Vec<Player>; #[derive(Debug)] pub struct State { pub players : Vec<Arc<Player>>, pub requests : Vec<Request> } impl State { pub fn new() -> State { State { players : Vec::new(), requests : Vec::new() } ...
//! ```elixir //! case Lumen.Web.Document.body(document) do //! {:ok, body} -> ... //! :error -> ... //! end //! ``` use liblumen_alloc::erts::exception; use liblumen_alloc::erts::process::Process; use liblumen_alloc::erts::term::prelude::*; use crate::{document, option_to_ok_tuple_or_error}; #[native_implemente...
use std::cmp; use std::cmp::Ordering; mod utils; fn main() { let data = utils::load_input("./data/day_9.txt").unwrap(); let nbs: Vec<u64> = data.lines().map(|nb| nb.parse().unwrap()).collect(); let invalid_nb: u64 = find_invalid_nb(&nbs).unwrap(); let weakness: u64 = find_weakness(&nbs, invalid_nb)....
use std::path::PathBuf; use anyhow::{bail, Context, Result}; use async_std::io::{Read, Write}; use async_std::net::{TcpListener, TcpStream}; use async_std::os::unix::net::{UnixListener, UnixStream}; use async_trait::async_trait; /// A new trait, which can be used to represent Unix- and TcpListeners. /// This is neces...
#![cfg(target_arch="wasm32")] extern crate mandelbrot; extern crate image; use mandelbrot::point::{Point, PlotSpace, point_resolver}; use mandelbrot::mandelbrot_paint::paint_mandelbrot; use image::RgbImage; #[no_mangle] pub extern fn plot_mandelbrot(width: u32, height: u32, ss_scale: u32, subimage_height: u32, sub...
use crate::{DocBase, VarType}; const DESCRIPTION: &'static str = r#" Momentum of x price and x price y bars ago. This is simply a difference `x - x[y]`. "#; const ARGUMENTS: &'static str = r#" source (series(float)) Series of values to process. length (int) Offset from the current bar to the previous bar. "#; pub fn...
#[derive(Clone, Copy, Debug, PartialEq)] pub struct Energy { pub energy: f32, pub max: f32, pub regen_rate: f32, }
// 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. //! Helper library for integration testing netdump. use { failure::{format_err, Error}, fdio::{self, WatchEvent}, fidl_fuchsia_netemul_environ...
mod args; #[cfg(feature = "tui")] mod tui; use args::Args; use rlifesrc_lib::{Search, Status}; use std::process::exit; /// Runs the search without TUI. /// /// If `all` is true, it will print all possible results /// instead of only the first one. fn run_search(mut search: Box<dyn Search>, all: bool) { if all { ...
// Count Sorted Vowel Strings // https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/581/week-3-january-15th-january-21st/3607/ pub struct Solution; impl Solution { pub fn count_vowel_strings(n: i32) -> i32 { const NUM_VOWELS: usize = 5; let mut by_1st_char = [1; NUM_VOWE...
mod small_vec; pub use small_vec::{SmallVectorImpl, Span, StableId};
pub struct Solution; impl Solution { pub fn sort_colors(nums: &mut Vec<i32>) { let n = nums.len(); let mut two_pos = n; let mut one_pos = n; let mut i = 0; while i < one_pos { match nums[i] { 0 => i += 1, 1 => { ...
pub trait Same<Lhs, Rhs, Out = ()> { type Output; } impl<T, Out> Same<T, T, Out> for () { type Output = Out; } pub type SameOp<Lhs, Rhs> = <() as Same<Lhs, Rhs>>::Output; pub type SameExOp<Lhs, Rhs, Out> = <() as Same<Lhs, Rhs, Out>>::Output;
/// Macro that allows you to quickly define a handlebars helper by passing a /// name and a closure. /// /// # Examples /// /// ```rust /// #[macro_use] extern crate handlebars; /// #[macro_use] extern crate serde_json; /// /// handlebars_helper!(is_above_10: |x: u64| x > 10); /// /// # fn main() { /// # /// let mut ha...
//! 1D linear regression. use std::fmt; /// A linear regression predictor. #[derive(Clone, Debug)] pub struct LinearRegression { pub slope: f64, pub offset: f64, pub error_r2: f64, } impl LinearRegression { /// Train a linear regression using the least square error. pub fn train(x: &[f64], y: &[f6...
#![link(name="git2")] extern crate git2; use git2::git2; use std::io::TempDir; #[test] fn test_init_01() { let dir = TempDir::new("git2_test1").unwrap(); println!("new test repo in {}", dir.path().display()); let bare = false; let repo = match git2::Repository::init(dir.path(), bare) { Ok(r) ...
use std::error::Error; /// HTTP Client used to call the OANDA web services. #[derive(Debug)] pub struct Client { /// The reqwest object to use. Note that this is a synchronous client /// that cannot be used in async code. pub reqwest: reqwest::blocking::Client, /// OANDA host to use (do not include https://) ...
use mode::{Mode, normal, Transition}; use mode_map::ModeMap; use op::{InsertOp, PendingOp, NormalOp}; use state::State; use typeahead::{Parse, RemapType}; use client; pub struct StateMachine<K> where K: Ord, K: Copy, K: Parse, { state: State<K>, mode: Mode<K>, } impl<K> StateMachine<K> where K...
#[cfg(test)] mod tests { #[test] fn should_not_panic() { #[cfg(feature = "foo")] panic!("should not foo"); println!("aaa"); } }
use std::fs::File; use std::io::prelude::*; use std::{thread, time}; use std::collections::HashSet; use std::collections::HashMap; use serde_json::json; extern crate nalgebra as na; use crate::structs; use na::Point2; use na::Vector2; use std::collections::BTreeSet; use structs::Deck; use structs::DeckPositi...
use std::sync::Arc; use failure::Fallible; use headless_chrome::{Browser, LaunchOptions, Tab, browser::tab::SyncSendEvent, protocol::Event}; fn start() -> Fallible<()> { let browser = Browser::new(LaunchOptions { headless: false, ..Default::default() })?; let tab = browser.wait_for_initi...
pub mod org_bluez_adapter1; pub mod org_bluez_device1; pub mod org_bluez_gatt_service1; pub mod org_bluez_gatt_characteristic1; pub mod org_bluez_gatt_descriptor1; pub mod utils; pub mod dbus_processor; #[cfg(test)] mod tests { #[test] fn it_works() { assert_eq!(2 + 2, 4); } }
//! Websocket server implementation //! //! The websocket uses Tokio under the hood and manages a state for each connection. It also shares //! the latest token to all clients and logs every events concerning connecting and disconnecting. use std::fmt::Debug; use std::rc::Rc; use std::cell::RefCell; use std::path::Pa...
#[doc = "Reader of register TDCR"] pub type R = crate::R<u32, super::TDCR>; #[doc = "Reader of field `TDCF`"] pub type TDCF_R = crate::R<u8, u8>; #[doc = "Reader of field `TDCO`"] pub type TDCO_R = crate::R<u8, u8>; impl R { #[doc = "Bits 0:6 - Transmitter Delay Compensation Filter Window Length"] #[inline(alwa...
use anyhow::Result; use clap::{Parser, Subcommand}; use mdbook::preprocess::{CmdPreprocessor, Preprocessor}; use mdbook_plantuml::plantuml_config; use std::io; use std::process; #[derive(Parser)] #[clap(version, author, about)] pub struct Args { /// Log to './output.log' /// /// (may help troubleshooting r...
use common::*; mod depgraph; mod occ; use futures::{future, stream, FutureExt, StreamExt}; use rocksdb::DB; use rustop::opts; use web3::types::U256; // define a "trait alias" (see https://www.worthe-it.co.za/blog/2017-01-15-aliasing-traits-in-rust.html) trait BlockDataStream: stream::Stream<Item = (u64, (Vec<U256>, ...
use std::fmt; pub mod roll; use serde::Serialize; #[derive(Serialize, Debug, PartialEq, Eq, Clone)] pub enum DiceExpression { Many(Vec<DiceExpression>), Sum(Box<DiceExpression>), Max(Box<DiceExpression>), Min(Box<DiceExpression>), Add(Box<DiceExpression>, Box<DiceExpression>), Multiply(Box<Dice...
use super::*; use std::{ collections::hash_map::{Entry, OccupiedEntry, VacantEntry}, mem::ManuallyDrop, ptr, }; use crate::{ marker_type::UnsafeIgnoredType, prefix_type::WithMetadata, sabi_types::{RMut, RRef}, }; /// The enum stored alongside the unerased HashMap. pub(super) enum BoxedREntry<...
use rustc_serialize::base64; use std::{num, str, string}; #[derive(Debug)] pub enum MacaroonError { InitializationError, HashFailed, NotUTF8(str::Utf8Error), UnknownSerialization, DeserializationError(String), BadMacaroon(&'static str), KeyError(&'static str), DecryptionError(&'static s...
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[cfg(feature = "Devices_Perception_Provider")] pub mod Provider; #[repr(transparent)] #[doc(hidden)] pub struct IKnownCameraIntrinsicsPropertiesStatics(pub ::windows::core::IInspectable); un...
// Copyright 2016 Mozilla Foundation // // 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...
//! OAuth 1 //! //!# Example //! //! TODO extern crate time; use std::default::Default; use std::fmt; use self::time::now_utc; use std::rand::{thread_rng, Rng}; #[derive(Copy, Show, PartialEq, Eq, Clone)] #[unstable] /// Signature Type pub enum SignatureMethod { /// HMAC_SHA1 HMAC_SHA1, /// RSA_SHA1 R...
use crate::prelude::*; use std::os::raw::c_void; use std::ptr; #[repr(C)] #[derive(Debug)] pub struct VkPipelineDepthStencilStateCreateInfo { pub sType: VkStructureType, pub pNext: *const c_void, pub flags: VkPipelineDepthStencilStateCreateFlagBits, pub depthTestEnable: VkBool32, pub depthWriteEna...
// 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 fidl_fuchsia_intl::Profile; /// Manual implementations of `Clone` for intl FIDL data types. pub trait CloneExt { fn clone(&self) -> Self; } // Th...
extern crate rand; extern crate ansi_term; use std::io; use std::cmp::Ordering; use rand::Rng; use ansi_term::Colour::{Red, Blue, Yellow, Green}; fn main() { println!("{}", Blue.bold().underline().paint("\n\n-- Guess the number --\n\n")); println!("Please input your guess, between 1-100."); let secret_num...
use std::error::Error; use std::fs::File; use std::io::prelude::*; use std::path::Path; mod lib; fn main() { let s = get_file_string(); let steps = lib::solve_first(&*s); println!("shortest amount of steps: \n{}", steps); let steps = lib::solve_second(&*s); println!("Max amount of steps: \n{}", s...
extern crate femapi; fn main() { femapi::init_server(); }
use std::{ fmt::Display, sync::atomic::{AtomicI64, Ordering}, }; use async_trait::async_trait; use data_types::{CompactionLevel, ParquetFile, ParquetFileId, ParquetFileParams, PartitionId}; use parking_lot::Mutex; use super::{Commit, Error}; #[derive(Debug, PartialEq, Eq, Clone)] pub(crate) struct CommitHist...
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)]...
use std::{ borrow::Cow, iter::{FusedIterator, Peekable}, str::CharIndices, }; #[derive(Debug, Clone, Copy)] enum State { Start, S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, Trap, } impl Default for State { fn default() -> Self { Self::Start ...
//! HTTP helpers. use std::io::Read; use std::result; use hyper::Client; use hyper::header::ContentType; use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value}; pub use hyper::status::StatusCode; pub use hyper::Error as HttpError; header! { (SoapAction, "SOAPAction") => [String] } /// Simplified HTTP response repr...
use errors::*; use net::endpoint::Endpoint; use net::event::{ClientEvent, Event, ServerEvent}; use net::session_client::SessionClient; use net::session_server::SessionServer; use std; use std::collections::{hash_map, HashMap}; struct StdNetListenCon { socket: std::net::TcpListener, } impl StdNetListenCon { fn...
#[doc = "Reader of register FMC"] pub type R = crate::R<u32, super::FMC>; #[doc = "Writer for register FMC"] pub type W = crate::W<u32, super::FMC>; #[doc = "Register FMC `reset()`'s with value 0"] impl crate::ResetValue for super::FMC { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { ...
use crate::{err_fmt, Err}; use bytes::Bytes; use futures::{ future::BoxFuture, prelude::*, task::{Context, Poll}, }; use http::{Method, Request, Response, Uri}; use hyper::Body; use std::pin::Pin; #[derive(Debug)] pub(crate) struct Client { base: Uri, client: hyper::Client<hyper::client::HttpConnec...
use std::os::raw::c_char; /// The boolean value type. /// /// See [documentation](https://developer.apple.com/documentation/objectivec/bool). pub type BOOL = c_char; /// The [`BOOL`](type.BOOL.html) equivalent to /// [`false`](https://doc.rust-lang.org/std/keyword.false.html). /// /// See [documentation](https://deve...
// error-pattern: cyclic import import zed::bar; import bar::zed; fn main(args: vec[str]) { log "loop"; }
use std::collections::HashMap; use chrono::prelude::*; use serde_derive::{Deserialize, Serialize}; use strum_macros::Display; /// This enum represents the status of the internal task handling of Pueue. /// They basically represent the internal task life-cycle. #[derive(Clone, Debug, Display, PartialEq, Serialize, Des...
// Copyright 2019 The n-sql Project 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 // ex...
extern crate clap; use clap::{App, Arg, SubCommand}; mod extractor; mod creator; fn main() { let matches = App::new("wtar") .version("1.0") .author("Wyatt E. <wyatt.k.emery@gmail.com>") .about("A small version of tar that is compatible with tar -H ustar. Only supports files, directories and links") ...
extern crate rand_chacha; extern crate rand_core; pub use self::rand_chacha::ChaChaRng; pub use self::rand_core::{RngCore, SeedableRng}; pub fn make_seeded_rng(fuzzer_input: &[u8]) -> ChaChaRng { // We need 8 bytes worth of data to convet into u64, so start with zero and replace // as much of those as there i...
use structs::other::Error; #[derive(Debug, Fail)] pub enum CBError { #[fail(display = "http: {}", _0)] Http(#[cause] super::hyper::Error), #[fail(display = "serde: {}\n {}", error, data)] Serde { #[cause] error: super::serde_json::Error, data: String, }, #[fail(displa...
#[macro_use] extern crate lazy_static; use std::env; use std::path::Path; #[cfg(windows)] lazy_static! { static ref LIBS: Vec<&'static str> = vec!["improbable_worker", "RakNetLibStatic", "ssl", "zlibstatic",]; } #[cfg(unix)] lazy_static! { static ref LIBS: Vec<&'static str> = vec!["improbable_worker"...
use std::io::Read; fn read<T: std::str::FromStr>() -> T { let token: String = std::io::stdin() .bytes() .map(|c| c.ok().unwrap() as char) .skip_while(|c| c.is_whitespace()) .take_while(|c| !c.is_whitespace()) .collect(); token.parse().ok().unwrap() } fn main() { let...
pub mod client; use crate::client::{ClientActor,ClientCommand}; use actix::*; use actix_rt::Arbiter; use actix::io::SinkWrite; use awc::Client; use std::{io,thread}; use futures::StreamExt; /* * Connects to the websocket; and if valid, can send a text inputted from the terminal. */ fn main() { std::env::set_...
use nodes::prelude::*; pub struct Leaf { content: NodeList<NodeP> } impl Leaf { pub fn from(io: &Io, env: &GraphChain, items: Vec<source::Item>) -> Leaf { Leaf { content: NodeList::from(io, items.into_iter().map(|n| item_node(io, env, n)) ) } } pu...
use bitflags::bitflags; use either::Either; use crate::io::Encode; use crate::mssql::io::MssqlBufMutExt; use crate::mssql::protocol::header::{AllHeaders, Header}; use crate::mssql::MssqlArguments; pub(crate) struct RpcRequest<'a> { pub(crate) transaction_descriptor: u64, // the procedure can be encoded as a ...
#[cfg(not(feature = "threading"))] use std::rc::Rc; #[cfg(feature = "threading")] use std::sync::Arc; // type aliases instead of newtypes because you can't do `fn method(self: PyRc<Self>)` with a // newtype; requires the arbitrary_self_types unstable feature #[cfg(feature = "threading")] pub type PyRc<T> = Arc<T>; #[...
use num::cast::FromPrimitive; use num::{One, Zero}; use std::iter::Sum; use std::ops::{Add, Div, Mul, Sub}; #[derive(Debug, Clone)] pub struct Position<I> { x: I, y: I, z: I, } impl<I> Position<I> { pub fn new(x: I, y: I, z: I) -> Self { Position { x, y, z } } } impl<I: Add<Output = I> + ...
use crate::smb2::{ helper_functions::negotiate_context::{ CompressionCapabilities, ContextType, EncryptionCapabilities, NegotiateContext, NetnameNegotiateContextId, PreauthIntegrityCapabilities, RdmaTransformCapabilities, TransportCapabilities, }, requests::negotiate::Negotiate, }; ...
extern crate cpal; extern crate rand; #[cfg(test)] extern crate float_cmp; mod synthesizer; use synthesizer::{Synthesizer, Voice, VoiceKind}; use cpal::{EventLoop, StreamData, UnknownTypeOutputBuffer}; // series of events, each event is just the beginning of a bar // generates new events, // add attributes (whic...
use gtk::prelude::*; pub struct MainWindow { window: gtk::Window, results_store: gtk::ListStore, query_entry: gtk::Entry, } macro_rules! clone { (@param _) => ( _ ); (@param $x:ident) => ( $x ); ($($n:ident),+ => move || $body:expr) => ( { $( let $n = $n.clone(); )+ ...
use std::{sync::mpsc, thread, time::Duration}; // multiple producer, single consumer #[test] #[ignore = "safe concurrency"] fn ownership_transference() { println!("\n--- 16.2 fearless concurrency : channels and ownership transference ---\n"); let (tx, rx) = mpsc::channel(); thread::spawn(move || { ...
extern crate rand; mod bitcrush { use rand::prelude::*; static bits: u32 = 8; #[no_mangle] pub extern "C" fn awgn_generator()->f64 { let mut tmp1: f64 = 0.0; let mut tmp2: f64 = 0.0; let mut result: f64 = 0.0;
//! This module contains implementations of [`iox_query`] interfaces for [QuerierNamespace]. use crate::{ namespace::QuerierNamespace, query_log::QueryLog, system_tables::{SystemSchemaProvider, SYSTEM_SCHEMA}, table::QuerierTable, }; use async_trait::async_trait; use data_types::NamespaceId; use datafu...
/// 虚拟块设备前端驱动 /// ref: https://github.com/rcore-os/virtio-drivers/blob/master/src/blk.rs /// thanks! use bitflags::bitflags; use volatile::Volatile; use core::future::Future; use core::pin::Pin; use core::task::{Context, Poll}; use core::ptr::NonNull; use super::mmio::VirtIOHeader; use super::queue::VirtQue...
extern crate rustplot; use rustplot::chart_builder; use rustplot::chart_builder::Chart; use rustplot::data_parser; #[test] fn xy_scatter_tests() { let data_1 = data_parser::get_str_col(0, 0, 1, "./resources/box_plot_tests.csv"); let data_2 = data_parser::get_num_col(3, 0, 15, "./resources/box_plot_tests.csv")...
use crate::runtime::data::launches::structures::Launch; use tui::widgets::{Paragraph, Borders, Block}; use tui::text::{Spans, Span}; use crate::utilities::countdown; use chrono::Utc; use webbrowser::BrowserOptions; use tui::style::{Style, Color}; use crate::runtime::state::State; pub fn render_list(state: &mut State, ...
//! The Oasis ABIs. use std::collections::BTreeSet; use oasis_contract_sdk_types as contract_sdk; use oasis_runtime_sdk::{ context::Context, modules::core::{self}, types::token, }; use super::{gas, ExecutionContext, ExecutionResult, ABI}; use crate::{wasm::ContractError, Config, Error}; mod env; mod memo...
use std::iter::FromIterator; pub struct SimpleLinkedList<T> { head: Option<Box<Node<T>>>, } struct Node<T> { data: T, next: Option<Box<Node<T>>>, } impl<T> SimpleLinkedList<T> { pub fn new() -> Self { SimpleLinkedList{head: None} } pub fn len(&self) -> usize { // TODO: store ...
// Copyright 2020-2021, The Tremor 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 agr...
#![cfg_attr(feature = "clippy", feature(plugin))] // Use clippy if it's available #![cfg_attr(feature = "clippy", plugin(clippy))] #![cfg_attr(feature = "clippy", deny(clippy))] // And make every warning fatal. #[macro_use] extern crate lazy_static; mod ascii; mod unicode; pub mod display; pub mod human_names;
use crate::{ markdown::Markdown, model::{Article, ArticleSearchIndex, DisambiguationSearchIndex, SearchIndex, Section}, }; use serde::{Deserialize, Serialize}; use std::{collections::HashMap, convert::TryFrom, fs, fs::File, io::Read}; #[derive(Debug, Clone, Deserialize, Serialize)] pub struct Disambiguation { ...
// Copyright 2013 The Servo 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>, at ...
use std::fs::File; use std::io::Read; fn main() { let mut in_dat_fh = File::open("./data/input.txt").unwrap(); let mut in_dat = String::new(); in_dat_fh.read_to_string(&mut in_dat).unwrap(); } #[cfg(test)] mod tests {}
use proconio::input; fn main() { input! { p: char, q: char, }; let (p, q) = if p < q { (p, q) } else { (q, p) }; let index = |ch: char| { ch as usize - 'A' as usize }; let mut x = [0, 3, 1, 4, 1, 5, 9]; for i in 1..x.len() { x[i] += x...
use std::sync::Arc; use std::thread::ThreadId; use firefly_codegen::meta::CompiledModule; use firefly_syntax_base::ApplicationMetadata; use crate::compiler::queries; use crate::diagnostics::ErrorReported; use crate::interner::*; use crate::parser::Parser; #[salsa::query_group(CompilerStorage)] pub trait Compiler: Pa...
// Copyright 2018 Mattias Cibien // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://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 according to tho...
use crate::{ camera::{ProjectionExt, ScaledOrthographicProjection}, controller::Player, input::CursorState, physics::PhysicsBundle, plugins::{config::DebugConfig, timed::Timed}, }; use game_camera::CameraPlugin; use game_controller::ControllerSystem; use game_core::{modes::ModeExt, GameStage, Global...
use super::*; // Any mathematical expression #[derive(Clone)] pub enum Expression { Constant(Constant), Variable(Variable), TermSum(TermSum), Term(Term), BasicTerm(BasicTerm), } impl Expression { /// Converts to smallest type possible /// Where TermSum > Term > BasicTerm > [Variable, Const...
mod entity; mod space; use crate::entity::Entity; use crate::space::Vector; fn main() { let mut rng = rand::thread_rng(); let e1 = Entity::random(&mut rng); println!("e1 direction: {:?}", e1.direction); let e2 = Entity::random(&mut rng); println!("e2 direction: {:?}", e2.direction); let avg = ...
pub const WHITE: Side = 0u8; pub const BLACK: Side = 1u8; pub type Side = u8;
// 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 ...