text
stringlengths
8
4.13M
use std::fs; use std::io::{stdin, stdout, ErrorKind, Write}; /* ** SHOPLIST : ** ** First Rust project, practice only. ** This code is free to use, have fun :) */ fn add_to_list(file_content: &mut String) { let mut readed = String::new(); print!("What do you want to add to your list ? : "); stdout().flu...
use crate::cpu::cpu::CPU; impl CPU { pub fn add(&mut self, target: u8, use_carry: bool) -> u8 { let c_flag = if use_carry && self.reg.f.c { 1 } else { 0 }; let (_val, c1) = self.reg.a.overflowing_add(target); let (val, c2) = _val.overflowing_add(c_flag); self.reg.f.z = val == 0; ...
use geometry::Point; use models::Mouse; use std::hash::Hash; use std::hash::Hasher; #[derive(Copy, Clone, PartialEq, Debug)] pub struct Dot { pub point: Point, pub i: usize, pub j: usize, } impl Dot { pub fn new(i: usize, j: usize) -> Dot { Dot { point: Point { ...
use std::cmp::Reverse; use proconio::input; fn main() { input! { n: usize, x: usize, y: usize, z: usize, a: [u8; n], b: [u8; n], }; let mut math: Vec<usize> = (0..n).collect(); // stable math.sort_by_key(|&i| Reverse(a[i])); let mut eng = math.s...
pub struct Solution; impl Solution { pub fn bulb_switch(n: i32) -> i32 { (n as f64).sqrt().floor() as i32 } } #[test] fn test0319() { fn case(n: i32, want: i32) { let got = Solution::bulb_switch(n); assert_eq!(got, want); } case(3, 1); }
use P31::Primes; pub fn main() { let mut primes = Primes::new(); println!("Is {} a prime number? : {}", 53, primes.is_prime(53)); println!("Is {} a prime number? : {}", 1957, primes.is_prime(1957)); }
//! Contains the various decision tree learning algorithms. use std::{ collections::{BTreeMap, HashMap}, hash::Hash, iter::IntoIterator, marker::PhantomData, slice::Iter as SliceIter, vec::IntoIter as VecIter, }; pub mod c45; pub mod id3; pub mod id4; /// A collection of attributes. pub trait...
//! Module with all structs & functions charged of writing .dbf file content use std::fs::File; use std::io::{BufWriter, Write}; use std::path::Path; use byteorder::WriteBytesExt; use header::Header; use reading::TERMINATOR_VALUE; use record::RecordFieldInfo; use {Error, Record}; /// A dbase file ends with this byte...
//! # BAPS3 Protocol Library for Rust //! //! This library is organised as follows: //! //! ## Basics //! - The `util` module contains miscellaneous utility functions and macros; //! - The `proto` module contains low-level machinery for encoding and decoding //! BAPS3 messages. //! //! ## Clients and Servers //! - Th...
use crate::context::*; use crate::types::*; use crate::util::*; use lsp_types::request::ExecuteCommand; use lsp_types::*; pub fn organize_imports(meta: EditorMeta, ctx: &mut Context) { let file_uri = Url::from_file_path(&meta.buffile).unwrap(); let req_params = ExecuteCommandParams { command: "java.ed...
use std::unimplemented; use parser::mir::{Declaration, Expression, Module}; pub struct Interpeter<'module> { module: &'module Module, } pub struct State<'module> { module: &'module Module, call: Vec<Value<'module>>, } #[derive(Clone, PartialEq, Debug)] pub enum Value<'module> { Builtin(String), ...
use sevendays_crafting_calculator::do_the_thing; fn main() -> Result<(), anyhow::Error> { do_the_thing()?; // do_the_thing_2()?; Ok(()) }
use core::cell::RefCell; use core::mem; use core::ptr::{self, NonNull}; use intrusive_collections::container_of; use intrusive_collections::{LinkOps, RBTreeLink}; use liblumen_core::alloc::Layout; use crate::blocks::{Block, BlockRef, FreeBlock, FreeBlockRef, FreeBlocks}; use crate::sorted::{Link, SortKey, SortOrder,...
#[derive(Debug, PartialEq)] pub enum Prefix<'a> { Server { host: &'a str, }, User { nick: &'a str, username: Option<&'a str>, host: &'a str, }, } #[derive(Debug, PartialEq)] pub struct RawEvent<'a> { pub prefix: Option<Prefix<'a>>, pub command: &'a str, pub p...
// 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 agreed to ...
#[doc = "Reader of register BOOT7_CURR"] pub type R = crate::R<u32, super::BOOT7_CURR>; #[doc = "Writer for register BOOT7_CURR"] pub type W = crate::W<u32, super::BOOT7_CURR>; #[doc = "Register BOOT7_CURR `reset()`'s with value 0"] impl crate::ResetValue for super::BOOT7_CURR { type Type = u32; #[inline(always...
use crate::S; use wasm_bindgen::UnwrapThrowExt; use web_sys as web; #[derive(Debug)] pub struct VText { value: S, node: Option<web::Text>, } impl VText { pub fn new<V: Into<S>>(value: V) -> Self { VText { value: value.into(), node: None, } } pub fn create(&...
use std::fmt::Display; use crate::query_adaptor::QueryAdaptor; /// An opaque, monotonic generational identifier of a buffer in a /// [`PartitionData`]. /// /// A [`BatchIdent`] is strictly greater than all those that were obtained /// before it. /// /// [`PartitionData`]: super::PartitionData #[derive(Debug, Default,...
use std::io; fn main() { println!("Please enter a temperator followed by F (for Fahrenheit) and C (for Celsius)"); let mut temperature = String::new(); io::stdin() .read_line(&mut temperature) .expect("Failed to read line"); let temperature: f32 = temperature.trim().parse().unwrap(); ...
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub struct Rotor { map: String, notch: Option<char>, } impl Rotor { pub fn new(map: &str, notch: Option<char>) -> Rotor { Rotor { map: String::from(map), notch } } } pub struct Enigma { pub rotors: Vec<Rotor>, pub refrector: String, pub rotor_offsets: Vec<i32>, pub plugboard: S...
use encoding::Encoding; use fontmetrics::FontMetrics; use std::fmt; use std::sync::Arc; use units::{LengthUnit, UserSpace}; /// A font ready to be used in a TextObject. /// /// The way to get FontRef is to call /// [Canvas::get_font](struct.Canvas.html#method.get_font) with a /// [FontSource](trait.FontSource.html). I...
#![crate_name = "uu_od"] /* * This file is part of the uutils coreutils package. * * (c) Ben Hirsch <benhirsch24@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; use std::fs::File; use std::io::Re...
use crate::{integer::Integer, rational::Rational}; use core::ops::SubAssign; // SubAssign The subtraction assignment operator -=. // ['Rational', 'Rational', 'Rational::subtract_assign', 'no', [], ['ref']] impl SubAssign<Rational> for Rational { fn sub_assign(&mut self, rhs: Rational) { Rational:...
use super::prelude::*; fn join(nums: &[i32]) -> String { use std::fmt::Write; if nums.is_empty() { return String::new(); } let mut res = format!("{}", nums[0]); for num in &nums[1..] { res.push(','); let _ = write!(res, "{}", num); } res } #[command] pub async ...
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // [START import_declarations] use failure::{Error, ResultExt}; use fidl_fidl_examples_echo::{EchoRequest, EchoRequestStream, EchoServiceRequest}; use fuch...
use std::num::NonZeroU8; use std::collections::HashMap; #[derive(Clone)] pub struct Letters { inner: HashMap<char, NonZeroU8>, } impl Letters { pub fn from_string(string: &str) -> Result<Letters, ()> { let mut result = Letters::empty(); for (i, letter) in string.chars().enumerate() { ...
use std::{ io, sync::{Arc, Mutex, RwLock}, thread, }; /// Utility flag to help threads indicate to other threads that they should /// stop doing work. #[derive(Clone)] pub struct KeepGoing(Arc<RwLock<bool>>); impl KeepGoing { /// Creates a new `KeepGoing` with a default state of `true`. pub fn new...
mod ast; #[macro_use] mod error; pub mod evaluate; #[allow(dead_code)] pub mod internal; pub mod parser; pub mod traits; pub use ast::AST; pub use error::{SMError, SMResult}; pub use evaluate::{Context, Runner}; pub use traits::{ToTex, ToWolfram}; #[test] fn it_works() {}
use crate::entities::weapons; use crate::helpers::Logger; use crate::utils::{output, readable::Readable, texthash::TextHash}; use std::str::FromStr; use strum::AsStaticRef; #[derive(AsStaticStr)] pub enum EntityType { Weapon, } impl Default for EntityType { fn default() -> EntityType { EntityType::Wea...
#[derive(Debug)] struct Rectangle { width: u32, height: u32, } impl Rectangle { fn area(&self) -> u32 { self.width * self.height } fn can_hold(&self, target: &Rectangle) -> bool { self.width > target.width && self.height > target.height } } fn main() { let rectangle = Rect...
use crate::{types::*, utils::regex::SerializeRegex}; use onig::FindCaptures; use serde::{Deserialize, Serialize}; pub mod composition; use composition::{Composition, Group, MatchGraph}; use self::composition::GraphId; #[derive(Serialize, Deserialize, Debug)] pub struct TokenEngine { pub(crate) composition: Compo...
#[macro_use] extern crate rskafka_wire_format_derive; pub mod apis; mod data; mod error; mod request; mod response; pub use data::{ api_key::ApiKey, error::ErrorCode, record::{Record, RecordBatch}, BrokerId, }; pub use request::KafkaRequest; pub use response::KafkaResponse; #[cfg(test)] mod test_util...
//! General actions #![allow(unused_imports)] #![allow(dead_code)] use chrono::*; use bill::Currency; use icalendar::Calendar; use std::{env,fs}; use std::time; use std::fmt::Write; use std::path::{Path,PathBuf}; use util; use super::BillType; use storage::{Storage,StorageDir,Storable,StorageResult}; use project::...
#![feature(proc_macro_hygiene)] #[allow(unused)] #[derive(macro_test::DeriveMacro)] struct Test(#[test] u8); fn main() { macro_test::my_macro!(); macro_test::my_macro1!(); println!("{}", answer()); #[macro_test::attribute_macro_twice] println!("twice"); }
use bulletproofs::r1cs::{ConstraintSystem, R1CSError}; use curve25519_dalek::scalar::Scalar; use error::SpacesuitError; use value::AllocatedQuantity; /// Enforces that the quantity of v is in the range [0, 2^n). pub fn fill_cs<CS: ConstraintSystem>( cs: &mut CS, v: AllocatedQuantity, n: usize, ) -> Result<...
use crate::resource::Resource; use log::{error, info}; use std::io::{self, Error, ErrorKind, Read, Write}; use url::Url; pub struct Log {} impl Resource for Log { fn new(_: Url) -> Result<Log, crate::error::Error> { Ok(Log {}) } fn close(&mut self) {} } impl Read for Log { fn read(&mut self, ...
use std::collections::HashMap; use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard}; use std::time::{Duration, Instant}; use error::BannerError; #[derive(Clone, Debug)] pub struct HashCache<T> { cache: Arc<RwLock<HashMap<String, (T, Instant)>>>, duration: Duration, } impl<T> From<HashMap<String, (...
use std::io::{Read, Result as IOResult}; pub use crate::lump_data::brush_model::BrushModel; pub use crate::lump_data::face::Face; pub use crate::lump_data::vertex::Vertex; mod brush_model; mod face; mod vertex; #[derive(Clone, Copy, Debug)] #[repr(u8)] pub enum LumpType { Entities = 0, Textures = 1, Planes = 2...
use crate::topology::config::{ component::ExampleError, GlobalOptions, SinkDescription, SourceDescription, TransformDescription, }; use colored::*; use indexmap::IndexMap; use serde::Serialize; use std::collections::BTreeMap; use structopt::StructOpt; use toml::Value; #[derive(StructOpt, Debug)] #[structopt(re...
use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::ty::is_type_diagnostic_item; use clippy_utils::{find_macro_calls, is_expn_of, return_ty}; use rustc_hir as hir; use rustc_hir::intravisit::FnKind; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; ...
use aoc2020_rust::read_input; fn main() { let input_str = read_input(); part1(&input_str); part2(&input_str); } fn part1(input: &String) { let nums: Vec<i32> = input .lines() .map(|line| line.parse().expect("Input lines should all be integers.")) .collect(); for (i, x) in n...
// Authors: Matthew Bartlett & Arron Harman // Major: (Software Development & Math) & (Software Development) // Creation Date: October 27, 2020 // Due Date: November 24, 2020 // Course: CSC328 // Professor Name: Dr. Frye // Assignment: Chat Server // File...
use input_i_scanner::InputIScanner; fn main() { let stdin = std::io::stdin(); let mut _i_i = InputIScanner::from(stdin.lock()); macro_rules! scan { (($($t: ty),+)) => { ($(scan!($t)),+) }; ($t: ty) => { _i_i.scan::<$t>() as $t }; (($($t: ty),...
#[macro_export] macro_rules! r#kern_try { ($expr:expr) => { match $expr { mach::kern_return::KERN_SUCCESS => (), err_code => return ::std::result::Result::Err(::std::io::Error::from_raw_os_error(err_code).into()), } }; ($expr:expr,) => { r#kern_try!($expr) ...
/* * Copyright © 2019-today Peter M. Stahl pemistahl@gmail.com * * 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 a...
use std::convert::AsRef; use std::fs::File; use std::io; use std::io::prelude::*; use std::mem; use std::path::Path; use std::slice; #[derive(Debug, Clone)] pub struct Bitmap { width: usize, height: usize, compression: Compression, bit_count: usize, data: BitmapData, } impl Bitmap { /// Loads ...
use std::io::{Read, Write}; use std::net::TcpStream; use serde::Serialize; pub static OK_RESP: &[u8] = &[0x62, 0x6F, 0x6B]; pub fn new_log_add_req(name: &str) -> Vec<u8> { #[derive(Serialize)] struct Body { log_name: String, } let mut body = vec![0x00, 0x01]; let req = serde_cbor::to_vec...
use crate::Asset; /// How much someone is willing to exchange for an asset. #[derive( Clone, Debug, Default, Eq, Ord, PartialEq, PartialOrd, parity_scale_codec::Decode, parity_scale_codec::Encode, )] pub struct OfferRate<B> { asset: Asset, rate: B, } impl<B> OfferRate<B> { ...
/* origin: FreeBSD /usr/src/lib/msun/src/e_acosf.c */ /* * Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com. */ /* * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun Microsystems, Inc. bus...
use indexmap::{IndexMap, IndexSet}; use crate::{ dynamic::{Field, SchemaError}, registry::{MetaField, MetaType, Registry}, }; /// A GraphQL object type /// /// # Examples /// /// ``` /// use async_graphql::{dynamic::*, value, Value}; /// /// let query = Object::new("Query").field(Field::new("value", TypeRef::...
use crate::{ ast::{ self, Assignment, Ast, AstKind, AstString, Call, Identifier, Int, List, MatchCase, OrPattern, Struct, StructAccess, Symbol, Text, TextPart, }, builtin_functions::{self, BuiltinFunction}, cst::{self, CstDb}, cst_to_ast::CstToAst, error::{CompilerError, Compiler...
//! Visual state container. pub mod selection; pub trait StateGroup { const MASK: u32; } pub trait State { type Group: StateGroup; const VALUE: u32; } #[macro_export] macro_rules! state_group { ($([$group:ident: $mask:literal] = { $($state:ident = $value:literal),+ $(,)? })+) => { ...
//! This module defines the CommonTokens type, //! used to pass constants of type from `syn` to //! many functions in the `abi_stable_derive_lib::stable_abi` module. use proc_macro2::{Span, TokenStream as TokenStream2}; use std::{ cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}, marker::PhantomData, }; use c...
use super::{checkout::Checkout, subscription::Subscription, virtual_currency::VirtualCurrency}; use serde::Deserialize; /// Информация о покупке /// https://developers.xsolla.com/ru/api/v2/getting-started/#api_param_webhooks_payment_purchase #[derive(Debug, Deserialize)] pub struct PurchaseInfo { pub virtual_curre...
// This file was generated by gir (https://github.com/gtk-rs/gir) // from ../gir-files // DO NOT EDIT use crate::Session; use glib::object::Cast; use glib::translate::*; use std::fmt; glib::wrapper! { #[doc(alias = "SoupSessionAsync")] pub struct SessionAsync(Object<ffi::SoupSessionAsync, ffi::SoupSessionAsyn...
use super::{process, Config, SubCommand}; use alfred::ItemBuilder; use chrono::prelude::Local; pub fn run(x: SubCommand) { debug!("Starting in run"); let print_config; let mut config: Config; match x { SubCommand::Config { display, auth_token, number_pins, ...
#[test] fn test_struct_2d_members() { let origin_x = 0; let origin_y = 0; } struct Point { x: i32, y: i32, } #[test] fn test_immutable_struct() { let origin = Point { x: 0, y: 0 }; println!("the origin is at ({}, {})", origin.x, origin.y); } #[test] fn test_mutable_struct() { let mut poin...
//! //! //! Work Tock //! ========== //! //! A command line work tracking program. //! //! Use --help to get basic usage on the command line //! //! Basic Usage //! ---------- //! //! You can use this program to clockin //! //! work_tock -i <JobName> //! //! clockout //! //! work_tock -o //!...
use std::collections::HashMap; use logos::{Lexer, Logos}; use thiserror::Error; use crate::direction::Direction; use crate::op::Op; #[derive(Debug, Error)] pub enum AsmError { #[error("line {lineno}: parse error: {msg}")] Parse { lineno: usize, msg: String }, #[error("line {lineno}: code size overflow")...
use crate::errors::AppError; use crate::schema::*; use diesel::prelude::*; type Result<T> = std::result::Result<T, AppError>; #[derive(Queryable, Identifiable, Serialize, Debug, PartialEq)] pub struct User { pub id: i32, pub username: String, } // NOTE: Add bookmark for last page: 124 pub fn create_user(conn: &Sq...
// Fibonacci implementation using Rust's Iterator trait to find // the nth fibonacci number struct Fib { c: u64, n: u64 } impl Fib { fn new() -> Fib { Fib { c: 0, n: 1} } /// returns the nth number of the Fibonacci sequence #[allow(dead_code)] fn get_nth(index: usize) -> u64 { ...
#![feature(box_syntax, slice_get_slice)] use std::fs::File; use std::io::{self, Read, Write}; use std::ops::{Index, IndexMut}; use std::path::Path; use std::slice::SliceIndex; // Sizes pub const PAGE: usize = 0x100; pub const BANK: usize = PAGE * 256; pub const MEMORY: usize = BANK * 256; pub const FULL_MEMORY: usize...
use crate::auth; use crate::handlers::types::*; use crate::Pool; use actix_web::{web, Error, HttpResponse}; use actix_web_httpauth::extractors::bearer::BearerAuth; use crate::controllers::email_setting_controller::*; pub async fn update_email_details( db: web::Data<Pool>, auth: BearerAuth, space_name: web...
use std::ops::RangeInclusive; use crate::parser::errors::CustomError; use crate::parser::prelude::*; use crate::parser::trivia::from_utf8_unchecked; use toml_datetime::*; use winnow::combinator::alt; use winnow::combinator::cut_err; use winnow::combinator::opt; use winnow::combinator::preceded; use winnow::token::one...
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[cfg(feature = "Graphics_DirectX_Direct3D11")] pub mod Direct3D11; #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :...
#[doc = r"Value read from the register"] pub struct R { bits: u8, } #[doc = r"Value to write to the register"] pub struct W { bits: u8, } impl super::RXCSRH3 { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'...
use std::fmt; use std::str; use thiserror::Error; use super::term::prelude::{Atom, Encoded, Term, TypedTerm}; // The largest value as an integer of a latin-1 ASCII character const MAX_LATIN1_CHAR: u16 = 255; /// Represents the original encoding of a binary /// /// In the case of `Raw`, there is no specific encoding...
pub mod add; pub mod sub; pub fn version() { println!("math v0.0.1") }
export t; export create; export union; export intersect; export copy; export clone; export get; export equal; export clear; export set_all; export invert; export difference; export set; export is_true; export is_false; export to_vec; export to_str; export eq_vec; // FIXME: With recursive object types, we could imple...
extern crate hound; extern crate num; extern crate rustfft; use std::f32::consts::PI; use hound::{SampleFormat, WavReader, WavSamples, WavSpec, WavWriter}; use num::complex::Complex; use rustfft::FFTplanner; trait Signal { fn energy(self) -> f64; } impl<'a, R> Signal for WavSamples<'a, R, i16> where R: std:...
pub use std::{ fmt::{self, Display, Formatter}, process::Command, }; pub use structopt::StructOpt; pub use crate::{mode::Mode, opt::Opt};
use std::collections::HashMap; use llvm::*; use llvm::Attribute::*; use parser::*; use parser; use llvm::Function; pub fn generate_expression<'a, 'b>(node: &'b Expr, values: &'a HashMap<&String, &'a Arg>, builder: &'a CSemiBox<'a, Builder>, ...
//! This crate contains the API for the protocol of the analytics server. `Event` is the type which is sent to the //! analytics server. Here are some examples of `Event` structures using different `Message` variants: //! //! All Channels: {"received_time":"2017-05-01T21:21:01.070462025Z","serviced_time":"2017-05-01T21...
//! Max object notifications and infrastructure. use crate::symbol::SymbolRef; use core::ffi::c_void; /// A type that encapsulates the Max notify method signature, can be cast to /// `MaxMethod` and supplied as the `"notify"` class method for a class. pub type NotifyMethod<T> = unsafe extern "C" fn( x: *mut T, ...
#![recursion_limit = "512"] mod todo; use vgtk::ext::*; use vgtk::lib::gio::{ActionExt, ApplicationFlags, SimpleAction}; use vgtk::lib::gtk::*; use vgtk::{gtk, gtk_if, run, Component, UpdateAction, VNode}; use crate::todo::about::AboutDialog; use crate::todo::filter::Filter; use crate::todo::menu::AppMenu; use crate...
use crate::PyObjectRef; pub trait IntoObject where Self: Into<PyObjectRef>, { fn into_object(self) -> PyObjectRef { self.into() } } impl<T> IntoObject for T where T: Into<PyObjectRef> {}
use std::{usize, vec::Vec}; use std::any::Any; use statrs::distribution::Beta; use rand::random; use rand::distributions::Distribution; use rand::rngs::StdRng; use rand::{Rng, SeedableRng, thread_rng}; trait Replayable { fn as_any(&self) -> &Any; fn initialize(&mut self); fn play(&mut self) -> f64; fn...
use criterion::{black_box, criterion_group, criterion_main, Criterion}; use parser::lexer::Lexer; use parser::parser::Parser; use parser::resolver::Resolver; use parser::types::Pass; const PROGRAM: &str = "print \"HOLA\" and \"CHAU\"; print nil and \"HOLA\"; print \"HOLA\" and false; print false and \"HOLA\"; print ni...
use quicksilver::{ graphics::{Font, Image}, Error, Future, }; pub struct Images { pub empty_mino: Image, pub i_mino: Image, pub o_mino: Image, pub j_mino: Image, pub l_mino: Image, pub s_mino: Image, pub z_mino: Image, pub t_mino: Image, } pub struct Resources { pub font: F...
#[doc = "Reader of register CONFCHR1"] pub type R = crate::R<u32, super::CONFCHR1>; #[doc = "Writer for register CONFCHR1"] pub type W = crate::W<u32, super::CONFCHR1>; #[doc = "Register CONFCHR1 `reset()`'s with value 0"] impl crate::ResetValue for super::CONFCHR1 { type Type = u32; #[inline(always)] fn re...
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" {} pub type DevicePortalConnection = *mut ::core::ffi::c_void; pub type DevicePortalConnectionClosedEventArgs = *mut ::core::ffi::c_void; #[repr(transparent)] pub ...
use flo_script::*; use flo_script::gluon_host::*; use futures::stream; use futures::executor; #[test] pub fn read_input_stream_as_output() { let host = GluonScriptHost::new(); let input_x = FloScriptSymbol::with_name("x"); host.editor().set_input_type::<i32>(input_x); // S...
use std::sync::Arc; use std::sync::RwLock; use std::sync::mpsc::Receiver; use event::InputEvent; use buffer::Buffer; use client::Client; pub struct GenericClient { reciever: Receiver, buffers: Arc<RwLock<Vec<Buffer>>> } pub impl Client for GenericClient { fn new(buffers: Arc<RwLock<Vec<Buffer>>>, reciever...
#[doc = r"Value read from the register"] pub struct R { bits: u32, } #[doc = r"Value to write to the register"] pub struct W { bits: u32, } impl super::CC { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w m...
extern crate jlib; use jlib::address::traits::seed::SeedI; use jlib::address::types::seed::SeedBuilder; use jlib::wallet::wallet::{ WalletType }; fn main() { let passphrase = Some("Masterphrase"); let seed_builder = SeedBuilder::new(WalletType::SM2P256V1); let master_seed_hex = seed...
use super::*; use smart_pointer::ref_cell_demo::LimitTracker; use smart_pointer::ref_cell_demo::Messenger; use std::cell::RefCell; #[test] fn it_works() { assert_eq!(2 + 2, 4); } #[test] fn case_sensitive() { let query = "duct"; let contents = "\ Rust: safe, fast, productive. Pick three."; assert_eq!...
// treap aka randomized binary search tree // treap is a data structure that stores pairs (X, Y) in a binary tree in such a way: // it is a binary search tree by X and a binary heap by Y // references: // https://cp-algorithms.com/data_structures/treap.html use rand::Rng; use rand::distributions::{Distribution, Stand...
/* * Copyright (c) 2019, Piotr Pszczółkowski * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of condit...
fn sum (arr:&[u32]) -> Option<u32>{ let mut sum:u32 = 0; let max:u32 = 2147483648; let mut flag =false; for element in arr.iter(){ if max - sum < *element{ flag = true; break; } sum = sum + element; } if flag == true{ None }els...
//! mount provides a Datastore that has other Datastores //! mounted at various key prefixes and is threadsafe mod async_results; mod sync_results; use std::cmp::Ordering; use crate::datastore::{Datastore as DatastoreT, Read, Write}; use crate::error::DSError; use crate::key::Key; use crate::query::{self, QResult, Q...
use crate::{ structs::{CustomerData,DriverData} }; use solana_program::{ account_info::{next_account_info,AccountInfo}, entrypoint::ProgramResult, msg, program_error::ProgramError, pubkey::Pubkey, }; use borsh::{BorshSerialize,BorshDeserialize}; use std::io::ErrorKind::InvalidData; use crate::he...
fn add(x: i32, y: i32) -> i32 { x + y } fn add2() -> fn(i32, i32) -> i32 { |x, y| x + y } fn log(s: String) { println!("log: {}", s); } fn main() { log("sample".to_string()); println!("5 + 6 = {}", add(5, 6)); log( format!("7 + 10 = {}", add2()(7, 10)) ); }
#[derive(Debug)] pub struct Address { addr: u16 } impl From<[u8; 2]> for Address { fn from(opcode: [u8; 2]) -> Address { let [hi, lo] = opcode; Address { addr: ((hi as u16 & 0x0F) << 8) ^ lo as u16 } } } #[derive(Debug)] pub struct RegisterAndValue { register: usize...
use std::fmt; use std::iter::FromIterator; use std::collections::BTreeSet; const DIMS: usize = 9; const AREA: usize = DIMS * DIMS; struct Sudoku { board: [u32; AREA], unsolved_cells: Vec<usize>, coords: [(usize, usize); AREA], cols: [[u32; DIMS]; DIMS], rows: [[u32; DIMS]; DIMS], blocks: [[u32; DIMS];...
mod ch1 { pub mod ex1; pub mod read_lines; } use ch1::ex1::filter_duplicates; use ch1::ex1::filter_duplicates_sort_by_length; use ch1::ex1::only_duplicates; use ch1::ex1::queue_n_till_blank_line; use ch1::ex1::reverse_lines; use ch1::ex1::reverse_n_lines; fn main() { // reverse_lines("./poem.txt"); /...
use rand; use rand::Rng; command!(vend(_ctx, msg, args) { let mut goods = "some cheesy crackers/some nacho cheese Doritos/a Hershey bar/a Milky Way/a day old donut/a water bottle/a pack of condoms/a can of bepis/a Rice Krispy treat/a Reeses peanut butter cup/the latest One Punch Man volume/nude leaks of Raini/a st...
use std::fs; pub fn sum_fuel_01() -> i64 { let filename = "./src/aoc01/input.txt"; let contents = fs::read_to_string(filename).expect("Something went wrong reading the file"); let inputs = contents.lines().map(|num| num.parse::<i64>().unwrap()); let sum = sum_fuel_requirements_01(inputs); sum } pub fn sum_f...
#[must_use] pub fn timeit(label: impl Into<String>) -> impl Drop { use std::time::Instant; struct Guard { label: String, start: Instant, } impl Drop for Guard { fn drop(&mut self) { eprintln!("{}: {:.2?}", self.label, self.start.elapsed()) } } Guard...
use crate::prelude::*; use std::os::raw::c_void; use std::ptr; #[repr(C)] #[derive(Debug)] pub struct VkPipelineColorBlendStateCreateInfo { pub sType: VkStructureType, pub pNext: *const c_void, pub flags: VkPipelineColorBlendStateCreateFlagBits, pub logicOpEnable: VkBool32, pub logicOp: VkLogicOp,...