text
stringlengths
8
4.13M
use reqwest::{Response, StatusCode}; use std::time::UNIX_EPOCH; use tokio::time::Duration; static RESET_HEADER: &str = "x-rate-limit-reset"; pub fn check_rate_limit(resp: &Response) -> Option<Duration> { if resp.status() != StatusCode::TOO_MANY_REQUESTS { return None; } let rate_reset_at = resp.h...
use std::collections::HashMap; use std::io::Read; use std::sync::Arc; use hyper::client::Client; use hyper::client::Response; use hyper::client::IntoUrl; use hyper::header::ContentType; use hyper::header::Headers; use hyper::mime; use serde::Deserialize; use url::form_urlencoded; use super::errors::*; use super::re...
use std::cmp::min; fn one_away(s1: String, s2: String) -> bool { let mut dp = vec![vec![0; s2.len() + 1]; s1.len() + 1]; for i in 0..s1.len() + 1 { for j in 0..s2.len() + 1 { if i == 0 { dp[i][j] = j; continue; } if j == 0 { ...
extern crate sysinfo; use cursive::views::Dialog; use cursive::Cursive; use cursive::views::LinearLayout; use sysinfo::{ProcessExt, ProcessorExt, SystemExt, DiskExt}; use std::{thread, time}; fn get_my_processes(system : &mut sysinfo::System) -> String { system.refresh_all(); let mut my_vec = Vec::new(); ...
//! use std::fmt; use serde::{Deserialize, Serialize}; #[macro_export] macro_rules! location { () => { $crate::Location { file: file!().to_string(), line: line!(), column: column!(), } } } #[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, ...
// Copyright 2016 coroutine-rs Developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except accordi...
use std::convert::{TryFrom, TryInto}; use proc_macro2::Span; use syn::{spanned::Spanned, Error, ExprIf, Result}; use crate::glsl::Glsl; use crate::glsl::GlslFragment; use crate::glsl::GlslLine; use super::YaslExprFunctionScope; use super::YaslExprLineScope; use crate::yasl_block::YaslBlock; #[derive(Debug)] pub str...
#![no_main] #[macro_use] extern crate libfuzzer_sys; extern crate parser_c; use std::str; fuzz_target!(|data: &[u8]| { if let Ok(data) = str::from_utf8(&data) { let _ = parser_c::parse(&data, "input"); } });
fn main() { let puzzle = "iwrupvqb"; for i in 0.. { let puzzle_number = String::from(puzzle) + &i.to_string(); let md5 = md5::compute(&puzzle_number); if hex::encode(*md5).to_string().starts_with("000000") { dbg!(puzzle_number, md5); break; } } }
use std::ops::Add; use bevy::{core::FixedTimestep, prelude::*}; #[derive(Debug, Copy, Clone)] enum InputCommand { LEFT, RIGHT, UP, DOWN, } struct OwnedInput { owner_id: u8, command: InputCommand, } struct PlayerConfig { move_speed: f32, } struct Player { id: u8, name: String, } ...
use std::cmp::Ordering::{self, *}; use crate::{Atomize, IsBot, IsTop, LatticeFrom, LatticeOrd, Merge}; /// Wraps a lattice in [`Option`], treating [`None`] as a new bottom element which compares as less /// than to all other values. /// /// This can be used for giving a sensible default/bottom element to lattices tha...
#![doc = "generated by AutoRust 0.1.0"] #![allow(unused_mut)] #![allow(unused_variables)] #![allow(unused_imports)] use crate::models::*; use reqwest::StatusCode; use snafu::{ResultExt, Snafu}; pub mod operations { use crate::models::*; use reqwest::StatusCode; use snafu::{ResultExt, Snafu}; pub async f...
use std::convert::TryFrom; use std::net::SocketAddr; use std::{io, sync::Arc}; use async_trait::async_trait; use crate::{ app::dns_client::DnsClient, proxy::{stream::SimpleProxyStream, OutboundHandler, ProxyStream, TcpOutboundHandler}, session::{Session, SocksAddr}, }; pub struct Handler { pub actors...
use aoc_lib::AocImplementation; use itertools::Itertools; use image; fn main() { let day = Day8{}; day.start(8); } struct Day8 {} impl AocImplementation<u8> for Day8 { fn process_input(&self, input: &str) -> Vec<u8> { input.split("").filter(|s| s != &"").map(|s| s.parse().unwrap()).collect() ...
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { _reserved0: [u8; 0x04], #[doc = "0x04..0x44 - Cluster CH%s, containing ?CR1, ?CR2, ?FRCR, ?SLOTR, ?IM, ?SR, ?CLRFR, ?DR"] pub ch: [CH; 2], } impl RegisterBlock { #[doc = "0x04..0x24 - Cluster CH%s, containing ?CR1, ?CR2, ?FRCR, ?SLOTR, ?IM...
use actix_web::{delete, get, post, put, web}; use actix_web::web::Json; use sqlx::SqlitePool; use crate::{common}; use crate::common::{DynamicResult, make_api_response}; use crate::errors::ApiError; use crate::middleware::Auth; use crate::runs::{Run, UpdateRun}; #[derive(Serialize)] pub struct ListRunsResult { ...
use assembly_core::nom::{ bytes::complete::take, combinator::{cond, map, map_res}, multi::length_count, number::complete::{le_u32, le_u64, le_u8}, IResult, }; use std::convert::TryFrom; use super::core::{ FileVersion, SceneRef, SceneTransition, SceneTransitionInfo, SceneTransitionPoint, ZoneFil...
//! StarkNet L2 sequencer client. mod builder; pub mod error; pub mod reply; pub mod request; use self::request::{add_transaction::ContractDefinition, Call}; use crate::{ core::{ BlockId, CallSignatureElem, Chain, ClassHash, ConstructorParam, ContractAddress, ContractAddressSalt, Fee, StarknetTrans...
//! Module with everything related to the OAuth2 login flow mod port; mod callback_endpoint; pub mod db; use crate::env::Env; use actix_web::{HttpServer, App}; use rand::Rng; use std::sync::mpsc::{Sender, channel}; use crate::api::oauth::LoginData; use crate::{Result, unwrap_other_err}; /// Struct des...
use std::rc::Rc; use flux::ast::SourceLocation; use flux::semantic::nodes::Expression; use flux::semantic::types::MonoType; use flux::semantic::walk::{Node, Visitor}; use lspower::lsp; pub struct FunctionInfo { pub name: String, pub package_name: String, pub required_args: Vec<String>, pub optional_ar...
//! More examples on sample-based and frame-based implementation of digital //! systems. I implemented these as iterator based, as usual. //! //! Runs entirely locally without hardware. Rounding might be different than on //! device. Except for when printing you must be vigilent to not become reliant //! on any std too...
#[macro_use] extern crate lazy_static; use regex::Regex; mod z_decode; mod z_encode; pub use z_decode::z_decode; pub use z_encode::z_encode; #[derive(Debug, PartialEq, Eq)] pub struct GhcSummary { pub allocs: u64, pub gcs: u64, pub avg_res: u64, pub max_res: u64, pub in_use: u64, } lazy_static!...
use hacspec_lib::prelude::*; use unsafe_hacspec_examples::aes_gcm::gf128::*; #[test] fn test_gmac() { let msg = ByteSeq::from_hex("feedfacedeadbeeffeedfacedeadbeefabaddad20000000000000000000000005a8def2f0c9e53f1f75d7853659e2a20eeb2b22aafde6419a058ab4f6f746bf40fc0c3b780f244452da3ebf1c5d82cdea2418997200ef82e44ae7e3...
/* * 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::alloc; use std::env; use std::mem; use nix::unistd; use reverie::syscalls::Displayable; u...
use std::collections::HashMap; use std::time::SystemTime; /// `InputCellID` is a unique identifier for an input cell. #[derive(Clone, Copy, Debug, PartialEq)] pub struct InputCellID { position: (u32, u32), } /// `ComputeCellID` is a unique identifier for a compute cell. /// Values of type `InputCellID` and `Comp...
extern "C" { pub static mut end: u32; } static mut allocator_end: u32 = 0; #[lang="exchange_malloc"] unsafe fn kmalloc(size: usize, align: usize) -> *mut u8 { let aligned_size: u32 = (size + align) as u32; let ret = (allocator_end & !(align as u32 - 1)) + align as u32; allocator_end = ret + aligned_si...
use std::fs; const ROWS: i32 = 128; const COLUMNS: i32 = 8; fn parse_seat_id(code: String) -> i32 { let mut lower = 0; let mut upper = ROWS; for i in code[..7].chars() { let m = (lower + upper) / 2; if i == 'F' { upper = m; } else if i == 'B' { lower = m; ...
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
use std::cmp; use std::cmp::Ordering; #[derive(Debug, Copy, Clone)] enum Segment { HorizontalSegment { x_1: i32, x_2: i32, y: i32 }, VerticalSegment { y_1: i32, y_2: i32, x: i32 }, } #[derive(Eq, PartialEq, Debug, Copy, Clone)] pub struct Point(i32, i32); impl Point { fn manhattan_distance(&self) -> i32 {...
extern crate byteorder; use salticidae::{Deserializable, Deserialize, Serializable, Serialize, Stream}; use tokio::net::TcpListener; use tokio::net::TcpStream; use tokio::runtime::Runtime; use tokio::sync::oneshot; #[test] fn test_listen() { #[derive(Serialize, Deserialize, Debug, PartialEq, Clone)] enum Messa...
//! Utilities for working with `/proc`, where Linux's `procfs` is typically //! mounted. `/proc` serves as an adjunct to Linux's main syscall surface area, //! providing additional features with an awkward interface. //! //! This module does a considerable amount of work to determine whether `/proc` //! is mounted, wit...
mod main_controller; use router::Router; #[derive(Debug)] pub struct Routes {} impl Routes { pub fn new() -> Router { let mut router = Router::new(); router.get("/", main_controller::Index, "index"); router } }
//! ## `Call Account` Receipt Binary Format Version 0 //! //! On success (`is_success = 1`) //! //! ```text //! +---------------------------------------------------+ //! | | | | | //! | tx type | version | is_success | new State | //! | (1 byte) | (2 bytes) | ...
extern crate base58; use pow::*; use std::time::{SystemTime, UNIX_EPOCH}; use std::{ fmt, str }; use self::base58::ToBase58; macro_rules! genesis_block { () => { Block::new("Genesis Block".to_string(), vec![]); } } #[derive(Debug)] pub struct Block { pub time_stamp: u64, pub data: String, ...
extern crate libc; use libc::*; use std::net::{TcpStream}; //use std::thread; use std::io::{Read, Write}; use std::str; use std::os::unix::io::AsRawFd; #[link(name = "osl", kind = "static")] #[link(name = "ssl", kind = "static")] #[link(name = "crypto", kind = "static")] extern { fn newctx(cert_file: *const c_...
// Passthrough decoder for librespot use std::{ io::{Read, Seek}, time::{SystemTime, UNIX_EPOCH}, }; // TODO: move this to the Symphonia Ogg demuxer use ogg::{OggReadError, Packet, PacketReader, PacketWriteEndInfo, PacketWriter}; use super::{AudioDecoder, AudioPacket, AudioPacketPosition, DecoderError, Decode...
use super::{ super::{backend::Backend, entity::Entity}, GetEntityFuture, ListEntitiesFuture, RemoveEntitiesFuture, RemoveEntityFuture, UpsertEntitiesFuture, UpsertEntityFuture, }; use futures_util::future::{self, FutureExt, TryFutureExt}; pub trait Repository<E: Entity, B: Backend> { /// Retrieve an im...
pub fn print_fun(uper:i32,lower:i32){ for index in uper..lower{ println!("Downward:{}",index); } }
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use base::prelude::*; use atomic::{Atomic}; const UNINITIALIZED: u8 = 0; const WORKING: u8 = 1; const INITIALI...
fn f() { } fn main() { // Can't produce a bare function by binding let g: native fn() = bind f(); //!^ ERROR mismatched types: expected `native fn()` but found `fn@()` }
use criterion::{criterion_group, criterion_main, Criterion}; use pixelwar_client_rs::proof; fn criterion_benchmark(c: &mut Criterion) { let mut proof_gen = proof::ProofGeneratorBuilder::new() .with_prefix("prefix-") .with_suffix_length(20) .with_digest_prefix("00000") ...
//! DMA-based serial logging - Teensy 4 example //! //! This use the same setup as the `t4_uart.rs` example. Connect //! a serial receive to pin 14, and you should receive log messages //! and timing measurements. #![no_std] #![no_main] extern crate panic_halt; mod demo; use cortex_m_rt::entry; use cortex_m_rt::int...
use reqwest::r#async::Client; use std::sync::Arc; use std::time::Duration; use tokio::runtime::Runtime; pub struct DaemonRuntime<'a> { pub runtime: &'a mut Runtime, pub client: Arc<Client>, } impl<'a> DaemonRuntime<'a> { pub fn new(runtime: &'a mut Runtime) -> Self { // This client contains a thre...
use crate::llvm; use crate::builder::Builder; use crate::common::CodegenCx; use libc::c_uint; use llvm::coverageinfo::CounterMappingRegion; use rustc_codegen_ssa::coverageinfo::map::{CounterExpression, FunctionCoverage}; use rustc_codegen_ssa::traits::{ BaseTypeMethods, CoverageInfoBuilderMethods, CoverageInfoMet...
use rug::Float; use std::fs::create_dir_all; use std::path::Path; use std::sync::mpsc::channel; use structopt::StructOpt; use threadpool::ThreadPool; use mandelbrot::{color_palette, Mandel}; #[derive(StructOpt)] #[structopt(name = "mandlebrot", about = "Generate Mandlebrot zoom images")] struct Opt { #[structopt(...
/********************************************** > File Name : Range.rs > Author : lunar > Email : lunar_ubuntu@qq.com > Created Time : Fri 01 Apr 2022 04:27:46 PM CST > Location : Shanghai > Copyright@ https://github.com/xiaoqixian **********************************************/ use std::co...
extern crate base64; use hex; use reqwest::{StatusCode, Url}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use std::fmt; use std::fs; use super::constants::*; /// Get list of `Color` using Google Cloud Vision API pub(crate) fn get_dominant_colors(image_url: &Url) -> Result<Vec<Color>, CloudVis...
extern crate day_02_corruption_checksum; extern crate utils; use day_02_corruption_checksum::corr_checksum; use utils::file2str; fn main() { let puzzle_string = file2str("puzzle.txt"); let checksum = corr_checksum(&puzzle_string); println!("The checksum is: {}", checksum); }
use crate::dice::ui::RollDiceDialog; use crate::state; use cursive::theme::*; use cursive::traits::*; use cursive::utils::span::SpannedString; use cursive::view::*; use cursive::views::*; use cursive::Cursive; use enumset::EnumSet; use std::sync::mpsc; pub struct Ui { cursive: Cursive, ui_rx: mpsc::Receiver<Ui...
//! [Generic Types], Traits, and Lifetimes //! //! [generic types]: https://doc.rust-lang.org/book/ch10-00-generics.html pub mod sec00; pub mod sec01; pub mod sec02; pub mod sec03; pub use sec01::{largest, Point}; pub use sec02::{detailed_notify, detailed_notify2, notify, notify2, summarizable}; pub use sec02::{Articl...
#[repr(C)] #[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)] pub struct Vertex { // wgpu::FrontFace::Ccw pub(crate) position: [f32; 3], pub(crate) color: [f32; 3], } // descriptor impl Vertex { pub fn descriptor<'a>() -> wgpu::VertexBufferLayout<'a> { wgpu::VertexBufferLayout { ...
extern crate utils; use std::env; use std::collections::BTreeSet; use std::ops::RangeInclusive; use std::io::{self, BufReader}; use std::io::prelude::*; use std::fs::File; use utils::*; type Seat = String; type Input = Vec<Seat>; fn bsp_to_val(s: &str, l_chr: char, h_chr: char, mut range: RangeInclusive<usize>) -> ...
use std::io::{self}; fn main() -> io::Result<()> { let files_results = vec![ ("test.txt", 1, 1), ("input.txt", 1, 1) ]; for (f, result_1, result_2) in files_results.into_iter() { println!("File: {}", f); let file_content: Vec<String> = std::fs::read_to_string(f)? ...
use std::fs; use std::path::PathBuf; use serde_json::Value; fn main() { fs::remove_dir_all("out").unwrap(); fs::create_dir("out").unwrap(); in_to_out("./in"); println!("All done.") } fn in_to_out(starting_path: &str) { for entry in fs::read_dir(starting_path).unwrap() { let in_path = entr...
use aoc::*; use std::iter; fn main() -> Result<()> { let input: Vec<_> = input("16.txt")?.bytes().map(|b| b - b'0').collect(); let offset = extract(&input[0..7]); let mut signal: Vec<_> = iter::repeat(input) .take(10000) .flatten() .skip(offset) .collect(); for _ in 0....
use crate::component::entry::TxEntry; use crate::error::SubmitTxError; use crate::pool::TxPool; use crate::FeeRate; use ckb_error::{Error, InternalErrorKind}; use ckb_snapshot::Snapshot; use ckb_types::{ core::{ cell::{ resolve_transaction, OverlayCellProvider, ResolvedTransaction, TransactionsP...
use crate::{ rows::{row::Row, row_schema::RowSchema}, table::table_name::TableName, table_column_name::TableColumnName, }; use apllodb_shared_components::{NnSqlValue, SqlValue}; use std::collections::HashSet; /// - people: /// - id BIGINT NOT NULL, PRIMARY KEY /// - age INTEGER NOT NULL #[derive(Clone,...
use crate::{alphabet::Alphabet, dfa::DFA, range_set::Range, state::State}; use core::{marker::PhantomData, ops::Bound}; use valis_ds::{ ops::{Complement, Difference, Intersection, Union}, set::{Set, SetIterExt, VectorSet}, }; #[derive(Debug, PartialEq, Eq, Clone, Hash)] pub struct StandardDFA<A, I: State> { ...
use mysql::from_row; use mysql::error::Error::MySqlError; use common::utils::*; use common::lazy_static::SQL_POOL; pub fn is_voted(user_id: &str, comment_id: &str) -> bool { let mut result = SQL_POOL.prep_exec(r#" SELECT count(id) FROM comment_vote WHERE ...
//! Mutator context for each application thread. use crate::plan::barriers::{Barrier, WriteTarget}; use crate::plan::global::Plan; use crate::plan::AllocationSemantics as AllocationType; use crate::policy::space::Space; use crate::util::alloc::allocators::{AllocatorSelector, Allocators}; use crate::util::OpaquePointer...
use cargo_rename_demo::rename_demo; fn main() { rename_demo::foo(); }
#[macro_use] extern crate log; #[cfg(target_os="android")] #[allow(non_snake_case)] pub mod android; pub mod server; pub mod client; pub mod types;
//! Rust crate associated with the article [`DSS21`]. //! //! Provides an efficient function to compute the condition number of *V_n*, the Vandermonde matrix associated with the *n*th cyclotomic polynomial. //! The condition number is computed via the trace of the matrix *H_n*, as shown in [`DSS20`]. //! //! [`DSS20`]:...
// Inspired by: https://github.com/denismr/SymmetricPCVT/blob/master/C%2B%2B/SPCVT.cc use bitset_core::BitSet; use std::vec::Vec; use crate::{utils::Octant, Fov, FovCallbackEnum, FovConfig, Los, VisionShape}; use rl_utils::{tranthong_func, Area, Coord}; const fn nth_triangle_nr(n: usize) -> usize { (n * (n + 1))...
use crate::schema::*; #[derive(Queryable, Debug)] pub struct Actor { pub actor_id: i32, pub first_name: String, pub last_name: String, pub last_update: diesel::pg::data_types::PgTimestamp } #[derive(Insertable)] #[table_name = "actor"] pub struct NewActor { pub actor_id: i32, pub first_name: S...
extern crate chrono; use chrono::{DateTime, Utc}; pub fn log(msg: String) { let now: DateTime<Utc> = Utc::now(); print!("[{}]: ", now.to_rfc3339()); println!("{}", msg); }
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use std::io::{self, prelude::*}; use serde::{Serialize, Deserialize}; mod helper; pub use helper::*; #[derive(PartialEq, Eq, Clone, Copy, Debug, Hash, Serialize, Deserialize)] pub struct Pointer { #[serde(rename = "FileID")] pub file: i32, #[serd...
use std::error::Error; use std::io::{self, prelude::*}; fn main() -> Result<(), Box<dyn Error>> { run_tests(io::stdin().lock()) } /// Panics if the input isn't correctly formatted. #[allow(non_snake_case)] fn run_tests(input: impl BufRead) -> Result<(), Box<dyn Error>> { let mut lines = input.lines(); le...
use crate::{ widget, widget::unit::content::{ContentBoxItemLayout, ContentBoxItemNode, ContentBoxNode}, widget_component, }; use serde::{Deserialize, Serialize}; #[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct ContentBoxProps { #[serde(default)] pub clipping: bool, } implement_p...
use async_trait::async_trait; use uuid::Uuid; use common::cache::Cache; use common::error::Error; use common::infrastructure::cache::InMemCache; use common::result::Result; use crate::domain::author::AuthorId; use crate::domain::category::CategoryId; use crate::domain::collection::{Collection, CollectionId, Collectio...
#[macro_use] extern crate lazy_static; use chrono::{DateTime, NaiveDateTime, Utc}; use redis::FromRedisValue; use redis::InfoDict; use std::collections::HashMap; use std::time::Duration; lazy_static! { static ref IGNORE_COMMANDS: Vec<&'static str> = vec!["SLOWLOG", "INFO"]; } #[derive(Default, Debug)] struct Red...
extern crate day_06_memory_reallocation; use day_06_memory_reallocation::memory_reallocate; fn main() { let puzzle = vec![4, 1, 15, 12, 0, 9, 9, 5, 5, 8, 7, 3, 14, 5, 12, 3]; let steps = memory_reallocate(puzzle); println!("Steps to seen config: {}", steps); }
//! This module corresponds to `mach/mach_init.h`. use port::mach_port_t; use mach_types::{thread_port_t, host_t}; use vm_types::vm_size_t; use kern_return::kern_return_t; extern "C" { pub fn mach_host_self() -> mach_port_t; pub fn mach_thread_self() -> thread_port_t; pub fn host_page_size(host: host_t, s...
pub mod planet_events;
use alloc::{boxed::Box, sync::Arc}; use core::{ops::Drop, task::Poll}; pub struct Buffer { device: Arc<wgpu::Device>, pub(crate) buffer: Arc<wgpu::Buffer>, pub(crate) offset: usize, pub(crate) size: usize, free: Box<dyn Fn() + Sync + Send + 'static>, } impl Buffer { pub(crate) fn new<F>(device...
use crate::utils::{ config::{ LOCK_TYPE_FLAG, METRIC_TYPE_FLAG_MASK, REMAIN_FLAGS_BITS, SINCE_TYPE_TIMESTAMP, VALUE_MASK, }, transaction::{get_sum_sudt_amount, XChainKind}, types::{Error, ToCKBCellDataView}, }; use alloc::string::String; use alloc::vec::Vec; use bech32::ToBase32; use bitcoin_spv...
pub mod cmd_queue; pub mod modeless; pub mod personal_data; pub use cmd_queue::CmdQueue; pub use modeless::Modeless; pub use personal_data::PersonalData;
use super::*; #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] #[repr(transparent)] pub struct ToneSweep(u8); impl ToneSweep { const_new!(); bitfield_int!(u8; 0..=2: u8, sweep_shift, with_sweep_shift, set_sweep_shift); bitfield_bool!(u8; 3, frequency_decreasing, with_frequency_decreasing, set_frequency_decr...
use crate::request::prelude::*; pub struct DeleteInvite<'a> { code: String, fut: Option<Pending<'a, ()>>, http: &'a Client, reason: Option<String>, } impl<'a> DeleteInvite<'a> { pub(crate) fn new(http: &'a Client, code: impl Into<String>) -> Self { Self { code: code.into(), ...
extern crate staticfile; extern crate mount; extern crate iron; use std::env; use std::path::Path; use staticfile::Static; use mount::Mount; use iron::Iron; fn main() { let mut mount = Mount::new(); let root = env::var("ROOT").unwrap(); mount.mount("/", Static::new(Path::new(&*root).join("html"))); Ir...
use gembiler::code_generator::intermediate; #[test] fn it_works() { let code = r#" DECLARE a, b BEGIN READ a; IF a GEQ 0 THEN WHILE a GE 0 DO b ASSIGN a DIV 2; b ASSIGN 2 TIMES b; IF a GE...
//! ## Data for the [`Mission` component](https://docs.lu-dev.net/en/latest/components/084-mission.html) use serde::{Deserialize, Serialize}; /// Data for the [`Mission` component](https://docs.lu-dev.net/en/latest/components/084-mission.html) #[derive(Default, Debug, PartialEq, Deserialize, Serialize)] pub struct Mi...
use std::fmt::{ Debug, Formatter, Result as FmtResult }; use std::cmp::{ PartialEq, Ordering }; use std::hash::{ Hash, Hasher }; use std::collections::HashMap; use std::cell::RefCell; use std::rc::Rc; use crate::vm::error::RuntimeError; use crate::common::Value; #[derive(Clone, PartialEq)] pub struct Table { pub tb...
fn is_valid(s: &str) -> bool { use regex::Regex; let re = Regex::new(r"^([0-9]+)-([0-9]+) ([a-z]): ([a-z]+)").unwrap(); let cap = re.captures(s).unwrap(); let min:usize = cap[1].parse().unwrap(); let max:usize = cap[2].parse().unwrap(); let cnt = cap[4].matches(&cap[3]).count(); min <= cnt &...
use actix_web::web::Data; use actix_web_httpauth::extractors::basic::BasicAuth; use actix_web::HttpResponse; use super::*; use crate::controller::State as TargetState; use crate::controller::{Command, Event}; ///////////////////// lamp commands /////////////////////////////// pub fn toggle(state: Data<State>, auth: B...
use std::hash::Hash; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Suit { Diamonds, Clubs, Hearts, Spades, } impl Suit { pub fn list() -> Vec<Self> { vec![Self::Diamonds, Self::Clubs, Self::Hearts, Self::Spades] } } #[cfg(test)] mod tests { use super::Suit; #[te...
use flate2::{read::GzDecoder, write::GzEncoder, Compression}; use group::{RsaGroup, RsaQuotientGroup, SemiGroup}; use num_bigint::BigUint; use num_traits::Num; use rug::{ops::Pow, Assign, Integer}; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; use std::fs::File; use std::io::{BufRead, BufReader}...
use std::collections::HashMap; use tera::{Result, Value}; use super::TeraFilter; pub fn all<'a>() -> Vec<(&'static str, TeraFilter<'a>)> { let mut result = Vec::new(); result.push(("TitleCase", &case::title_case as TeraFilter<'a>)); result.push(("togglecase", &case::toggle_case as TeraFilter<'a>)); r...
use std::time::Instant; pub struct FpsCounter { pub start_time: Instant, pub frame_count: usize, pub fps: usize, } impl FpsCounter { pub fn new() -> Self { FpsCounter { start_time: Instant::now(), frame_count: 0, fps: 0, } } pub fn rese...
use crate::{ field_access::Access, ident_or_index::IdentOrIndex, parse_utils::ParsePunctuated, structural_alias_impl::TypeParamBounds, }; use as_derive_utils::{ attribute_parsing::with_nested_meta, datastructure::{DataStructure,Field,FieldMap}, utils::{LinearResult,SynResultExt,SynPathExt},...
use super::{RdfProp, RdfStorePropExt}; use extend::ext; use skorm_store::{NamedNode, NamedOrBlankNode, RdfStore, SubjectExt}; #[derive(Debug, Clone, Copy)] pub struct RdfClass<'a> { store: &'a RdfStore, name: NamedNode<'a>, } impl<'a> RdfClass<'a> { pub fn name(&self) -> &'a str { self.name.iri().as_ref() ...
use super::super::{ components, resources::game_map::{GameMap, TileProperties}, }; use specs::{Read, ReadStorage, System, WriteStorage}; pub struct CollisionsSolid; impl<'a> System<'a> for CollisionsSolid { type SystemData = ( WriteStorage<'a, components::Moved>, ReadStorage<'a, components...
use crate::context::QueryEnv; use crate::parser::query::{Selection, TypeCondition}; use crate::{Context, ContextSelectionSet, ObjectType, Result, Schema, SchemaEnv, Type}; use futures::{Future, Stream}; use std::pin::Pin; /// Represents a GraphQL subscription object #[async_trait::async_trait] pub trait SubscriptionTy...
use image::DynamicImage; use super::super::Transformer; impl Transformer for DynamicImage { fn as_vector(&self) -> Vec<f32> { self.raw_pixels().iter().map(|&elem| elem as f32).collect() } }
/* chapter 4 syntax and semantics */ struct Circle { h: f64, v: f64, r: f64, } impl Circle { fn area(&self) -> f64 { std::f64::consts::PI * (self.r * self.r) } fn grow(&self, increment: f64) -> Circle { Circle { h: self.h, v: self.v, r: self.r + increment } } } fn main() { ...
use std::{fmt, ops::Deref}; use serde::{ de::{self, Visitor}, ser::Serializer, }; use serde_derive::{Deserialize, Serialize}; #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "PascalCase")] pub struct KV { pub key: String, pub value: KVValue, } impl KV { pub fn new<K, V>(key: K, valu...
//! Proof Implemation //! use std::fmt::Display; use crate::hash::{hash_leaf, hash_mid}; use crate::merkle_tree::ProofNode; #[derive(Debug)] pub struct Proof<T: Display> { root_hash: String, val: T, path: Vec<ProofNode>, } impl<T> Proof<T> where T: Display { pub fn new(root_hash: String, val: T,...
use logger::Logger; use std::io; use std::time::Instant; pub struct MultiLogger { loggers: Vec<Box<dyn Logger>> } impl MultiLogger { pub fn new() -> Self { Self { loggers: Vec::new() } } pub fn log_to<L: Logger + 'static>(&mut self, logger: L) { self.loggers.push(Box::n...
// This is the main function fn main() { // The statements here will be executed when the compiled binary is called // Print text to the console println!("Hello World!"); // In general, the `{}` will be automatically replaced with any // arguments. These will be stringified. println!("{} days...
#[macro_use] pub mod rule; pub mod lr1; pub mod parser; pub use lr1::*;