text
stringlengths
8
4.13M
/// An enum to represent all characters in the Tamil block. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum Tamil { /// \u{b82}: 'ஂ' SignAnusvara, /// \u{b83}: 'ஃ' SignVisarga, /// \u{b85}: 'அ' LetterA, /// \u{b86}: 'ஆ' LetterAa, /// \u{b87}: 'இ' LetterI, /// \u{...
mod builtin; mod state; use std::fmt; use serde::Serialize; use std::rc::Rc; use crate::rt::builtin::Builtin; use crate::rt::state::Runtime; use crate::syntax::symbol::{ImSymbolMap, Symbol}; pub fn run(func: FuncValue, opts: Opts) -> Result<Output, Error> { let mut ctx = Runtime::new(func, builtin::builtins(), ...
//! # The database (`*.fdb`) file format used for the core database (`CDClient`) //! //! Among the resource files distributed with the LEGO® Universe game client is //! a copy of the core database. This database includes information on all zones, //! objects, components, behaviors, items, loot, currency, missions, scri...
use super::SDTHeader; #[repr(packed)] #[derive(Clone, Copy, Debug)] pub struct SSDT { pub header: &'static SDTHeader, pub data: &'static [u8], } impl SSDT { pub fn new(header: &'static SDTHeader) -> Option<Self> { if header.valid("SSDT") { Some(SSDT { header: header, ...
use crate::components::Tabs; use crate::{ components::Token, data::MealPlans, date::format_date, root::{AppRoute, DataHandle}, services::{Error, MealPlansService, RecipeService}, }; use oikos_api::components::schemas::{RecipeList, RecipeListItem}; use yew::{prelude::*, services::fetch::FetchTask}; u...
#[derive(Clone, Copy, Debug, PartialEq)] pub enum Direction { Up, Down, Left, Right } impl Direction { pub fn get_opposite_direction(self) -> Direction { use self::Direction::*; match self { Up => Down, Down => Up, Left => Right, Right => Left, } } } #[cfg(test...
// pub enum InputMode { // Normal, // Editing // } pub struct App { pub input: String, pub current: usize, } impl Default for App { fn default() -> Self { App { current: 0, input: String::new(), } } }
use std::fs; struct PageResult { nextPage : u32, enemy : String // TODO: make this use the character type, // then we can use a factory to assign an enemy } struct PageData { text: String, nextPageOptions: Vec<u32>, battleInitiated: bool, enemy: String } fn read_page(page : u32) -> PageData { //...
use crate::{ websocket::{ main_subscriber::UpdateSubscribe, push_messages::{ PermissionIdSubjectAction, InternalMessage, PublicMessage, InnerInternalMessage, InnerPublicMessage, UserRoleCreated, RolePermissionCreated, }, }, constants::{...
// implements the IO compression and uncompression submodule pub enum Method { JPG, PNG, GIF, RAW, } pub fn compress(/*image*/ method: Method, file_name: &str) { }
use std::collections::LinkedList; use lexeme::Lexeme; use lexeme::OperatorType; use lexeme::VarType; use token_stream::TokenStream; /// Identify the token and return the corresponding lexeme /// ``` /// token_to_lexeme("if") = Lexeme::If /// ``` fn token_to_lexeme(token: &str) -> Lexeme { assert!(token.len() > 0)...
use std::fs::File; use std::io::prelude::*; use std::collections::{HashMap, HashSet}; use lazy_static::lazy_static; use regex::Regex; // map_part_1 tells which bag can be placed in which bags // map_part_2 tells which bag contains which bags fn parse_line(input: &str, map_part_1: &mut HashMap<String, Vec<String>>, ma...
fn read<T: std::str::FromStr>() -> T { let mut s = String::new(); std::io::stdin().read_line(&mut s).ok(); s.trim().parse().ok().unwrap() } fn read_col<T: std::str::FromStr>(n: u32) -> Vec<T> { (0..n).map(|_| read()).collect() } fn cnt(s:&String)->Vec<u32>{ let mut ret:Vec<u32> =vec![0;26]; fo...
use rand::Rng; fn initialize_cards() -> Vec<u8> { let mut cards: Vec<u8> = Vec::new(); for i in 1..14 { cards.extend(vec![i; 4]); } cards } fn initialize_player<R: Rng>(cards: &mut Vec<u8>, rng: &mut R) -> Option<Vec<u8>> { let mut player: Vec<u8> = Vec::new(); for _i in 0..2 { ...
use crate::usubtraction; // This File handles Screen Buffer calles. fn string_to_vec(w: usize, h: usize, string: &str) -> Vec<char> { let mut string: String = string.chars().map(|c| c).collect(); let len = string.len(); let space: String = (0..usubtraction(w, len)).map(|_| ' ').collect(); string.push_s...
use log::*; use std::sync::{Arc}; use super::ClaRW; use super::{ClaTrait, ClaBundleStatus}; use crate::system::{ SystemModules, BusHandle }; use crate::routing::*; use tokio::sync::mpsc::{Sender}; use tokio::sync::RwLock; use msgbus::{Message, MsgBusHandle}; use crate::bus::ModuleMsgEnum; use super::AdapterConfiguratio...
// (C) Copyright 2019-2020 Hewlett Packard Enterprise Development LP use std::convert::TryFrom; use crate::dockerfile_parser::Instruction; use crate::SpannedString; use crate::error::*; use crate::parse_string; use crate::parser::{Pair, Rule}; use crate::splicer::Span; /// A Dockerfile [`ARG` instruction][arg]. /// ...
//! Products Service, presents CRUD operations use diesel::connection::AnsiTransactionManager; use diesel::pg::Pg; use diesel::Connection; use failure::Error as FailureError; use validator::Validate; use r2d2::ManageConnection; use stq_types::{Alpha3, BaseProductId, CompanyPackageId, ProductPrice, ShippingId}; use e...
use entry::Entry; use rand::Rng; use rand::XorShiftRng; use std::cmp; use std::mem; use std::ops::{Add, Index, IndexMut, Sub}; use std::ptr; #[repr(C)] struct Node<T, U> { links_len: usize, entry: Entry<T, U>, links: [*mut Node<T, U>; 0], } const MAX_HEIGHT: usize = 32; impl<T, U> Node<T, U> { pub fn...
use crate::errors::ConnectorXPythonError; use crate::pandas::destination::PandasDestination; use crate::pandas::typesystem::PandasTypeSystem; use chrono::{DateTime, NaiveDate, NaiveDateTime, Utc}; use connectorx::{ impl_transport, sources::oracle::{OracleSource, OracleTypeSystem}, typesystem::TypeConversion...
#![allow(dead_code)] use std::fs::File; use std::io::Read; pub const ADDRESS_SPACE: usize = ::std::u16::MAX as usize; pub const MEMORY_SIZE: usize = 1024 * 16; // 16KiB pub trait Memory { fn read_u8(&self, addr: u16) -> u8; fn read_u16(&self, addr: u16) -> u16 { (self.read_u8(addr + 1) as u16) ...
#[doc = "Register `TIM4_CCR6` reader"] pub type R = crate::R<TIM4_CCR6_SPEC>; #[doc = "Register `TIM4_CCR6` writer"] pub type W = crate::W<TIM4_CCR6_SPEC>; #[doc = "Field `CCR6` reader - CCR6"] pub type CCR6_R = crate::FieldReader<u16>; #[doc = "Field `CCR6` writer - CCR6"] pub type CCR6_W<'a, REG, const O: u8> = crate...
use super::super::super::context::{Context, ParentOrRoot}; use super::super::super::error::*; use super::super::super::traits::WorkType; use super::super::super::utils::station_fn_ctx2; use super::super::super::work::{WorkBox, WorkOutput}; use conveyor::{into_box, station_fn, WorkStation, Chain}; use conveyor_work::pac...
enum IpAddrKind { V4(String), // 带参数的成员 V6(String), } struct IpAddr { kind: IpAddrKind, address: String, } fn main() { let homev4 = IpAddrKind::V4(String::from("127.0.0.1")); let homev4 = IpAddrKind::V6(String::from("::1")); }
extern crate nfa; use nfa::*; #[test] fn test() { let re = Regex::Dot; let fa = re.make_fa(); for c in &['a', ' ', 'é'] { let mut s = String::new(); for len in 0..100 { assert!(fa.accepts(&s) == (len == 1)); s.push(*c); } } }
use block::Block; use module::Module; use util::opacity_to_hex; pub struct Bar { pub update_interval: u64, blocks: Vec<Box<Block>>, modules: Vec<Module>, separator: Option<String>, background: Option<String>, background_opacity: Option<String>, foreground: Option<String>, foreground_opa...
fn fn_largest (list: &[i32]) -> i32 { let mut largest = list[0] ; for &item in list { if item > largest { largest = item ; } } largest } fn main() { // Listing 10-1: Code to find the largest number in a list of numbers let number_list = vec![34, 50, 25, 100, 65] ; let mut largest = number_list[0] ; ...
use tiled; use graphics; use physics as p; use conniecs::Entity; use wrapped2d::user_data::UserData; pub use tilemap::chunks::{Chunk, Chunks}; pub use tilemap::layer::Layer; pub use tilemap::tilesets::Tilesets; pub mod chunks; pub mod layer; pub mod tilesets; pub struct Map { pub tilesets: Tilesets, pub l...
#[macro_use] extern crate serde_struct_wrapper; #[macro_use] extern crate text_io; pub mod api; pub mod util; pub mod workspace; use api::*; use console::style; use crossbeam_channel::unbounded; use failure::bail; use futures::prelude::*; use futures::stream::futures_unordered::FuturesUnordered; use indicatif::Progr...
use dns; use endpoint; use std::fs::{rename, File, create_dir_all}; use std::io::{Read, Write}; use dirs; use std::path::PathBuf; use rand; pub fn load() -> u64 { let path = dirs::home_dir().unwrap_or(PathBuf::from("/")); let path = path.join(".devguard/clock"); if !path.exists() { store(1); ...
extern crate test; extern crate crc; extern crate rand; extern crate rocksdb; extern crate tempfile; mod bench_wal;
use alloc::boxed::Box; use core::any::Any; use core::cmp::Ordering; use core::fmt::Debug; /// The trait for Client Contexts pub trait ClientContext: ClientContextClone + Debug + ClientContextCmp {} #[doc(hidden)] /// Trait to clone a [`ClientContext`] pub trait ClientContextClone { /// Method to clone a [`ClientC...
use std::{collections::HashMap, hash::Hash}; struct Solution {} impl Solution { pub fn roman_to_int(s: String) -> i32 { let mut num = 0; let mut key : usize = 0; let number = s.as_bytes(); let hashMap : HashMap<char, u16> = HashMap::from([('I', 1), ('V', 5), ('X', 10), ('L', 50), ('C',...
#![feature(plugin)] #![plugin(rocket_codegen)] extern crate rocket; #[macro_use] extern crate rocket_contrib; #[macro_use] extern crate serde_derive; #[macro_use] extern crate diesel; extern crate r2d2; extern crate r2d2_diesel; mod db; mod schema; use rocket_contrib::{Json, Value}; mod user; use user::{User}; #[...
/// Indicate if a key is not zero. This trait must be implemented on keys /// used by the UpsertMut when a key is flagged as Identity (MS SQL). /// In such a case, the provider will check that property to /// determine if the entity must be inserted or updated. pub trait IsDefined { fn is_defined(&self) -> bool; } ...
/* * Datadog API V1 Collection * * Collection of all Datadog Public endpoints. * * The version of the OpenAPI document: 1.0 * Contact: support@datadoghq.com * Generated by: https://openapi-generator.tech */ /// TargetFormatType : If the `target_type` of the remapper is `attribute`, try to cast the value to a n...
use io::i2c; pub fn power_off() -> ! { loop { i2c::write_byte(i2c::Device::MCU, 0x20, 0x1).unwrap(); } } pub fn reboot() -> ! { loop { i2c::write_byte(i2c::Device::MCU, 0x20, 0x4).unwrap(); } }
//! This build script compiles all shaders from `SHADER_SRC` into SPIR-V representations in //! `SPIRV_OUT`. use std::io::Read; const SHADER_SRC: &str = "assets/shaders"; const SPIRV_OUT: &str = "assets/generated/spirv"; fn main() -> Result<(), Box<dyn std::error::Error>> { use glsl_to_spirv::ShaderType; pr...
// Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>,...
// Copyright 2015, Paul Osborne <osbpau@gmail.com> // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/license/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 //...
use crate::migration::Migrations; use crate::snapshot::RocksDBSnapshot; use crate::transaction::RocksDBTransaction; use crate::{internal_error, Col, DBConfig, Result}; use ckb_logger::{info, warn}; use rocksdb::ops::{GetColumnFamilys, GetPinnedCF, GetPropertyCF, IterateCF, OpenCF, SetOptions}; use rocksdb::{ ffi, C...
extern crate editdistancewf as wf; #[cfg(test)] mod basic_distances { use wf; #[test] pub fn two_identical_sequences_have_a_distance_of_zero () { let left = "left"; let right = "left"; assert_eq!(wf::distance(left.chars(), right.chars()), 0) } #[test] pub fn simple_i...
use std::fmt; use std::error::Error; use std::collections::HashMap; use crate::http::Method; use crate::http::url::URL; // ERROR HANDLING ------------------- #[derive(Debug)] pub enum RequestError { NoHost } impl fmt::Display for RequestError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { ...
// This file was generated mod file_type_private { pub trait Sealed { } } /// Extension for [`FileType`](std::fs::FileType) pub trait IsntFileTypeExt: file_type_private::Sealed { /// The negation of [`is_dir`](std::fs::FileType::is_dir) #[must_use] fn is_not_dir(&self) -> bool; /// The negation of [`i...
use super::super::frame::{ Color, Pixel }; use super::shape::{ Coord, Shape }; pub struct Point { pub coord: Coord, pub color: Color } impl Shape for Point { fn to_pixels(&self) -> Vec<Pixel> { if self.coord.x < 0 || self.coord.y < 0 { vec![] } else { vec![Pixel::ne...
// Vectors are re-sizable arrays. Like slices, their size is not known at // compile time, but they can grow or shrink at any time. A vector is // represented using 3 parameters: // // - pointer to the data // - length // - capacity // // The capacity indicates how much memory is reserved for the vector. The // v...
extern crate winres; fn main() { // only run if target os is windows if std::env::var("CARGO_CFG_TARGET_OS").unwrap() != "windows" { return; } // only build the resource for release builds // as calling rc.exe might be slow if std::env::var("PROFILE").unwrap() == "release" { le...
// https://adventofcode.com/2018/day/5 use std::env; use std::fs::File; use std::io::prelude::*; // Iterates every unit of the input polymer, adding each to reacted_polymer. // If the last unit added to the reacted_polymer matches the opposite of the // current unit (e.g. 'a' opposite is 'A'), a reaction occurs and po...
#![warn(unused_crate_dependencies)] #![warn(clippy::pedantic)] #![warn(clippy::cargo)] #![allow(clippy::module_name_repetitions)] use crate::function::{ get_declared_runtime_package_version, get_main, is_function, ExplicitRuntimeDependencyError, MainError, }; use crate::layers::{RuntimeLayer, RuntimeLayerError...
use twitch_anon::TwitchAnon; fn main() { let anon = TwitchAnon::new() .add_channel("BareCoolCowSaysMooMah") .run(); loop { if let Ok(t_msg) = anon.messages.recv() { if t_msg.message.starts_with('!') { dbg!(&t_msg.message); let command = t_msg...
use crate::prettyprint::PrettyPrintable; use crate::prettyprint::PrettyPrintable::Atom; use crate::process::{Proc, Value, ProcCons, ValueCons}; #[derive(PartialEq, Clone, Copy, Debug)] pub enum BuiltInChannel { EqU, UToS, If, EqB, AndB, OrB, NotB, XorB, BToS, EqI, LeI, L...
//! This module is required in order to satisfy the requirements of defmt, while running tests. //! Note that this will cause all log `defmt::` log statements to be thrown away. use atat::AtatClient; use core::ptr::NonNull; use embedded_time::{rate::Fraction, Clock, Instant}; #[defmt::global_logger] struct Logger; imp...
use std::env; use std::path::PathBuf; extern crate bindgen; extern crate gcc; /// In order to build ChibiOS and generate bindings, ChibiOS must know about its chip type, /// its device type, and its port. Each of these things controls slightly different aspects /// of compilation. The port influences what files are c...
#![recursion_limit = "512"] mod app; mod counter; mod header; mod nav; mod progressbar; mod queue; mod table; mod wsding; use wasm_bindgen::prelude::*; use yew::prelude::*; use crate::app::Model; #[wasm_bindgen(start)] pub fn run_app() { App::<Model>::new().mount_to_body(); }
struct Foo <'a> { x: &'a i32, } impl <'a> Foo <'a> { fn x(&self) -> &'a i32{ self.x } } fn main() { let my_string = String::from("hello,world"); let word = first_word(&my_string[..]); let my_string_literal = "hello,world"; let word = first_word(&my_string_literal[..]); let wor...
//! # The XML `<AllSettings>` format //! //! This is use in: //! - The `res/ui/ingame/settings.xml` file
use std::io; use std::sync::mpsc::Sender; use std::sync::{Mutex, Arc}; #[derive(Debug)] pub enum InputMessage { Echo(String), Error, } pub fn input_loop(sender: Sender<InputMessage>, close: Arc<Mutex<bool>>) { let stdin = io::stdin(); loop { let mut input = String::new(); stdin.read_line(&mut input).unwrap()...
//! # Drivers //! Binary application drivers. #[cfg(feature = "postgres")] pub mod postgres; #[cfg(feature = "sqlite")] pub mod sqlite; use crate::core::{Csrf, Key, Service, User}; use chrono::{DateTime, Utc}; /// Driver errors. #[derive(Debug, Fail)] pub enum Error { /// Diesel result error wrapper. #[fail(d...
fn fac(n: u64) -> u64 { let mut num = 1; let mut i = 1; while i <= n { num = num * i; i+=1; } num } fn dec2_fact_string(nb: u64) -> String { let mut n = nb; let mut i = 1; let mut tab : Vec<String> = vec![]; while n > 0 { let mut num = n % i; ...
extern crate sevent; extern crate mio; use mio::net::TcpStream; use std::time::SystemTime; use std::rc::Rc; use std::cell::RefCell; use std::collections::HashSet; use sevent::iobuf::IoBuffer; struct Echo { connections: Rc<RefCell<HashSet<usize>>>, } impl sevent::ConnectionHandler for Echo { fn on_read(&mut...
// This file is part of Substrate. // Copyright (C) 2017-2020 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 F...
fn main() { let list = vec![2, 5, 3, 4, 1]; let sorted_list_bubble = bubble_sort(list.clone()); println!("Sorted List: {:?}", sorted_list_bubble); } fn bubble_sort(mut input_list: Vec<usize>) -> Vec<usize> { let n = input_list.len(); for i in 0..(n-1) { for j in 0..(n - i - 1) { ...
//! Tests auto-converted from "sass-spec/spec/non_conformant/errors/import/url" #[allow(unused)] use super::rsass; // From "sass-spec/spec/non_conformant/errors/import/url/control-else.hrx" #[test] fn control_else() { assert_eq!( rsass( "@if (false) {\r\ \n} @else {\r\ \...
pub use compute::*; pub use render::*; pub mod compute; pub mod render; use nalgebra::{Matrix4, Vector3, Vector4}; pub type Mat4 = Matrix4<f32>; pub type Vec4 = Vector4<f32>; pub type Vec3 = Vector3<f32>; pub trait QueryEmitters { fn query_emitters(&self) -> &Vec<Emitter>; } pub trait QueryProjView { fn qu...
//! Alphamask Adapator //use crate::math::blend_pix; use crate::color::Rgb8; use crate::color::Gray8; use crate::pixfmt::Pixfmt; use crate::Color; use crate::Pixel; use crate::Source; use crate::math::lerp_u8; use crate::math::multiply_u8; use crate::color::Rgba8; /// Alpha Mask Adaptor pub struct AlphaMaskAdaptor<T...
use criterion::Criterion; use primal::Sieve; fn warmup_100w() { // Prime@1000000 Sieve::new(15485863); } fn warmup_1000w() { // Prime@10000000 Sieve::new(179424673); } fn warmup_10000w() { // Prime@100000000 Sieve::new(2038074743); } pub fn warmup_benches(c: &mut Criterion) { c.bench_fun...
use std::io::{self, BufReader, BufRead}; use std::fs::File; use std::path::Path; pub mod ntt; pub mod packed; /** I/O util **/ pub fn read_input_to_u128(p : &Path) -> io::Result<Vec<u128>> { let f = File::open(p)?; let f = BufReader::new(f); let mut v: Vec<u128> = Vec::new(); for line in f.lines()...
// Copyright 2016 FullContact, Inc // // 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 accordin...
#[doc = "Register `HSEM_C1ISR` reader"] pub type R = crate::R<HSEM_C1ISR_SPEC>; #[doc = "Field `ISF` reader - ISF"] pub type ISF_R = crate::FieldReader<u32>; impl R { #[doc = "Bits 0:31 - ISF"] #[inline(always)] pub fn isf(&self) -> ISF_R { ISF_R::new(self.bits) } } #[doc = "HSEM i1terrupt statu...
//! ICMP protocol support and implementations. //! //! This package is useful for sending and receiving packets //! over the Internet Control Message Protocol (ICMP). It //! currently offers a simple API and implementation for `ping`. //! //! ## Installation //! //! Add this to your `Cargo.toml`: //! //! ```toml //! [d...
type NodeRef<T> = Box<Node<T>>; type NodeOption<U> = Option<NodeRef<U>>; #[derive(Debug)] pub struct Node<U> { val: U, next: NodeOption<U>, } impl<T> Node<T> { pub fn new(val: T, next: Option<NodeRef<T>>) -> Node<T> { Node { val, next, } } pub fn new_empty(v...
#[macro_use] extern crate criterion; use criterion::Criterion; use nom_edn::*; fn deps_edn(c: &mut Criterion) { let edn = include_str!("../fixtures/deps.edn"); c.bench_function("deps.edn", move |b| b.iter(|| edn!(&edn))); } fn unicode_char_found(c: &mut Criterion) { let chr = "\\u3F3A"; c.bench_fun...
use std::sync::{mpsc, Mutex, Arc}; use std::{thread, io}; use termios::{Termios, tcsetattr}; use termios::os::linux::{ICANON, ECHO, TCSANOW}; use termion::input::{TermRead}; use termion::event::Key::Char; use termion::event::Key as TermionKey; enum Mode { Line, Symbol, } #[derive(Debug, Eq, PartialEq, Hash)]...
use std::env; use image::{ImageBuffer, Rgb}; use itertools::izip; use rand::distributions::{Distribution, Standard}; use rand::{thread_rng, Rng}; use rayon::iter::ParallelIterator; use rayon::prelude::*; pub type Pix = Rgb<u8>; pub type ImgRgb = ImageBuffer<Pix, Vec<u8>>; fn euclidi<'a, T, U>(a: T, b: T) -> f32 wher...
// Copyright 2022. The Tari Project // SPDX-License-Identifier: BSD-3-Clause //! Schnorr Signature module //! This module defines generic traits for handling the digital signature operations, agnostic //! of the underlying elliptic curve implementation use core::{ cmp::Ordering, hash::{Hash, Hasher}, mark...
use std::iter; use quote::quote; use syn::{ parse::{self, Parse, ParseStream}, Expr, Block, Stmt, Ident, Token, }; use super::{decode_item, encode_item, Field, Item}; pub struct ExprIf { pub name: Option<Ident>, expr: syn::ExprIf, } impl Parse for ExprIf { fn parse(input: ParseStream) -> parse::...
use std::{collections::HashMap, fmt::Display, rc::Rc, sync::{Arc, RwLock}}; use chrono::{Local, NaiveDate, NaiveDateTime}; use hotplot::chart::line::{self, data::{PlotSettings, PlotThemeSettings, Settings, ThemeSettings}}; use iced::{Canvas, Clipboard, Column, Command, Container, Element, Length, PickList, Row, Text, ...
use std::collections::HashSet; use std::collections::HashMap; fn main() { let input = 361527; println!("Answer #1: {}", distance(input)); println!("Answer #2: {}", first_val_over(input)); } #[derive(PartialEq, Eq, Debug)] struct Node(i32, i32, Compass); impl Node { fn turn(&self) -> Node { mat...
use crate::block_hasher::BlockHasher; use crate::file_hash::FileHash; use blake2::{Blake2b, Blake2s}; use md5::Md5; use sha1::Sha1; use sha2::{Sha256, Sha512}; use std::fs::File; use std::path::{Path, MAIN_SEPARATOR}; use strum::IntoEnumIterator; use strum_macros::{EnumIter, EnumString, IntoStaticStr}; mod block_hasher...
// // Copyright (C) 2020 Abstract Horizon // All rights reserved. This program and the accompanying materials // are made available under the terms of the Apache License v2.0 // which accompanies this distribution, and is available at // https://www.apache.org/licenses/LICENSE-2.0 // // Contributors: // Daniel Send...
#![allow(dead_code)] use crate::intcode::*; const INTCODE_PATH: &str = "src/day5_input.txt"; pub fn solve_day_5_pt1() -> i64 { let input = std::fs::read_to_string(INTCODE_PATH).unwrap(); let mut machine = IntcodeMachine::from(&input); let mut ret = machine.step(Some(1)); //let mut count = 1; ...
use std::{thread, time}; use rust_ml::neuron::activations::{linear, relu, sigmoid}; use rust_ml::neuron::layers::Layer; use rust_ml::neuron::networks::Network; use rust_ml::neuron::transfers::dense; use rust_ml::rl::agents::NeuroEvolutionAgent; use rust_ml::rl::environments::JumpEnvironment; use rust_ml::rl::prelude::...
extern crate env_logger; extern crate libc; extern crate log; use std::ffi::CString; use std::iter; use bagua_core_internal::communicators::BaguaSingleCommunicator; use bagua_core_internal::datatypes::{BaguaBucket, BaguaTensor, BaguaTensorDtype}; use bagua_core_internal::BaguaCommBackend; use libc::c_char; use std::{...
mod util; use std::process::Command; use std::error::Error; use std::str::{FromStr}; use std::num::ParseIntError; use std::fmt::{Debug, Display, Formatter}; use std::thread; use std::time::{Duration, Instant}; use std::sync::{Arc, Mutex}; use crate::ResponseState::{Running, Success, Failed}; use crate::util::Config; ...
extern crate rand; extern crate x11_rs as x11; use x11::{Display, Event, Window, GC}; use x11::shm::ShmImage; use std::thread; use std::time::Duration; use rand::Rng; fn main() { let display = Display::open().unwrap(); let window = Window::create(&display, 640, 480).unwrap(); let gc = GC::create(&window)....
use crate::blob_bdev::BlobStoreBDev; use crate::env::Buf; use crate::generated::{ spdk_blob, spdk_blob_close, spdk_blob_get_id, spdk_blob_get_num_clusters, spdk_blob_id, spdk_blob_io_read, spdk_blob_io_write, spdk_blob_resize, spdk_blob_store, spdk_blob_sync_md, spdk_bs_alloc_io_channel, spdk_bs_create_blob...
mod comparison; mod subroutine; mod register_operations; mod register_i; mod misc; mod display; extern crate rand; use rand::Rng; pub struct CPU { registers: [u8; 16], memory: [u8; 4096], program_counter: usize, stack: [u16; 16], stack_pointer: usize, i: u16, seed: [u64; 4], display: ...
use std::collections::{BTreeMap, HashSet}; use std::fs::File; use std::io::{self, BufRead}; use std::iter::repeat; use std::path::PathBuf; use std::str; use std::task::Poll; use std::time::Duration; use std::{cmp, env}; use anyhow::{bail, format_err, Context as _}; use cargo_util::paths; use crates_io::{self, NewCrate...
use once_cell::sync::Lazy; use std::collections::HashMap; // This map has been filled from https://en.wikipedia.org/wiki/ISO_3166-1 pub static COUNTRIES_LANGS: Lazy<HashMap<String, Vec<&'static str>>> = Lazy::new(|| { [ // australia ("AU", vec!["en"]), // austria ("AT", vec!["de"]),...
use std::sync::atomic::{AtomicI64, AtomicU32, Ordering}; use std::sync::Arc; use crate::frame::Frame; #[derive(Debug, Clone)] pub(crate) struct StreamID { inner: Arc<AtomicU32>, } impl StreamID { pub(crate) fn new(value: u32) -> StreamID { let inner = Arc::new(AtomicU32::new(value)); StreamID...
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct KeyInfo { #[serde(rename = "Start")] pub start: String, #[serde(rename = "Expiry")] pub expiry: Str...
use criterion::{black_box, criterion_group, criterion_main, Criterion}; use timely::dataflow::operators::{Inspect, Map, ToStream}; const NUM_OPS: usize = 20; const NUM_ROWS: usize = 100_000; const STARTING_STRING: &str = "foobar"; trait Operation { fn name() -> &'static str; fn action(s: String) -> String; } ...
use std::collections::HashMap; use std::str::FromStr; /// Check if any rule matches `val` and hence it is a valid value. fn valid(val: u32, rules: &Vec<Rule>) -> bool { rules .iter() .flat_map(|rule| rule.1.iter()) .any(|&Range(start, end)| start <= val && val <= end) } fn challenge1(input...
use std::time::Duration; use crate::{ bson::doc, cmap::StreamDescription, coll::{ options::{CommitQuorum, CreateIndexOptions}, Namespace, }, concern::WriteConcern, index::{options::IndexOptions, IndexModel}, operation::{test::handle_response_test, CreateIndexes, Operation}, ...
extern crate presentrs; extern crate yew; use presentrs::Presentrs; use yew::prelude::*; fn main() { yew::initialize(); App::<Presentrs>::new().mount_to_body(); yew::run_loop(); }
use std::collections::HashMap; use aoc_runner_derive::*; #[derive(Debug)] struct Bag { description: String, contains: Vec<(usize, String)>, } impl Bag { fn parse(from: &str) -> Bag { let mut s = from.split(" contain "); let part1 = s.next().unwrap(); let part2 = s.next().unwrap();...
use super::item; pub struct DroppedItem { pub x: i32, pub y: i32, item: item::Item, } impl DroppedItem { pub fn new(x: i32, y: i32, item: item::Item) -> DroppedItem { DroppedItem { x, y, item } } pub fn item(&self) -> &item::Item { &self.item } pub fn into_item(self) ...
extern crate ewasm_api; extern "C" { pub fn bignum_add(input: *const u32, output: *mut u32); } #[cfg(not(test))] #[no_mangle] pub extern "C" fn main() { ewasm_api::consume_gas(500); let input = ewasm_api::calldata_acquire(); let mut output = [0u8; 64]; unsafe { bignum_add(input.as_ptr() as *...
#![macro_use] /// Gets the offset of a field. Used by container_of! macro_rules! offset_of( ($ty:ty, $field:ident) => { &(*(::std::ptr::null::<$ty>())).$field as *const _ as usize } ); /// Gets the parent struct from a pointer. /// VERY unsafe. The parent struct _must_ be repr(C), and the /// type passed to t...
use event_sauce::{ prelude::*, AggregateCreate, AggregateUpdate, CreateEventBuilder, Deletable, Entity, Event, EventData, Persistable, UpdateEventBuilder, }; use event_sauce_storage_sqlx::SqlxPgStoreTransaction; // use event_sauce::UpdateEntity; use event_sauce_storage_sqlx::SqlxPgStore; use sqlx::PgPool; use u...