text
stringlengths
8
4.13M
use std::ops::{Deref, DerefMut, Range, Add, AddAssign}; use std::borrow::Borrow; use std::mem::{self, MaybeUninit}; use std::fmt; use std::error::Error; use std::path::PathBuf; use std::sync::Arc; use std::hash::{Hash, Hasher, BuildHasher}; use std::collections::{HashMap, hash_map::{Entry, OccupiedEntry}}; use lsp_type...
pub use self::death::Dead; pub use self::explored::Explored; pub use self::fighter::Fighter; pub use self::health::Health; pub use self::init::Init; pub use self::intent::{Direction, Action, Intent}; pub use self::mob::Mob; pub use self::name::Name; pub use self::player::Player; pub use self::tile::Tile; mod death; mo...
use diesel::{Connection, SqliteConnection}; pub mod models; pub mod schema; pub fn establish_connection() -> SqliteConnection { let database_url = "data.sqlite"; SqliteConnection::establish(&database_url) .unwrap_or_else(|_| panic!("Error connecting to {}", database_url)) }
#[doc = "Register `SECCFGR3` reader"] pub type R = crate::R<SECCFGR3_SPEC>; #[doc = "Register `SECCFGR3` writer"] pub type W = crate::W<SECCFGR3_SPEC>; #[doc = "Field `LPTIM6SEC` reader - secure access mode for LPTIM6"] pub type LPTIM6SEC_R = crate::BitReader; #[doc = "Field `LPTIM6SEC` writer - secure access mode for ...
#[doc = "Register `AHB1ENR` reader"] pub type R = crate::R<AHB1ENR_SPEC>; #[doc = "Register `AHB1ENR` writer"] pub type W = crate::W<AHB1ENR_SPEC>; #[doc = "Field `GPDMA1EN` reader - GPDMA1 clock enable Set and reset by software."] pub type GPDMA1EN_R = crate::BitReader; #[doc = "Field `GPDMA1EN` writer - GPDMA1 clock ...
//! Example to demonstrate how to use the `keep_default_for` attribute. //! //! The generated `impl` blocks generate an item for each trait item by //! default. This means that default methods in traits are also implemented via //! the proxy type. Sometimes, this is not what you want. One special case is //! when the d...
/* * Knuth-Morris-Pratt string matcher (Rust) * * Copyright (c) 2021 Project Nayuki. (MIT License) * https://www.nayuki.io/page/knuth-morris-pratt-string-matching * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Softwa...
#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] use asynchronous_codec::{Decoder, Encoder}; use bytes::BytesMut; use prost::Message; use std::io::Cursor; use std::marker::PhantomData; use unsigned_varint::codec::UviBytes; /// [`Codec`] implements [`Encoder`] and [`Decoder`], uses [`unsigned_varint`] /// to prefi...
use crate::file::FileWriter; use std::collections::HashMap; use std::fs::{File, OpenOptions}; use std::io::{Error, Read, Write}; use std::path::PathBuf; use std::ptr::hash; use std::sync::{Arc, Mutex, RwLock}; pub struct Storage { child_count: Arc<Mutex<usize>>, storage_file: Arc<Mutex<StorageFiles>>, hash...
extern crate gio; extern crate gtk; use crate::xml_test::*; use gtk::{prelude::*, Widget, Container, Builder}; use std::collections::{HashMap}; use std::iter::FromIterator; macro_rules! class( { $type: ty, $class: literal } => { impl ComponentT for $type { fn class() -> &'static str { $class ...
extern crate cryptopals_lib; extern crate rusty_aes; use std::cmp::Ordering; use crate::cryptopals_lib::utils::file_io_utils; use crate::rusty_aes::decrypt::Decrypt; use crate::cryptopals_lib::hex; pub fn main() { let file_name = "challenge_files/8.txt"; //read file to string let input = file_io_utils...
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - RAMCFG memory 1 control register"] pub m1cr: M1CR, _reserved1: [u8; 0x04], #[doc = "0x08 - RAMCFG memory interrupt status register"] pub m1isr: M1ISR, _reserved2: [u8; 0x1c], #[doc = "0x28 - RAMCFG memory 1 eras...
// https://docs.rs/structopt/0.3.21/structopt/index.html // https://blog.logrocket.com/json-and-rust-why-serde_json-is-the-top-choice/ // https://github.com/serde-rs/json // ✅ ❌ 🚧 🦀 use std::io::BufReader; // Read, Error use std::path::Path; use serde::{Deserialize, Serialize}; use serde_json::Result; // use std::p...
use std::{borrow::Cow, marker}; use chrono_tz::Tz; use either::Either; use crate::{ errors::{Error, FromSqlError, Result}, types::{ block::ColumnIdx, column::{ArcColumnWrapper, ColumnData}, Column, ColumnType, Value, }, Block, }; pub trait RowBuilder { fn apply<K: ColumnTy...
mod logic; #[cfg(not(target_family = "wasm"))] mod nif; #[cfg(target_family = "wasm")] mod wasm;
use std::ops::{Add, AddAssign, BitAnd, Mul, Sub, BitXor}; use std::cmp::{min, max}; use std::hint::unreachable_unchecked; #[derive(Copy, Clone, Debug, Eq, PartialEq)] struct Pt(i32, i32); impl Pt { fn mag(&self) -> i32 { self.0 + self.1 } } #[derive(Copy, Clone, Debug, Eq, PartialEq)] struct Wire { ...
#[macro_use] extern crate chai; mod state; mod test_layer; fn main() { let state = state::State {}; let mut app = chai::Application::new(480, 480, "the big gay", state); let layer = test_layer::TestLayer::new(); app.push_layer(layer); app.start(); }
use nalgebra::core::DMatrix as DMatrix; use linear::miscelanous::*; use std; #[no_mangle] pub unsafe extern fn regress_point(weights: *mut [f64; 3], point: [f64; 2]) -> f64 { point[0] * (*weights)[1] + point[1] * (*weights)[2] + (*weights)[0] } #[no_mangle] pub extern fn linear_regression(raw_points : *mut std::o...
use chomp::ascii::{is_horizontal_space, is_whitespace}; use chomp::prelude::*; use std::io::Read; use std::iter::FromIterator; use std::collections::HashMap; use std::str; #[derive(Debug, PartialEq)] pub struct Header { name: String, value: String, } struct EOLMatcher { found_carriage_return: bool, } im...
use rusqlite::{Connection, Result, Row}; use sea_query::{ColumnDef, Expr, Func, Iden, Order, Query, SqliteQueryBuilder, Table}; sea_query::sea_query_driver_rusqlite!(); use sea_query_driver_rusqlite::RusqliteValues; fn main() -> Result<()> { let conn = Connection::open_in_memory()?; // Schema let sql = ...
use crate::{ custom_client::{OsuStatsScore, ScraperScore}, util::{numbers::round, osu::grade_emote}, }; use rosu_v2::prelude::{GameMode, GameMods, Grade, MatchScore, Score}; use std::fmt::Write; pub trait ScoreExt: Send + Sync { // Required to implement fn count_miss(&self) -> u32; fn count_50(&se...
#![no_std] #![no_main] #![feature(custom_test_frameworks)] #![test_runner(glade::test_runner)] #![reexport_test_harness_main = "test_main"] extern crate alloc; use alloc::boxed::Box; // namespacing use bootloader::{entry_point, BootInfo}; use core::panic::PanicInfo; use glade::{print, println}; #[cfg(test)] use gla...
pub mod cache; pub mod event;
mod blog; mod camera; mod category; mod exposure_mode; mod location; mod photo; mod post; mod size; mod tag; pub use blog::Blog; pub use camera::Camera; pub use category::{Category, CategoryKind}; pub use exposure_mode::ExposureMode; pub use location::Location; pub use photo::{Photo, PhotoFile, PhotoPath}; pub use pos...
use texture::Texture; pub use self::image_importer::ImageImporter; mod image_importer; pub type ImportResult<T> = Result<T, String>; pub trait Importer<I> { type Texture: Texture; fn import(input: I) -> ImportResult<Self::Texture>; }
pub mod model; pub mod routes; mod controller; mod service;
use crate::block::Block; use crate::crypto::hash::{Hashable, H256}; use std::collections::{HashMap, HashSet}; pub struct BlockBuffer { /// All blocks that have been received but not processed. blocks: HashMap<H256, Block>, // TODO: we could use a sorted vector for better performance /// Mapping between...
use std::collections::VecDeque; fn main() { use std::io::BufRead; let rule = Rule::new(); let stdin = std::io::stdin(); for problem in stdin.lock().lines().filter_map(|r| r.ok()) { println!("{}", Sudoku::solve(problem, &rule)); } } struct Rule { size: usize, digits: String, n_c...
use super::{frame::DeipProposal, runtime, RuntimeT}; use node_template_runtime::Call; use serde::{ser::Serializer, Serialize}; impl Serialize for runtime::WrappedCall<<RuntimeT as DeipProposal>::Call> { fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where ...
use crate::construction::constraints::{ConstraintPipeline, TOTAL_DISTANCE_KEY, TOTAL_DURATION_KEY}; use crate::construction::heuristics::{InsertionContext, RegistryContext, SolutionContext}; use crate::helpers::models::problem::*; use crate::helpers::models::solution::create_route_context_with_activities; use crate::mo...
use super::ignore; use super::options::Options; use super::Error; use lazy_static::lazy_static; use regex::Regex; use rsass::output::Format; use rsass::{parse_scss_data, FileContext, GlobalScope}; use std::io::Write; pub struct TestFixture { fn_name: String, input: String, expectation: TestExpectation, ...
struct Callbacks<T> { callbacks: Vec<Box<FnMut(&T)>>, } impl<T> Callbacks<T> { pub fn new() -> Self { Callbacks { callbacks: Vec::new() } } pub fn register<F: FnMut(&T) + 'static>(&mut self, c: F) { self.callbacks.push(Box::new(c)); } pub fn call(&mut self, val: &T) { ...
mod expr; mod program; mod stmt; pub use expr::Expression; pub use program::Program; pub use stmt::Statement;
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; pub type QueryParam = String; pub type TimespanParam = String; pub type WorkspacesParam = Vec<String>; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct QueryBody { ...
struct Solution; use crate::shared::tree_node::TreeNode; use std::cell::RefCell; use std::rc::Rc; /// https://leetcode.com/problems/binary-tree-level-order-traversal-ii/ impl Solution { pub fn level_order_bottom(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> { // Solution::bfs_iterative(root) ...
const INPUT: &str = include_str!("../input.txt"); fn get_seat(char_iter: &mut impl Iterator<Item = char>) -> u64 { char_iter.fold(0, |acc, c| { let half = match c { 'R' | 'B' => 1, _ => 0, }; (acc << 1) | half }) } fn part1() -> u64 { INPUT .lines() ...
use crate::hittable::*; use crate::ray::*; use crate::vec3::*; pub trait Material { fn scatter(r_in: &Ray, rec: &HitRecord, attenuation: &Color, scattered: &Ray) -> bool; } pub struct Lambertian { pub albedo: Color, } impl Lambertian { pub fn from(a: &Color) -> Self { Self { albedo: a } } } ...
#![deny(clippy::all, clippy::pedantic)] pub fn primes_up_to(upper_bound: usize) -> Vec<usize> { let mut marked = (0..=upper_bound).map(|_| true).collect::<Vec<bool>>(); (2..=upper_bound) .filter(|num| { if !marked[*num] { return false; } let mut mult...
//! 中断模块 (的函数封装)-> 初始化 //! //! mod context; mod handler; mod timer; // 2021-3-10 // ? pub use context::Context; /// 初始化中断相关的子模块 /// /// - [`handler::init`] /// - [`timer::init`] pub fn init() { handler::init(); // 2021-3-10 timer::init(); println!("mod interrupt initialized"); }
use std::ops::{Add, AddAssign, Sub, SubAssign}; fn main() { let num = add(4, 6); println!("num = {}", num); let num1 = sub(4, 6); println!("num = {}", num); let mut p = Point { x: 30, y: 50 }; println!("Point({}, {})", p.x, p.y); p.add(5, 5); println!("Point({}, {})", p.x, p.y); ...
use super::BackendTypes; use rustc_middle::mir::coverage::*; use rustc_middle::ty::Instance; pub trait CoverageInfoMethods: BackendTypes { fn coverageinfo_finalize(&self); } pub trait CoverageInfoBuilderMethods<'tcx>: BackendTypes { fn create_pgo_func_name_var(&self, instance: Instance<'tcx>) -> Self::Value; ...
/*! Data stores that store the result of partial word lookups to prevent repeated work. */ use std::hash::{Hash, Hasher}; use rustc_hash::{FxHashMap, FxHasher}; use crate::trie::Trie; #[derive(Clone)] pub struct CachedWords { words_cache: FxHashMap<u64, Vec<String>>, } impl CachedWords { pub fn default() -...
#[doc = "Register `ITLINE31` reader"] pub type R = crate::R<ITLINE31_SPEC>; #[doc = "Field `RNG` reader - RNG"] pub type RNG_R = crate::BitReader; #[doc = "Field `AES` reader - AES"] pub type AES_R = crate::BitReader; impl R { #[doc = "Bit 0 - RNG"] #[inline(always)] pub fn rng(&self) -> RNG_R { RNG...
use SafeWrapper; use ir::{User, Instruction, TerminatorInst, CatchPadInst, Block}; use sys; pub struct CatchReturnInst<'ctx>(TerminatorInst<'ctx>); impl<'ctx> CatchReturnInst<'ctx> { /// Creates a new catch return instruction. pub fn new(catch_pad: &CatchPadInst, block: &Block) -> Self { ...
use futures::Stream; use crate::netlink_packet_route::{link::LinkMessage, RtnlMessage}; use netlink_packet_core::{ header::flags::{NLM_F_DUMP, NLM_F_REQUEST}, NetlinkFlags, NetlinkMessage, NetlinkPayload, }; use crate::{Error, ErrorKind, Handle}; lazy_static! { // Flags for `ip link get` static ref G...
use crate::rtb_type; rtb_type! { OperatingSystem, 500, OtherNotListed=0; Nintendo3DSSystemSoftware=1; Android=2; AppleTVSoftware=3; Asha=4; Bada=5; BlackBerry=6; BREW=7; ChromeOS=8; Darwin=9; FireOS=10; FirefoxOS=11; HelenOS=12; Ios=13; Linux=14; MacOS=15; MeeGo=16; MorphOS=17; NetBSD=18; NucleusPLUS=19; PSVitaSystemS...
use anyhow::Result; /// Trait describing interface for available operations on repositories pub trait RepoOperations { /// Executing custom git command on a repository /// /// # Arguments /// /// * `cmd` - command to execute, e.g. status --porcelain fn custom_cmd(&self, cmd: String) -> Result<(...
#[link(name = "glfw", vers = "0.1", uuid = "6199FAD3-6D03-4E29-87E7-7DC1B1B65C2C", author = "Brendan Zabarauskas", url = "https://github.com/bjz/glfw3-rs")]; #[comment = "Bindings and wrapper functions for glfw3."]; #[crate_type = "lib"]; use core::libc::*; use support::event; pub use support::con...
use strum::EnumIter; #[derive(Clone, Copy, EnumIter, PartialEq, Eq, Hash, Debug)] pub enum Color { Red, Blue, Green, White, Yellow, All, Black, } impl Color { pub fn to_string(&self) -> &str { match self { Color::Red => ":red_square:", Color::Blue => ":b...
#![feature(proc_macro_hygiene, decl_macro)] #[macro_use] extern crate rocket; extern crate rocket_contrib; use rocket::fairing::AdHoc; use auth::authsettings::AuthSettings; mod api; mod protected; mod auth; mod routes; fn main() { let routes_vec = routes::get_routes(); rocket::ignite() .mount("/", ...
#[derive(Debug, Clone, Eq, PartialEq)] pub enum MemoryError { OutOfBounds, InvalidAccess, ReadOnly, Overflow, Underflow, Overlap, } pub mod address; pub mod address_space; pub mod sparse; pub mod zero; pub mod rom;
use super::role::RoleEntity; use crate::{ repository::{GetEntityFuture, ListEntitiesFuture, Repository}, utils, Backend, Entity, }; use twilight_model::{ guild::Member, gateway::payload::MemberUpdate, id::{GuildId, RoleId, UserId}, }; #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::...
extern crate watchexec; use watchexec::{cli, run}; fn main() { run(cli::get_args()); }
#![allow(dead_code)] #![allow(unused_imports)] use std::fmt; use std::mem; #[derive(Debug)] pub struct List<T> { head: ListEnum<T> } #[derive(Debug)] pub struct IntoIter<T> (List<T>); pub struct Iter<'a, T> { next: Option<&'a Node<T>>, } pub struct IterMut<'a, T> { next: Option<&'a mut Node<T>>, } #[d...
#[macro_use] extern crate diesel; pub mod domain; pub mod controller; pub mod response; pub mod request; pub mod repository; pub mod service; pub mod driver; pub mod model; pub mod schema; #[cfg(test)] mod tests;
use super::{GoalSpecific, InvisibleGoal, ResponseContextEntry, VisibleGoal}; use crate::base::{Cohesion, ComputeMode, Hiding, Relevance}; use crate::pos::InteractionPoint; use crate::resp::OutputForm; use serde::Deserialize; #[serde(rename_all = "camelCase")] #[derive(Deserialize, Clone, Default, Debug, Eq, PartialEq)...
mod candidate_uncles; use crate::component::entry::TxEntry; use crate::config::BlockAssemblerConfig; use crate::error::BlockAssemblerError as Error; pub use candidate_uncles::CandidateUncles; use ckb_chain_spec::consensus::Consensus; use ckb_jsonrpc_types::{BlockTemplate, CellbaseTemplate, TransactionTemplate, UncleTe...
fn main() { // Comments // this is an example of a line comment // rugular comments which are ignored by the compiler // println!("Hello Rust!") /* * This is another type of comment, a block comment. In general, * line comments are the recommended comment style. But * block comment...
use anyhow::Result; use std::time::Duration; use crossterm::event::{poll, read, Event, KeyCode, KeyEvent}; use super::result_list::ResultList; use crate::ig::Ig; #[derive(Default)] pub(crate) struct InputHandler { input_buffer: String, } impl InputHandler { pub(crate) fn handle_input(&mut self, result_list:...
extern crate dmbc; extern crate exonum; extern crate exonum_testkit; extern crate hyper; extern crate iron; extern crate iron_test; extern crate mount; extern crate serde_json; pub mod dmbc_testkit; use dmbc_testkit::{DmbcTestApiBuilder, DmbcTestKitApi}; use exonum::crypto; use hyper::status::StatusCode; use dmbc::c...
use std::fs; #[derive(Debug)] struct Instruction { op_code: i64, step: usize, modes: Vec<i64> } fn parse_instruction(mut instruction: i64) -> Instruction { let mut parameters = vec![]; while instruction > 0 { parameters.push(instruction % 10); instruction /= 10; } let op_c...
#[doc = "Register `IR` reader"] pub type R = crate::R<IR_SPEC>; #[doc = "Register `IR` writer"] pub type W = crate::W<IR_SPEC>; #[doc = "Field `RF0N` reader - Rx FIFO 0 New Message"] pub type RF0N_R = crate::BitReader; #[doc = "Field `RF0N` writer - Rx FIFO 0 New Message"] pub type RF0N_W<'a, REG, const O: u8> = crate:...
use std::collections::HashMap; use std::marker::PhantomData; use analyser::interface::*; use ndarray::prelude::*; use ops::prelude::*; use tensor::Datum; use Result; pub fn build(pb: &::tfpb::node_def::NodeDef) -> Result<Box<Op>> { let begin_mask = pb.get_attr_opt_int("begin_mask")?.unwrap_or(0); let end_mask...
use super::*; pub(crate) fn echo_command(ctx: &Context) -> CommandResult { for part in ctx.parts { let output = Output::new().add(*part).build(); ctx.status(output); } Ok(Response::Nothing) }
// https://beta.atcoder.jp/contests/abc002/tasks/abc002_4 macro_rules! scan { ($t:ty) => { { let mut line: String = String::new(); std::io::stdin().read_line(&mut line).unwrap(); line.trim().parse::<$t>().unwrap() } }; ($($t:ty),*) => { { ...
#![no_std] #![no_main] use ruduino::Pin; use ruduino::cores::current::{port}; #[no_mangle] pub extern fn main() { port::B5::set_output(); loop { port::B5::set_high(); ruduino::delay::delay_ms(1000); port::B5::set_low(); ruduino::delay::delay_ms(1000); } }
use anyhow::{anyhow, Result}; use druid::Vec2; use druid::{ piet::{PietText, Text, TextAttribute, TextLayoutBuilder}, Color, Command, EventCtx, ExtEventSink, Target, UpdateCtx, WidgetId, WindowId, }; use druid::{Env, PaintCtx}; use git2::Repository; use language::{new_highlight_config, new_parser, LapceLanguage...
use std::borrow::Cow; use std::error::Error; use std::{str, marker}; use heed_traits::{BytesDecode, BytesEncode}; use bytemuck::try_cast_slice; /// Describes an [`prim@str`]. pub struct Str<'a> { _phantom: marker::PhantomData<&'a ()>, } impl<'a> BytesEncode for Str<'a> { type EItem = &'a str; fn bytes_e...
#[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::ADCTRIM { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w m...
use crate::uses::*; use core::sync::atomic::{AtomicU64, Ordering}; use core::time::Duration; use super::Timer; const DEFAULT_RESET: Duration = Duration::from_millis(20); pub static apic_timer: ApicTimer = ApicTimer::new(DEFAULT_RESET); pub struct ApicTimer { elapsed_time: AtomicU64, nano_reset: AtomicU64, } impl ...
use super::*; #[allow(unused_imports)] use cgmath::SquareMatrix; type Subject = RayGenerator; fn subject() -> Subject { let transform = Transform::new(Matrix4::identity()); let fov = FieldOfView::new(Vector2::new(90.0, 90.0)); let image = Image::new(Vector2::new(20, 10)); Subject::new(&transform, &f...
// use std::collections::HashSet; use amethyst::{core::timing::Time, ecs::prelude::*}; use crate::resources::{Context, Game, MessageChannel, Msg, State}; #[derive(Debug)] pub struct TickSystem { last_tick: f64, } impl Default for TickSystem { fn default() -> Self { TickSystem { last_tick: 0.0 } }...
use crate::buffering::BufferingBuilder; use crate::csv; use crate::storage::error::Error; use crate::storage::{Entry, SeriesTable, SeriesWriter}; use bytes::buf::Buf; use futures::{Stream, StreamExt}; use std::sync::Arc; use warp::reject::Rejection; use warp::{http::StatusCode, Filter}; enum ImportError { Parse(St...
extern crate elevator; #[macro_use] extern crate serde_derive; extern crate serde; extern crate serde_json; extern crate floating_duration; use std::time::Instant; use std::env; use std::fs::File; use std::io::{self, Read, Write, BufRead, BufReader}; use std::io::prelude::*; use elevator::buildings; use elevator::bui...
enum Easing { Linear, Parabolic, } impl Easing { fn get_scalar(progress: f64, easing: Easing) -> f64 { match easing { Easing::Linear => { progress }, Easing::Parabolic => { progress * progress }, } } } struct PropertyAnimation<T> { from: T, to: T, progress: f64, duration: f64, } impl<...
use regex::Regex; use std::env; use std::ffi::CString; use std::fs::File; use std::io::{BufRead, BufReader}; use std::os::raw::{c_char, c_int}; mod dimacs; extern "C" { fn drat_main(argc: c_int, argv: *const *const c_char) -> c_int; } fn main() { let args: Vec<_> = env::args().collect(); if args.len() < ...
use crate::util::{ Bezier, FollowBezierAnimation, Globals, Group, GroupBoxQuad, GroupMiddleQuad, Maps, MyShader, SelectedBoxQuad, SelectingBoxQuad, TurnRoundAnimation, }; use crate::inputs::Action; use bevy::{ prelude::*, render::pipeline::{RenderPipeline, RenderPipelines}, }; // There is culling bet...
use std::{ io::Read, sync::atomic::{AtomicI32, Ordering}, }; use lazy_static::lazy_static; use tokio::io::{AsyncWrite, AsyncWriteExt}; use crate::error::Result; /// Closure to obtain a new, unique request ID. pub(crate) fn next_request_id() -> i32 { lazy_static! { static ref REQUEST_ID: AtomicI32...
#[derive(Serialize, Deserialize, Debug, Default, Clone, Eq, PartialEq)] pub struct Meta { pub title: String, pub context: String, pub teammates: Vec<String>, }
use std::collections::HashMap; use std::path::Path; use std::ffi::OsStr; use iron::prelude::*; use iron_sessionstorage::Value as SessionValue; use iron_sessionstorage::traits::SessionRequestExt; use rand::*; use crypto::md5::Md5; use crypto::digest::Digest; // used for input_str, result_str use chrono::{Local, NaiveD...
/// Sort an array using merge sort /// /// # Parameters /// /// - `arr`: A vector to sort in-place /// /// # Type parameters /// /// - `T`: A type that can be checked for equality and ordering e.g. a `i32`, a /// `u8`, or a `f32`. /// /// # Undefined Behavior /// /// Does not work with `String` vectors. /// /// #...
use super::*; use rayon::prelude::*; impl Graph { /// Return iterator on the node of the graph. pub fn get_nodes_iter(&self) -> impl Iterator<Item = (NodeT, Option<NodeTypeT>)> + '_ { (0..self.get_nodes_number()) .map(move |node_id| (node_id, self.get_unchecked_node_type(node_id))) } ...
use num::Num; use num::pow; use std::fmt; use std::ops::{Add, Sub, Mul, Neg}; /// Quaternion represents a three dimensional component (x, y, z) with a definied /// amount of rotation (w). /// /// # Remarks /// /// This struct is implemented to be used with numerical types. #[derive(Clone, Copy)] pub struct Quat<N: Cop...
use crate::error::{from_protobuf_error, NiaServerError, NiaServerResult}; use crate::protocol::Serializable; use protobuf::Message; #[derive(Clone, Debug, PartialEq, Eq)] pub struct ActionKeyPress { key_code: i32, } impl ActionKeyPress { pub fn new(key_code: i32) -> ActionKeyPress { ActionKeyPress { k...
#[doc = "Register `HYSCR4` reader"] pub type R = crate::R<HYSCR4_SPEC>; #[doc = "Register `HYSCR4` writer"] pub type W = crate::W<HYSCR4_SPEC>; #[doc = "Field `PG` reader - Port G hysteresis control on/off"] pub type PG_R = crate::FieldReader<u16>; #[doc = "Field `PG` writer - Port G hysteresis control on/off"] pub typ...
use phi::{Phi, View, ViewAction}; use phi::gfx::{CopySprite, Sprite, AnimatedSprite, AnimatedSpriteDescr}; use phi::data::{Rectangle, MaybeAlive}; use views::shared::{Background, BgSet}; use views::panel::{Panel, PanelFactory}; use views::panel; use views::card::{Card, CardFactory}; use sdl2::pixels::Color; const DEBU...
use crate::num_traits::FromPrimitive; use fmt::Display; use serde::{de, Deserialize, Deserializer}; use std::{fmt, marker::Copy}; #[derive(Debug, Primitive, Copy, PartialEq, Eq)] #[repr(u8)] pub enum ExposureMode { Undefined = 0, Manual = 1, ProgramAE = 2, AperturePriority = 3, ShutterPriority = 4,...
#[doc = "Register `CR` reader"] pub type R = crate::R<CR_SPEC>; #[doc = "Register `CR` writer"] pub type W = crate::W<CR_SPEC>; #[doc = "Field `EN` reader - EN"] pub type EN_R = crate::BitReader; #[doc = "Field `EN` writer - EN"] pub type EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `CACHEI...
fn main() { //defn: The String type, which is provided by Rust’s standard library rather than coded into the core language, is a growable, mutable, owned, UTF-8 encoded string type. ///////////////// // new strings // ///////////////// // new empty string let mut s = String::new(); // push...
use crate::binds::BindCount; use crate::binds::{BindsInternal, CollectBinds}; use crate::{Column, WriteSql}; use std::fmt::{self, Write}; #[derive(Debug, Clone)] pub enum Group { Col(Column), And { lhs: Box<Group>, rhs: Box<Group> }, Raw(String), } impl Group { pub fn raw(sql: &str) -> Self { ...
use crate::generate::grammars::{LexicalGrammar, Production, ProductionStep, SyntaxGrammar}; use crate::generate::rules::{Associativity, Precedence, Symbol, SymbolType, TokenSet}; use lazy_static::lazy_static; use std::cmp::Ordering; use std::fmt; use std::hash::{Hash, Hasher}; use std::u32; lazy_static! { static r...
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ use std::ffi::OsString; use std::os::unix::ffi::OsStringExt; use std::path::PathBuf; use bytes::By...
use crossterm::{ cursor, queue, style::{Color, Print, ResetColor, SetBackgroundColor, SetForegroundColor}, terminal::{self, Clear, ClearType}, Result, }; use std::io::Write; pub const ENTRY_COLOR: Color = Color::Rgb { r: 255, g: 180, b: 100, }; const HEADER_COLOR: Color = Color::Black; co...
#[doc = r" Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - MSPI PIO Transfer Control/Status Register"] pub ctrl: CTRL, #[doc = "0x04 - MSPI Transfer Configuration Register"] pub cfg: CFG, #[doc = "0x08 - MSPI Transfer Address Register"] pub addr: ADDR, #[doc = "0x0c - ...
use super::User; use crate::utils; use actix_web::{error, web, HttpResponse, Responder}; use serde::Deserialize; #[derive(Deserialize)] pub struct Info { pub term: String, } pub fn search(info: web::Query<Info>) -> Result<HttpResponse, actix_web::Error> { let term = &info.term; dbg!(&term); let mut user_query_co...
use std::fs::File; use std::io::Read; fn main() { let mut reader: Box<dyn Read> = Box::new(File::open("Cargo.toml").unwrap()); process_file(&mut reader); } fn process_file(reader: &mut Box<dyn Read>) { let mut buf = String::new(); reader.read_to_string(&mut buf).unwrap(); println!("{}", buf); }...
#![no_std] #![no_main] //#![feature(min_const_fn)] //#![feature(const_let)] // pick a panicking behavior //extern crate panic_halt; // you can put a breakpoint on `rust_begin_unwind` to catch panics // extern crate panic_abort; // requires nightly // extern crate panic_itm; // logs messages over ITM; requires ITM supp...
use crate::client::Client; use crate::style::{reset_style, set_style}; use crate::window::Window; use serde_json::Value; use std::collections::HashMap; use std::io::Write; //use termion; use termion::clear::CurrentLine; use termion::color; use termion::cursor::Goto; use termion::event::{Event, Key, MouseButton, MouseEv...
use crate::ast::{Expression, Statement, Value, Visitor}; use crate::callable::{LoxFunction, NativeFunction}; use crate::class::Class; use crate::environment::{Environment, EnvironmentError}; use crate::instance::Instance; use crate::token::{Token, TokenType}; use std::collections::BTreeMap; use std::fmt; use std::io; u...
// 3rd party imports {{{ use alpm::Alpm; use alpm::SigLevel; // }}} // Own imports {{{ use crate::config::Config; use crate::error::Error; // }}} /// The default path to package database. const DB_PATH: &str = "/var/lib/pacman"; /// The default installation root. const ROOT: &str = "/"; /// A handle for interactin...