text
stringlengths
8
4.13M
fn main() { let steps = 394; // part one { use std::collections::VecDeque; let iterations = 2017; let mut buffer = VecDeque::with_capacity(iterations + 1); buffer.push_back(0); let mut current_position = 0; for i in 1..(iterations + 1) { let new...
// Topic: Decision making with match // // Program requirements: // * Display "it's true" or "it's false" based on the value of a variable // // Notes: // * Use a variable set to either true or false // * Use a match expression to determine which message to display fn main() { let my_bool = true; match my_boo...
use std::collections::{HashMap, VecDeque}; use std::mem; use std::net::SocketAddr; use std::sync::{Arc, Mutex}; use dcsjsonrpc_common::{Notification, Request, Response, RpcError, Version}; use futures::channel::mpsc::{channel, Sender}; use futures::{FutureExt, SinkExt, StreamExt}; use serde_json::Value; use tokio::net...
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use crate::{ callbacks::*, enums::*, error::{Error, Fallible}, security, }; use core::{convert::TryInto, ptr::NonNull}; use s2n_tls_sys::*; use std::{ ffi::{c_void, CString}, path::Path,...
use std::collections::BTreeMap; #[macro_use] extern crate easy_util; extern crate rustc_serialize; use rustc_serialize::json::Json; use rustc_serialize::json::ToJson; use std::str::FromStr; extern crate regex; use regex::Regex; use std::rc::{Rc}; use std::sync::Arc; extern crate postgres; use postgr...
use commander_rust_core::{Options, Argument, ArgumentType}; use commander_rust_core::traits::GetArgs; #[test] fn options_test() { let option = Options::from(r#"-a, --all-numbers <a> [b] [...c], "hello world!""#); assert_eq!(option.short, Some(String::from("a"))); assert_eq!(option.long, String::from("all-n...
#[allow(clippy::module_inception)] mod num_format; pub mod sub; pub mod token; pub mod unescaped_text;
use crate::day9::part1::*; use crate::io::*; #[test] fn test1() { let input = read_file("day9/input_test_part1_test1").unwrap(); assert_eq!(solve(&input), 32); } #[test] fn test2() { let input = read_file("day9/input_test_part1_test2").unwrap(); assert_eq!(solve(&input), 8317); } #[test] fn test3() {...
use sdl2::event::Event; use sdl2::image::InitFlag; use std::collections::HashSet; use std::time::Duration; use sdl_isometric::states::*; use sdl_isometric::*; fn main() -> Result<(), String> { let sdl_context = sdl2::init().expect("ERROR on SDL CONTEXT"); let video_subsystem = sdl_context.video().expect("ERRO...
// 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 ...
// Copyright 2018 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at: // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
use std::{collections::HashSet, fs::read_to_string}; fn main() { let input = read_to_string("src/inputs/06.txt").unwrap(); part1(&input); part2(&input); } fn part1(input: &String) -> () { let signal = input.lines().next().unwrap(); println!("{}", find_unique_section(signal, 4)); } fn part2(input:...
use anyhow::Result; use bitvec::prelude::*; use byteorder::{LittleEndian, ReadBytesExt}; #[allow(clippy::unnecessary_wraps)] fn concatenate_merge( _key: &[u8], // the key being merged old_value: Option<&[u8]>, // the previous value, if one existed merged_bytes: &[u8], // the new bytes b...
// Copyright 2019 WHTCORPS INC Project Authors. Licensed under Apache-2.0. use crate::causet_options::NoetherDBOptions; pub trait PrimaryCausetNetworkOptions { type NoetherDBOptions: NoetherDBOptions; fn new() -> Self; fn ground_state_write_retardationr(&self) -> u32; fn ground_state_write_pullback(&...
use neon::prelude::*; #[inline(always)] pub fn call_method<'a, AS>( cx: &mut impl Context<'a>, this: Handle<'a, JsFunction>, method_name: &str, args: AS, ) -> JsResult<'a, JsValue> where AS: AsRef<[Handle<'a, JsValue>]>, { let method: Handle<JsFunction> = this.get(cx, method_name)?; method....
extern crate boguin; extern crate clap; extern crate env_logger; extern crate http_with_url as http; #[macro_use] extern crate log; use std::error::Error; use std::io::{self, Read, Write}; use boguin::Client; use clap::{App, Arg, ArgMatches}; use http::{Request, Response, Url}; fn build_request(matches: ArgMatches) ...
#[derive(Debug)] struct Structure(i32); #[derive(Debug)] struct Deep(Structure); #[derive(Debug)] struct Person<'a> { name: &'a str, age: u8, } fn main() { println!("{:?} months in a year ", 12); println!( "{1:?} {0:?} is the {actor:?} name.", "Slater", "Christian", ac...
extern crate regex; use regex::Regex; fn main() { let re = Regex::new(r"^[0-9]+$").unwrap(); println!("{}", re.is_match("2014-01-01")); println!("{}", re.is_match("2014")); println!("{}", re.is_match("h32")); println!("{}", re.is_match("h4")); println!("{}", re.is_match("32o")); println!("...
extern crate bytes; #[macro_use] extern crate futures; extern crate futures_state_stream; extern crate imap_proto; extern crate native_tls; extern crate nom; extern crate tokio; extern crate tokio_codec; extern crate tokio_tls; pub mod client; pub mod proto; pub use client::{ImapClient, TlsClient}; pub mod types { ...
extern crate chrono; extern crate cron_parser; pub mod offer; pub mod order; pub mod treat; #[cfg(test)] mod tests { use super::*; const COOKIE: &str = "Cookie"; const BROWNIE: &str = "Brownie"; const DONUT: &str = "Mini Gingerbread Donut"; const CHEESECAKE: &str = "Key Lime Cheesecake"; // S...
use std::borrow::Cow; use std::sync::Arc; use std::time::Duration; use failure::Error; use log::Log; use sentry::integrations::{failure, log, panic}; use sentry::{Client, ClientOptions, Hub}; use config::Config; use constants::USER_AGENT; pub fn setup(log: Box<Log>) { log::init(Some(log), Default::default()); ...
extern crate blurz; use crate::ble_connectivity::handlers::handle_sensor_data; use crate::timestamp_in_sec; use crate::types::sensor_data::SensorData; use crate::types::sensor_type::SensorType; use blurz::bluetooth_device::BluetoothDevice; use blurz::bluetooth_gatt_characteristic::BluetoothGATTCharacteristic; use blu...
// 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...
use bloom_filter_plus::*; fn main() { // test 1 // let filter = BloomFilter::new(); // filter.insert("key").unwrap(); // filter.debug(); // assert_eq!(true, filter.contains("key").unwrap()); // assert_eq!(false, filter.contains("key1").unwrap()); // filter.save_to_file("test.bitmap").unwrap...
pub type MyCallback=fn(i32) -> i32; struct Network { count: i32, name: &'static str, onRead:MyCallback, onWrite:MyCallback, } impl Network { fn read(&mut self) { self.count+=1; (self.onRead)(100); } fn write(&mut self) { self.count+=2; (self.onWrite)...
#[doc = "Register `UCAxMCTLW` reader"] pub struct R(crate::R<UCAXMCTLW_SPEC>); impl core::ops::Deref for R { type Target = crate::R<UCAXMCTLW_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<UCAXMCTLW_SPEC>> for R { #[inline(always)] fn from(read...
use chrono::{DateTime, FixedOffset}; use regex::Regex; use std::collections::HashMap; use std::fs; #[macro_use] extern crate lazy_static; fn main() { let mut guards: Vec<Guard> = vec![]; // read the puzzle input let contents = fs::read_to_string("input.txt").expect("Something went wrong reading the file")...
mod delete; mod flush; mod fsync; mod get; mod health; mod put; mod update_meta; mod version; mod write; pub use delete::delete; pub use flush::flush; pub use fsync::fsync; pub use get::{get, Signature}; pub use health::health; pub use put::put; pub use update_meta::update_meta; pub use version::version; pub use write...
// use std::collections::HashSet; // use super::item::{Entity, Equipable, State, Curse}; // pub struct WeaponRanged { // name: String, // image: &'static str, // shape: &'static str, // description: &'static str, // damage: u32, // weight: i32, // durabillity: (u8, u32), //current, total //...
use std::{env, process, io}; use clap::{ self, App, Arg, SubCommand, crate_name, crate_authors, crate_version }; use crate::lib; use crate::lib::term; pub fn run(args: &Vec<String>) { // current directory to exe dir let current_exe = env::current_exe().unwrap(); env::set_current_dir(current_e...
use std::collections::{HashMap, HashSet}; use std::ops::DerefMut; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; use winit::platform::unix::EventLoopExtUnix; use crate::events::EventState; use crate::geom::{Position, Rect}; use crate::renderer::Renderer; use crate::view::{View, ViewId, Wid...
use std::io; use std::net::ToSocketAddrs; use smallvec::SmallVec; use futures::future; use futures::Future; use tokio; use tokio::net::{TcpStream, TcpListener}; use tokio::prelude::*; use tokio_codec::Framed; use num_cpus; use net2::TcpBuilder; use net2::unix::UnixTcpBuilderExt; use std::thread; use builtins::basic_c...
use bytes::{Buf, Bytes}; use crate::error::Error; use crate::io::BufExt; pub trait MySqlBufExt: Buf { // Read a length-encoded integer. // NOTE: 0xfb or NULL is only returned for binary value encoding to indicate NULL. // NOTE: 0xff is only returned during a result set to indicate ERR. // <https://dev...
use crate::{ asm, target::{CLIDebugger, EmptyDebugger}, traits::Debugger, Display, Exception, Input, Memory, CODE_MAPPING_OFFSET, CPU, }; /// The actual Emulator itself pub struct Emulator<K, D> where K: Input, D: Display, { file: Option<g3a::File>, cpu: CPU, memory: Memory, inp...
use std::fmt::Display; use sbtclient::SbtClientError; pub fn error(message: &str) -> SbtClientError { SbtClientError { message: message.to_string() } } pub fn detailed_error<E: Display>(message: &str, e: E) -> SbtClientError { let error_message = format!("{}. Details: {}", message, e); error(&error_messag...
use crate::color::*; use crate::int_math::{cos, inc, inc_i32, sin}; use crate::lights::*; /// A strobing light show. pub struct StrobeShow { brightness: i8, // brightness of one of the two colors (the other is max) hue: i32, // the hue of the same color (the other has opposite hue) delay: i32, //...
// use std::io; // #[derive(Debug)] // enum Currencies { // USD, // Aed, // Yen // } // fn converter(curr:Currencies)->i32{ // match curr { // Currencies::USD => 156, // Currencies::Aed => 43, // Currencies::Yen=>22 // } // } // fn main() { // let...
use crate::bloom::BloomFilter; use crate::SipHasherBuilder; #[cfg(feature = "serde")] use serde_crate::{Deserialize, Serialize}; use std::borrow::Borrow; use std::hash::{BuildHasher, Hash}; /// A growable, space-efficient probabilistic data structure to test for membership in a set. /// /// A scalable bloom filter use...
static WASM: &[u8] = include_bytes!("../../../target/wasm32-unknown-unknown/release/wormhole.wasm"); use cosmwasm_std::{from_slice, Env, HumanAddr, InitResponse}; use cosmwasm_storage::to_length_prefixed; use cosmwasm_vm::testing::{init, mock_env, mock_instance, MockApi, MockQuerier, MockStorage}; use cosmwasm_vm::{In...
extern crate randomorg; fn main() { use randomorg::Random; use std::env; let r = Random::new(env::var("RANDOM_ORG_API_KEY").unwrap()); println!( "Result: {:?}", r.generate_integers(-100, 100, 15, true).unwrap() ); }
// This file is part of Substrate. // Copyright (C) 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 // // http://www.a...
use std::any::{Any, TypeId}; use std::collections::HashMap; /// A typesafe heterogeneous set pub struct TypeSet { elements: HashMap<TypeId, Box<dyn Any>>, } impl TypeSet { pub fn new() -> Self { Self { elements: HashMap::new(), } } pub fn insert<E: 'static>(&mut self, elem...
#![cfg(not(tarpaulin_include))] use actix_web::dev::HttpResponseBuilder; use actix_web::error::ResponseError; use actix_web::http::StatusCode; use actix_web::HttpResponse; use anyhow::Error; use serde_json::json; use std::fmt::Display; pub type ApiResult<T> = std::result::Result<T, ApiError>; #[derive(Debug)] pub st...
use super::{bank::Bank, internal_prelude::*}; use fmod_sys::*; use std::{ ffi::{c_void, CString}, ptr, sync::{ atomic::{AtomicBool, AtomicPtr, Ordering}, Arc, }, thread, time, }; struct SystemHandle { system: AtomicPtr<FMOD_STUDIO_SYSTEM>, shutdown: AtomicBool, } impl Drop ...
// https://github.com/gnosis/ethcontract-rs/blob/main/src/secret.rs //! This module implements secrets in the form of protected memory. use super::hash; use thiserror::Error; use secp256k1::key::ONE_KEY; use secp256k1::Error as Secp256k1Error; use secp256k1::{Message, PublicKey, Secp256k1, SecretKey}; use serde::{Dese...
#![no_std] #![no_main] extern crate panic_halt; use fomu_pac; use fomu_rt::entry; mod rgb; mod timer; use rgb::RgbControl; use timer::Timer; const SYSTEM_CLOCK_FREQUENCY: u32 = 12_000_000; // USB-support using the c-code from riscv-blink #[link(name = "fomu-usb", kind = "static")] extern "C" { fn usb_init();...
//! # Day 2: 1202 Program Alarm //! //! ## Problem Description //! //! This is the first day to introduce Intcode programs. The problem //! was basically to implement an Intcode computer supporting 2 basic //! operations. In part 1 you replace positions 1 and 2 of the program //! with given numbers to check the value t...
use async_std::fs::{create_dir_all, set_permissions, Permissions}; use std::{ fs::File, io, path::{Path, PathBuf}, }; use zip::read::ZipFile; use zip::result::ZipError; #[derive(Debug)] pub struct FileUnzipResult { pub name: Option<String>, pub result: Result<(), UnzipFileError>, } #[derive(Debug)...
struct Solution; impl Solution { fn combine(n: i32, k: i32) -> Vec<Vec<i32>> { let mut res = vec![]; let nums: Vec<i32> = (1..=n).collect(); let n = n as usize; let k = k as usize; let mut cur: Vec<i32> = vec![]; Self::dfs(0, 0, &mut cur, &mut res, &nums, n, k); ...
type Fold = (bool,usize); type Point = (usize,usize); fn print_points(points : &Vec<Point>) { for y in 0..=*points.iter().map(|(_,b)| b).max().unwrap() { for x in 0..=*points.iter().map(|(a,_)| a).max().unwrap() { print!("{}", if points.contains(&(x,y)) {"XX"} else {" "}); } pr...
//! Public module. use DTO; /// Struct for signup verification #[derive(Clone, RustcEncodable, RustcDecodable)] pub struct RegisterDTO { /// The users username pub username: String, /// The users password pub password: String, /// The users email pub email: String, /// Posible referer ...
// Copyright (c) 2021 RBB S.r.l // opensource@mintlayer.org // SPDX-License-Identifier: MIT // Licensed under the MIT License; // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://spdx.org/licenses/MIT // // Unless required by applicable law or agr...
use std::{ fmt, ops::*, slice::{ Iter as SliceIter, IterMut as SliceIterMut, }, }; use super::*; /** * A generic matrix struct where `T` needs has as few requirements as possible. */ #[derive(Clone)] pub struct Matrix<T> where T: MatrixNum, { data: Vec<T>, rows: MatrixSiz...
use day_02; #[test] fn test_part_one() { assert_eq!(day_02::find_total_wrapping("2x3x4"), 58); assert_eq!(day_02::find_total_wrapping("1x1x10"), 43); } #[test] fn test_part_two() { assert_eq!(day_02::find_total_ribbon("2x3x4"), 34); assert_eq!(day_02::find_total_ribbon("1x1x10"), 14); }
//! This module serves as the entry point into Xt's main binary. // This file is part of Xt. // This is the Xt text editor; it edits text. // Copyright (C) 2016-2018 The Xt Developers // This program is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as /...
#![feature(async_closure)] #![feature(array_map)] #![feature(test)] use vujio::*; #[cfg(test)] mod tests; #[derive(Clone)] struct AppState { client_bundle: String, } #[derive(Serialize, Deserialize, Debug)] struct ClientState { some_string: String, } #[server("127.0.0.1:8080", AppState, ClientState)] #[asy...
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use anyhow::Context; use crate::mp::threads::worker::Worker; use crate::upgrade::send_stream_upgrade_context::SendStreamUpgradeC...
#[macro_use] pub mod macros; pub mod grib_reader; pub mod predictor; pub mod footprint; pub mod point; pub mod dataset_reader; pub mod guidance; pub use predictor::grib_reader::*; pub use predictor::predictor::*; pub use predictor::footprint::*; pub use predictor::point::*; pub use predictor::dataset_reader::*; pub u...
use ggez::{graphics, Context, GameResult}; use ggez::event::{self, EventHandler}; pub struct MyGame { // Your state here... } impl MyGame { pub fn new(_context: &mut Context) -> MyGame { // Load/create resources such as images here. MyGame { // ... } } } impl EventHand...
mod app; mod chatwheel; mod configure; mod consts; mod line; mod pulseaudio; use std::error::Error; use crate::app::{forward_audio, play_audio_file, App}; use crate::chatwheel::Chatwheel; pub struct Settings { forward_to_mic: bool, play_id: Option<String>, profile: Option<String>, } impl From<clap::ArgM...
// This file is part of Substrate. // Copyright (C) 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 // // http://www.a...
// Copyright 2019 German Research Center for Artificial Intelligence (DFKI) // Author: Clemens Lutz <clemens.lutz@dfki.de> // // 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 you...
//! Platform-specific devices. pub mod pp;
use std::borrow::Cow; use crate::{ProtocolSupportDecoder, ProtocolSupportEncoder}; impl<'a, T> ProtocolSupportEncoder for Cow<'a, T> where T: ProtocolSupportEncoder + ToOwned + ?Sized, T::Owned: ProtocolSupportEncoder, { fn calculate_len(&self, version: &crate::ProtocolVersion) -> usize { match se...
use serde::Deserialize; #[derive(Deserialize, Debug)] pub struct Catalogue { pub name: String, pub secondary_name: String, pub pk: u32, pub url: String, pub source_url: String, pub description: String, pub rows: String, } pub mod activity { use super::Deserialize; /// Activities a...
// * Daily Coding Problem April 11 2021 // * [Medium] -- Google // Given a singly linked list and an integer k, remove the kth last element from the list. // k is guaranteed to be smaller than the length of the list. // The list is very long, so making more than one pass is prohibitively expensive. use std::collect...
#![allow(unused_imports)] #![allow(unused_macros)] #![allow(non_snake_case)] #![allow(dead_code)] #![allow(unused_variables)] #![allow(unused_mut)] #![allow(unused_assignments)] use proconio::input; use proconio::marker::Usize1; use std::collections::*; use std::cmp::*; use std::f64::consts::*; const MOD: u64 = 100000...
#[doc = "Register `ST0CH1RST` reader"] pub struct R(crate::R<ST0CH1RST_SPEC>); impl core::ops::Deref for R { type Target = crate::R<ST0CH1RST_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<ST0CH1RST_SPEC>> for R { #[inline(always)] fn from(read...
use crate::protos::zinctx::{QueryRequest, QueryResponse, Value}; pub fn send_request(proto: QueryRequest) -> QueryResponse { let mut response = QueryResponse::new(); let mut val = Value::new(); val.set_stringval("hello".to_string()); response.set_output(val); response }
// SPDX-FileCopyrightText: 2020 Sveriges Television AB // // SPDX-License-Identifier: Apache-2.0 use std::ffi::CStr; use std::fs::File; use std::ptr; use flate2::read::GzDecoder; use libc::{c_char, c_double, c_int, c_uchar, c_uint, c_void}; use resvg::{cairo, usvg}; mod parse; mod transition; use transition::Tree; ...
// SPDX-License-Identifier: Apache-2.0 // Copyright (c) The Starcoin Core Contributors use crate::{CliState, StarcoinOpt}; use anyhow::Result; use clap::Parser; use scmd::{CommandAction, ExecContext}; use starcoin_crypto::HashValue; /// Some commands for node manager. #[derive(Debug, Parser)] #[clap(name = "manager")...
struct Solution; impl Solution { fn h_index(citations: Vec<i32>) -> i32 { let n = citations.len(); let mut count: Vec<usize> = vec![0; n + 1]; for c in citations { let i = c as usize; if i < n { count[i] += 1; } else { coun...
use binary_search_for_range::*; // https://atcoder.jp/contests/abc174/submissions/15971483 fn main() { let n: usize; let k: i64; let a: Vec<i64>; text_io::scan!("{} {}", n, k); a = (0..n).map(|_| text_io::read!()).collect(); use std::cmp::Ordering::*; let ans = (0..1_000_000_001) .binary_search_by...
mod camera; mod controller; mod projection; mod view; pub use camera::Camera; pub use controller::CameraController; pub use projection::Projection; pub use view::View;
use matrix::{Scalar,Mat,RoCM,ResizableBuffer,PanelTranspose}; use thread_comm::ThreadInfo; use composables::{GemmNode,AlgorithmStep}; use std::marker::PhantomData; pub struct TransposingOutputPanel<T: Scalar, At: Mat<T>, Bt: Mat<T>, Ct: Mat<T> + ResizableBuffer<T> + RoCM<T> + PanelTra...
use serde::{Deserialize, Serialize}; use super::handler_id::HandlerId; use super::traits::Worker; /// Serializable messages to worker #[derive(Serialize, Deserialize, Debug)] pub(crate) enum ToWorker<W> where W: Worker, { /// Client is connected Connected(HandlerId), /// Incoming message to Worker ...
use std::collections::{HashMap, HashSet}; use std::fs::File; use std::io::Read; const SEA_MONSTER: &'static str = " # # ## ## ### # # # # # # "; fn main() { let mut buf = String::new(); let mut file = File::open("input").unwrap(); file.read_to_string(&mut buf).unwrap();...
use std::io::Result; use std::process::{Child, Command, ExitStatus, Output}; pub trait CommandLogExt { fn spawn_with_log(&mut self) -> Result<Child>; fn output_with_log(&mut self) -> Result<Output>; fn status_with_log(&mut self) -> Result<ExitStatus> { Ok(self.output_with_log()?.status) } } ...
use filedesc::FileDesc; use std::io::{IoSlice, IoSliceMut}; use std::os::unix::io::{AsRawFd, IntoRawFd}; use std::path::Path; use std::task::{Context, Poll}; use tokio::io::unix::AsyncFd; use crate::ancillary::SocketAncillary; use crate::{UCred, sys}; /// Unix seqpacket socket. /// /// Note that there are no function...
/// To check if the widget's label matches the given string. /// /// Example: /// /// ``` /// extern crate gtk; /// #[macro_use] /// extern crate gtk_test; /// /// use gtk::{Button, prelude::ButtonExt, prelude::LabelExt}; /// /// # fn main() { /// gtk::init().expect("GTK init failed"); /// let but = Button::new(); /// ...
/// lib.rs /// /// Collects all modules for the rust_game crate pub mod input; pub mod entity; pub mod level; pub mod misc; pub mod game; pub mod traits;
/// Sorts a slice in-place using /// [Quick sort](https://en.wikipedia.org/wiki/Quicksort), /// [Dual-Pivot Quicksort](https://www.researchgate.net/publication/259264490_Dual_pivot_Quicksort) /// All kinds of slices can be sorted as long as they implement /// [`PartialOrd`](https://doc.rust-lang.org/std/cmp/trait.Part...
use super::geometry::Ray; use super::geometry::RayIntersection; use super::geometry::Vec3; use std::f32; use std::option::Option; pub trait RayIntersect { fn intersect(&self, ray: Ray) -> Option<RayIntersection>; } #[derive(Copy, Clone)] pub struct Sphere { pub c: Vec3, // center pub r: f32, // radius ...
use std::io::BufWriter; use std::io::Write; fn main() { let iterations = std::env::args() .nth(1) .map(|s| s.parse::<usize>().unwrap()) .unwrap_or(10_000); let stdout = std::io::stdout(); let lock = stdout.lock(); let mut writer = BufWriter::new(lock); for _ in 0..iteratio...
use super::Err; use crate::ast::*; // use conch_parser::ast::builder::{Builder, RcBuilder}; // use conch_parser::lexer::Lexer; // use conch_parser::parse::Parser; use glob::glob as enumerate_glob; use std::path::PathBuf; pub(super) struct ResolverPass; impl super::Pass for ResolverPass { const NAME: &'static str...
use cgmath::Vector3; mod canvas; mod collision; mod ray; mod scene; mod shading; mod util; use self::canvas::Canvas; use self::scene::{scene_objects::Sphere, Scene}; const CANVAS_WIDTH: u32 = 200; const CANVAS_HEIGHT: u32 = 100; const CAMERA_DISTANCE: f64 = 100.0; const RAYS_PER_PIXEL: u64 = 100; fn main() { l...
mod router; mod rpc_map; use std::convert::TryFrom; use std::marker::PhantomData; use async_trait::async_trait; use protocol::traits::{Context, MessageCodec, MessageHandler, TrustFeedback}; use protocol::{Bytes, ProtocolResult}; use crate::endpoint::{Endpoint, EndpointScheme, RpcEndpoint}; use crate::message::Networ...
use std::env; use std::sync::mpsc; use std::thread; use std::thread::JoinHandle; use std::time::SystemTime; fn prime_by_euler(page: usize) -> Vec<usize> { let mut sieve: Vec<bool> = vec![false; page]; let mut prime_array: Vec<usize> = Vec::new(); for i in 2..page { if !sieve[i] { prime_array.push(i...
use data_encoding::BASE32_NOPAD; use hmacsha1::hmac_sha1; use std::time::SystemTime; #[cfg(feature = "wasm")] pub mod wasm; pub fn create_totp(key: &str) -> Result<u32, OtpError> { let now = SystemTime::now(); let time_since_epoch = now.duration_since(SystemTime::UNIX_EPOCH)?; create_otp(key, (time_since_...
// //! Copyright 2020 Alibaba Group Holding 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 ...
use super::logger; use clap::{App, ArgMatches, SubCommand}; use elba::{ cli::build, util::{config::Config, errors::Res}, }; use failure::ResultExt; use std::env::current_dir; pub fn cli() -> App<'static, 'static> { SubCommand::with_name("lock").about("Generates an elba.lock according to the manifest") } p...
use machine::state::State; /// prestore data pub fn presti(_state: &mut State, _x: u8, _y: u8, _z: u8) { // Nothing to do here :) }
use std::{ io::{Read, Write}, net::{SocketAddr, TcpStream}, }; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use crate::utils::MyResult; pub struct TcpClient { stream: TcpStream, version: TransporterVersion, } pub enum TransporterVersion { // TODO Support full version Intermedi...
pub mod ast_node; pub mod compilation_unit; use compilation_unit::CompilationUnit; use cao_lang::compiler as cc; use wasm_bindgen::prelude::*; #[wasm_bindgen] /// Init the error handling of the library pub fn init_error_handling() { #[cfg(feature = "console_error_panic_hook")] console_error_panic_hook::set_o...
use crate::*; #[derive(Clone, Debug, trans::Trans)] pub struct BoundingBox { pub bottom_left: Vec2F64, pub size: Vec2F64, } impl BoundingBox { pub fn top_right(&self) -> Vec2F64 { Vec2F64 { x: self.bottom_left.x + self.size.x, y: self.bottom_left.y + self.size.y, } ...
// Copyright 2019 Conflux Foundation. All rights reserved. // Conflux is free software and distributed under GNU General Public License. // See http://www.gnu.org/licenses/ // FIXME: find a better place for this file. use std::ops::{Deref, DerefMut}; /// To prevent automatic copy from leaking guarded value. /// Plea...
fn sort<T: Clone + PartialOrd>(list: &[T]) -> Vec<T> { if list.len() <= 1 { return list.to_vec(); } let left = list.slice(0u, (list.len() / 2)); let right = list.slice(left.len(), list.len()); return merge(sort(left).as_slice(), sort(right).as_slice()); } fn merge<T: Clone + PartialOrd>(left: &[T], right: &[T]...
use std::fmt::Debug; use std::path::Path; /// A source that can parse files to ASTs. pub trait SourceParser<AST> { type Error: Debug; /// Parse a string. fn parse_str(&self, source: &str) -> Result<AST, Self::Error>; /// Parse a file. fn parse_file<P: AsRef<Path>>(&self, path: P) -> Result<AST, S...
#[repr(u8)] enum Foo { Foo(u8), } fn main() { match Foo::Foo(1) { _ => (), } }
use failure::Error; use protocol::{Action, Delta, Id, Reaction, Scene, Value}; use serde_derive::{Deserialize, Serialize}; use std::collections::{HashMap, HashSet}; use yew::agent::{Agent, AgentLink, Context, HandlerId, Transferable}; use yew::format::Json; use yew::services::websocket::{WebSocketService, WebSocketStat...