text
stringlengths
8
4.13M
// Copyright Jeron Aldaron Lau 2017 - 2020. // Distributed under either the Apache License, Version 2.0 // (See accompanying file LICENSE_APACHE_2_0.txt or copy at // https://apache.org/licenses/LICENSE-2.0), // or the Boost Software License, Version 1.0. // (See accompanying file LICENSE_BOOST_1_0.txt o...
mod deparse; mod errors; mod flatten; mod known_external; mod lex; mod lite_parse; mod parse_keywords; mod parser; mod type_check; pub use deparse::{escape_for_script_arg, escape_quote_string}; pub use errors::ParseError; pub use flatten::{flatten_block, flatten_expression, flatten_pipeline, FlatShape}; pub use known_...
/// A `(x, y)` position on screen. pub type Pos = (usize, usize); /// A `(cols, rows)` size. pub type Size = (usize, usize); pub trait HasSize { fn size(&self) -> Size; } pub trait HasPosition { fn origin(&self) -> Pos; fn set_origin(&mut self, new_origin: Pos); } /// A cursor position. pub struct Cursor...
extern crate clap; mod block; mod pow; use clap::{Arg, App}; use block::BlockChain; fn main() { let matches = App::new("Blkchain_3am") .version("1.0.0") .author("Boot-Error <booterror99@gmail.com>") .about("Tiny blockchain implementation") .arg(Arg::with_name("add"...
fn consume_u8(b: &Vec<u8>, cursor: usize) -> (u8, usize) { (b[cursor], cursor + 1) } fn consume_u16(b: &Vec<u8>, cursor: usize) -> (u16, usize) { let (left, cursor) = consume_u8(b, cursor); let (right, cursor) = consume_u8(b, cursor); (((left as u16) << 8) | (right as u16), cursor) } fn consume_u32(b:...
#![allow(dead_code)] #![allow(non_upper_case_globals)] #![allow(non_camel_case_types)] #[cfg(feature = "bindgen")] include!(concat!(env!("OUT_DIR"), "/bindings.rs")); #[cfg(not(feature = "bindgen"))] include!("./bindings.rs"); extern "C" { pub(crate) fn dup(fd: std::os::raw::c_int) -> std::os::raw::c_int; } use...
use azure_core::prelude::*; use azure_storage::core::prelude::*; use azure_storage_queues::prelude::*; use futures::stream::StreamExt; use std::error::Error; use std::num::NonZeroU32; #[tokio::main] async fn main() -> Result<(), Box<dyn Error + Send + Sync>> { // First we retrieve the account name and master key f...
// Vicfred // https://atcoder.jp/contests/abc157/tasks/abc157_b // simulation use std::io; use std::collections::HashSet; fn main() { let mut A = Vec::<Vec<i64>>::new(); for _ in 0..3 { let mut line = String::new(); io::stdin() .read_line(&mut line) .unwrap(); ...
// send command to renderengine use gfx; use glutin; use types::*; use camera::Camera; use std::io::Cursor; use std::sync::{Arc, Mutex, Once, ONCE_INIT}; use std::{mem, thread}; use std::time::Duration; pub enum RenderSystemState{ UnInited, Inited, Exited, } pub struct RenderSystem{ // Since we will be used in...
extern crate wm_daemons; use wm_daemons::config::{load_config, load_config_path}; use wm_daemons::dbus_listen::{CallbackMap, match_method}; #[macro_use] extern crate clap; use clap::{Arg, App}; extern crate config; use self::config::types::Config; extern crate dbus; use self::dbus::{Connection, BusType}; use std::e...
fn main() { println!("cargo:rustc-link-lib=rtlsdr"); }
pub mod dijkstra { use std::collections::BTreeSet; use std::cmp::Ordering; use std::u32; #[derive(Copy, Clone, Eq, PartialEq)] pub struct Distance { pub node: usize, pub cost: u32, } pub struct Edge { pub node: usize, pub cost: u32, } impl Ord for Distance { fn cmp(&self, other: &Distance) -> Or...
#[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { // TODO: Handle this issue in the sdk // Introduce delay so that dapr grpc port is assigned before app tries to connect std::thread::sleep(std::time::Duration::new(2, 0)); // Get the Dapr port and create a connection let por...
mod blend_mode; mod composite; mod line_cap; mod line_join; mod mask; mod text_based; mod text_grouping; mod text_shape; mod transform; pub use self::{ blend_mode::*, composite::*, line_cap::*, line_join::*, mask::*, text_based::*, text_grouping::*, text_shape::*, transform::*, };
use objc::Encode; use objc::Encoding; // https://developer.apple.com/documentation/foundation/nssize #[derive(Clone, Copy, Debug, Default)] #[repr(C)] pub struct NSSize { pub height: f64, pub width: f64, } impl NSSize { pub fn new(width: f64, height: f64) -> Self { Self { width, height } } } unsafe impl ...
#![allow(unused, unused_mut)] use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use chrono::prelude::*; use num_traits::ToPrimitive; use num_traits::cast::FromPrimitive; use rust_decimal::Decimal; use serde_json; use uuid::Uuid; use postgres; use postgres::rows::{Row, Rows}; use postgres::stmt::Statement; use ...
use std::env; use std::fs; fn main() { let args: Vec<String> = env::args().collect(); let slope = &args[1].parse::<f64>().unwrap(); let filename = &args[2]; let contents = fs::read_to_string(filename) .expect("Something went wrong reading the file"); let split_contents = contents.lines(); let lines: ...
use std::sync::Arc; use crossbeam::atomic::AtomicCell; use futures::{ executor::ThreadPool, future::{Future, RemoteHandle}, task::SpawnExt, }; pub struct AsyncResult<T: Send> { future: Option<RemoteHandle<T>>, result: Option<T>, ready: Arc<AtomicCell<bool>>, } impl<T: Send> AsyncResult<T> { ...
use lsp_types; use jrsonnet_evaluator; use jrsonnet_parser; use jrsonnet_parser::peg::str::LineCol; pub fn location_to_position(code: &str, line_col: &LineCol) -> lsp_types::Position { let lines = code.split('\n'); let mut offset = line_col.offset; for line in lines { if offset <= line.len() { ...
use wasm_bindgen::prelude::*; #[wasm_bindgen] pub fn solve(a: f64, b: f64) -> f64 { (a.powi(2) + b.powi(2)).sqrt() }
impl Solution { pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> { let mut end_vec = vec![0 as i32, 1 as i32]; for (i, num1) in nums.iter().enumerate() { for (j, suposed_num2) in nums.iter().enumerate() { if (i != j) { if (num1 + suposed_num2 =...
#[doc = "Reader of register RX_FIFO_CTRL"] pub type R = crate::R<u32, super::RX_FIFO_CTRL>; #[doc = "Writer for register RX_FIFO_CTRL"] pub type W = crate::W<u32, super::RX_FIFO_CTRL>; #[doc = "Register RX_FIFO_CTRL `reset()`'s with value 0"] impl crate::ResetValue for super::RX_FIFO_CTRL { type Type = u32; #[i...
mod search; pub use self::search::*; mod help; pub use self::help::*; pub mod servers;
use std::env; use std::ffi::OsString; use std::fs; use std::io::{self, Write}; use std::path::PathBuf; use crate::directories::PROJECT_DIRS; pub fn config_file() -> PathBuf { env::var("BAT_CONFIG_PATH") .ok() .map(PathBuf::from) .filter(|config_path| config_path.is_file()) .unwrap_...
pub mod api; pub mod handlers; pub mod schema; pub mod storage;
/*! Contains structural aliases for tuples, with shared,mutable,and by value access to every field of the tuple. `Tuple*` traits can be used with any tuple at least as large as the size indicated by the trait. You can use `Tuple3` with any tuple type starting with `(A,B,C`. Eg:`(A,B,C)`,`(A,B,C,D)`,`(A,B,C,D,E)`,etcet...
#![allow(non_snake_case)] #[allow(unused_imports)] use std::io::{self, Write}; #[allow(unused_imports)] use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque}; #[allow(unused_imports)] use std::cmp::{max, min, Ordering}; macro_rules! input { (source = $s:expr, $($r:tt)*) => { let...
use std::sync::mpsc; use std::sync::Arc; use std::sync::Mutex; use std::thread; // public /// Create a `ThreadPool` struct to manage all worker thread including creating and send message pub struct ThreadPool { workers: Vec<Worker>, sender: mpsc::Sender<Message>, } /// Create a `Job` type alias for a Box that...
use iced::{scrollable, Element, Length, Sandbox, Scrollable, Settings}; use std::cell::RefCell; use std::io::prelude::*; use std::path::{Path, PathBuf}; use std::rc::Rc; use std::{env, fs, io}; use crate::cssom::{Origin, Stylesheet}; use crate::layout::{font, layout_tree, Dimensions}; use crate::painter; use crate::p...
//! A crate exposing common functions helpers for doing proper error handling in a //! FFI context. //! //! //! ## Error Handling Theory //! //! This employs a thread-local variable which holds the most recent error as //! well as some convenience functions for getting/clearing this variable. //! //! The theory is if a...
use crate::{ChainConstants, HashOf, HeaderExt, NumberOf, Storage}; use codec::{Decode, Encode}; use frame_support::sp_io::TestExternalities; use scale_info::TypeInfo; use sp_arithmetic::traits::Zero; use sp_consensus_subspace::{KzgExtension, PosExtension}; use sp_runtime::traits::{BlakeTwo256, Header as HeaderT}; use s...
//! High performance FID (Fully Indexable Dictionary) library. //! //! [Master API Docs](https://laysakura.github.io/fid-rs/fid_rs/) //! | //! [Released API Docs](https://docs.rs/crate/fid-rs) //! | //! [Benchmark Results](https://laysakura.github.io/fid-rs/criterion/report/) //! | //! [Changelog](https://github.com/la...
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DedicatedHsmOperation { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>...
#[allow(dead_code)] #[derive(Copy, Clone,PartialEq,Debug)] pub enum Allergen { Eggs = 1, Peanuts = 2, Shellfish = 4, Strawberries = 8, Tomatoes = 16, Chocolate = 32, Pollen = 64, Cats = 128 } pub struct allergy { score: usize } pub fn Allergies(s: usize) -> allergy { allergy {...
use anyhow::{anyhow, bail, Result}; use csv::Reader; use csv::StringRecord; use log::{debug, info, warn}; use serde::Deserialize; use std::collections::{HashMap, HashSet}; use std::env; use futures::{stream, StreamExt}; use std::fs::File; use std::io::{BufRead, BufReader}; use std::sync::{Arc, Mutex, RwLock}; use st...
use parser::ParseNode; use parser::GrammarItem; pub trait Visitor<T> { fn visit(&mut self, n: &ParseNode) -> T{ match n.entry { GrammarItem::LiteralInt(_) => self.visit_literal_int(n), GrammarItem::Variable(_) => self.visit_variable(n), GrammarItem::Abstraction(_,_) => self.visit_abstraction(n)...
use std::env; use std::fs::File; use std::io::Write; use std::path::Path; fn main() { let directory = env::var("OUT_DIR").unwrap(); let path = Path::new(&directory).join("type.rs"); let mut file = File::create(path).unwrap(); file.write(b"type Test = ();\n").unwrap(); }
use std::borrow::Borrow; use std::collections::HashMap; use std::fmt::{Display,Debug,Error,Formatter}; use std::iter::Peekable; use std::ops::Deref; #[derive(PartialEq, Eq, Hash)] pub struct ByteString(pub Vec<u8>); impl Deref for ByteString { type Target = [u8]; fn deref(&self) -> &[u8] { let ByteSt...
use std::ops::{Add, Sub}; struct Tuple { x:f64, y:f64, z:f64, w:f64 } pub fn almost_equal(a:f64,b:f64)->bool{ return (a-b).abs()<0.0001 } impl Tuple { pub fn new_tuple(x: f64, y: f64,z: f64,w:f64) -> Tuple { Tuple { x: x, y: y,z:z,w:w } // this is fine, as we're in the same module }...
extern crate serde_json; #[test] fn serialize_test() { let x = O(linked_hash_map![ "foo".to_string() => Some(Box::new(A( vec![ Some(Box::new(I(42))), Some(Box::new(F(42.0))), ...
//! Wrapper around route url string, and associated history state. use crate::route_service::RouteService; use serde::Deserialize; use serde::Serialize; use stdweb::unstable::TryFrom; use stdweb::JsSerialize; use stdweb::Value; use std::ops::Deref; use yew::agent::Transferable; /// Any state that can be stored by the...
use qas::prelude::*; qas!("tests/c/arithmetic.c"); #[cfg(test)] #[test] fn main() { assert_eq!(add(29, 41), 70); assert_eq!(mulf(2.5, 4.0), 10.0); assert_eq!(divd(6.9, 3.0), 2.3000000000000003); }
use std::env; use std::io; use std::io::Read; use std::fs::File; const MEMORY_SIZE: usize = 32768; fn increment_with_overflow(value: &mut u8) { if *value == u8::max_value() { *value = 0; } else { *value += 1; } } fn decrement_with_overflow(value: &mut u8) { if *value == 0 { *v...
pub mod thread_simple_demo; pub mod channel; pub mod mutex_demo; /* 将程序中的计算拆分进多个线程可以改善性能,因为程序可以同时进行多个任务,不过这也会增加复杂性。 因为线程是同时运行的,所以无法预先保证不同线程中的代码的执行顺序。这会导致诸如此类的问题: 竞争状态(Race conditions),多个线程以不一致的顺序访问数据或资源 死锁(Deadlocks),两个线程相互等待对方停止使用其所拥有的资源,这会阻止它们继续运行 只会发生在特定情况且难以稳定重现和修复的 bug. 起初,Rust 团队认为确保内存安全和防止并发问题是两个分别需要不同方法应对的...
//! This crate provides three derive macros for [`eosio_core`] traits. //! //! # Examples //! //! ``` //! use eosio_core::{Read, Write, NumBytes}; //! //! #[derive(Read, Write, NumBytes, PartialEq, Debug)] //! #[eosio_core_root_path = "::eosio_core"] //! struct Thing(u8); //! //! let thing = Thing(30); //! //! // Numbe...
use std::fs::File; use std::io::Read; use ascii::{AsciiChar, AsciiString}; fn expand(line: &str) -> String { let mut res = String::new(); // Add Dots around the input from left and from right to deal with // the corner cases let mut input = AsciiString::new(); input.push(AsciiChar::Dot); input...
extern crate lbasi; use lbasi::*; #[test] fn test_operator_identification() { assert_eq!(interpreter::Token { kind: interpreter::TokenType::Add, value: "+".to_string(), }, interpreter::Token::op('+')); assert_eq!(interpreter::Token { ...
use std::collections::BTreeMap; use fopply::{binding::*, parsing::*, read_fpl, utils::char_index::*}; #[test] fn test() { assert!(parser::expr("(a+b)+c").is_ok()); assert!(parser::expr("a+b+c").is_ok()); assert!(parser::expr("a+sin(b)").is_ok()); assert!(parser::expr("a+$f(b)").is_ok()); assert!(parser::expr("$t...
use std::str::FromStr; use juice_sdk_rs::{client, transports, types::H256, Result}; #[tokio::main] async fn main() -> Result<()> { let transport = transports::http::Http::new("http://10.1.1.40:7009")?; let client = client::Client::new(transport, true); let receipt = client .transaction_receipt( ...
extern crate regex; use self::regex::Regex; use std::collections::BinaryHeap; use token_analysis::token; fn tokenize_source_code( source_code: String, ) -> Vec<Result<Vec<token::Token<'static>>, token::TokenError>> { source_code .split(";") .map(|line_of_code| tokenize_line(String::from(line_o...
use proconio::input; fn main() { input! { n:u32, } let mut ans = 1; for i in 1..10 { ans = 111 * i; if ans >= n { break; } } println!("{}", ans); }
use crate::hitable::Hitable; use rand::random; use crate::vec3::Vec3; use crate::material::Material; pub fn final_scene() -> Vec<Hitable> { // Randomly generate a number of small spheres. let mut small_spheres: Vec<Hitable> = vec![]; let radius = 0.2; for a in -11..11 { for b in -11..11 { ...
//! Basic library that has code that is shared between userspace and kernel #![no_std] #![feature(asm)] #![feature(allocator_api)] #![feature(alloc_prelude)] #![feature(alloc_error_handler)] #![feature(const_fn_trait_bound)] extern crate alloc; pub mod atomic; pub mod cell; pub mod collections; pub mod futex; pub mod...
use std::io::{self, Write}; fn main() -> io::Result<()> { io::stdout().write(b"hello world\n")?; Ok(()) }
use crate::{ config::Config, db_conn::DbConn, with_config, with_db_conn, with_reqwest_client, ConfirmQueryParams, InstallQueryParams, }; use reqwest::Client; use std::sync::Arc; use warp::{filters::BoxedFilter, Filter}; fn path_prefix_install() -> BoxedFilter<()> { warp::path("shopify_install").boxed() } ...
#[doc = "Reader of register PWR_BUCK_CTL"] pub type R = crate::R<u32, super::PWR_BUCK_CTL>; #[doc = "Writer for register PWR_BUCK_CTL"] pub type W = crate::W<u32, super::PWR_BUCK_CTL>; #[doc = "Register PWR_BUCK_CTL `reset()`'s with value 0x05"] impl crate::ResetValue for super::PWR_BUCK_CTL { type Type = u32; ...
#[doc = "Reader of register ATT0"] pub type R = crate::R<u32, super::ATT0>; #[doc = "Writer for register ATT0"] pub type W = crate::W<u32, super::ATT0>; #[doc = "Register ATT0 `reset()`'s with value 0x0124"] impl crate::ResetValue for super::ATT0 { type Type = u32; #[inline(always)] fn reset_value() -> Self...
use alloc::boxed::Box; use system::error::{Error, Result, EPERM, ESPIPE}; use system::syscall::Stat; /// Resource seek #[derive(Copy, Clone, Debug)] pub enum ResourceSeek { /// Start point Start(usize), /// Current point Current(isize), /// End point End(isize), } /// A system resource #[allo...
use nu_engine::env_to_string; use nu_protocol::ast::Call; use nu_protocol::engine::{Command, EngineState, Stack}; use nu_protocol::{ Category, Example, IntoPipelineData, PipelineData, ShellError, Signature, Value, }; #[derive(Clone)] pub struct Env; impl Command for Env { fn name(&self) -> &str { "env...
#[doc = "Reader of register RCC_MC_APB4ENSETR"] pub type R = crate::R<u32, super::RCC_MC_APB4ENSETR>; #[doc = "Writer for register RCC_MC_APB4ENSETR"] pub type W = crate::W<u32, super::RCC_MC_APB4ENSETR>; #[doc = "Register RCC_MC_APB4ENSETR `reset()`'s with value 0"] impl crate::ResetValue for super::RCC_MC_APB4ENSETR ...
use std::sync::Arc; use std::collections::LinkedList; use std::mem; use role::Kind; mod atomic_cell; use self::atomic_cell::AtomicCell; pub trait Notify { /// Resume execution context. /// /// It should be no-op to notify currently executing context. fn notify(self); } #[derive(Debug)] pub struct ...
use std::num::ParseIntError; pub fn int(string: &str) -> Result<i32, ParseIntError> { string.parse::<i32>() }
#[doc = "Power Control Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify...
use octocrab::models::issues::*; use reqwest::Url; use serde::*; use crate::*; type DateTime = chrono::DateTime<chrono::Utc>; #[derive(Serialize, Debug)] pub struct CommentRec { pub id: u64, pub node_id: String, pub url: Url, pub html_url: Url, pub body: Option<String>, pub body_text: Option<...
#[doc = "Register `MPCBB2_VCTR7` reader"] pub type R = crate::R<MPCBB2_VCTR7_SPEC>; #[doc = "Register `MPCBB2_VCTR7` writer"] pub type W = crate::W<MPCBB2_VCTR7_SPEC>; #[doc = "Field `B224` reader - B224"] pub type B224_R = crate::BitReader; #[doc = "Field `B224` writer - B224"] pub type B224_W<'a, REG, const O: u8> = ...
//! Example on spawning tasks with different priority. #![no_main] #![no_std] use rtic::app; use stm32_rtic_defmt as _; // global logger + panicking-behavior + memory layout #[app(device = stm32f1xx_hal::pac)] const APP: () = { struct Resources { // Resources go here! } #[init(spawn = [low_prio_...
use maplit::hashmap; use crate::dom::{element::Element, listener::ListenerRef}; #[test] fn test_name_change() { let old = Element { id: vec![0], name: "div".into(), ..Default::default() }; let new = Element { id: vec![0], name: "p".into(), ..Default::defaul...
use crate::component::{CompositeSprite, CompositeSpriteAnimation, CompositeSurfaceCache}; use core::{ app::AppLifeCycle, ecs::{Comp, Universe, WorldRef}, Scalar, }; pub type CompositeSpriteAnimationSystemResources<'a> = ( WorldRef, &'a AppLifeCycle, Comp<&'a mut CompositeSprite>, Comp<&'a m...
use amethyst::{ prelude::*, assets::{Handle, Prefab, PrefabData, PrefabLoader, RonFormat, ProgressCounter}, controls::ControlTagPrefab, derive::PrefabData, core::transform::Transform, ecs::{Entity, Write}, renderer::{camera::CameraPrefab, light::LightPrefab}, utils::auto_fov::AutoFov, ...
//! The server's API //! //! ## Overview //! //! Spidey exposes its API as a RESTful HTTP service, running over a local //! network socket and returning results as JSON objects. This type of API was //! picked for two reasons: //! //! 1. I already knew how to do it (which aids coding); //! 2. There already exist tools ...
use priv_prelude::*; use super::*; /// A TCP packet #[derive(Clone, PartialEq)] pub struct TcpPacket { buffer: Bytes, } impl fmt::Debug for TcpPacket { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { struct Kind(pub u8); impl fmt::Debug for Kind { fn fmt(&self, f: &mut fmt:...
#[doc = "Reader of register MEMPOWERDOWN"] pub type R = crate::R<u32, super::MEMPOWERDOWN>; #[doc = "Writer for register MEMPOWERDOWN"] pub type W = crate::W<u32, super::MEMPOWERDOWN>; #[doc = "Register MEMPOWERDOWN `reset()`'s with value 0"] impl crate::ResetValue for super::MEMPOWERDOWN { type Type = u32; #[i...
use server::protocol::PlaneType; use server::*; use fnv::FnvHashMap; use std::time::Duration; lazy_static! { pub static ref FLAG_RADIUS: FnvHashMap<Plane, Distance> = { let mut map = FnvHashMap::default(); // These are just random guesses // TODO: rev-eng these from official server map.insert( PlaneType:...
//! Vertical math operations crate mod float;
// src/lexer.rs use crate::token::*; pub struct Lexer { input: String, position: usize, // 当前字符位置 read_position: usize, // 当前读取位置(在当前字符位置之后) ch: u8, // 当前字符 } impl Lexer { pub fn new(input: &str) -> Lexer { let mut l = Lexer { input: String::from(input), ...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 mod common; mod mock_chain_test_helper; mod rpc_chain_test_helper; #[macro_use] extern crate rusty_fork; use anyhow::Result; use coerce_rt::actor::context::{ActorContext, ActorStatus}; use libra_crypto::HashValue; use libra_logger:...
//! Insertion Sort (Chapter 2: Getting Started) //! //! ```text //! for j = 2 to A.length //! key = A[j] //! // insert A[j] into the sorted sequence A[1 .. j - 1] //! i = j - 1 //! while i > 0 and A[i] > key //! a[i + 1] = A[i] //! i = i - 1 //! A[i + 1] = key //! ``` /// Plain ...
#![cfg(feature = "std")] use tabled::settings::{ object::{Cell, Columns, Object, Rows, Segment}, Alignment, Format, Modify, Padding, Style, }; use crate::matrix::Matrix; use testing_table::test_table; #[cfg(feature = "color")] use owo_colors::OwoColorize; test_table!( formatting_full_test, Matrix::n...
use std::env; use tokio::net::TcpListener; mod relay; mod tests; #[tokio::main] async fn main() { let address = env::args().nth(1).unwrap_or("0.0.0.0".to_string()); let port = env::args().nth(2).unwrap_or("0".to_string()); let host = env::args().nth(3).unwrap_or("".to_string()); let server = relay::S...
extern crate peroxide; extern crate fitsio; use peroxide::fuga::*; use fitsio::*; fn main() -> Result<(), Box<dyn Error>> { let mut fptr = FitsFile::open("data/nsa_v1_0_1.fits")?; fptr.pretty_print()?; let hdu = fptr.hdu(0)?; if let hdu::HduInfo::ImageInfo { shape, .. } = hdu.info { println!...
use menu::anilist::{AniListPagination, AniListUserView}; use serenity::{ model::application::interaction::application_command::ApplicationCommandInteraction, model::prelude::{GuildId, Interaction}, prelude::{Context, SerenityError}, }; use crate::utils::{get_application_command, regitser_command, CommandOp...
/* https://projecteuler.net The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime. There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97. How many circular primes are there below one million? NOTES: */ // r...
pub mod ebo; pub mod vao; pub mod vao_builder; pub mod vbo;
pub mod map; pub mod mrr; pub mod pak; pub mod pr; use map::Map; use mrr::Mrr; use pak::Pak; use pr::PrecisionAndRecall; use std::collections::{HashSet, HashMap}; use std::io::BufReader; use std::io::prelude::*; use std::fs::File; use std::env; use std::process; fn main() { let relevant_docs = get_relevance_info...
// // Copyright 2021 The Project Oak 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 required by applicable law o...
use std::borrow::Cow; use std::collections::HashSet; use std::sync::Arc; use itertools::Itertools; use strum::EnumCount; use command_data_derive::CommandData; use discorsd::{async_trait, BotState}; use discorsd::commands::*; use discorsd::errors::BotError; use crate::avalon::characters::Character; use crate::avalon:...
use crate::{borrow_streamer::BorrowStreamer, Advice, Array, Metadata, ReadAt, WriteAt}; #[cfg(feature = "io-streams")] use io_streams::StreamReader; use std::{ cmp::min, convert::TryInto, io::{self, IoSlice, IoSliceMut, Read}, }; impl Array for [u8] { #[inline] fn metadata(&self) -> io::Result<Meta...
//! Provides structures used to load audio files. use std::sync::Arc; use super::AudioContext; use assets::*; /// A loaded audio file #[derive(Clone)] pub struct Source { pub(crate) pointer: AssetPtr<Arc<Vec<u8>>, Source>, } impl AsRef<Arc<Vec<u8>>> for Source { fn as_ref(&self) -> &Arc<Vec<u8>> { s...
#![warn(clippy::pedantic)] use libcnb_test::{assert_contains, assert_not_contains}; use test_support::Builder::{Heroku20, Heroku22}; use test_support::{ assert_health_check_responds, get_function_invoker_build_config, test_node_function, }; #[test] #[ignore] fn simple_javascript_function_heroku_20() { test_no...
use std::net::{SocketAddr, Ipv4Addr, IpAddr}; fn main() -> Result<(), Box<dyn std::error::Error>> { let proxy_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 25566); let server_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 25565); proxy::start(proxy_address, server_a...
pub mod talk { pub mod cat; pub mod dog; } #[test] #[should_panic] #[ignore] fn test_hello() { assert_eq!("cat hello--", talk::cat::hello()); }
extern crate mynumber; use mynumber::corporate; #[test] fn verify_with_shorter_corporate_number_returns_error() { let number = "12345"; assert!(corporate::verify(number).is_err()); } #[test] fn verify_with_longer_corporate_number_returns_error() { let number = "12345678901234567890"; assert!(corporat...
use crate::responses::*; use crate::QueueServiceProperties; use azure_core::headers::add_optional_header; use azure_core::prelude::*; use azure_storage::core::clients::StorageClient; use std::convert::TryInto; #[derive(Debug, Clone)] pub struct SetQueueServicePropertiesBuilder<'a> { storage_client: &'a StorageClie...
use maud::Markup; fn layout(content: Markup) -> String { let template = html! { head { link rel="stylesheet" type="text/css" href="/static/main.css" / meta name="viewport" content="width=device-width, initial-scale=1" / } body { (content) } };...
use super::*; use jsonwebtoken::DecodingKey; pub trait ToDecodingKey { fn to_decoding_key(&'_ self) -> DecodingKey<'_>; } impl ToDecodingKey for RSAPublicKey { fn to_decoding_key(&'_ self) -> DecodingKey<'_> { DecodingKey::from_rsa_components(&self.n.base64, &self.e.base64) } }
//! JSONRPC types use failure::{format_err, Error}; use serde::{ de::{DeserializeOwned, Error as DeError}, Deserialize, Deserializer, Serialize, Serializer, }; use std::fmt::{self, Display}; use tendermint::Address; /// JSONRPC requests pub trait Request { /// Response type for this command type Respo...
// Reference: https://leetcode.com/problems/single-number-iii/discuss/750622/Python-4-Lines-O(n)-time-O(1)-space-explained pub fn single_number(nums: Vec<i32>) -> Vec<i32> { let sum = nums.iter().fold(0, |acc, x| acc ^ *x); let nz = (sum & (sum - 1)) ^ sum; let num1 = nums.iter().filter(|x| *x & nz != 0).fo...
use rand::Rng; fn main() -> Result<(), Box<dyn std::error::Error>> { let pattern = std::env::args().nth(1).expect("give me a regex pattern"); let n = std::env::args() .nth(2) .and_then(|arg| arg.parse().ok()) .unwrap_or(1); let pattern = rand_regex::Regex::compile(&pattern, 1)?; ...
use super::super::atom::{ btn::{self, Btn}, common::Common, dropdown::{self, Dropdown}, fa, slider::{self, Slider}, text::Text, }; use super::super::organism::{ popup_color_pallet::{self, PopupColorPallet}, room_modeless::RoomModeless, }; use super::ShowingModal; use crate::arena::{block...
extern crate rand; use std::collections::HashMap; use rand::prelude::*; #[derive(Debug)] enum Tree { Terminal(String), // atomic word NonTerminal(String, Vec<Tree>) // expandable term } // expand a term `k` according to the rules in `g` into a `Tree` fn expand_tree(g: &HashMap<&str,Vec<&str>>, k...