text
stringlengths
8
4.13M
#[cfg(feature = "built_in_types")] use cakcukus::{ traits::{Differentiation, TermTrait}, Polynomial, Term, }; #[cfg(feature = "built_in_types")] #[test] fn differentiate_return() { // Build the initial equation, being 2x^2 - 3x + 5 let terms: Polynomial<f32> = Polynomial(vec![ Term::new(2., 2.)...
//! //! Jump Game //! //! https://leetcode.com/problems/jump-game/ //! //! Given an array of non-negative integers, you are initially positioned at the first index of the array. //! //! Each element in the array represents your maximum jump length at that position. //! //! Determine if you are able to reach the last in...
// Copyright 2016 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 ...
fn main() { listing_8_20(); listing_8_21(); listing_8_22(); listing_8_23(); listing_8_24(); listing_8_25(); listing_8_26(); } // Listing 8-20: Creating a new hash map and inserting some keys and values fn listing_8_20() { use std::collections::HashMap; let mut scores = HashMap::new...
extern crate event_rust; use event_rust::*; use event_rust::sys::*; use std::collections::HashMap; extern crate libc; struct SocketManger { pub socks : HashMap<u64, Socket>, } static mut s_count : i32 = 0; fn client_read_callback(ev : *mut EventLoop, fd : u64, _ : EventFlags, data : *mut()) -> i32 { let so...
use blake2::{ Digest, Blake2b }; use crate::config::HASH_SALT; pub fn to_hash(input: String) -> String { let mut hasher = Blake2b::new(); hasher.input(HASH_SALT); hasher.input(input.as_str()); format!("{:x}", hasher.result()) }
use eyre::{ // eyre, // Result, Context as _, }; use async_graphql::{ Context, // ID, FieldResult, }; use crate::host::Host; pub struct MyNamespace; #[async_graphql::Object] impl MyNamespace { async fn hosts<'ctx>( &self, ctx: &'ctx Context<'_>, // slug: Option<Stri...
/* * ORY Hydra * * Welcome to the ORY Hydra HTTP API documentation. You will find documentation for all HTTP APIs here. * * The version of the OpenAPI document: v1.10.6 * * Generated by: https://openapi-generator.tech */ /// PluginConfigInterface : PluginConfigInterface The interface between Docker and the pl...
fn day2_part1(input: &str) -> u32 { input .split("\n") .map(|l| { l.split_whitespace() .map(|n| u32::from_str_radix(n, 10).unwrap()) .collect::<Vec<u32>>() }) .map(|l| { l.iter().cloned().max().unwrap() - l.iter().min().unwrap()...
use std::path::Path; use cdragon_utils::GuardedFile; use memmap::MmapMut; /// Same as `GuardedFile`, but return a memory mapping pub struct GuardedMmap<P: AsRef<Path>> { gfile: GuardedFile<P>, mmap: MmapMut, } impl<P: AsRef<Path>> GuardedMmap<P> { /// Open file and map it to memory /// /// Create ...
use std::env; use aes::{Aes128}; use cfb_mode::Cfb; use cfb_mode::cipher::{NewCipher, AsyncStreamCipher}; use windows::{Win32::System::Memory::*, Win32::System::SystemServices::*}; use ntapi::{ntmmapi::*, ntpsapi::*, ntobapi::*, winapi::ctypes::*}; use obfstr::obfstr; type Aes128Cfb = Cfb<Aes128>; pub struct Injector...
extern crate rustray; use rustray::geometry::Vec3; //use rustray::geometry::Ray; use rustray::camera::Camera; use rustray::scene::Scene; // use rustray::display; // use std::vec::Vec; use std::thread; use std::thread::JoinHandle; use std::sync::{Arc, Mutex, RwLock}; use rustray::object::Sphere; use rustray::object::P...
use crate::{exec, reduce, test, Selection}; use anyhow::{anyhow, Result}; use bit_set::BitSet; use core::cmp::Ordering; use std::{ fs, io::{BufRead, BufReader, Result as IOResult, Write}, path::{Path, PathBuf}, }; macro_rules! optional_arg { ($cmd:ident, $arg:expr, $fmt:expr) => { if let Some(v...
#[allow(unused_imports)] use serde_json::Value; #[derive(Debug, Serialize, Deserialize)] pub struct SettingsAcls { /// ACL policies settings. #[serde(rename = "acl_policy_settings")] pub acl_policy_settings: Option <crate::models::SettingsAclsAclPolicySettings>, }
#[doc = "Register `LFCLKSRC` reader"] pub struct R(crate::R<LFCLKSRC_SPEC>); impl core::ops::Deref for R { type Target = crate::R<LFCLKSRC_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<LFCLKSRC_SPEC>> for R { #[inline(always)] fn from(reader: ...
use super::error::Error; use super::store; use gotham::hyper; #[derive(Clone, gotham_derive::NewMiddleware)] pub struct Cors(hyper::header::HeaderValue); impl Cors { pub fn new(cors: hyper::header::HeaderValue) -> Self { Self(cors) } } impl gotham::middleware::Middleware for Cors { fn call<C>( ...
//! Definitions for BMP280 I2C registers. /// I2C registers present in a BMP280. #[repr(u8)] #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] pub enum Register { /// Digital temperature coefficient 1. DigT1 = 0x88, /// Digital temperature coefficient 1. DigT2 = 0x8a, /// Digital temper...
use compressor::Compressor; use page_manager::BlockIter; use utils::ring_buffer::BiasedRingBuffer; use utils::Baseable; use utils::seeking_iterator::SeekingIterator; use utils::progress::Progress; use index::listing::UsedCompressor; #[derive(Debug, PartialEq, Eq, Ord, PartialOrd, Copy, Clone)] pub struct Posting(pub D...
use dbus_codegen::{generate, GenOpts, ServerAccess}; use std::fs::{self, File}; use std::io::Write; fn main() { let xml = fs::read_to_string("interface.xml").unwrap(); let mut dbus_opts = GenOpts::default(); dbus_opts.serveraccess = ServerAccess::AsRefClosure; let interface = generate(&xml, &dbus_opts)...
use std::f64; pub fn sum_of_multiples(limit: u32, factors: &[u32]) -> u32 { let m = factors.iter().fold(u32::max_value(), |a, &b| a.min(b)); let l = m ; let mut total = 0; let mut trav: Vec<u32> = Vec::new(); for n in ( l..limit){ for i in factors{ if *i==0 { ...
use syscall::*; use syscall::platform::nr::*; use crate::linux::types::pid_t; use std::ffi::c_void; use std::fmt; use std::mem; use std::fmt::Formatter; use std::borrow::Borrow; use crate::linux::types::IoVec; //include/uapi/linux/ptrace.h //arch/x86/include/uapi/asm/ptrace-abi.h //arch/x86/include/uapi/asm/ptrace.h /...
use std::collections::HashMap; use crate::types::BeepboopError; use crate::types::Expr; use crate::types::Value; // pub mod interpreter { pub fn run_cmd(mut state: ProgramState, cmd: Expr) -> ProgramState { match state.eval(cmd) { Ok(_val) => state, Err(error) => { eprintln!("{}",error)...
extern crate syntax_ll; extern crate ast; use ast::Expr; use syntax_ll::parse; fn assert_parses(expr: &str, ast: &str) { let result = parse(expr); assert!(result.is_ok(), "\n`{}` failed to parse:\n {:?}\n", expr, result); let result = format!("{:?}", result.unwrap()); assert_eq!(result, ast); } fn ...
use std::path; use std::time; use plotters::prelude::*; pub fn latency( path: path::PathBuf, title: String, mut values: Vec<u64>, ) -> Result<(), Box<dyn std::error::Error>> { println!("plotting latency graph {}", title); let root = BitMapBackend::new(&path, (1024, 768)).into_drawing_area(); ...
use core::{ cmp::{Ord, Ordering}, fmt, }; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use necsim_core_bond::{NonNegativeF64, NonZeroOneU64, PositiveF64}; use crate::{ cogs::{ backup::BackedUp, coalescence_sampler::CoalescenceRngSample, Backup, Habitat, LineageReference,...
//! Tegra210 Fuse implementation. use register::mmio::ReadWrite; use crate::timer::usleep; /// Representation of the Fuse registers. #[repr(C)] pub struct Fuse { pub ctrl: ReadWrite<u32>, pub reg_addr: ReadWrite<u32>, pub reg_read: ReadWrite<u32>, pub reg_write: ReadWrite<u32>, pub time_rd1: Read...
pub mod client_builder; pub mod client; pub mod into_url; pub mod request_builder; pub mod socket_builder; pub mod response; pub mod multipart; pub mod body; pub mod error; pub mod mime; pub mod web_command; pub mod web_socket; pub use client_builder::*; pub use client::*; pub use into_url::*; pub use request_builder:...
extern crate wasm_bindgen; use wasm_bindgen::prelude::*; #[wasm_bindgen] extern { fn alert(s: &str); } #[wasm_bindgen] pub fn is_prime(n: u64){ let judgement = (2..(n as f64).sqrt() as u64 + 1).all(|i| n % i != 0); if judgement { alert("This is a prime number! :)"); } else { alert("...
extern crate image; use std::sync::Arc; use std::sync::Mutex; use std::thread; use std::time::Instant; use image::{ImageBuffer, RgbImage}; fn get_color_from_iterations(i: i32, max_iterations: i32) -> (i32, i32, i32) { if i == max_iterations { (0, 0, 0) } else { let mut red = (i % 32) * 3; ...
#![cfg_attr(feature = "cargo-clippy", allow(clippy::match_wild_err_arm))] /// Read list of domain names from the command line or a file extern crate clap; extern crate futures; use clap::{App, Arg}; use futures::{stream, StreamExt}; use reqwest::Client; use std::io::{self, BufRead}; use std::time::Duration; /// A por...
//! a collection of streams which can be mutated after creation time in a thread-safe way //! This was directly copied from futures::stream::select_all //! At the moment it's pretty much the same as the original SelectAll impl, except that it features //! a mutex in order for the high-level future to be able to accept ...
use gl; pub fn create_buffer(vertices: &Vec<f32>, gl: &gl::Gl) -> gl::types::GLuint { let mut buffer_id: gl::types::GLuint = 0; unsafe { gl.GenBuffers(1, &mut buffer_id); gl.BindBuffer(gl::ARRAY_BUFFER, buffer_id); gl.BufferData( gl::ARRAY_BUFFER, // target (vertices.len() * std::mem::s...
use crate::domain::repository::{DatabaseRepository, RepositoryError}; use super::connection::ConnectionFactory; use mongodb::ThreadedClient; pub struct DatabaseRepositoryImpl<'a> { pub connection_factory: &'a ConnectionFactory<'a>, } impl<'a> DatabaseRepository for DatabaseRepositoryImpl<'a> { fn get_names(...
#![allow(dead_code)] #![allow(unused_imports)] extern crate byteorder; extern crate speexdsp; use byteorder::{BigEndian, ByteOrder}; use std::io::Read; #[cfg(feature = "sys")] fn main() { use speexdsp::preprocess::SpeexPreprocessConst::*; use speexdsp::preprocess::*; const NN: usize = 160; let mut in...
use std::{collections::HashMap, sync::Arc}; use leveled_hash_map::LeveledHashMap; #[allow(dead_code)] #[derive(Debug)] struct MultiName { us: &'static str, tw: &'static str, cn: &'static str, } fn main() { let earth_map: LeveledHashMap<&'static str, MultiName> = { let mut map = LeveledHashMap...
use std::collections::{HashMap, HashSet}; use std::collections::hash_set; pub fn vectors() { let mut a = Vec::new(); a.push(1); a.push(2); a.push(3); println!("{:?}",a); a.push(44); println!("{:?}",a); //usize isize let idx:usize = 0; a[idx] = 321; println!("a[0] = {}",...
///! Defines the CUDA evaluation context. use crossbeam; use device::{self, Device, EvalMode, ScalarArgument}; use device::cuda::{Executor, Gpu, Kernel, JITDaemon}; use device::cuda::api::{self, Argument}; use device::cuda::kernel::Thunk; use explorer; use ir; use std; use std::f64; use std::sync::{atomic, mpsc, Arc}; ...
use std::{collections::{HashMap, HashSet}, fs}; fn main() { let content = fs::read_to_string("input.txt").unwrap(); let trimmed = content.trim(); let wires: Vec<&str> = trimmed.split("\n").collect(); let wire1 = wires[0].split(",").collect(); let wire2 = wires[1].split(",").collect(); println...
//pub const MAP_ROWS: usize = 50; //pub const MAP_COLS: usize = 50; pub const MAP_ROWS: usize = 15; pub const MAP_COLS: usize = 128; pub const MAX_REGS: usize = 128; //was 128, risk of crashing if less than N_FEATURES, during feature loading. if > 256 will also crash! // pub const N_OPS: u8 = 6; <-- moved to ...
#![allow(clippy::result_unit_err)] use xcm::{ v0::{Result as XcmResult, Xcm}, VersionedXcm, }; pub trait TestExt { fn new_ext() -> sp_io::TestExternalities; fn reset_ext(); fn execute_with<R>(execute: impl FnOnce() -> R) -> R; } pub trait UmpMsgHandler { fn handle_ump_msg(from: u32, msg: Vec<u8>) -> Result<(),...
// This is valid syntax going in; a valid rust program going out. #[macro_export] macro_rules! avec { () => { Vec::new() }; ($($element:expr),+ $(,)?) => {{ // creating an array of expressions. // evaluating expressions multiple times. let mut vs = Vec::with_capacity($crate::...
#![feature(slice_ptr_range)] #[cfg(test)] extern crate quickcheck; #[cfg(test)] #[macro_use(quickcheck)] extern crate quickcheck_macros; pub type Float = f32; pub use std::f32::consts; #[cfg(test)] const EPSILON: Float = 1e-4; #[cfg(test)] fn eq_approx(x: Float, y: Float) -> bool { Float::abs(x - y) < EPSILON ...
// Copyright 2019 WHTCORPS INC Project Authors. Licensed under Apache-2.0. use std::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}; use std::string::ToString; use crate::codec::error::Error; use crate::codec::Result; use crate::expr::EvalContext; /// BinaryLiteral is the internal type for storing bit / hex literal ...
pub mod average; pub mod bar; pub mod solve;
use crate::did::EventHash; use ic_kit::candid::{CandidType, Deserialize}; use ic_kit::Principal; use serde::Serialize; use sha2::{Digest, Sha256}; use std::collections::BTreeSet; #[derive(CandidType, Serialize, Deserialize, Clone, Debug)] pub struct Event { /// The timestamp in ms. pub time: u64, /// The c...
extern crate image; extern crate tobj; extern crate nalgebra; extern crate rand; use image::{RgbImage, Rgb}; use std::path::Path; use tobj::{Mesh,Model,Material}; use nalgebra::{Point, Point2, Point3, Vector3}; use rand::Rng; //probably gonna swap these out with nalgebra lib #[derive(Debug, Clone, Copy)] struct Verte...
use actix::{Actor, Addr, Context, Handler}; use dotenv::var; use log::{info, warn}; // use tokio_postgres::types::ToSql; use tokio_postgres::{connect, Client, NoTls}; use anyhow::Error; // use postgres::Connection; // use r2d2::Pool; // use r2d2_postgres::{PostgresConnectionManager, TlsMode}; // use std::io; use crat...
#[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::CR3 { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W...
use x86::{controlregs, dtables, irq}; use super::apic; use super::interrupts::{InterruptDescriptor, InterruptNumber, PrivilegeLevel, load_idt, set_idt_entry}; use super::interrupt_handlers; use super::segments::KERNEL_CS; use super::timer; pub fn initialize_cpu() { // Need to initialize SSE as early as possible d...
use std::io; use std::net::SocketAddr; error_chain!{ foreign_links { IoError(io::Error); } } pub struct Client { } impl Client { pub fn connect(addr: SocketAddr) -> Result<Client> { try!(Err("pote")) } pub fn run(self) { } }
use crate::init::info::Information; use crate::tools::http::HttpSenderOptions; use crate::tools::Auth; use coap_lite::CoapResponse; use url::Url; mod helper; pub struct CoapSender { coap_url: Url, } impl CoapSender { pub fn new(info: &Information) -> Self { CoapSender { coap_url: info.coa...
pub mod corpus; pub mod index;
// The code below is a stub. Just enough to satisfy the compiler. // In order to pass the tests you can add-to or change any of this code. #[derive(PartialEq, Debug)] pub enum Direction { North, East, South, West, } pub struct Robot{ x: isize, y: isize, direction: Direction, } impl Robot { ...
use super::super::{Match, NativePatternHandler, RuntimeError, Scope}; pub fn native(start: Scope, handler: NativePatternHandler) -> Result<Match, RuntimeError> { handler(start) }
use crate::node::stats::NodeStatsStreamFactory; use crate::node::NodeStats; use std::fs::File; use std::future::Future; use std::io::BufReader; use std::path::{Path, PathBuf}; use std::pin::Pin; use std::task::{Context, Poll}; use std::time::Duration; use tokio::stream::Stream; use tracing::info; #[derive(Clone, Debug...
use thiserror::Error; #[doc(hidden)] #[derive(Debug, PartialEq, Eq, Error)] pub enum JsonError { /// The JSON is syntactically invalid due to EOF. #[error("The given JSON is syntactically invalid due to EOF.")] Eof, /// JSON syntax error. #[error("The given JSON is syntactically invalid at line {l...
use json5_parser::{JVal, Span}; use super::names::Names; use crate::error::Result; use super::json_array_to_rust::GatResult; use crate::imp::structs::var_type::VarType; use crate::imp::structs::rust_value::{RustValue}; use crate::imp::structs::qv::Qv; use crate::imp::structs::rust_param::RustParam; pub fn array_null_o...
mod error; pub use crate::error::Error; use bitvec::prelude::*; use error::InvalidHeaderKind; use std::iter::Peekable; use std::num::ParseIntError; use std::str::Chars; #[derive(Debug, PartialEq)] struct Header { bitorder: BitOrder, byteorder: ByteOrder, negativekind: NegativeKind, pad_bits: bool, } #[derive(Deb...
use crate::geometry::{RawColliderSet, RawShape, RawShapeType}; use crate::math::{RawRotation, RawVector}; use rapier::geometry::{ActiveCollisionTypes, ShapeType}; use rapier::math::Point; use rapier::pipeline::{ActiveEvents, ActiveHooks}; use wasm_bindgen::prelude::*; #[wasm_bindgen] impl RawColliderSet { /// The ...
//! # archive //! //! The `archive` module is an abstraction layer for //! interacting with a crate/api to extract files from //! compressed archives. //! //! The current crate in use is `zip-rs`. //! //! # Remarks //! //! Much of the actual boiler-plate needed to use `zip-rs` //! was taken from the `zip-rs` example co...
use std::io::{self, BufRead, BufReader, Read}; use std::str::FromStr; use std::fs::File; use std::ops::{Index, IndexMut}; use std::collections::BTreeMap; use std::cmp; pub const FREQ_THRESHOLD: usize = 4095; mod mmaped_array { use std::marker::PhantomData; use std::fs::File; use memmap::Mmap; #[deriv...
// Copyright (c) 2021 Kim J. Nordmo and WormieCorp. // Licensed under the MIT license. See LICENSE.txt file in the project pub use aer_license::LicenseType; pub use aer_version::{SemVersion, Versions}; pub use url::Url; pub use crate::metadata::{Description, PackageMetadata}; pub use crate::updater::PackageUpdateData...
#[doc = "Reader of register CTIAPPSET"] pub type R = crate::R<u32, super::CTIAPPSET>; #[doc = "Writer for register CTIAPPSET"] pub type W = crate::W<u32, super::CTIAPPSET>; #[doc = "Register CTIAPPSET `reset()`'s with value 0"] impl crate::ResetValue for super::CTIAPPSET { type Type = u32; #[inline(always)] ...
// Copyright 2018 Alex Crawford // // 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 i...
use crate::{common::{Rect2D, Transform, Tree, TreeEvent, TreeNode}, render::components::Mesh2D, window::ViewPortSize}; use hibitset::BitSet; use specs::{Entities, Entity, ReadExpect, ReadStorage, System, SystemData, World, WriteStorage, prelude::ComponentEvent}; use shrev::{ReaderId}; use nalgebra::{Vector2,Vector3}; ...
mod cli; mod files; mod patching; use cli::Cli; fn main() { Cli::new() }
extern crate util; use std::collections::HashSet; pub fn part_one() -> () { let lines = util::read_input(8); let list: Vec<&str> = lines.split("\n").collect(); let mut seen_lines : HashSet<i32> = HashSet::new(); let mut pc : i32 = 0; let mut acc = 0; loop { if seen_lines.contains(&pc)...
/* CollatzSequence.rs ---------------------------------------------------------- Description: A simple program to solve project Euler 14 https://projecteuler.net/problem=14 Use: compile using Rustc or Cargo, than simply run the compiled file. -------------------------------------------------------...
#[doc = "Register `EVENTS_ENDEPIN[%s]` reader"] pub struct R(crate::R<EVENTS_ENDEPIN_SPEC>); impl core::ops::Deref for R { type Target = crate::R<EVENTS_ENDEPIN_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<EVENTS_ENDEPIN_SPEC>> for R { #[inline(a...
/** * [214] Shortest Palindrome * * You are given a string s. You can convert s to a palindrome by adding characters in front of it. Return the shortest palindrome you can find by performing this transformation.   Example 1: Input: s = "aacecaaa" Output: "aaacecaaa" Example 2: Input: s = "abcd" Output: "dcbabcd"   C...
use std::fs; pub fn main() { println!("------------------------------------ DAY 1 ------------------------------------"); let input = fs::read_to_string("input/day1.txt").unwrap(); let input_split: Vec<i32> = input .split("\n") .filter(|n| n != &"") .map(|n| n.parse().unwrap()) ...
use rodio::Source; use serde::{Deserialize, Serialize}; use std::collections::VecDeque; use std::sync::{Arc, Mutex}; pub trait APUChannel { fn get_output(&mut self) -> f32; } pub trait TimedAPUChannel: APUChannel { fn timer_clock(&mut self); } #[derive(Serialize, Deserialize)] pub struct BufferedChannel { ...
// Copyright 2022 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 ...
use crate::utils::ENV; use slog::LevelFilter; use slog::{o, Drain, FnValue, Level, Logger}; use std::fs::OpenOptions; use std::sync::Mutex; const APP_NAME: &str = "demo App"; pub struct Logging { pub logger: Logger, } impl Logging { pub fn new() -> Logger { //! if path includes in logconfig, log to f...
use std::cell::UnsafeCell; pub struct Cell<T> { value: UnsafeCell<T>, } // implied by UnsafeCell // impl<T> !Sync for Cell<T> {} impl<T> Cell<T> { pub fn new(value: T) -> Self { Cell { value: UnsafeCell::new(value), } } pub fn set(&self, value: T) { unsafe { ...
//! Anything related to the adapter API (IBluetooth). use bt_topshim::btif::{ BaseCallbacks, BaseCallbacksDispatcher, BluetoothInterface, BtBondState, BtDiscoveryState, BtProperty, BtPropertyType, BtSspVariant, BtState, BtStatus, BtTransport, RawAddress, }; use bt_topshim::profiles::hid_host::{HHCallbacksDispa...
//! C API wrappers for calling Telamon through FFI. //! //! The goal of the C API is to provide thin wrappers over existing Rust functionality, and only //! provides some cosmetic improvements to try and provide a somewhat idiomatic C interface. extern crate libc; extern crate telamon; extern crate telamon_kernels; u...
use clap::{App, Arg}; use dorea::server::{DoreaServer, ServerOption}; use dorea::DOREA_VERSION; use std::path::PathBuf; const TEMPLATE: &str = " ⎐ {bin} - (V{version}) ⎐ USAGE: {usage} FLAGS: {flags} OPTIONS: {options} Dorea-Core: https://github.com/mrxiaozhuox/dorea.git Dorea-Repo: https://github.com/doreadb/ ...
use std::fmt::{Debug, Display}; use std::io::prelude::*; use std::ops::Add; trait HasArea { fn area(&self) -> f64; } struct Circle { x: f64, y: f64, radius: f64, } impl HasArea for Circle { fn area(&self) -> f64 { ::std::f64::consts::PI * (self.radius * self.radius) } } fn foo<T: Deb...
use tonic::transport::Server; use proto::auth::auth_server::AuthServer; mod auth; mod proto; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { env_logger::init(); let addr = "127.0.0.1:5050".parse()?; let auth_service = auth::AuthService::default(); Server::builder() ...
struct Solution; impl Solution { pub fn single_numbers2(nums: Vec<i32>) -> Vec<i32> { let mut set = std::collections::HashSet::new(); for i in nums { if set.contains(&i) { set.remove(&i); } else { set.insert(i); } } ...
use std::sync::Arc; use bvh::aabb::{Bounded, AABB}; use bvh::bounding_hierarchy::BHShape; use nalgebra::{Point2, Point3, Vector2, Vector3}; use tobj::Mesh; use crate::helpers::{ coordinate_system, gamma, max_dimension_vec_3, permute, uniform_sample_triangle, }; use crate::lights::area::AreaLight; use crate::light...
// * Daily Coding Problem August 4th 2020 // * [Medium] -- Square // * A competitive runner would like to create a route that starts and ends // * at his house, with the condition that the route goes entirely uphill // * at first, and then entirely downhill. // * Given a dictionary of places of the form {location: e...
pub mod models; pub mod validator; #[cfg(test)] mod tests { use crate::models::IAPRequest; use crate::validator::ReqClient; #[tokio::test] async fn it_works() { let data = IAPRequest { receipt_data: "asdfadsf".into(), password: "adsf".into(), exclude_old_tra...
/* Copyright (C) 2005-2006 Jean-Marc Valin File: fftwrap.c Wrapper for various FFTs Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright noti...
use std::convert::TryInto; use abci::{Event, KVPair}; use chain_core::common::{TendermintEventKey, TendermintEventType}; use chain_core::init::coin::Coin; use chain_core::init::config::SlashRatio; use chain_core::state::account::StakedStateAddress; use chain_core::state::tendermint::TendermintVotePower; use chain_cor...
use rustyline::error::ReadlineError; use rustyline::Editor; mod gl_ast; mod gl_env; mod gl_eval; mod gl_exception; mod gl_lexer; mod gl_parser; mod gl_runtime; mod gl_statement; mod gl_std; mod gl_token; mod gl_token_position; mod gl_tokens; const GL_VERSION: &str = "0.1.0-alpha"; fn main() { let gl_args: Vec<String...
#![no_std] #[macro_use] extern crate bitflags; extern crate volatile_register; #[allow(non_snake_case)] pub mod peripheral; #[cfg(test)] mod tests { #[test] fn it_works() {} }
struct Foo<'a> { i: &'a i32, } /* データ型のライフタイム 関数と同様に、データ型はメンバのライフタイムを指定できます。 Rustは、参照を含む構造体が、その参照あ指す所有者よりも長く存在しないことを検証します。 構造体には何も何ところを指している参照を含めることはできません */ fn main() { let x = 42; let foo = Foo { i: &x }; println!("{}", foo.i); }
// This should fail even without validation //@compile-flags: -Zmiri-disable-validation #![feature(never_type)] struct Human; fn main() { let _x: ! = unsafe { std::mem::transmute::<Human, !>(Human) //~ ERROR: entering unreachable code }; }
pub use super::core::*; use serde::{Serialize, Deserialize}; use async_trait::async_trait; #[derive(Deserialize,Serialize)] pub struct DestinationLogConfig {} pub struct DestinationLog { name : String } #[typetag::serde(name = "log")] impl DestinationConfig for DestinationLogConfig { fn name(&self) -> Strin...
use mkit::{ self, db::{self, Bloom}, }; use std::{cmp, convert::TryFrom, hash, marker, time}; use crate::{Error, Result}; // Iterator wrapper, to wrap full-table scanners and count seqno, // index-items, deleted items and epoch. pub struct BuildScan<K, V, D, I> { iter: I, entry: Option<db::Entry<K, V...
// Size to use when doing `cargo bench`; extensively tuned to run in // "not too long" on my laptop -nmatsakis const BENCH_SIZE: usize = 250_000_000 / 512; fn bench_harness<F: FnMut(&mut [u32])>(mut f: F, b: &mut test::Bencher) { let base_vec = super::default_vec(BENCH_SIZE); let mut sort_vec = vec![]; b.i...
// Copyright 2019 Conflux Foundation. All rights reserved. // Conflux is free software and distributed under GNU General Public License. // See http://www.gnu.org/licenses/ use crate::{ consensus::SharedConsensusGraph, light_protocol::{ common::{FullPeerFilter, LedgerInfo}, handler::sync::TxInf...
struct Solution; impl Solution { fn find_the_distance_value(arr1: Vec<i32>, arr2: Vec<i32>, d: i32) -> i32 { let mut count: Vec<Vec<i32>> = vec![vec![0; 2001]; 2]; for x in arr1 { count[0][(x + 1000) as usize] += 1; } for x in arr2 { count[1][(x + 1000) as us...
use futures01::Future; use itertools::Itertools; use serde::de::DeserializeOwned; use serde_json::{self as json, Value as Json}; use std::collections::{BTreeSet, HashMap}; use std::fmt; /// Macro generating functions for RPC requests. /// Args must implement/derive Serialize trait. /// Generates params vector from inp...
use crate::{Error, Result}; use quick_xml::events::BytesStart; use quick_xml::Reader; use std::io::BufRead; pub(crate) fn get_attribute<B: BufRead>( reader: &Reader<B>, tag: &BytesStart, attr: &str, ) -> Result<Option<String>> { tag.attributes() .flat_map(|x| x) .map(|x| (x....
use super::schema::users; use super::schema::books; #[derive(Queryable)] pub struct Post { pub id: i32, pub title: String, pub body: String, pub published: bool, } //New user registration #[derive(Insertable,Queryable,Serialize,Deserialize)] #[table_name="users"] pub struct UserReg{ pub name:Str...
mod parser; mod lexer; pub use parser::Parser;
mod ast_kind; mod ast_print_mode; mod decl_kind; mod error_code; mod goal_prec; mod param_kind; mod parameter_kind; mod sort_kind; mod symbol_kind; pub use self::ast_kind::Z3_ast_kind; pub use self::ast_print_mode::Z3_ast_print_mode; pub use self::decl_kind::Z3_decl_kind; pub use self::error_code::Z3_error_code; pub u...