text
stringlengths
8
4.13M
use crate::key_code::KeyCode; use num_enum::TryFromPrimitive; #[derive(Debug, Clone, Copy)] #[repr(u8)] pub enum DescriptorType { Hid = 0x21, Report = 0x22, _Physical = 0x23, } #[derive(Debug, Clone, Copy, PartialEq)] #[repr(u8)] pub enum Request { GetReport = 0x01, GetIdle = 0x02, GetProtocol...
/// A trait describing a buffer that is interleaved. /// /// This allows for accessing the raw underlying interleaved buffer. pub trait AsInterleaved<T> { /// Access the underlying raw interleaved buffer. /// /// # Examples /// /// ```rust /// use audio::AsInterleaved; /// /// fn test<B>...
use crate::parser::stream::Stream; use crate::parser::*; use crate::token::Token; use anyhow::Result; use trace; type RHS = (Op, Expr); pub fn parse_op(stream: &mut Stream) -> Result<Option<RHS>> { trace!(stream, "parse_op", { parse_op_bool(stream) .or_else(|| parse_op_eq(stream)) ...
use super::util::{linecross, Point, Polygon}; use std::collections::HashMap; ///-----------------------------TODO------------------------------------------- /// /// make a function that generates polygon type from grid. /// ///--------------------------------------------------------------------------- pub...
use structopt::StructOpt; #[derive(Debug, StructOpt)] #[structopt( name = "project-example", about = "A SpatialOS worker written in Rust." )] pub struct Opt { #[structopt(name = "WORKER_TYPE", long = "worker-type", short = "w")] pub worker_type: String, #[structopt(name = "WORKER_ID", long = "work...
use super::abstract_container::AbstractContainer; use super::arche_type::{ArcheType, ArcheTypeError}; use super::arche_type_hash::ArcheTypeHash; use super::component::Component; use super::component_type::ComponentType; use super::container::Container; use std::collections::HashMap; pub trait ComponentTuple: 'static +...
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Clock Calibration Unit Core Release Register"] pub crel: CREL, #[doc = "0x04 - Calibration Configuration Register"] pub ccfg: CCFG, #[doc = "0x08 - Calibration Status Register"] pub cstat: CSTAT, #[doc = "0x0c -...
// Copyright 2014 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 ...
use super::*; use std::collections::HashMap; use std::cmp::max; use dungeon::generator::Evaluate; use std::iter::FromIterator; use item::Equipment; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Monster { life: i32, damage: i32, name: String, /// Designer defined difficulty difficulty: ...
// 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 ...
/// Minter represents the minting state. #[derive(Clone, PartialEq, ::prost::Message)] pub struct Minter { /// current annual inflation rate #[prost(string, tag = "1")] pub inflation: std::string::String, /// current annual expected provisions #[prost(string, tag = "2")] pub annual_provisions: s...
use bytes::{Buf, Bytes}; use crate::error::Error; #[derive(Debug)] pub(crate) struct Order { #[allow(dead_code)] columns: Bytes, } impl Order { pub(crate) fn get(buf: &mut Bytes) -> Result<Self, Error> { let len = buf.get_u16_le(); let columns = buf.split_to(len as usize); Ok(Sel...
#[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::TBMR { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w...
use std::io::Cursor; use std::path::PathBuf; use rocket::response; use rocket::response::NamedFile; use rocket::Response; use super::all_request; use super::Context; #[get("/")] pub fn index<'a>(ctx: Context) -> response::Result<'a> { all_request(ctx) } #[get("/favicon.ico")] pub fn favicon() -> Option<NamedFil...
use day_09::{self, INPUT}; use criterion::{black_box, criterion_group, criterion_main, Criterion}; fn criterion_benchmark(c: &mut Criterion) { let motions = day_09::parse_input(INPUT); c.bench_function("day_09::parse_input", |b| { b.iter(|| day_09::parse_input(black_box(INPUT))); }); c.bench_...
#[doc = "Reader of register ALTCLKCFG"] pub type R = crate::R<u32, super::ALTCLKCFG>; #[doc = "Writer for register ALTCLKCFG"] pub type W = crate::W<u32, super::ALTCLKCFG>; #[doc = "Register ALTCLKCFG `reset()`'s with value 0"] impl crate::ResetValue for super::ALTCLKCFG { type Type = u32; #[inline(always)] ...
use sdl2::event::Event; use sdl2::pixels::Color; use sdl2::render::{Renderer, Texture, TextureQuery}; use sdl2_ttf::Font; use setup; const SCREEN_WIDTH: u32 = 640; const SCREEN_HEIGHT: u32 = 480; pub fn timer() { let mut basic_window_setup = setup::init("Timer", SCREEN_WIDTH, SCREEN_HEIGHT); let mut events...
//! CBOR deserialisation tooling use error::Error; use len::{Len, LenSz, StringLenSz, Sz}; use result::Result; use std::{self, collections::BTreeMap, io::BufRead}; use types::{Special, Type}; pub trait Deserialize: Sized { /// method to implement to deserialise an object from the given /// `Deserializer`. ...
extern crate tuix; use tuix::*; use femtovg::{ renderer::OpenGl, Baseline, Canvas, FillRule, FontId, ImageFlags, ImageId, LineCap, LineJoin, Paint, Path, Renderer, Solidity, }; static THEME: &'static str = include_str!("themes/widget_theme.css"); fn main() { // Create the app let mut app = Applic...
#![no_main] #![no_std] extern crate cortex_m; extern crate cortex_m_rt; extern crate panic_itm; extern crate stm32f407g_disc as board; extern crate embedded_hal as hal; use cortex_m_rt::entry; use board::hal::delay::Delay; use board::hal::prelude::*; use board::hal::stm32; use board::gpio; use board::gpio::gpiod::{...
use std::fmt; trait Graph<N, E> { fn has_edge(&self, &N, &N) -> bool; fn edges(&self, &N) -> Vec<E>; } fn distance<N, E, G: Graph<N, E>>(graph: &G, start: &N, end: &N) -> u32 { 0 } trait Graph_v2 { type N; type E; fn has_edge(&self, &Self::N, &Self::N) -> bool; fn edges(&self, &Self::N) ...
extern crate webplatform; fn main() { print!("HELLO FROM RUST"); webplatform::init().element_query("#container").unwrap().html_set("<h1>HELLO FROM RUST</h1>"); } // Functions that you wish to access from Javascript must be marked as no_mangle #[no_mangle] pub fn doub(a: i32) -> i32 { return a + a }
// Copyright 2019-2020 PolkaX. Licensed under MIT or Apache-2.0. /// Type alias to use this library's [`FormatError`] type in a `Result`. pub type Result<T> = std::result::Result<T, FormatError>; /// Errors generated from this library. #[derive(Debug, thiserror::Error)] pub enum FormatError { /// The object is no...
use self::diesel::prelude::*; use actix_web::actix::Handler; use chrono::Utc; use diesel::{self, QueryDsl, RunQueryDsl}; use uuid::Uuid; use crate::model::db::Database; use crate::model::response::MyError; use crate::model::{ member::Member, project::{CreateProject, NewProject, Project, ProjectById, ProjectMem...
use super::Lab; use std::arch::x86_64::*; use std::{f32, iter, mem}; use simd::labs_to_rgbs::{lab_slice_to_simd, labs_to_xyzs, xyzs_to_rgbs}; static BLANK_LAB: Lab = Lab { l: f32::NAN, a: f32::NAN, b: f32::NAN, }; /// Converts a slice of `Lab`s to `[u8; 3]` BGR triples using 256-bit SIMD operations. /// /...
use std::collections::HashSet; use std::io; use std::io::Read; use std::ops::Add; #[derive(Hash, PartialEq, Eq, Clone, Copy)] struct Pos { x: i8, y: i8, } impl Add for Pos { type Output = Self; fn add(self, other: Pos) -> Pos { Pos {x: self.x + other.x, y: self.y + other.y} } } fn main()...
use std::io; fn main() { println!("Temprature Converter:"); let temp = loop { println!("Enter temprature:"); let mut temp = String::new(); io::stdin() .read_line(&mut temp) .expect("Failed to read temprature"); let temp: f64 = match temp.trim().parse() ...
//! Construct planar sheets. use surface::LatticeType; use surface::Sheet; use coord::{Coord, Direction, Translate}; use describe::{unwrap_name, Describe}; use error::Result; use iterator::{ResidueIter, ResidueIterOut}; use system::*; use std::fmt; use std::fmt::{Display, Formatter}; impl_component![Cuboid]; impl_t...
pub mod command; pub mod response_handling; use anyhow::Result; use teloxide::types::{CallbackQuery, PollAnswer}; use teloxide::{ prelude::*, types::{InlineKeyboardButtonKind, MessageKind}, }; use self::{ command::Command, response_handling::perform_reponse_to_callback_query, response_handling::{...
use ::game::player::Player; pub trait Item { fn new() -> Self; fn save(); fn restore(); fn spawn(); fn attributes(); fn give_to_player(player: &mut Player) -> bool; fn pickup(player: &mut Player) -> bool; }
use crate::pixel::Pixel; use sdl2::render::WindowCanvas; use sdl2::EventPump; use sdl2::Sdl; pub struct Display { pub context: Sdl, canvas: WindowCanvas, event_pump: EventPump, pixels: Vec<Pixel>, width: u32, height: u32, } pub struct DisplayBuilder { name: String, width: u32, heig...
use crate::{ config::{cache_duration, serve_mode, ServeMode}, database::get_connection, errors::QSParseError, feed_generator::FeedGenerator, responses, source::Source, utils::{now, NabuResult}, }; use actix_web::{HttpRequest, HttpResponse}; use atom_syndication::{Feed, FixedDateTime, Generat...
#[doc = "Reader of register PLL2DIVR"] pub type R = crate::R<u32, super::PLL2DIVR>; #[doc = "Writer for register PLL2DIVR"] pub type W = crate::W<u32, super::PLL2DIVR>; #[doc = "Register PLL2DIVR `reset()`'s with value 0x0101_0280"] impl crate::ResetValue for super::PLL2DIVR { type Type = u32; #[inline(always)]...
use frame_system as system; use frame_support::assert_ok; use move_core_types::identifier::Identifier; use move_core_types::language_storage::ModuleId; use move_core_types::language_storage::StructTag; use move_vm::data::*; use move_vm_runtime::data_cache::RemoteCache; use serde::Deserialize; use sp_mvm::storage::MoveV...
#![feature(test)] #![feature(nll)] extern crate test; pub mod scheme; #[cfg(test)] mod tests { use test::Bencher; use scheme::interpreter::Interpreter; use scheme::value::Sexp::*; use scheme::error::LispError::*; #[test] fn it_works() { let mut interp = Interpreter::new(); as...
//! LP55231 //! //! This is a driver for the [TI LP55231](http://www.ti.com/product/LP55231) RGB LED controller IC //! using the [`embedded_hal`](https://github.com/rust-embedded/embedded-hal/) traits. //! //! NOTE that this driver is not yet platform agnostic, as it relies on `cortex_m` for a delay. //! //! This drive...
use super::button::Button; use seed::virtual_dom::IntoNodes; use seed::{prelude::*, *}; use std::borrow::Cow; use std::rc::Rc; use web_sys::MouseEvent; // ------ NavBar ------ pub struct NavBar<Ms: 'static> { brand: Brand<Ms>, content: Vec<Node<Ms>>, toggle: Button<Ms>, attrs: Attrs, style: Style...
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct AppBroadcastingMonitor(pub ::windows::core::II...
#![no_std] pub mod local_apic; pub mod xapic; pub use local_apic::LocalApic; pub use xapic::XApic;
// // mtpng - a multithreaded parallel PNG encoder in Rust // writer.rs - low-level PNG chunk writer // // Copyright (c) 2018 Brion Vibber // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Softwar...
//! An example of a multisig to execute arbitrary Solana transactions. #![feature(proc_macro_hygiene)] use anchor_lang::prelude::*; use anchor_lang::solana_program; use anchor_lang::solana_program::instruction::Instruction; use std::convert::Into; #[program] pub mod multisig { use super::*; pub fn create_mu...
//! Provides a Rust binding to the OpenGL API. //! //! This library attempts to provide a complete set of bindings to the OpenGL API while providing //! a small boost in type-safety over the raw OpenGL API. This library does not abstract the OpenGL //! API in any way, and in many cases still leaves the task of catching...
use crate::time_frame::TimeFrame; #[derive(Clone, Debug)] pub struct ChallengeData { pub name: String, pub time_frame: TimeFrame, }
use std::env; // test if rustc forced against libunwind instead of libgcc_s // passes a simple example application // $ rustc test.rs // $ ldd test // should contain libunwind by default // application should work too without crashing // rust-bin uses libgcc_s but a symlink to libunwind inside // /opt/rust-bin-$VERSI...
struct Cardinal; struct BlueJay; struct Turpial; struct Tucan; struct Turkey; trait Red {} trait Blue {} trait Yellow {} trait MultiColor {} impl Red for Cardinal {} impl Blue for BlueJay {} impl Yellow for Turpial {} impl MultiColor for Tucan {} // These functions are only valid for types which implement these // t...
const FIXED: i32 = 10; static GLOBAL : &str = "GLOBAL VAR"; fn is_big(nr :i32) -> bool{ nr > FIXED } fn main(){ let nr = 16; println!("{GLOBAL}"); println!("{} is {}", nr, if is_big(nr) {"big"}else{"small"}); }
use super::simd::*; use super::math::*; use super::collide::*; use super::world::*; pub trait Hitable { fn hit(&self, ray: Ray, t_min: f32, t_max: f32, world: &World, out_hit: &mut HitRecord) -> bool; } #[derive(Copy, Clone, Default)] pub struct PackedIdx { value: i32 } /// A QBVHNode has up to four children...
pub struct Solution; #[derive(Debug, PartialEq, Eq)] pub enum NestedInteger { Int(i32), List(Vec<NestedInteger>), } impl Solution { pub fn deserialize(s: String) -> NestedInteger { let mut stack = vec![Vec::new()]; let mut chars = s.chars().peekable(); while let Some(ch) = chars.ne...
use std::io; use std::io::prelude::*; use std::collections::HashMap; type int = i64; #[derive(Debug)] enum Instruction { Add(int, int, usize), Eq(int, int, usize), Hlt, Inp(usize), Jnz(int, usize), Jz(int, usize), Lt(int, int, usize), Mul(int, int, usize), Out(int), Rbo(int), }...
// 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. use { failure::Error, fidl_fuchsia_bluetooth::{self, Int8}, fidl_fuchsia_bluetooth_control::{AdapterInfo, AdapterState, RemoteDevice}, std:...
use std::env; use std::io::BufReader; use std::io::BufRead; use std::fs::File; use std::collections::HashSet; fn accumulated_frequency(start_freq: i32, adjustments: &[i32]) -> i32 { let mut sum = start_freq; for adj in adjustments { sum += adj; } sum } fn first_repeated_cumulative_freq(start_f...
//! A simple `!Unpin` I/O backend for async-std, designed for use in tests. //! //! This crate provides the `PinCursor` struct which wraps around `async_std::io::Cursor` //! but is explicitly **not** `Unpin`. It is a little building block to help write tests //! where you want to ensure that your own asynchronous IO co...
use std::fs; use std::str; #[test] fn validate_9_1() { assert_eq!(algorithm("src/day_9/input_test.txt", 5), 127); } fn algorithm(file_location: &str, preamble: usize) -> i64 { let content = fs::read_to_string(file_location).unwrap(); let mut xmas_codes: Vec<i64> = vec![]; let mut preamble_codes: Vec<i...
use std::collections::HashMap; use std::fmt; use std::fs::File; use std::path::Path; use serde::{Deserialize, Serialize}; use crate::error::Error; #[derive(Debug, Deserialize, Serialize, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct Stroke(String); #[derive(Debug, Deserialize, PartialEq, Eq, Hash)] pub struct T...
use std::error::Error; use std::net::SocketAddr; use std::sync::Arc; use tokio::net::{TcpListener, TcpStream}; use tokio_rustls::rustls::ServerConfig; use tokio_rustls::server::TlsStream; use tokio_rustls::TlsAcceptor; use crate::session::{create_session, Session}; type Upstream = TcpStream; type Downstream = TlsStre...
use criterion::{ criterion_group, criterion_main, measurement::WallTime, BatchSize, BenchmarkGroup, BenchmarkId, Criterion, Throughput, }; use rustpython_compiler::Mode; use rustpython_vm::{AsObject, Interpreter, PyResult, Settings}; use std::{ ffi, fs, io, path::{Path, PathBuf}, }; // List of microben...
pub struct Solution; use std::path::{ Component::{Normal, ParentDir}, Path, }; impl Solution { pub fn simplify_path(path: String) -> String { let mut parts = Vec::new(); for component in Path::new(&path).components() { match component { Normal(s) => { ...
// Merge k Sorted Lists // https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/582/week-4-january-22nd-january-28th/3615/ use crate::linked_list::ListNode; pub struct Solution; use std::cmp::Ordering; use std::collections::BinaryHeap; impl PartialOrd<ListNode> for ListNode { fn partial_...
// error-pattern: Unsatisfied precondition constraint (for example, even(y fn print_even(y: int) : even(y) { log y; } pred even(y: int) -> bool { true } fn main() { let y: int = 42; check even(y); do { print_even(y); do { do { do { y += 1; } while (true); } while (true); ...
use super::*; #[test] fn with_locked_adds_heap_message_to_mailbox_and_returns_message() { with_process_arc(|arc_process| { TestRunner::new(Config::with_source_file(file!())) .run(&strategy::term(arc_process.clone()), |message| { let destination = arc_process.pid_term(); ...
/* * Open Service Cloud API * * Open Service Cloud API to manage different backend cloud services. * * The version of the OpenAPI document: 0.0.3 * Contact: wanghui71leon@gmail.com * Generated by: https://openapi-generator.tech */ #[derive(Debug, PartialEq, Serialize, Deserialize)] pub struct CloudServerReques...
extern crate docopt; extern crate serde; #[macro_use] extern crate serde_derive; extern crate walkdir; extern crate image; extern crate img_hash; use std::io::{self, BufWriter, Stderr, Stdout, Write}; use docopt::Docopt; use img_hash::{ImageHash, HashType}; use walkdir::{DirEntry, WalkDir}; const USAGE: &'static str...
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[repr(transparent)] #[doc(hidden)] pub struct ISpatialGraphInteropFrameOfReferencePreview(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ISpatialGraphInteropF...
#[cfg(test)] mod tests { use crate::chip8::cpu::{Cpu, PROGRAM_COUNTER_START_ADDR}; use crate::modules::display::BYTES_PER_CHARACTER; #[test] fn test_ret() { let mut cpu = init(vec!(0x00, 0xEE)); cpu.push(0xFF); cpu.run(); assert_eq!(cpu.program_counter, 0xFF); } ...
extern crate windows_winmd as winmd; #[test] fn stringable() { let reader = winmd::TypeReader::get(); let def = reader.expect_type_def(("Windows.Foundation", "IStringable")); assert!(def.name() == ("Windows.Foundation", "IStringable")); let methods: Vec<winmd::parsed::MethodDef> = def.methods().colle...
//! LEGO EV3 ultrasonic sensor use super::{Sensor, SensorPort}; use crate::{sensor_mode, Attribute, Device, Driver, Ev3Error, Ev3Result}; use std::cell::Cell; /// LEGO EV3 ultrasonic sensor. #[derive(Debug, Clone, Device, Sensor)] pub struct UltrasonicSensor { driver: Driver, cm_scale: Cell<Option<f32>>, ...
::windows_sys::core::link ! ( "efswrt.dll""system" #[doc = "*Required features: `\"Win32_Security_EnterpriseData\"`*"] fn ProtectFileToEnterpriseIdentity ( fileorfolderpath : :: windows_sys::core::PCWSTR , identity : :: windows_sys::core::PCWSTR ) -> :: windows_sys::core::HRESULT ); #[cfg(feature = "Win32_Foundation")]...
use super::conf::{CMutConf, Rc33M}; use super::nav::CursorNav; use traits::{Leaf, PathInfo, SubOrd}; use node::{Node, NodesPtr, insert_maybe_split}; use std::{fmt, mem}; use std::iter::FromIterator; use std::marker::PhantomData; use arrayvec::ArrayVec; // Note: The working of `CursorMut` is fundamentally different f...
use clap::ArgMatches; pub const DEFAULT_BULK_SIZE: usize = 100; pub const DEFAULT_CHANNEL_SIZE: usize = 100; pub const DEFAULT_DELIMITER: u8 = b','; use super::channel::Channel; use super::csv::OptionsCsv; #[derive(Debug, Clone)] pub struct Options { pub channel: Channel, pub csv: OptionsCsv, pub manifes...
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // 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 ...
use gl::types::*; use anyhow::Result; use super::{ShaderExt, Shader}; pub type VertexShader = Shader<Vertex>; pub struct Vertex {} impl ShaderExt for Vertex { fn new() -> Vertex { Vertex{} } fn ty() -> GLenum { gl::VERTEX_SHADER } fn name() -> &'static str { "vertex" ...
use anyhow::{anyhow, Error}; use inkwell::values::PointerValue; use serde_json::Value; use std::{collections::HashMap, rc::Rc}; pub struct Env<'ctx> { pub names: HashMap<String, u64>, pub parent: Option<Rc<Env<'ctx>>>, pub ptr: Option<Rc<PointerValue<'ctx>>>, counter: u64, } impl<'ctx> Env<'ctx> { ...
use wasm_bindgen::JsValue; use wasm_bindgen_test::*; use js_sys::*; #[wasm_bindgen_test] fn test() { let bytes = Int8Array::new(&JsValue::from(10)); // TODO: figure out how to do `bytes[2] = 2` bytes.subarray(2, 3).fill(2, 0, 1); let v = DataView::new(&bytes.buffer(), 2, 8); assert_eq!(v.byte_off...
use crate::{ error::CompilerError, hir::{self}, id::CountableId, lir::{self, Lir}, mir::{self}, mir_optimize::OptimizeMir, module::Module, string_to_rcst::ModuleError, TracingConfig, }; use itertools::Itertools; use rustc_hash::{FxHashMap, FxHashSet}; use std::sync::Arc; #[salsa::qu...
// Copyright 2015 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 ...
use num_traits::Zero; /// Algorithm: [`Wikipedia`]<https://en.wikipedia.org/wiki/Integer_square_root#Example_implementation_in_C>. /// Calculates the integer square root of an integer. pub trait Sqrt { fn sqrt(&self) -> Self; } impl Sqrt for u64 { fn sqrt(&self) -> Self { let val = *self; if val == 1 { ...
mod board; mod bot; use std::f64; use std::rc::Rc; use gio::prelude::*; use gtk::prelude::*; use gtk::Application; use crate::board::{Board, PlayerMark}; use crate::bot::Bot; const APP_ID: &str = "com.github.dmitmel.tic-tac-toe-evolution"; const BOARD_CELL_SIZE: i32 = 32; const BOARD_MARK_MARGIN: f64 = 0.1; const ...
#![warn(clippy::all)] #![warn(clippy::pedantic)] use std::cmp::Ordering; fn main() { run(); } fn run() { let start = std::time::Instant::now(); // code goes here let res = TriangleNum::default() .find(|n| num_divisors(*n) > 500) .unwrap(); let span = start.elapsed().as_nanos(); println!("{} {}"...
extern crate libsamplerate_sys; #[cfg(test)] mod tests { use libsamplerate_sys::*; #[test] fn linking_works() { unsafe { let mut error = 0; let _state = src_new(SRC_SINC_BEST_QUALITY, 2, &mut error); } } }
use std::{ ops, intrinsics::{fadd_fast, fsub_fast, fmul_fast, fdiv_fast} }; #[derive(Debug, Clone, Copy)] pub struct Vector3 { x: f32, y: f32, z: f32 } impl ops::Add for Vector3 { type Output = Self; fn add(self, rhs: Self) -> Self::Output { unsafe { Vector3 { ...
#![feature(use_extern_macros)] extern crate wasm_bindgen; extern crate js_sys; use js_sys::Date; use wasm_bindgen::prelude::*; #[wasm_bindgen] extern "C" { // Binding for the `setInverval` method in JS. This function takes a "long // lived" closure as the first argument so we use `Closure` instead of // ...
use bevy_app::prelude::*; use bevy_ecs::IntoQuerySystem; pub use common::*; pub use event::*; pub use listeners::*; pub use sockets::*; use system::*; mod common; mod event; mod listener; mod listeners; mod socket; mod sockets; mod system; pub mod prelude { pub use crate::{ common::{IpAddress, ListenerId,...
#[cfg(all(not(target_arch = "wasm32"), test))] mod test; use anyhow::*; use liblumen_alloc::erts::exception::{self, *}; use liblumen_alloc::erts::process::trace::Trace; use liblumen_alloc::erts::term::prelude::*; #[native_implemented::function(erlang:+/1)] pub fn result(number: Term) -> exception::Result<Term> { ...
use std::collections::VecDeque; use std::fs::File; use std::io::Read; use std::cmp; #[repr(u8)] #[derive(PartialEq)] enum ParamType { PositionMode = 0, ImmediateMode = 1, RelativeMode = 2, } fn get_param_type(mode: i64) -> ParamType { match mode { 0 => ParamType::PositionMode, 1 => Par...
/* * @lc app=leetcode.cn id=67 lang=rust * * [67] 二进制求和 * * https://leetcode-cn.com/problems/add-binary/description/ * * algorithms * Easy (46.61%) * Total Accepted: 18.5K * Total Submissions: 39.3K * Testcase Example: '"11"\n"1"' * * 给定两个二进制字符串,返回他们的和(用二进制表示)。 * * 输入为非空字符串且只包含数字 1 和 0。 * * 示例 1: ...
use crate::capabilities::attempt_server_capability; use crate::capabilities::CAPABILITY_SIGNATURE_HELP; use crate::context::*; use crate::position::*; use crate::types::*; use crate::util::*; use lsp_types::request::*; use lsp_types::*; use serde::Deserialize; use url::Url; pub fn text_document_signature_help(meta: Ed...
pub mod generic_func_strat; pub mod functional_validation; use generic_func_strat::run as gfs_run; use functional_validation::fv_run; //cargo rustc -- -Z unstable-options --pretty=expanded fn main(){ gfs_run(); fv_run(); }
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // 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 ...
use { crate::{ math::Scalar, noise::{ fns::{ArcNoiseFn, HeightmapNoise, PerlinConsts, PerlinNoise, PlaneNoise, ScaledNoise}, NoiseArgs, }, random::Seed, }, std::sync::Arc, }; pub trait HeightmapScalar: Scalar + PerlinConsts {} impl HeightmapScalar for...
//! Scheduling of processing and solving steps. //! //! The current implementation is temporary and will be replaced with something more flexible. use log::info; use partial_ref::{partial, PartialRef}; use crate::{ cdcl::conflict_step, clause::{ collect_garbage, reduce::{reduce_locals, reduce_...
use std::fs::{create_dir_all, File}; use std::io::prelude::*; use std::io::Result; use std::path::Path; pub fn define_ast(output_dir: &str, base_name: &str, types: Vec<&str>) -> Result<()> { let directory = Path::new(".").join(output_dir); create_dir_all(directory.clone())?; let file_path = directory.join(...
use actix::prelude::*; #[derive(MessageResponse)] struct Added(usize); #[derive(Message)] #[rtype(result = Added)] struct Sum(usize, usize); fn main() {}
use std::cell::RefCell; use std::collections::HashMap; use std::convert::TryFrom; use std::fmt; use std::fs; use std::rc::Rc; use crate::error::LispyError; use crate::parser; use crate::Result; // Unfortunately I didn't find a better way to share the environment // between `Lval`s and also have a reference to a paren...
// Copyright 2019 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. #![cfg(test)] use { cobalt_sw_delivery_registry as metrics, failure::Error, fidl_fuchsia_paver as paver, fidl_fuchsia_pkg::PackageResolverR...
//! A binary for testing the OJN parser use remani::chart::ojm_dump; use std::{env, ffi::OsStr}; fn output_help(binary_name: &OsStr) { println!("Usage: {} path/to/ojmfile", binary_name.to_string_lossy()); } pub fn main() { let mut args = env::args_os(); let binary = args.next().unwrap_or(format!("./{}"...
use rocket; mod token; use spliff_lib::{self, state::SolanaClient}; #[rocket::catch(404)] fn not_found(req: &rocket::Request) -> String { format!("Invalid path: {}", req.uri()) } #[rocket::get("/ping")] fn ping() -> &'static str { "OK" } #[rocket::main] async fn main() { println!("{:?}", spliff_lib::hell...
use std::io; fn main(){ let reader = io::stdin(); let mut ip = String::new(); reader.read_line(&mut ip).ok().expect("Read Error"); let ns: Vec<i32> = ip .split_whitespace() .map(|s| s.parse().unwrap()) .collect(); let mut res = 0; for num in &ns { res = res + num;...
use anyhow::{anyhow, Result}; use std::convert::{TryFrom, TryInto}; #[derive(serde::Deserialize)] pub struct Settings { pub application: ApplicationSettings, pub observer: ObserverSettings, pub ecosystem: EcosystemSettings, } #[derive(serde::Deserialize)] pub struct ApplicationSettings { pub addr_host...
#[doc = "Reader of register DECCTRL"] pub type R = crate::R<u32, super::DECCTRL>; #[doc = "Writer for register DECCTRL"] pub type W = crate::W<u32, super::DECCTRL>; #[doc = "Register DECCTRL `reset()`'s with value 0"] impl crate::ResetValue for super::DECCTRL { type Type = u32; #[inline(always)] fn reset_va...
use std::{ collections::HashMap, path::Path, sync::mpsc::{self, Receiver}, }; use rbx_dom_weak::{RbxTree, RbxInstanceProperties}; use log::info; use crate::{ place_runner::{PlaceRunner, PlaceRunnerOptions, open_rbx_place_file}, message_receiver::RobloxMessage, }; pub const DEFAULT_PORT: u16 = 540...