text
stringlengths
8
4.13M
use core::cmp::min; use std::error::Error; use clap::ArgMatches; use regex::Regex; pub trait ModuloSignedExt { fn modulo(&self, n: Self) -> Self; } macro_rules! modulo_signed_ext_impl { ($($t:ty)*) => ($( impl ModuloSignedExt for $t { #[inline] fn modulo(&self, n: Self) -> Self...
use std::collections::HashMap; use logic::ChannelGroupValue; use rustc_serialize::json; use logic::fade::FadeTime; use piston_window::keyboard::Key; #[derive(Debug, Clone, RustcDecodable, RustcEncodable)] /// The version of a switch that is encodable for json pub struct JsonSwitch { /// The list of channel group...
use crate::dd_challenge::Solution; impl Solution { pub fn add_two_numbers_ii(l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>) -> Option<Box<ListNode>> { let mut stack1 = Vec::new(); let mut stack2 = Vec::new(); let mut l1 = l1; while let Some(l) = l1 { stack1.push(l...
fn main() { let goal = 19690720; let code = get_codes(); for noun in 0..=100 { for verb in 0..=100 { if calculate(code.clone(), noun, verb) == goal { println!("{}", 100 * noun + verb); std::process::exit(1); } } } } fn calculate(m...
use std::ffi::c_void; use std::mem::{size_of, transmute}; use std::ptr::null_mut; use std::rc::Rc; use gtk::prelude::*; use winapi::{ shared::{ minwindef::{LPARAM, LRESULT, UINT, WPARAM}, windef::HWND, }, um::{ shellapi::{Shell_NotifyIconA, NIF_ICON, NIF_MESSAGE, NIM_ADD, NOTIFYICON...
use std::collections::BinaryHeap; /// `Systems` builder #[derive(Default)] pub struct Builder { sys: BinaryHeap<Sys> } /// temporary system structure that stores /// a `System`'s `exe()` and `PRIORITY`. struct Sys { exe: crate::SysFn, ord: crate::Order, prep: PrepFn, flush: bool, } /// closure ...
#![allow(clippy::uninlined_format_args)] #[macro_use] mod macros; use syn::*; #[test] fn test_macro_variable_attr() { let tokens = pm2::Stream::from_iter(vec![ pm2::Tree::Group(Group::new(pm2::Delim::None, quote! { #[test] })), pm2::Tree::Ident(Ident::new("fn", pm2::Span::call_site())), pm2:...
use geom::{Distance, Duration, LonLat, Time}; use serde_derive::{Deserialize, Serialize}; #[derive(Serialize, Deserialize)] pub struct Trip { pub from: Endpoint, pub to: Endpoint, pub depart_at: Time, pub mode: Mode, // (household, person within household) pub person: (usize, usize), // (t...
use super::*; use nix::sys::stat; use nix::sys::time::{TimeVal, TimeValLike}; use std::fs; use std::os::unix::fs::{symlink, PermissionsExt}; use tempfile::TempDir; struct Setup { dir: TempDir, } impl Setup { fn path<P: AsRef<Path>>(&self, local: P) -> String { self.dir.path().join(local).to_string_lo...
use std::io; fn main() { loop { println!("\n::::::::::::::::::::::::::::::::::::::::::::::"); println!("Fahrenheit a Celsius: F/f"); println!("Celsius a Fahrenheit: C/c"); println!("Salir: q/Q"); println!("ingrese la opción: "); let mut entrada = String::new(); ...
use crate::common::*; pub(crate) struct RecipeContext<'a> { pub(crate) config: &'a Config, pub(crate) scope: BTreeMap<&'a str, (bool, String)>, pub(crate) working_directory: &'a Path, pub(crate) settings: &'a Settings<'a>, }
use super::lexer; use super::lexer::{FatToken, Position, Token}; use super::ast; use super::ast::AstNode; pub fn parse<I: IntoIterator<Item = FatToken>>(tokens: I) -> Option<Parser<I::IntoIter>> { let mut input = tokens.into_iter(); if let Some(first) = input.next() { Some(Parser { input, ...
pub fn missing_ranges(slice: &[i32]) -> Vec<String> { let mut v: Vec<String> = Vec::new(); let end = slice.to_vec().iter().fold(0i32, |s, i| { if *i == s+1 { v.push(s.to_string()); } else if *i != s { v.push(s.to_string() + "-" + &(*i-1).to_string()); } ...
use std::io; use std::io::prelude::*; fn main() -> std::io::Result<()> { let mut buf = [0; 64]; loop { let n = io::stdin().read(&mut buf)?; io::stdout().write(&buf[..n])?; } }
struct Solution; use std::collections::HashSet; impl Solution { fn min_time(n: i32, edges: Vec<Vec<i32>>, has_apple: Vec<bool>) -> i32 { let n = n as usize; let mut graph = vec![HashSet::new(); n]; for e in edges { let u = e[0] as usize; let v = e[1] as usize; ...
use conquer_once::spin::OnceCell; use cortex_m::{ Peripherals, peripheral::syst::SystClkSource, interrupt }; use cortex_m_rt::exception; use crossbeam_queue::ArrayQueue; use heapless::binary_heap::{BinaryHeap, Min}; use heapless::consts::*; use crate::task::waker::TimerWaker; static mut COUNT: u64 = 0; s...
mod cpu; mod ppu; mod apu; mod io; mod cart; mod interconnect; mod opcode; mod integer_casting; use self::cpu::*; use self::interconnect::*; use minifb::{WindowOptions, Window, Key, Scale}; pub struct NES { cpu: NESCpu, interconnect: Interconnect, window: Window, } impl NES { pub fn new() -> NES { ...
use std::io; /* S2 .. S2 S1 * S3 . * . . * . S1 * S3 S4 .. S4 */ fn spiral_to_cart(i : i32) -> (i32, i32) { if i == 1 { return (0, 0); } let ring : i32 = (f64::from(i).sqrt().ceil() as i32) / 2; let ring_len = 2 * ring - 1; let ring_min = ring_len * ring_len; le...
use std::num::ParseIntError; use std::str::FromStr; use std::collections::HashSet; #[derive(Debug, PartialEq, Clone)] pub struct Instruction { name: String, arg: i32, } impl FromStr for Instruction { type Err = ParseIntError; fn from_str(s: &str) -> Result<Self, Self::Err> { let arg: i32 = s[...
//! This is the Server module for Xt. // 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 // published by the Free Sof...
use raindrops::raindrops; fn main() { println!("{}", raindrops(14)); }
use psyche_core::brain::{Brain, BrainActivityMap}; use psyche_core::brain_builder::BrainBuilder; use psyche_core::config::Config; use psyche_core::offspring_builder::OffspringBuilder; use serde_json::Result as JsonResult; #[inline] pub fn brain_to_json(brain: &Brain, pretty: bool) -> JsonResult<String> { if pretty...
use fs_extra::{self as fsx, dir as dirx}; use std::{ env, error::Error, fs, io::{Read, Write}, path::*, process::*, }; type BResult<T = ()> = Result<T, Box<dyn Error>>; #[cfg(target_os = "linux")] const SERVER_BUILD_DIR_NAME: &str = "alvr_server_linux"; #[cfg(windows)] const SERVER_BUILD_DIR_N...
fn main() -> std::io::Result<()> { use perf_event::events::Hardware; use perf_event::{Builder, Group}; let mut group = Group::new()?; let cycles = Builder::new() .group(&mut group) .kind(Hardware::CPU_CYCLES) .build()?; let insns = Builder::new() .group(&mut group) ...
use serde::Deserialize; use serde::Serialize; use super::coordinate::Coordinate; use super::position::Position; /// Mathematical set numbers. #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] pub enum NumberSet { /// [Natural numbers](https://en.wikipedia.org/wiki/Natural_number), here including **0**. ...
/* Copyright 2018 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...
#![feature(stmt_expr_attributes, proc_macro_hygiene)] fn main() { tracing_subscriber::fmt().init(); fn call(v: &&&str) { emit::info!("Logging with a deeply nested {value: ***v}"); emit::info!("Logging with a deeply nested {#[emit::as_display] value: v}"); } }
use bevy::{ diagnostic::{DiagnosticId, Diagnostics}, prelude::*, ui, }; use crate::DebugIgnore; #[derive(Debug)] pub struct DiagnosticList { style: Style, } #[derive(Debug)] pub struct DiagnosticListItem { id: DiagnosticId, } #[derive(Debug, Clone)] pub struct Style { pub font: Handle<Font>,...
use std::io; use actix::Message; use byteorder::{BigEndian, ByteOrder}; use bytes::{BufMut, BytesMut}; use serde_derive::{Deserialize, Serialize}; use serde_json::{from_slice, to_string}; use tokio_util::codec::{Decoder, Encoder}; use crate::messages::{UrlGetterMsg, UrlPasterMsg}; #[derive(Serialize, Deserialize, De...
pub mod config; pub mod error; pub mod parser; pub(crate) mod position; pub mod types; pub mod util; pub use htmlentity::entity;
extern crate rand; use rand::distributions::{Distribution, Normal, Standard, Uniform}; use rand::Rng; pub fn genRandomNum() { let mut rng = rand::thread_rng(); let n1: u8 = rng.gen(); let n2: u16 = rng.gen(); println!("Random u8: {}", n1); println!("Random u16: {}", n2); println!("Random u32: ...
fn main() { let array:[u32; 6] = [1,2,3,4,5,6]; let mut sum = 0; for x in array.iter() { sum += x; } println!("sum is {}", sum); let array_ref: &[u32] = &array; sum = 0; for x in array_ref { sum += x; } println!("sum is {}", sum); sum = 0; for x in &arra...
// ----------------------------------------------------------------------------- // Rust SECoP playground // // This program is free software; you can redistribute it and/or modify it under // the terms of the GNU General Public License as published by the Free Software // Foundation; either version 2 of the License, o...
// Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). #![deny(warnings)] // Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to...
use egui::*; pub fn plot_barchart( ui: &mut egui::Ui, size: Vec2, values: &[f32], top_value: f32, value_unit: &'static str, value_decimals: usize, ) -> egui::Response { let (rect, response) = ui.allocate_at_least(size, Sense::hover()); let style = ui.style().noninteractive(); let m...
use std::fmt; use std::str::FromStr; use svc_agent::AgentId; use uuid::Uuid; #[derive(Debug)] pub(crate) struct HandleId { rtc_stream_id: Uuid, rtc_id: Uuid, janus_handle_id: i64, janus_session_id: i64, backend_id: AgentId, } impl HandleId { pub(crate) fn rtc_stream_id(&self) -> Uuid { ...
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::cmp::Ordering; use std::rc::Rc; use crate::aast_defs::Tprim; use crate::ident::Ident; use crate::pos::Pos; use crate::typing_d...
use async_trait::async_trait; use crate::common::{Mission, SnapshotConfig, SnapshotPath}; use crate::error::Result; use crate::traits::{Diff, Key, Metadata, SnapshotStorage}; #[derive(Clone, Debug, Default)] pub struct SnapshotMetaFlag { pub force: bool, pub force_last: bool, } #[derive(Clone, Debug, Default...
use std::{ collections::{BTreeMap, BTreeSet}, ops::Range, }; use nimiq_collections::BitSet; use nimiq_keys::Address; use nimiq_primitives::{ coin::Coin, policy::Policy, slots_allocation::{JailedValidator, PenalizedSlot}, }; use nimiq_serde::{Deserialize, Serialize}; /// Data structure to keep trac...
// $ cargo run --bin ex5 fn main() { let (a, b) = { let mut s = String::new(); std::io::stdin().read_line(&mut s).unwrap(); let mut iter = s.split_whitespace().map(|i| i.parse::<i32>().unwrap()); (iter.next().unwrap(), iter.next().unwrap()) }; println!("{}", a + b); }
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::node::NodeService; use anyhow::Result; use starcoin_account_service::AccountService; use starcoin_chain_service::ChainReaderService; use starcoin_config::NodeConfig; use starcoin_dev::playground::PlaygroudService; use sta...
use async_trait::async_trait; use tonic::{transport::Channel, Request}; use super::{proto::*, CompactionRuntime}; use crate::error::Result; type CompactionClient = compaction_client::CompactionClient<Channel>; pub struct RemoteCompaction { client: CompactionClient, } impl RemoteCompaction { pub async fn new...
use std::collections::HashMap; use std::io::{Read, Seek}; use anyhow::{anyhow, Result}; use bevy::sprite::Rect; use byte::{BytesExt, TryRead}; use glam::Vec2; use modular_bitfield::prelude::*; use super::frames::Frames; #[derive(Debug)] pub struct MapElement { pub id: i32, pub origin_x: i16, pub origin_y...
use chrono::Weekday; use nom::character::complete::alpha1; use super::error::{ParseError, ParseResult}; use crate::period::Period; pub fn parse_weekday(input: &str) -> ParseResult<Period> { let (input, dim) = alpha1(input)?; match dim { "weekday" => Ok((input, Period::Weekday)), "weekend" => Ok((input, Period::...
use crate::Lexer; use crate::TokenType; use crate::Object; use crate::Container; use crate::traits::LexerTrait; use crate::traits::ParseTrait; use crate::traits::EvalTrait; use crate::traits::NamespaceTrait; use crate::Result; use crate::error::ParseError; /// Bool /// #[derive(Debug, Clone, PartialEq)] pub struct ...
use torrent_name_parser::Metadata; pub fn main() { let m = Metadata::from("Euphoria.US.S01E03.Made.You.Look.1080p.AMZN.WEB-DL.DDP5.1.H.264-KiNGS") .unwrap(); print!("Title: {}, ", m.title()); if m.is_show() { print!("Season: {}, ", m.season().unwrap()); print!("Episode: {}, ", m.epi...
use part1::part1; use part2::part2; mod part1; mod part2; fn main() { let input = include_str!("../assets/test.txt") .trim() .split('\n') .map(|s| { let mut split = s.split(' '); let on = match split.next().unwrap() { "on" => true, "...
use std::fmt::{Display, Formatter, Result as FmtResult}; use crate::http::StatusCode; use std::net::TcpStream; use std::io::{Write, Result as IoResult}; pub struct Response { status_code: StatusCode, body: Option<String>, } impl Response { pub fn new(status_code: StatusCode, body: Option<String>) -> Self...
#![warn(clippy::all, clippy::pedantic)] pub mod deck; pub mod error; pub mod format; use crate::deck::Deck; use crate::error::*; use base64::{decode, encode}; use integer_encoding::VarInt; /// Convert a Hearthstone deck code into a Deck struct pub fn decode_deck_code(deck_code: &str) -> Result<Deck, DeckCodeError> {...
use resol_vbus::chrono::prelude::*; pub struct TickSource { interval: i64, last_interval: i64, } impl TickSource { pub fn new(interval: i64, now: DateTime<UTC>) -> TickSource { let last_interval = if interval > 0 { now.timestamp() / interval } else { 0 }; ...
use std::env; mod data; use data::{Matrix, Row}; extern crate structopt; use structopt::StructOpt; #[derive(StructOpt)] #[structopt(name = "mse")] struct Opts { /// activation type (e.g. sigmoid, relu) acttype: String, #[structopt(short = "i", long = "in")] gradin: Option<String>, #[structopt(sho...
#[cfg(feature = "profiler")] use thread_profiler::profile_scope; use std::{fmt::Debug, str::FromStr}; #[derive(Debug, Clone, PartialEq, Eq)] pub enum Opcode { ADD(isize, isize, isize), MULT(isize, isize, isize), INPUT(isize), OUTPUT(isize), JNZ(isize, isize), JZ(isize, isize), LESS(isize, ...
extern crate time; extern crate regex; use std::collections::HashMap; use super::database::Matrix; mod template; #[derive(Debug, PartialEq)] pub struct Metric { pub name: String, pub value: i64, pub timestamp: u32, } impl Metric { pub fn new<T: AsRef<str>>(name: T, value: i64, time: &time::Timespec)...
use crate::error; use core::sync::atomic::{AtomicUsize, Ordering}; const HIGH_BIT: usize = !(usize::MAX >> 1); const MAX_FAILED_BORROWS: usize = HIGH_BIT + (HIGH_BIT >> 1); pub(super) struct BorrowState(AtomicUsize); /// Unlocks a shared borrow on drop. pub struct SharedBorrow<'a>(&'a BorrowState); impl Drop for Sh...
use crate::frontend::camera::Camera; use crate::frontend::glyph::Glyph; use crate::frontend::screen::grid::Grid; use crate::frontend::tileset; use crate::frontend::tileset::Tileset; use crate::frontend::ui::{draw_ui, UIElement}; use crate::geom::{Point, Vector}; use crate::client::network_client::NetworkClient; use cr...
#![feature(tool_lints)] #![warn(clippy::all)] use std::str::FromStr; struct Star { name: String, light_curve: Vec<i32>, } impl Star { fn group_brightness_values(&self) -> Vec<Vec<i32>> { let mut res: Vec<Vec<i32>> = Vec::new(); let mut iter = self.light_curve.iter(); let mut curr: i32 = *iter.next...
use std::fmt::Display; pub struct CompleteBinaryTree<T> where T: Copy + Ord + Display{ pub nodes: Vec<T>, } impl<T> CompleteBinaryTree<T> where T: Copy + Ord + Display { pub fn new(nodes: Vec<T>) -> CompleteBinaryTree<T> { CompleteBinaryTree { nodes: nodes } } fn left_idx(i: usize) -> usize ...
use actix_web::{App, HttpServer}; use actix_web_prom::PrometheusMetrics; use prometheus::{opts, IntCounterVec}; use teloxide::prelude::*; mod config; mod dispatch; mod metro; mod spending; mod weather; use config::Config; use dispatch::parse_messages; #[actix_web::main] async fn main() { let prometheus = Prometh...
use bevy::prelude::*; use bevy_asset_loader::{AssetCollection, AssetLoader}; /// This example demonstrates how you can use [AssetLoader::init_resource] to initialize /// assets implementing [FromWorld] after your collections are inserted into the ECS. /// /// In this showcase we load two textures in an [AssetCollectio...
// Copyright 2021 Parity Technologies // // 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 // except accor...
pub mod binding_builder; #[allow(dead_code)] #[allow(non_snake_case)] pub mod binding_glsl; pub mod pipelines; pub mod shader; pub mod uniformbuffer; pub fn compute_group_size(resource_size: wgpu::Extent3d, group_local_size: wgpu::Extent3d) -> wgpu::Extent3d { wgpu::Extent3d { width: (resource_size.width +...
use serde::Deserialize; use serde::Serialize; use std::cmp::Reverse; use std::fs::File; use std::io::BufReader; use std::io::Write; #[derive(Serialize, Deserialize)] pub struct Score { pub value: i16, } pub struct Scores { pub scores: Vec<Score>, } impl Scores { pub fn new(path: &str) -> Self { S...
// External crate imports use snafu::Snafu; // Standard library imports use std::io; use std::path::PathBuf; use std::str; #[derive(Debug, Snafu)] pub enum Error { #[snafu(display("Argument '{}' couldn't be parsed into a u64: {}", arg, source))] U64Parse { source: <u64 as str::FromStr>::Err, a...
use itertools::Itertools; use std::fs::File; use std::io::{BufRead, BufReader}; fn main() { part1(); part2(); } fn part1() { let reader = BufReader::new(File::open("res/day4.in").unwrap()); let unique_passphrases_count = reader .lines() .map(|line| { line.unwrap() ...
use std::collections::BTreeSet; use crate::genome::Genome; use crate::world::{Depot, Customer}; use rand::prelude::*; use std::i64::MAX; const PROB_MUTATION: f64 = 0.2; const FRAC_INSERT: f64 = 0.4; const FRAC_SWAP: f64 = 0.3; const FRAC_SCRAMBLE: f64 = 0.3; const PROB_CROSSOVER: f64 = 0.9; const FRAC...
// Stacked Borrows detects that we are casting & to &mut and so it changes why we fail //@compile-flags: -Zmiri-disable-stacked-borrows use std::mem::transmute; #[allow(mutable_transmutes)] fn main() { unsafe { let s = "this is a test"; transmute::<&[u8], &mut [u8]>(s.as_bytes())[4] = 42; //~ ERRO...
use std::cmp::Ordering; use std::collections::HashMap; #[derive(Debug)] struct Cart { id: usize, position: Position, direction: Direction, next_turn_choice: TurnChoice, } #[derive(Clone, Debug, Eq)] struct Position { y: usize, x: usize, } impl Ord for Position { fn cmp(&self, other: &Posi...
#![cfg(all(test, target_os = "linux", not(target_env = "kernel")))] use std::os::raw::c_char; use std::ptr; #[test] fn is_selinux_enabled() { let r = unsafe { super::is_selinux_enabled() }; assert!(r == 0 || r == 1); } #[test] fn getcon() { let mut context: *mut c_char = ptr::null_mut(); let r = unsa...
extern crate speedtest_watchdog as speedtest; use std::net::TcpStream; use speedtest::csv::*; use speedtest::g_drive::file::*; const GOOGLE_DNS: &'static str = "8.8.8.8:53"; const FILE: &'static str = "speedtest.csv"; fn main() { let connected = TcpStream::connect(GOOGLE_DNS).is_ok(); println!("Connected: {...
use crate::{ProtocolSupportDecoder, ProtocolSupportEncoder, RangeValidatedSupport, VarNum}; impl ProtocolSupportEncoder for String { fn calculate_len(&self, _: &crate::ProtocolVersion) -> usize { VarNum::<i32>::calculate_len(&(self.len() as i32)) + self.len() } fn encode<W: std::io::Write>( ...
use std::{cell::Cell, fmt}; use crate::{Colour, Style}; /// An `DisplayANSI` includes a format function and a `Style` struct DisplayANSI<F: FnOnce(&mut fmt::Formatter) -> fmt::Result> { style: Style, f: Cell<Option<F>>, } impl<F: FnOnce(&mut fmt::Formatter) -> fmt::Result> fmt::Display for DisplayANSI<F> { ...
use chrono::Utc; use diesel::prelude::*; use uuid::Uuid; use actix_session::Session; use actix_web::{web, Error as ActixWebError, HttpResponse, Responder}; use diesel::result::Error as DieselError; use serde::{Deserialize, Serialize}; use crate::models::{Comment, NewComment, NewCommentWithID}; use crate::State; use c...
use tracker_sparql; fn main() { let query = "SELECT ?title nie:url(?u) WHERE { { ?u a nfo:FileDataObject } { ?u <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#Software> } { ?u <http://www.semanticdesktop.org/ontologies/2007/01/19/...
use std::vec::Vec; use std::time::Instant; use std::thread; use std::sync::{mpsc, Arc}; fn main() { println!("Hello, world!"); let stop: usize = 1000*1000*1000*1; let start = Instant::now(); let count = eratosthenes_single(stop); let end = start.elapsed(); println!("{}, {:?}", count, end); ...
extern crate occlum_dcap; use occlum_dcap::*; use std::convert::TryFrom; use std::io::Result; use std::str; struct DcapDemo { dcap_quote: DcapQuote, quote_size: u32, quote_buf: Vec<u8>, req_data: sgx_report_data_t, supplemental_size: u32, suppl_buf: Vec<u8>, } impl DcapDemo { pub fn new(re...
mod anchor; mod closest; mod from; mod normalize; mod special_path; pub use { anchor::*, closest::*, from::*, normalize::*, special_path::*, };
//use std::cmp::*; use std::collections::*; use std::io::*; use std::str::*; // scanner from https://codeforces.com/contest/1396/submission/91365784 struct Scanner { stdin: Stdin, buffer: VecDeque<String>, } #[allow(dead_code)] impl Scanner { fn new() -> Self { Scanner { stdin: stdin(),...
use ggez::graphics; use semeion::*; use serde::{Deserialize, Serialize}; use crate::{entity, game}; /// The kinds of pheromones an Ant can leave as entity offspring. #[derive( Debug, Hash, PartialEq, PartialOrd, Eq, Ord, Clone, Copy, Serialize, Deserialize, )] #[serde(rename_al...
use crate::bytes; pub fn repeating_key_xor( input: &bytes::Bytes, key: &bytes::Bytes, ) -> Result<bytes::Bytes, &'static str> { let repeated_key = (0..input.len()).fold(Vec::new(), |mut acc, idx| { let key_idx = idx % key.len(); acc.push(key[key_idx]); acc }); let xored = bytes::fixed_xor_bytes(...
pub fn median2d(img: Vec<Vec<f32>>, win_width: usize, win_height: usize) -> Vec<Vec<f32>> { let mut out = img.clone(); let img_height = img[0].len(); let img_width = img.len(); let mut window = vec![0f32; win_width * win_height]; let edgex = win_width / 2; let edgey = win_height / 2; for...
use lazy_static::lazy_static; use std::collections::HashMap; use url; #[cfg(target_arch = "wasm32")] lazy_static! { static ref ENV: HashMap<String, String> = { use stdweb::js; let env = js! { return ENV; }; let env: HashMap<String, _> = env.into_object().expect("ENV isn't a JS object").into...
use num_derive::FromPrimitive; #[derive(FromPrimitive)] pub enum StreamCtl { Encode = 0x0, Decode = 0x1, WriteModel = 0x2, ReadModel = 0x3, } #[derive(FromPrimitive)] pub enum EncodeCtl { Stream = 0x0, Model = 0x1, Archive = 0x2, Destination = 0x3, Algorithm = 0x4, Piggyback = ...
use crate::config::Config; use crate::error::ErrorKind; use console::Term; use failure::{bail, Error, ResultExt}; use git2::{BranchType, Delta, ObjectType, Oid, Repository}; use ignore::gitignore::{Gitignore, GitignoreBuilder}; use std::path::PathBuf; use structopt::{clap, StructOpt}; use tempfile::TempDir; mod config...
/* 2. Fixed XOR Write a function that takes two equal-length buffers and produces their XOR sum. The string: 1c0111001f010100061a024b53535009181c ... after hex decoding, when xor'd against: 686974207468652062756c6c277320657965 ... should produce: 746865206b696420646f6e277420706c6179 */ extern crate serializ...
pub mod v5; pub mod v6; pub mod v7; pub mod v8;
#[cfg(test)] mod unit_tests; mod util; mod client; mod server; use std::sync::mpsc; use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpStream, TcpListener}; pub fn network_init() -> SocketAddr { SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080) } pub fn send(stream:&mut TcpStream, content: &[u8]) { ...
//! Module token is generated by GoGLL. Do not edit extern crate lazy_static; use std::rc::Rc; use std::fmt; use lazy_static::lazy_static; use std::collections::HashMap; /// Token is returned by the lexer for every scanned lexical token pub struct Token { pub typ: Type, pub lext: usize, pub rext: usize, inpu...
use super::*; // _ _ ____ ____ _ _ // | | | | _ \/ ___|(_) __ _ _ __ __ _| | // | | | | |_) \___ \| |/ _` | '_ \ / _` | | // | |_| | __/ ___) | | (_| | | | | (_| | | // \___/|_| |____/|_|\__, |_| |_|\__,_|_| // |___/ pub struct UPSignalRuntimeRef<V> where V: Clone + ...
#[derive(Debug, PartialEq, Eq)] pub struct RawClassFile { pub minor_version: u16, pub major_version: u16, pub constant_pool_table: Vec<RawCpInfo>, pub access_flags: u16, pub this_class_index: u16, pub super_class_index: u16, pub interface_table: Vec<u8>, pub field_table: Vec<RawInfo>,...
// Copyright 2020 WHTCORPS 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 in writing, sof...
#[derive(Debug, Clone)] pub struct Pattern { length: usize, pub patterns: Vec<String>, pub counts: Vec<u64>, max_count: u64 } impl Pattern { pub fn new(genome: &str, k: usize) -> Pattern { let length = genome.len(); let mut patterns = Vec::<String>::new(); let mut counts = V...
use types::webview::Return; use types::webview::Return::*; pub fn board_string(board: &pleco::Board) -> Option<Result<Return, String>> { Some(Ok(BoardString {board_string: board.pretty_string()})) } pub fn legal_moves(board: &pleco::Board) -> Option<Result<Return, String>> { let moves_list: Vec<(String, u16)>...
use std::fmt; use std::ops::Bound; use chrono::serde::ts_seconds; use chrono::{DateTime, Utc}; use diesel::pg::PgConnection; use diesel::result::Error; use serde_derive::{Deserialize, Serialize}; use serde_json::Value as JsonValue; use svc_agent::AgentId; use uuid::Uuid; use crate::backend::janus::JANUS_API_VERSION; ...
extern crate itertools; extern crate kaiju_compiler_core as compiler_core; extern crate kaiju_core as core; pub mod processor; pub mod state; pub mod vm; use crate::vm::Vm; use core::error::*; use std::ffi::CString; pub fn load_cstring(address: usize, vm: &Vm) -> SimpleResult<String> { let p = vm.state().load_da...
use super::super::environment::Environment; use super::super::nodes::{get_depth_space, RuleNode}; use std::io::{self, Write}; pub struct RuleWriter<W> { w: W, depth: usize, } impl<W: Write> RuleWriter<W> { pub fn new(w: W, depth: usize) -> RuleWriter<W> { RuleWriter { w, depth } } pub fn ...
// This file is part of Substrate. // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Softwa...
use super::*; use crate::{ action::{Add, ColumnValueStat, Stats}, time_utils::timestamp_to_delta_stats_string, DeltaDataTypeLong, }; use arrow::{ array::{ as_boolean_array, as_primitive_array, as_struct_array, make_array, Array, ArrayData, StructArray, }, buffer::MutableBuffer, }...
use crate::{Object, Result, Literal}; use std::collections::HashMap; use std::fmt::{self, Debug, Formatter}; use std::hash::Hash; use std::borrow::Borrow; use super::Value; #[derive(Clone, Default)] pub struct AttrMap { literals: HashMap<Literal, Value>, // TODO: allow for `Text`s to be stored in `literals`. objec...
// 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...
pub mod sequential; pub mod module; pub mod linear; pub mod optimizer; pub mod array; pub mod variables; pub mod quantize; pub mod func;