text
stringlengths
8
4.13M
use diar::domain::{model::Favorite, repository::IRepository}; use super::inmemory::repository::Repository; #[test] pub fn test_add() { let repo = Repository::new(Vec::new()); let fav = Favorite::new("name1", "path1"); let added = &repo.add(&fav); assert_eq!(added.as_ref().unwrap().name(), fav.name(...
// === MATCH Control Flow === // /* Rust has an extremely powerful control flow operator called match that allows you to compare a value against a series of patterns and then execute code based on which pattern matches. Patterns can be made up of literal values, variable names, wildcards, and many o...
#![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 RegistryNameCheckRequest { pub name: String, #[serde(rename = "type")] pub type_: registry_name_check_r...
//! Pathfinder build script. //! //! Just sets up `vergen` to query our git information for the build. fn main() { // our Dockerfile is set up to a dependency only run, to cache a layer with all of the // dependencies downloaded. during that "DEPENDENCY_LAYER" environment variable is set, // and we shouldn...
use anyhow::Result; use chrono::{DateTime, Utc}; use env_logger; use getopts; use getopts::Options; use libc::_exit; use log::{info, warn}; use nix::fcntl::{open, OFlag}; use nix::sys::signal::{sigaction, SaFlags, SigAction, SigHandler, SigSet, Signal}; use nix::sys::stat::Mode; use nix::unistd::{ chdir, chroot, du...
mod custom_resource; mod daemon_deployment; use crate::operator::custom_resource::{add_finalizer, remove_finalizer}; use crate::operator::daemon_deployment::{create_or_update, destroy, DaemonDeployment}; pub use custom_resource::TorHiddenService; use custom_resource::TorHiddenServiceSpec; use futures::{future, FutureE...
use crate::schema::users; use chrono::NaiveDateTime; use diesel::pg::PgConnection; use diesel::prelude::*; use serde_derive::Serialize; #[derive(Clone, Debug, Queryable, Identifiable, Serialize, PartialEq)] pub struct User { pub id: i64, pub puid: String, pub first_name: String, pub last_name: String, ...
fn prime_factors(mut num: i64) -> Vec<i64> { let mut result = vec![]; let mut i = 2; while num > 1 { while num % i == 0 { result.push(i); num /= i; } i +=1; } result } #[test] fn prime_factors_of_48() { assert_eq!(prime_factors(48), [2, 2, 2, 2,...
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum Error { AccessDeniedError(crate::error::AccessDeniedError), AttributeLimitExceededError(crate::error::AttributeLimitExceededError), BlockedError(crate::error::BlockedError),...
use serde_json::Value; use crate::validator::{ scope::ScopedSchema, state::ValidationState, types::{validate_as_ipv4, validate_as_ipv6}, }; // https://github.com/balena-os/meta-balena/blob/v2.29.2/meta-resin-common/recipes-connectivity/resin-net-config/resin-net-config/resin-net-config#L34-L39 // // This ...
use cpu::Cpu; use mmu::Mmu; // Below are the macros for loading the value of a register (reg2) into another // register (reg1). macro_rules! ldrr ( ([ $($fname:ident $reg1:ident $reg2:ident),+ ]) => ( $( pub fn $fname (cpu: &mut Cpu) { cpu.register.$reg1 = cpu.register.$reg2; ...
#[doc = "Reader of register INTR_MASK"] pub type R = crate::R<u32, super::INTR_MASK>; #[doc = "Writer for register INTR_MASK"] pub type W = crate::W<u32, super::INTR_MASK>; #[doc = "Register INTR_MASK `reset()`'s with value 0"] impl crate::ResetValue for super::INTR_MASK { type Type = u32; #[inline(always)] ...
use lisp_core::lexpr; pub type Result<T> = std::result::Result<T, Error>; #[derive(Debug)] pub enum Error { IoError(std::io::Error), ParseError(lexpr::parse::Error), UnexpectedType(lexpr::Value), } impl From<std::io::Error> for Error { fn from(e: std::io::Error) -> Self { Error::IoError(e) ...
mod config; mod http; mod kafka; mod log; mod metrics; use crate::log::kflog; use clap::ArgMatches; use std::sync::Arc; use tokio::sync::oneshot; fn app_args<'a>() -> ArgMatches<'a> { return clap::App::new("kprf") .version(clap::crate_version!()) .about("Kafka Producer Proxy") .arg( ...
#[derive(Debug, PartialEq, Copy, Clone)] pub enum Direction { North, South, } impl Default for Direction { fn default() -> Direction { Direction::North } } #[derive(PartialEq, Debug, Clone)] pub struct CardString { pub color: String, pub number: i32, } #[derive(PartialEq, Debug, Copy,...
#![allow(clippy::wrong_self_convention)] use super::vk; use std::ffi::CStr; use std::marker::PhantomData; use std::ops::Deref; use std::os::raw::{c_char, c_int, c_void}; use std::ptr; pub trait Builder<'a> { type Type; fn builder() -> Self::Type; } impl<'a> Builder<'a> for vk::BaseOutStructure { type Typ...
pub trait BuilderExtManualGetObjectExpect { fn get_object_expect<T: glib::object::IsA<glib::object::Object>>( &self, name: &str, ) -> T; } impl<U: gtk::prelude::BuilderExtManual> BuilderExtManualGetObjectExpect for U where U: gtk::prelude::BuilderExtManual, { fn get_object_expect<T: gli...
pub fn run(){ // For non primitive vars use & to borrow it // &str read only borrow, ownership is not changed // &mut str mutable borrow, ownership is not changed let my_vec = vec![1,2,3]; let my_vec2 = &my_vec; println!("{:?}",&my_vec ); }
use std::convert::TryInto; use luminance::texture::Dim2; use luminance::texture::Flat; use luminance::framebuffer::Framebuffer; use gl; use luminance::context::GraphicsContext; use luminance::state::GraphicsState; pub use luminance::state::StateQueryError; // pub use luminance_windowing::{CursorMode, Surface, WindowDim...
use std::os::unix::io::RawFd; use std::sync::atomic::Ordering; use std::sync::Arc; #[cfg(feature = "io_timeout")] use std::time::Duration; use std::{io, ptr}; #[cfg(feature = "io_timeout")] use super::{timeout_handler, TimerList}; use super::{EventData, IoData}; use crate::scheduler::Scheduler; #[cfg(feature = "io_tim...
#[doc = "Register `PECR` reader"] pub type R = crate::R<PECR_SPEC>; #[doc = "Register `PECR` writer"] pub type W = crate::W<PECR_SPEC>; #[doc = "Field `PELOCK` reader - FLASH_PECR and data EEPROM lock"] pub type PELOCK_R = crate::BitReader; #[doc = "Field `PELOCK` writer - FLASH_PECR and data EEPROM lock"] pub type PEL...
use std::ptr; use assets::AssetBundle; use capi::common::parse_asset_id; use libc::c_char; use error::Error; ffi_fn! { fn dmbc_asset_create( id: *const c_char, amount: u64, error: *mut Error, ) -> *mut AssetBundle { let asset_id = match parse_asset_id(id) { Ok(id) ...
#[macro_use] extern crate log; extern crate env_logger; extern crate lapin_futures as lapin; extern crate futures; extern crate tokio; extern crate uuid; extern crate signin; use uuid::Uuid; use futures::future::Future; use futures::Stream; use tokio::executor::current_thread::{ self, CurrentThread }; use tokio::...
use std::{ fmt, ops::{Index, Range}, }; use super::TokenKind; #[derive(Clone, Copy, PartialEq)] pub struct Token { pub kind: TokenKind, pub span: Span, } impl Token { /// Get the token's text as a slice of the input string pub fn text<'input>(&self, input: &'input str) -> &'input str { ...
// This file is part of dpdk. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/dpdk/master/COPYRIGHT. No part of dpdk, including this file, may be copied, modified, propagated, or distributed except accordin...
//! Implements all outgoing status packets /* use super::super::super::deque_buffer::DequeBuffer; use super::super::super::game_connection::GameConnection; //It's super super super effective! use super::super::{ ID_STATUS_STC_RESPONSE, ID_STATUS_STC_PONG }; use super::OutgoingPacket; use rustc_serialize::json; mod r...
$NetBSD: patch-src_utils.rs,v 1.1 2023/07/13 20:38:53 pin Exp $ Allow building on NetBSD. --- src/utils.rs.orig 2023-04-20 21:37:30.000000000 +0000 +++ src/utils.rs @@ -1,7 +1,7 @@ use log::trace; use std::env; -#[cfg(any(target_os = "freebsd", target_os = "linux"))] +#[cfg(any(target_os = "netbsd", target_os = "...
use std::{ffi::OsStr, fs::File, path::Path}; use anyhow::Result; use flate2::{Compression, GzBuilder}; use polars::prelude::*; use crate::Rank; fn read_graph_by_poloars(path: &Path, rank: &Rank) -> Result<DataFrame> { let schema = Schema::new(vec![ Field::new("gene_1", DataType::Utf8), Field::new...
use crate::common::models::Event; use crate::frontend::routes::Table; use yew::{html, Html}; impl Table for Event { fn title() -> &'static str { "Events" } fn render_header() -> Html { html! { <tr> <th>{ "#" }</th> <th>{ "Name" }</th> ...
use bincode; use std::fs::File; use std::io::prelude::*; pub fn read_from_file(file: &str) -> Vec<u8> { let mut file: File = File::open(file).unwrap(); let mut buf: Vec<u8> = Vec::with_capacity(file.metadata().unwrap().len() as usize); file.read_to_end(&mut buf).unwrap(); buf } pub fn read_...
mod event; mod event_manager; mod event_reader; mod event_writer; mod glue; pub use event::{Axis, Button, Direction, Event, Key, KeyKind}; pub use event_manager::EventManager; pub use event_writer::EventWriter;
/// Args models our command line arguments pub struct Args { pub command: Option<String>, pub private_key: Option<String>, pub server: Option<String>, pub subject: Option<String>, pub message: Option<String>, pub exec: Option<String>, }
use crate::{AnyBin, BinSegment, Bytes128}; /// Trait used to build a binary efficiently (with just one allocation & no re-allocation or /// even without allocation). /// /// ```rust /// use abin::{NewBin, BinSegment, Bin, AnyBin, BinBuilder}; /// /// let mut builder = NewBin::builder(); /// builder.push(BinSegment::St...
use super::memory::{MemoryError}; use crate::microvm::memory::address::AddressType; mod traits { use crate::microvm::mmu::MMU; use crate::microvm::memory::address::AddressType; pub trait Regs<Reg> { type RegIdentifier; fn get_reg(&self, ident: u32) -> Reg; fn set_reg(&mut self, ide...
use crate::BlockingProvider; use sputnik::backend::{Backend, Basic, MemoryAccount, MemoryVicinity}; use ethers::{ providers::Middleware, types::{H160, H256, U256}, }; use std::collections::BTreeMap; /// Memory backend with ability to fork another chain from an HTTP provider, storing all state /// values in a...
//! Types for working with errors. use std::{error, fmt}; use std::ops::Deref; /// A specialized `Result` typedef. pub type Result<T = (), E = Error> = ::std::result::Result<T, E>; /// The error structure used by the Parenchyma crate. #[derive(Debug)] pub struct Error { kind: ErrorKind, /// A boxed sendable,...
use crate::tests::util::{ create_multi_outputs_transaction, create_transaction, create_transaction_with_out_point, gen_block, start_chain, }; use ckb_chain_spec::consensus::Consensus; use ckb_core::block::Block; use ckb_core::block::BlockBuilder; use ckb_core::cell::{BlockInfo, CellMetaBuilder, CellProvider, Ce...
fn main() { let input = std::fs::read_to_string("../input.txt").unwrap(); let count = input .split("\n") .filter(|s| { if s.is_empty() { return false; } let mut parts: Vec<&str> = s.split(": ").collect(); if parts.len() != 2 { ...
#[doc = "Reader of register SW_CMP_P_SEL"] pub type R = crate::R<u32, super::SW_CMP_P_SEL>; #[doc = "Writer for register SW_CMP_P_SEL"] pub type W = crate::W<u32, super::SW_CMP_P_SEL>; #[doc = "Register SW_CMP_P_SEL `reset()`'s with value 0"] impl crate::ResetValue for super::SW_CMP_P_SEL { type Type = u32; #[i...
fn increment_power(power: i32) -> i32 { println!("My power is going to increase:"); power + 1 } fn main() { let power = increment_power(1); println!("My power level is now: {}", power); }
#[macro_export] macro_rules! assert_ts_eq { ($lhs:expr, $rhs:expr) => {{ let lhs: TokenStream = $lhs; let rhs: TokenStream = $rhs; if lhs.to_string() != rhs.to_string() { panic!( r#"assertion failed: `(left == right)` left: ``` {} ``` right: ``` {} ``` "#, ...
// Copyright 2018-2019 Mozilla // // 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...
use num_enum::TryFromPrimitive; use strum_macros::Display; use super::chunk::Chunk; #[derive(Debug, Eq, PartialEq, TryFromPrimitive, Display)] #[repr(u8)] pub enum OpCode { Constant, Nil, True, False, Pop, GetLocal, SetLocal, GetGlobal, DefineGlobal, SetGlobal, Equal, G...
type FsmIndex = usize; const FSM_COLUMN_SIZE: usize = 130; const FSM_LINEEND: FsmIndex = 129; #[derive(Default, Clone, Copy)] struct FsmAction { next: FsmIndex, offset: i32, } #[derive(Clone)] struct FsmColumn { ts: [FsmAction; FSM_COLUMN_SIZE], } impl FsmColumn { fn new() -> Self { Self { ...
use crate::colors::{BLACK, BRIGHT_GRAY, GRAY, GREEN}; use crate::{LinePart, ARROW_SEPARATOR}; use ansi_term::{ANSIStrings, Style}; pub fn active_tab(text: String) -> LinePart { let left_separator = Style::new().fg(GRAY).on(GREEN).paint(ARROW_SEPARATOR); let tab_text_len = text.chars().count() + 4; // 2 for lef...
extern crate tokio; use tokio::io; use tokio::executor::thread_pool::ThreadPool; use tokio::prelude::*; struct Server { lst_socks: Vec<tokio::net::TcpListener>, clients: Vec<tokio::net::TcpStream>, } fn main() { // Create a thread pool with default configuration values let thread_pool = ThreadPool::...
extern crate clap; extern crate ldap3; use clap::{App, Arg, SubCommand}; use ldap3::{LdapConn}; use std::collections::HashSet; use std::iter::FromIterator; fn main() { let matches = App::new("navkafka-cli") .version("0.1") .author("Kevin Sillerud <kevin.sillerud@nav.no>") .about("Applicat...
use regex::Regex; pub trait IrcExt { fn is_channel_name(&self) -> bool; fn is_ctcp(&self) -> bool; fn remove_colorization(&self) -> String; } impl<'a> IrcExt for &'a str { fn is_channel_name(&self) -> bool { return self.starts_with('#') || self.starts_with('&') || sel...
fn get_int_from_file() -> Result<i32,String> { let path = "input.txt"; let num_str = std::fs::read_to_string(path).map_err(|err| err.to_string())?; num_str.trim().parse::<i32>().map(|t| t * 2).map_err(|err| err.to_string()) } fn main() { match get_int_from_file() { Ok(x) => println!("{}",x), ...
use crate::arch::sys::raw_syscall; use crate::obj::{objid_split, ObjID}; const SYS_ATTACH: i64 = 4; const SYS_BECOME: i64 = 6; const SYS_THREAD_SYNC: i64 = 7; const SYS_KCONF: i64 = 14; const SYS_THRD_CTL: i64 = 10; const SYS_INVL_KSO: i64 = 3; const SYS_OCREATE: i64 = 21; const SYS_KACTION: i64 = 11; const SYS_KEC_RE...
#![doc = "generated by AutoRust 0.1.0"] #[cfg(feature = "package-2020-09")] mod package_2020_09; #[cfg(feature = "package-2020-09")] pub use package_2020_09::{models, operations, API_VERSION}; #[cfg(feature = "package-2020-06-preview")] mod package_2020_06_preview; #[cfg(feature = "package-2020-06-preview")] pub use pa...
//! Contains definitions for the elementary operations. mod addition; pub use addition::Addition; mod multiplication; pub use multiplication::Multiplication;
fn main() { println!("Hello world!"); println!("How are you?") }
use diesel::r2d2::ConnectionManager; use diesel::mysql::MysqlConnection; pub type Conn = r2d2::PooledConnection<ConnectionManager<MysqlConnection>>; pub type Pool = r2d2::Pool<ConnectionManager<MysqlConnection>>; pub fn init_database_pool(database_url: &str) -> Pool { let manager = ConnectionManager::<MysqlConnec...
extern crate confy; #[macro_use] extern crate serde_derive; pub mod config;
/* 2 3 1 4 20 18 2 18 */ fn main() { let n = read(); let mut vec = read_line(); vec.sort_by(|a, b| b.cmp(a)); let mut alice = 0; let mut bob = 0; for i in 0..n as usize { if i % 2 == 0 { alice += vec[i]; } else { bob += vec[i]; } } print...
use docset::{DocSet, SkipResult}; use query::Scorer; use DocId; use Score; /// Creates a `DocSet` that iterator through the intersection of two `DocSet`s. pub struct Intersection<TDocSet: DocSet> { docsets: Vec<TDocSet>, finished: bool, doc: DocId, } impl<TDocSet: DocSet> From<Vec<TDocSet>> for Intersecti...
extern crate nalgebra as na; use na::Vector2; use nphysics2d::object::{DefaultBodySet, DefaultColliderSet}; use nphysics2d::force_generator::DefaultForceGeneratorSet; use nphysics2d::joint::DefaultJointConstraintSet; use nphysics2d::world::{DefaultMechanicalWorld, DefaultGeometricalWorld}; pub struct PhysicsWorld { ...
use std::cmp::min; use std::sync::Arc; use cgmath::prelude::*; use crate::prelude::*; use crate::interaction::SurfaceInteraction; use super::{ Bxdf, BxdfType }; use crate::interaction::Sample; use crate::sampler::ONE_MINUS_EPSILON; #[derive(Clone, Debug)] pub struct Bsdf { pub eta: Float, n_s: Normal, n_g:...
/// LeetCode Monthly Challenge problem for March 23rd, 2021. pub struct Solution {} impl Solution { /// Given an integer array arr, and an integer target, returns the number /// of tuples i, j, k such that i < j < k and arr[i] + arr[j] + arr[k] == /// target. /// /// As the answer can be very larg...
/* * Copyright (c) 2013, David Renshaw (dwrenshaw@gmail.com) * * See the LICENSE file in the capnproto-rust root directory. */ pub mod PrimitiveList { use layout::*; pub struct Reader<'self, T> { reader : ListReader<'self> } impl <'self, T : PrimitiveElement> Reader<'self, T> { pu...
mod data_lake_client; pub use data_lake_client::DataLakeClient; mod file_system_client; pub use file_system_client::FileSystemClient;
use crate::eval::prelude::*; impl Eval<&ast::ExprWhile> for ConstCompiler<'_> { fn eval( &mut self, expr_while: &ast::ExprWhile, used: Used, ) -> Result<Option<ConstValue>, crate::CompileError> { let span = expr_while.span(); while expr_while.condition.as_bool(self, use...
use socketcan_isotp::{self, IsoTpSocket, StandardId}; use std::time::Duration; fn main() -> Result<(), socketcan_isotp::Error> { let tp_socket = IsoTpSocket::open( "vcan0", StandardId::new(0x321).expect("Invalid rx id"), StandardId::new(0x123).expect("Invalid tx id"), )?; loop { ...
pub struct Xorshift32 { state: u32, } impl Xorshift32 { pub fn new(seed: u32) -> Xorshift32 { Xorshift32 { state: seed } } fn xorshift32(&mut self) -> u32 { self.state ^= self.state << 13; self.state ^= self.state >> 17; self.state ^= self.state << 5; self.state...
pub use gdk::prelude::*; pub use gio::prelude::*; pub use glib::prelude::*; pub use gtk::prelude::*; pub use std::convert::TryFrom; pub use super::builder::BuilderExtManualGetObjectExpect;
#[doc = "Reader of register TRIM_LDO_0"] pub type R = crate::R<u32, super::TRIM_LDO_0>; #[doc = "Writer for register TRIM_LDO_0"] pub type W = crate::W<u32, super::TRIM_LDO_0>; #[doc = "Register TRIM_LDO_0 `reset()`'s with value 0x58"] impl crate::ResetValue for super::TRIM_LDO_0 { type Type = u32; #[inline(alw...
// Need pub keyword to be able to use in main functions // Using super rather than an abolsute path starting with crate // is that using super may make it easier to update your code to have // a different module hierarchy // For example if we wrapped the in another module, the super would still work // #[derive(Debug...
pub trait IsModel { fn name(&self) -> String; fn next(&mut self); } pub struct BasicModel { pub name: String, } pub struct Model { basic: BasicModel, } impl Model { pub fn new(name: &str) -> Self { Self { basic: BasicModel { name: name.to_string(), ...
use crate::{Points, SplineOpts}; use wasm_bindgen::prelude::*; #[allow(clippy::too_many_arguments, non_snake_case)] #[wasm_bindgen] pub fn getCurvePoints( pts: Vec<f64>, num_of_segments: Option<u32>, tension: Option<f64>, custom_tensions: Option<Vec<f64>>, invert_x_with_width: Option<f64>, invert_y_with_he...
#[aoc_generator(day9, part1)] pub fn parse_program(input: &str) -> Vec<i64> { input .split(',') .map(|i| i.parse::<i64>().unwrap()) .collect() } #[aoc(day9, part1)] fn solve_p1(tape: &[i64]) -> i64 { let mut tape = tape.to_owned(); intcode_computer(&mut tape, &mut 0, &mut 0, || 1) }...
extern crate image; extern crate num_cpus; extern crate rand; mod geometry; mod material; mod math; use geometry::*; use material::*; use math::*; use rand::random; use std::path::Path; use std::sync::{mpsc, Arc, Mutex}; use std::thread; const DEFAULT_SAMPLES: usize = 16; const DEFAULT_W_PIXELS: usize = 1024; const...
impl super::Cpu { pub fn absolute(&mut self) -> usize { self.clock += 4; <usize>::from( ((self.read(self.pc + 2) as usize) << 8) + // high byte, little endian (self.read(self.pc + 1)) as usize // low byte ) } pub fn absolute_x(&mut self) -> usize { l...
use crate::task::ShowParams; use crate::task::TimeWindow; use structopt::StructOpt; use structopt_flags::ForceFlag; #[derive(Debug, StructOpt)] pub enum Cmd { /// Show all #[structopt(name = "show")] Show(ShowOpt), /// Work on the task database #[structopt(name = "database")] Db(DbOpt), ///...
use std::collections::{BTreeMap, BTreeSet}; type Grade = u32; type Students = BTreeSet<String>; type Database = BTreeMap<Grade, Students>; #[derive(Default)] pub struct School { database: Database, } impl School { pub fn new() -> School { Default::default() } pub fn add(&mut self, grade: ...
use std::fmt; #[derive(PartialEq, Clone, Copy)] pub enum Pixel { Transparent, Black, White, } impl From<char> for Pixel { fn from(c: char) -> Pixel { match c { '0' => Pixel::Black, '1' => Pixel::White, '2' => Pixel::Transparent, _ => unreachable!(), } } } impl fmt::Display f...
use std::ops::Range; use lazycell::LazyCell; use nalgebra::Vector3; use crate::geometry::Geometry; use crate::material::Material; use crate::ray::Ray; #[derive(Default)] struct Cache { point: LazyCell<Vector3<f64>>, normal_front: LazyCell<(Vector3<f64>, bool)>, } pub struct Intersection<'g> { t: f64, ...
use rayon::iter::plumbing::{ bridge_producer_consumer, Folder, Producer, ProducerCallback, Reducer, UnindexedConsumer, }; use rayon::prelude::*; use std::time::{Duration, Instant}; use tracing::{span, Level}; pub struct Deadline<I> { pub(super) base: I, pub(super) deadline: Duration, } struct DeadlineCall...
use rand; use rand::distributions::{IndependentSample, Range}; pub fn roll(count: i32, sides: i32) -> i32 { let mut rand = rand::thread_rng(); let sides_range = Range::new(1, sides + 1); let mut result = 0; for _ in 0..count { result += sides_range.ind_sample(&mut rand); } result }
// Re-export the public interface defined in sub-modules pub use ui::sdl2::display::Display; pub use ui::sdl2::controller::Controller; pub use ui::sdl2::audio::Audio; mod display; mod controller; mod audio;
#[doc = "Register `BMTRG` reader"] pub type R = crate::R<BMTRG_SPEC>; #[doc = "Register `BMTRG` writer"] pub type W = crate::W<BMTRG_SPEC>; #[doc = "Field `SW` reader - SW"] pub type SW_R = crate::BitReader; #[doc = "Field `SW` writer - SW"] pub type SW_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "F...
use crate::app::UpdateResult as UR; use crate::ui::{UpdateContext, Widget, WidgetInner}; use rider_config::ConfigAccess; use sdl2::rect::{Point, Rect}; const ICON_DEST_WIDTH: u32 = 16; const ICON_DEST_HEIGHT: u32 = 16; const ICON_SRC_WIDTH: u32 = 16; const ICON_SRC_HEIGHT: u32 = 16; pub struct SettingsButton { in...
#[doc = "Register `CR2` reader"] pub type R = crate::R<CR2_SPEC>; #[doc = "Register `CR2` writer"] pub type W = crate::W<CR2_SPEC>; #[doc = "Field `ADD` reader - Address of the USART node"] pub type ADD_R = crate::FieldReader; #[doc = "Field `ADD` writer - Address of the USART node"] pub type ADD_W<'a, REG, const O: u8...
use combat_action::Action; use unit_base::CanAttack; use rand::{thread_rng, Rng}; pub fn get_player_actions() -> Vec<Action> { let player_fight = Action { group_id: 0, action: Box::new(move |player, enemy| { let mut rng = thread_rng(); let outgoing_damage = rng.gen_range(2,...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 //use anyhow::Result; use anyhow::Result; use libra_types::account_address::AccountAddress; use network_libp2p::PeerId; use std::{ convert::TryFrom, str::FromStr, time::{SystemTime, UNIX_EPOCH}, }; pub fn convert_peer_i...
use std::{collections::HashSet, i32}; #[aoc_generator(day1, part2)] pub fn input_gen(input: &str) -> Vec<i32> { input.lines().map(|l| l.parse::<i32>().unwrap()).collect() } #[aoc(day1, part1)] pub fn solve_part1(input: &str) -> i32 { input.lines().map(|l| l.parse::<i32>().unwrap()).sum() } #[aoc(day1, part2)...
use crate::game::game::*; use crate::output::export::*; pub fn gradient_descent(game: &mut Game) { let learning_rate: f64 = 0.01; if game.step_nb < 1000 { game.step_nb += 1; let (srs_b_d, srs_m_d): (f64, f64) = calculate_srs_derivative(game); let b_step_size: f64 = srs_b_d * learning_ra...
#[doc = "Register `EXTICR2` reader"] pub type R = crate::R<EXTICR2_SPEC>; #[doc = "Register `EXTICR2` writer"] pub type W = crate::W<EXTICR2_SPEC>; #[doc = "Field `EXTI4` reader - EXTI x configuration (x = 4 to 7)"] pub type EXTI4_R = crate::FieldReader; #[doc = "Field `EXTI4` writer - EXTI x configuration (x = 4 to 7)...
#[doc = "Reader of register UART_CTRL"] pub type R = crate::R<u32, super::UART_CTRL>; #[doc = "Writer for register UART_CTRL"] pub type W = crate::W<u32, super::UART_CTRL>; #[doc = "Register UART_CTRL `reset()`'s with value 0x0300_0000"] impl crate::ResetValue for super::UART_CTRL { type Type = u32; #[inline(al...
use pulldown_cmark::{Options, Parser}; use super::front_matter::FrontMatter; #[derive(Debug, Clone)] pub struct Note { pub front_matter: FrontMatter, pub content: String } impl Default for Note { fn default() -> Self { Self { front_matter: FrontMatter::default(), content: S...
pub fn autogenerate_task_name(current_date: chrono::Date<chrono::Local>) -> String { current_date.format("task_%Y%m%d").to_string() } #[cfg(test)] mod tests { use super::*; use chrono::Local; use chrono::TimeZone; #[test] fn test_autogenerate_task_name() { let mut dt = Local.ymd(1970, ...
use tokio::fs::File; use super::consts::paths::CACHE_DIR_PATH; #[cfg(test)] mod tests; pub async fn extract_tar(file_path: &str) -> Result<(), std::io::Error> { use flate2::read::GzDecoder; use tar::Archive; let tar = File::open(file_path).await?.try_into_std().unwrap(); let tar = GzDecoder::new(tar...
struct Point { x: f64, y: f64, } enum MaybePoint { ThePoint(Point), Nil, } fn main() { let p1 = Point{x: 1.0, y: 2.0,}; let p2 = box() Point{x: 3.0, y: 4.0,}; let p3 = ThePoint(Point{x: 5.0, y: 6.0,}); let p4 = box() ThePoint(Point{x: 5.0, y: 6.0,}); println!("Point on stack: {}" , & p1); ...
#[doc = "Register `BSRR` writer"] pub type W = crate::W<BSRR_SPEC>; #[doc = "Field `BS0` writer - Port x set bit y (y= 0..15)"] pub type BS0_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `BS1` writer - Port x set bit y (y= 0..15)"] pub type BS1_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG...
use core::convert::TryInto; use atat::AtatClient; use embedded_hal::digital::{InputPin, OutputPin}; use embedded_time::{duration::*, Clock}; use heapless::{ArrayLength, Bucket, Pos}; use crate::{ client::Device, command::{ mobile_control::{types::Functionality, ModuleSwitchOff, SetModuleFunctionality}...
use std::collections::HashMap; fn main() { // Vectors have their own methods and are basically like arrays. let mut my_vec: Vec<i32> = Vec::new(); let my_vec_from_macro = vec![1, 2, 3, 4]; //let dne = my_vec_from_macro[100]; let mut scores = HashMap::new(); scores.insert(String::from("Blue T...
//! NOTE: this crate is really just a shim for testing //! the other no-std crate. mod framed; mod multi_thread; mod ring_around_the_senders; mod single_thread; #[cfg(test)] mod tests { use bbqueue::{BBBuffer, Error as BBQError}; #[test] fn deref_deref_mut() { let bb: BBBuffer<6> = BBBuffer::new(...
pub mod board; pub mod engine; pub mod game_repository; pub mod controller; pub mod errors;
pub fn part_01_slow(data: String) -> i32 { let numbers: Vec<i32> = data .split_whitespace() .map(|x| x.parse::<i32>().unwrap()) .collect(); for x in numbers.clone() { for y in numbers.clone() { for z in numbers.clone() { if x + y + z == 2020 { ...
use std::{ cmp, collections::{HashMap, VecDeque}, hash::{BuildHasherDefault, Hasher}, }; /// A fixed sized container that pops old elements as new ones arrive #[derive(PartialEq, Debug)] pub struct ByteBuffer<T> { pub vec: Vec<T>, limit: usize, } impl<T: std::marker::Copy> ByteBuffer<T> { // P...