blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 5
140
| path
stringlengths 5
183
| src_encoding
stringclasses 6
values | length_bytes
int64 12
5.32M
| score
float64 2.52
4.94
| int_score
int64 3
5
| detected_licenses
listlengths 0
47
| license_type
stringclasses 2
values | text
stringlengths 12
5.32M
| download_success
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|
7632a2e147c9b6f31240a7de549d280295d860be
|
Rust
|
NLnetLabs/bcder
|
/src/encode/mod.rs
|
UTF-8
| 1,678 | 3.390625 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] |
permissive
|
//! Encoding data in BER.
//!
//! This modules provides means to encode data in BER.
//!
//! Encoding is done using helper types called _encoders_ that represent the
//! structure of the BER encoding. These types implement the trait
//! [`Values`]. A type that can be encoded as BER typically provides a method
//! named `encode` that produces a value of its encoder type representing the
//! value’s encoding. If necessary, they can also provide a method
//! `encode_as` that does the same thing but allows the caller to provide an
//! tag to use for encoding as is necessary for implicit tagging.
//!
//! The [`Values`] type can then be used to simply write the encoding to
//! anything that implements the standard library’s `io::Write` trait.
//!
//! The trait [`PrimitiveContent`] helps with producing encoders for types
//! that use the primitive encoding. Through this trait the types can declare
//! how their content is encoded and receive an automatic encoder type based
//! on that.
//!
//! The module also provides a number of helper types that make it easier
//! to implement encoders in various situations.
//!
//! For a more detailed introduction to writing the `encode` methods of
//! types, see the [encode section of the guide].
//!
//! [`Values`]: trait.Values.html
//! [`PrimitiveContent`]: trait.PrimitiveContent.html
//! [encode section of the guide]: ../guide/encode/index.html
pub use self::primitive::{PrimitiveContent, Primitive};
pub use self::values::{
Values,
Choice2, Choice3, Constructed, Iter, Nothing, Slice,
iter, sequence, sequence_as, set, set_as, slice, total_encoded_len,
write_header,
};
mod primitive;
mod values;
| true |
886d849d537863c83d133a684c2917661c0c3da8
|
Rust
|
rust-lang/rust
|
/tests/ui/suggestions/issue-105226.rs
|
UTF-8
| 421 | 3.375 | 3 |
[
"Apache-2.0",
"LLVM-exception",
"NCSA",
"BSD-2-Clause",
"LicenseRef-scancode-unicode",
"MIT",
"LicenseRef-scancode-other-permissive"
] |
permissive
|
use std::fmt;
struct S {
}
impl S {
fn hello<P>(&self, val: &P) where P: fmt::Display; {
//~^ ERROR non-item in item list
//~| ERROR associated function in `impl` without body
println!("val: {}", val);
}
}
impl S {
fn hello_empty<P>(&self, val: &P) where P: fmt::Display;
//~^ ERROR associated function in `impl` without body
}
fn main() {
let s = S{};
s.hello(&32);
}
| true |
0a4149932244efc5569c2c5b59d4dd2de220d759
|
Rust
|
mdsimmo/DailyCodingProblem
|
/prob_0070/src/lib.rs
|
UTF-8
| 1,191 | 3.703125 | 4 |
[] |
no_license
|
/*
A number is considered perfect if its digits sum up to exactly 10.
Given a positive integer n, return the n-th perfect number.
For example, given 1, you should return 19. Given 2, you should return 28.
Time to complete: 7 min
*/
pub fn nth_perfect(mut index: usize) -> u64 {
let mut count = 18;
loop {
if sum_digits(count) == 10 {
index -= 1;
if index == 0 {
return count
}
}
count += 1;
}
}
fn sum_digits(mut num: u64) -> u64 {
let mut sum = 0;
loop {
let div = num / 10;
sum += num % 10;
if div == 0 {
return sum;
} else {
num = div;
}
}
}
#[cfg(test)]
mod tests {
use ::{nth_perfect, sum_digits};
#[test]
fn test_sum_digits() {
assert_eq!(5+4+3+2, sum_digits(5432));
}
#[test]
fn test_one() {
assert_eq!(19, nth_perfect(1));
}
#[test]
fn test_two() {
assert_eq!(28, nth_perfect(2));
}
#[test]
fn test_nine() {
assert_eq!(91, nth_perfect(9));
}
#[test]
fn test_10() {
assert_eq!(109, nth_perfect(10));
}
}
| true |
8c1aba6a54fa0b3cfac58bb215a5ee1445725784
|
Rust
|
iCodeIN/softy
|
/src/ops/addition.rs
|
UTF-8
| 12,434 | 2.9375 | 3 |
[] |
no_license
|
use crate::value::*;
use std::mem;
pub fn addition(source1: Value, source2: Value) -> Value {
assert_eq!(source1.format, source2.format);
// Treat denormal input(s) as zero
let mut source1 = flush_denormal_to_zero(source1);
let mut source2 = flush_denormal_to_zero(source2);
// Ensure source with greater magnitude is lhs
if source1.exp < source2.exp || (source1.exp == source2.exp && source1.sig < source2.sig) {
mem::swap(&mut source1, &mut source2);
}
let format = &source1.format;
// Propagate (replace!) NaNs
let sig_quiet_bit = 1 << (format.num_sig_bits - 1);
let quiet_nan = Value::from_comps(false, format.exp_max(), sig_quiet_bit, format.clone());
if source1.is_nan() || source2.is_nan() {
return quiet_nan;
}
// TODO: Is this case really important?
if source1.is_inf() && source2.is_inf() && source1.sign != source2.sign {
return quiet_nan;
}
// Decode full sigs
let hidden_bit = 1 << format.num_sig_bits;
let source1_sig = hidden_bit | source1.sig;
let mut source2_sig = hidden_bit | source2.sig;
// Align rhs point (if applicable)
if source2.exp < source1.exp {
let shift_digits = source1.exp - source2.exp;
if shift_digits > format.num_sig_bits {
source2_sig = 0;
} else {
source2_sig >>= shift_digits;
}
}
// If sources' signs differ, negate rhs sig via two's complement
let sig_including_hidden_and_overflow_bits_mask = (1 << (format.num_sig_bits + 2)) - 1;
if source1.sign != source2.sign {
source2_sig = (!source2_sig).wrapping_add(1) & sig_including_hidden_and_overflow_bits_mask;
}
// Calculate sum
let sum_sign = source1.sign;
let mut sum_exp = source1.exp;
let mut sum_sig = (source1_sig + source2_sig) & sig_including_hidden_and_overflow_bits_mask;
let is_sum_zero = sum_exp == 0 || sum_sig == 0;
// Normalize sum in case of hidden bit overflow
let sum_sig_overflow = ((sum_sig >> (format.num_sig_bits + 1)) & 1) != 0;
if sum_sig_overflow {
sum_exp += 1;
sum_sig >>= 1;
}
// Check for infinity (exp overflow)
let is_sum_inf = sum_exp >= format.exp_max();
// Normalize sum in case of cancellations from potentially-negative rhs
let sum_sig_leading_zeros = sum_sig.leading_zeros() - (32 - (format.num_sig_bits + 1));
sum_sig <<= sum_sig_leading_zeros;
let is_sum_zero = is_sum_zero || sum_sig_leading_zeros >= sum_exp;
sum_exp = sum_exp.wrapping_sub(sum_sig_leading_zeros);
if is_sum_inf {
Value::from_comps(sum_sign, format.exp_max(), 0, format.clone())
} else if is_sum_zero {
// TODO: Handle sign properly (or not? :) )
Value::from_comps(false, 0, 0, format.clone())
} else {
// Remove hidden bit from sum
let sum_sig = sum_sig & ((1 << format.num_sig_bits) - 1);
Value::from_comps(sum_sign, sum_exp, sum_sig, format.clone())
}
}
fn flush_denormal_to_zero(value: Value) -> Value {
if value.exp == 0 {
Value::from_comps(value.sign, value.exp, 0, value.format)
} else {
value
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::format::*;
#[test]
fn addition_basic() {
let f = Format::ieee754_single();
let a = Value::from_comps(false, 127, 0, f.clone()); // 1.0
let b = Value::from_comps(false, 127, 0, f.clone()); // 1.0
let res = addition(a, b);
assert_eq!(res.to_bits(), 0x40000000); // 2.0
let a = Value::from_comps(false, 126, 0, f.clone()); // 0.5
let b = Value::from_comps(false, 126, 0, f.clone()); // 0.5
let res = addition(a, b);
assert_eq!(res.to_bits(), 0x3f800000); // 1.0
let a = Value::from_comps(false, 127, 0, f.clone()); // 1.0
let b = Value::from_comps(false, 126, 0, f.clone()); // 0.5
let res = addition(a, b);
assert_eq!(res.to_bits(), 0x3fc00000); // 1.5
let a = Value::from_comps(false, 0, 0, f.clone()); // 0.0
let b = Value::from_comps(false, 0, 0, f.clone()); // 0.0
let res = addition(a, b);
assert_eq!(res.to_bits(), 0x00000000); // 0.0
let a = Value::from_comps(false, 127, 0, f.clone()); // 1.0
let b = Value::from_comps(false, 0, 0, f.clone()); // 0.0
let res = addition(a, b);
assert_eq!(res.to_bits(), 0x3f800000); // 1.0
let a = Value::from_comps(false, 0, 0, f.clone()); // 0.0
let b = Value::from_comps(false, 127, 0, f.clone()); // 1.0
let res = addition(a, b);
assert_eq!(res.to_bits(), 0x3f800000); // 1.0
let a = Value::from_comps(true, 127, 0, f.clone()); // -1.0
let b = Value::from_comps(true, 127, 0, f.clone()); // -1.0
let res = addition(a, b);
assert_eq!(res.to_bits(), 0xc0000000); // -2.0
let a = Value::from_comps(true, 127, 1 << 22, f.clone()); // -1.5
let b = Value::from_comps(true, 127, 0, f.clone()); // -1.0
let res = addition(a, b);
assert_eq!(res.to_bits(), 0xc0200000); // -2.5
let a = Value::from_comps(true, 128, 1 << 22, f.clone()); // -3.0
let b = Value::from_comps(true, 128, 1 << 22, f.clone()); // -3.0
let res = addition(a, b);
assert_eq!(res.to_bits(), 0xc0c00000); // -6.0
}
#[test]
fn addition_daz_ftz() {
let f = Format::ieee754_single();
let a = Value::from_comps(false, 0, 1337, f.clone()); // any denormalized number
let b = Value::from_comps(false, 0, 0, f.clone()); // 0.0
let res = addition(a, b);
assert_eq!(res.to_bits(), 0x00000000); // 0.0
let a = Value::from_comps(false, 0, 0, f.clone()); // 0.0
let b = Value::from_comps(false, 0, 1337, f.clone()); // any denormalized number
let res = addition(a, b);
assert_eq!(res.to_bits(), 0x00000000); // 0.0
let a = Value::from_comps(false, 0, 1337, f.clone()); // any denormalized number
let b = Value::from_comps(false, 0, 1337, f.clone()); // any denormalized number
let res = addition(a, b);
assert_eq!(res.to_bits(), 0x00000000); // 0.0
let a = Value::from_comps(false, 128, 0, f.clone()); // 2.0
let b = Value::from_comps(false, 0, 1337, f.clone()); // any denormalized number
let res = addition(a, b);
assert_eq!(res.to_bits(), 0x40000000); // 2.0
let a = Value::from_comps(true, 128, 0, f.clone()); // -2.0
let b = Value::from_comps(true, 0, 1337, f.clone()); // any negative denormalized number
let res = addition(a, b);
assert_eq!(res.to_bits(), 0xc0000000); // -2.0
let a = Value::from_comps(false, 0, 1337, f.clone()); // any positive denormalized number
let b = Value::from_comps(true, 0, 1337, f.clone()); // any negative denormalized number
let res = addition(a, b);
assert_eq!(res.to_bits(), 0x00000000); // 0.0
}
#[test]
fn addition_non_matching_signs() {
let f = Format::ieee754_single();
let a = Value::from_comps(false, 127, 0, f.clone()); // 1.0
let b = Value::from_comps(true, 127, 0, f.clone()); // -1.0
let res = addition(a, b);
assert_eq!(res.to_bits(), 0x00000000); // 0.0
let a = Value::from_comps(false, 127, 0, f.clone()); // 1.0
let b = Value::from_comps(false, 0, 0, f.clone()); // 0.0
let res = addition(a, b);
assert_eq!(res.to_bits(), 0x3f800000); // 1.0
let a = Value::from_comps(false, 127, 0, f.clone()); // 1.0
let b = Value::from_comps(true, 0, 0, f.clone()); // -0.0
let res = addition(a, b);
assert_eq!(res.to_bits(), 0x3f800000); // 1.0
let a = Value::from_comps(false, 0, 0, f.clone()); // 0.0
let b = Value::from_comps(false, 127, 0, f.clone()); // 1.0
let res = addition(a, b);
assert_eq!(res.to_bits(), 0x3f800000); // 1.0
let a = Value::from_comps(true, 0, 0, f.clone()); // -0.0
let b = Value::from_comps(false, 127, 0, f.clone()); // 1.0
let res = addition(a, b);
assert_eq!(res.to_bits(), 0x3f800000); // 1.0
let a = Value::from_comps(true, 127, 0, f.clone()); // -1.0
let b = Value::from_comps(false, 127, 0, f.clone()); // 1.0
let res = addition(a, b);
assert_eq!(res.to_bits(), 0x00000000); // 0.0
let a = Value::from_comps(true, 0, 0, f.clone()); // -0.0
let b = Value::from_comps(false, 0, 0, f.clone()); // 0.0
let res = addition(a, b);
assert_eq!(res.to_bits(), 0x00000000); // 0.0
let a = Value::from_comps(false, 127, 0, f.clone()); // 1.0
let b = Value::from_comps(true, 127, 1 << 22, f.clone()); // -1.5
let res = addition(a, b);
assert_eq!(res.to_bits(), 0xbf000000); // -0.5
let a = Value::from_comps(true, 127, 1 << 22, f.clone()); // -1.5
let b = Value::from_comps(false, 127, 0, f.clone()); // 1.0
let res = addition(a, b);
assert_eq!(res.to_bits(), 0xbf000000); // -0.5
let a = Value::from_comps(false, 142, 0, f.clone()); // 32768.0
let b = Value::from_comps(true, 142, 1 << 6, f.clone()); // -32768.25
let res = addition(a, b);
assert_eq!(res.to_bits(), 0xbe800000); // -0.25
}
#[test]
fn addition_nan() {
let f = Format::ieee754_single();
let a = Value::from_comps(false, 255, 1337, f.clone()); // any NaN
let b = Value::from_comps(false, 0, 0, f.clone()); // 0.0
let res = addition(a, b);
assert_eq!(res.to_bits(), 0x7fc00000); // NaN
let a = Value::from_comps(false, 0, 0, f.clone()); // 0.0
let b = Value::from_comps(false, 255, 1337, f.clone()); // any NaN
let res = addition(a, b);
assert_eq!(res.to_bits(), 0x7fc00000); // NaN
let a = Value::from_comps(false, 255, 0, f.clone()); // +inf
let b = Value::from_comps(false, 255, 1337, f.clone()); // any NaN
let res = addition(a, b);
assert_eq!(res.to_bits(), 0x7fc00000); // NaN
let a = Value::from_comps(false, 255, 1337, f.clone()); // any NaN
let b = Value::from_comps(true, 255, 0, f.clone()); // -inf
let res = addition(a, b);
assert_eq!(res.to_bits(), 0x7fc00000); // NaN
let a = Value::from_comps(false, 255, 1337, f.clone()); // any NaN
let b = Value::from_comps(true, 255, 1338, f.clone()); // any NaN
let res = addition(a, b);
assert_eq!(res.to_bits(), 0x7fc00000); // NaN
}
#[test]
fn addition_inf() {
let f = Format::ieee754_single();
let a = Value::from_comps(false, 255, 0, f.clone()); // +inf
let b = Value::from_comps(false, 0, 0, f.clone()); // 0.0
let res = addition(a, b);
assert_eq!(res.to_bits(), 0x7f800000); // +inf
let a = Value::from_comps(false, 255, 0, f.clone()); // +inf
let b = Value::from_comps(false, 127, 0, f.clone()); // 1.0
let res = addition(a, b);
assert_eq!(res.to_bits(), 0x7f800000); // +inf
let a = Value::from_comps(false, 255, 0, f.clone()); // +inf
let b = Value::from_comps(false, 254, 0, f.clone()); // +max value
let res = addition(a, b);
assert_eq!(res.to_bits(), 0x7f800000); // +inf
let a = Value::from_comps(false, 255, 0, f.clone()); // +inf
let b = Value::from_comps(false, 255, 0, f.clone()); // +inf
let res = addition(a, b);
assert_eq!(res.to_bits(), 0x7f800000); // +inf
let a = Value::from_comps(true, 255, 0, f.clone()); // -inf
let b = Value::from_comps(true, 254, 0, f.clone()); // -max value
let res = addition(a, b);
assert_eq!(res.to_bits(), 0xff800000); // -inf
let a = Value::from_comps(true, 255, 0, f.clone()); // -inf
let b = Value::from_comps(true, 255, 0, f.clone()); // -inf
let res = addition(a, b);
assert_eq!(res.to_bits(), 0xff800000); // -inf
// TODO: Is this case really important?
let a = Value::from_comps(false, 255, 0, f.clone()); // +inf
let b = Value::from_comps(true, 255, 0, f.clone()); // -inf
let res = addition(a, b);
assert_eq!(res.to_bits(), 0x7fc00000); // NaN
}
}
| true |
8ccb169defc694a298861a6fac518b699bc8999e
|
Rust
|
ankurhimanshu14/novarche
|
/src/apis/human_resources/person.rs
|
UTF-8
| 6,432 | 2.671875 | 3 |
[
"Apache-2.0"
] |
permissive
|
pub mod person {
use chrono::NaiveDate;
use mysql::prelude::*;
use mysql::*;
#[derive(Debug, Clone)]
pub struct Person {
pub first_name: String,
pub middle_name: Option<String>,
pub last_name: String,
pub gender: String,
date_of_birth: NaiveDate,
pub pri_contact_no: Option<String>,
pub sec_contact_no: Option<String>,
pub personal_email: Option<String>,
pub per_address: String,
pub com_address: Option<String>,
pan: String,
pub uidai: usize,
uan: Option<usize>,
}
impl Person {
pub fn new(
first_name: String,
middle_name: Option<String>,
last_name: String,
gender: String,
date_of_birth: NaiveDate,
pri_contact_no: Option<String>,
sec_contact_no: Option<String>,
personal_email: Option<String>,
per_address: String,
com_address: Option<String>,
pan: String,
uidai: usize,
uan: Option<usize>,
) -> Self {
Person {
first_name,
middle_name: match &middle_name.clone().unwrap().len() {
0 => None,
_ => Some(middle_name.clone().unwrap())
},
last_name,
gender,
date_of_birth,
pri_contact_no: match &pri_contact_no.clone().unwrap().len() {
0 => None,
_ => Some(pri_contact_no.clone().unwrap())
},
sec_contact_no: match &sec_contact_no.clone().unwrap().len() {
0 => None,
_ => Some(sec_contact_no.clone().unwrap())
},
personal_email: match &personal_email.clone().unwrap().len() {
0 => None,
_ => Some(personal_email.clone().unwrap())
},
per_address,
com_address: match &com_address.clone().unwrap().len() {
0 => None,
_ => Some(com_address.clone().unwrap())
},
pan,
uidai,
uan
}
}
pub fn post(self) -> Result<()> {
let table = "CREATE TABLE IF NOT EXISTS person(
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
first_name VARCHAR(100) NOT NULL,
middle_name VARCHAR(100),
last_name VARCHAR(100) NOT NULL,
gender VARCHAR(100) NOT NULL,
date_of_birth DATETIME NOT NULL,
pri_contact_no VARCHAR(12),
sec_contact_no VARCHAR(12),
personal_email VARCHAR(100),
per_address TEXT NOT NULL,
com_address TEXT,
pan VARCHAR(10) UNIQUE,
uidai BIGINT UNIQUE,
uan BIGINT UNIQUE,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
modified_at DATETIME ON UPDATE CURRENT_TIMESTAMP
) ENGINE = InnoDB;";
let insert = r"INSERT INTO person(
first_name,
middle_name,
last_name,
gender,
date_of_birth,
pri_contact_no,
sec_contact_no,
personal_email,
per_address,
com_address,
pan,
uidai,
uan
) VALUES (
:first_name,
:middle_name,
:last_name,
:gender,
:date_of_birth,
:pri_contact_no,
:sec_contact_no,
:personal_email,
:per_address,
:com_address,
:pan,
:uidai,
:uan
);";
let url = "mysql://root:@localhost:3306/mws_database".to_string();
let pool = Pool::new(url)?;
let mut conn = pool.get_conn()?;
conn.query_drop(table)?;
conn.exec_drop(
insert,
params! {
"first_name" => self.first_name.clone(),
"middle_name" => self.middle_name.clone(),
"last_name" => self.last_name.clone(),
"gender" => self.gender.clone(),
"date_of_birth" => self.date_of_birth.clone(),
"pri_contact_no" => self.pri_contact_no.clone(),
"sec_contact_no" => self.sec_contact_no.clone(),
"personal_email" => self.personal_email.clone(),
"per_address" => self.per_address.clone(),
"com_address" => self.com_address.clone(),
"pan" => self.pan.clone(),
"uidai" => self.uidai.clone(),
"uan" => self.uan.clone(),
}
)?;
Ok(())
}
// pub fn get_person_list() -> Result<Vec<Person>> {
// let query = "SELECT * FROM person;";
// let url = "mysql://root:@localhost:3306/mws_database".to_string();
// let pool = Pool::new(url)?;
// let conn = pool.get_conn()?;
// let result: Vec<Row> = query.fetch(conn)?;
// let mut v1: Vec<Person> = Vec::new();
// for entries in result.iter() {
// let length: &usize = &entries.len();
// let mut v2: Vec<String> = Vec::new();
// for index in 0..*length {
// let val = &entries.get_opt::<String, usize>(index).unwrap();
// match val {
// Ok(_) => v2.push(val.as_ref().unwrap().to_string()),
// Err(_) => v2.push("".to_string()),
// }
// }
// v1.push(v2);
// }
// Ok(v1)
// }
}
}
| true |
ac1d8bb566aaf07f24d72ef079b58d176942aeea
|
Rust
|
jabedude/redox-ssh
|
/src/key_exchange/dh_group_sha1.rs
|
UTF-8
| 3,312 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
use connection::Connection;
use key_exchange::{KexResult, KeyExchange};
use message::MessageType;
use num_bigint::{BigInt, RandBigInt, ToBigInt};
use packet::{Packet, ReadPacketExt, WritePacketExt};
use rand;
const DH_GEX_GROUP: u8 = 31;
const DH_GEX_INIT: u8 = 32;
const DH_GEX_REPLY: u8 = 33;
const DH_GEX_REQUEST: u8 = 34;
/// Second Oakley Group
/// Source: https://tools.ietf.org/html/rfc2409#section-6.2
#[cfg_attr(rustfmt, rustfmt_skip)]
static OAKLEY_GROUP_2: &[u32] = &[
0xFFFFFFFF, 0xFFFFFFFF, 0xC90FDAA2, 0x2168C234, 0xC4C6628B, 0x80DC1CD1,
0x29024E08, 0x8A67CC74, 0x020BBEA6, 0x3B139B22, 0x514A0879, 0x8E3404DD,
0xEF9519B3, 0xCD3A431B, 0x302B0A6D, 0xF25F1437, 0x4FE1356D, 0x6D51C245,
0xE485B576, 0x625E7EC6, 0xF44C42E9, 0xA637ED6B, 0x0BFF5CB6, 0xF406B7ED,
0xEE386BFB, 0x5A899FA5, 0xAE9F2411, 0x7C4B1FE6, 0x49286651, 0xECE65381,
0xFFFFFFFF, 0xFFFFFFFF
];
pub struct DhGroupSha1 {
g: Option<BigInt>,
p: Option<BigInt>,
e: Option<BigInt>,
}
impl DhGroupSha1 {
pub fn new() -> DhGroupSha1 {
DhGroupSha1 {
g: None,
p: None,
e: None,
}
}
}
impl KeyExchange for DhGroupSha1 {
fn shared_secret<'a>(&'a self) -> Option<&'a [u8]> {
Some(&[])
}
fn exchange_hash<'a>(&'a self) -> Option<&'a [u8]> {
Some(&[])
}
fn hash(&self, data: &[&[u8]]) -> Vec<u8> {
vec![]
}
fn process(&mut self, conn: &mut Connection, packet: Packet) -> KexResult {
match packet.msg_type()
{
MessageType::KeyExchange(DH_GEX_REQUEST) => {
let mut reader = packet.reader();
let min = reader.read_uint32().unwrap();
let opt = reader.read_uint32().unwrap();
let max = reader.read_uint32().unwrap();
println!("Key Sizes: Min {}, Opt {}, Max {}", min, opt, max);
let mut rng = rand::thread_rng();
let g = rng.gen_biguint(opt as usize).to_bigint().unwrap();
let p = rng.gen_biguint(opt as usize).to_bigint().unwrap();
let mut packet =
Packet::new(MessageType::KeyExchange(DH_GEX_GROUP));
packet.with_writer(&|w| {
w.write_mpint(g.clone())?;
w.write_mpint(p.clone())?;
Ok(())
});
self.g = Some(g);
self.p = Some(p);
KexResult::Ok(packet)
}
MessageType::KeyExchange(DH_GEX_INIT) => {
let mut reader = packet.reader();
let e = reader.read_mpint().unwrap();
println!("Received e: {:?}", e);
let mut packet =
Packet::new(MessageType::KeyExchange(DH_GEX_REPLY));
packet.with_writer(&|w| {
w.write_string("HELLO WORLD")?;
w.write_mpint(e.clone())?;
w.write_string("HELLO WORLD")?;
Ok(())
});
self.e = Some(e);
KexResult::Done(packet)
}
_ => {
debug!("Unhandled key exchange packet: {:?}", packet);
KexResult::Error
}
}
}
}
| true |
6677a27e7082eb80004ed456a437714c145b922f
|
Rust
|
Grieverwzn/abstreet
|
/importer/src/bin/import_traffic.rs
|
UTF-8
| 734 | 2.546875 | 3 |
[
"Apache-2.0"
] |
permissive
|
use abstutil::{CmdArgs, Timer};
use map_model::Map;
use serde::Deserialize;
use sim::{ExternalPerson, Scenario};
fn main() {
let mut args = CmdArgs::new();
let map = args.required("--map");
let input = args.required("--input");
args.done();
let mut timer = Timer::new("import traffic demand data");
let map = Map::new(map, &mut timer);
let input: Input = abstutil::read_json(input, &mut timer);
let mut s = Scenario::empty(&map, &input.scenario_name);
// Include all buses/trains
s.only_seed_buses = None;
s.people = ExternalPerson::import(&map, input.people).unwrap();
s.save();
}
#[derive(Deserialize)]
struct Input {
scenario_name: String,
people: Vec<ExternalPerson>,
}
| true |
38dfd87b5302397dccde7553caf9038d9fffb81d
|
Rust
|
lar-rs/mio
|
/src/stirrer.rs
|
UTF-8
| 1,892 | 2.84375 | 3 |
[
"Apache-2.0"
] |
permissive
|
/// Stirrer
///
///
///
// use std::prelude::*;
use super::*;
use std::fs;
// use std::stream::Stream;
use std::path::{PathBuf};
impl From<&Interface> for Stirrer {
#[inline]
fn from(device:&Interface) -> Stirrer {
Stirrer{
path: device.path.to_path_buf()
}
}
}
impl From<&Stirrer> for Interface {
#[inline]
fn from(stirrer:&Stirrer) -> Interface {
Interface{
path:stirrer.path.to_path_buf()
}
}
}
use std::convert::TryFrom;
impl TryFrom<Interface> for Stirrer {
type Error = Error;
fn try_from(iface: Interface) -> Result<Self> {
iface.set_itype(IType::NDir)?;
Ok(Self{
path:iface.path,
})
}
}
pub struct Stirrer {
pub path : PathBuf,
}
/// Injection interface..
impl Stirrer {
/// current in mAh
pub fn current(&self ) -> Result<u32> {
let current = fs::read_to_string(self.path.join("current"))?.parse::<u32>()?;
Ok(current)
}
pub fn delay( &mut self) -> Result<u32> {
let delay = fs::read_to_string(self.path.join("delay"))?.parse::<u32>()?;
Ok(delay)
}
pub fn state(&self) -> Result<bool> {
match fs::read_to_string(self.path.join("state"))?.as_str() {
"1" => Ok(true),
_ => Ok(false),
}
}
pub fn start(&mut self) -> Result<()> {
fs::write(self.path.join("state"),b"1")?;
Ok(())
}
pub fn stop(&mut self) -> Result<()> {
fs::write(self.path.join("state"),b"0")?;
Ok(())
}
pub fn set_delay(&mut self,delay:u32) -> Result<()> {
fs::write(self.path.join("delay"),format!("{}",delay).as_bytes())?;
Ok(())
}
pub fn set_current( &mut self , current: u32 ) -> Result<()> {
fs::write(self.path.join("current"),format!("{}",current).as_bytes())?;
Ok(())
}
}
| true |
558f60424796c64e5c6a0d1cf9d7cabb66731f6f
|
Rust
|
ericpko/raytracer
|
/src/scene/camera.rs
|
UTF-8
| 695 | 2.890625 | 3 |
[
"MIT"
] |
permissive
|
use nalgebra as na;
use na::{ Vector3 };
#[derive(Default)]
pub struct Camera {
// Origin or "eye"
pub e: Vector3<f64>,
// Orthonormal frame such that -w is the viewing direction
pub u: Vector3<f64>,
pub v: Vector3<f64>,
pub w: Vector3<f64>,
// Image plane distance / focal length
pub d: f64,
// Width and height of the IMAGE PLANE
pub width: f64,
pub height: f64
}
impl Camera {
pub fn new( e: Vector3<f64>,
u: Vector3<f64>,
v: Vector3<f64>,
w: Vector3<f64>,
d: f64,
width: f64,
height: f64) -> Camera
{
Camera{e, u, v, w, d, width, height}
}
}
| true |
05cd3a011187c93df1584e853ca885eb0cffe02f
|
Rust
|
rishabh-bector/rustraytracer
|
/src/geometry/model.rs
|
UTF-8
| 3,357 | 2.90625 | 3 |
[] |
no_license
|
extern crate cgmath;
use crate::material::Material;
use crate::common::{Entity, ColliderResult, Ray};
use crate::geometry::triangle::Triangle;
use crate::geometry::kdtree::KDTree;
use crate::geometry::aabb::AABB;
use cgmath::{EuclideanSpace, InnerSpace, Matrix4, Point3, Vector3};
use obj::{load_obj, Obj};
use std::{fs::File, sync::{Arc}};
use std::io::BufReader;
use crate::cgmath::Transform;
pub struct Model {
material: Material,
tree: KDTree<Triangle>,
position: Point3<f64>,
triangles: Vec<Arc<Triangle>>,
aa_bb: AABB
}
impl Model {
pub fn new(path: &str, material: Material, position: Point3<f64>, scale: Vector3<f64>) -> Model {
println!("Opening model @ {}", path);
let input = BufReader::new(File::open(path).unwrap());
let model: Obj = load_obj(input).unwrap();
let mut triangles = Vec::new();
let translation = position.to_vec();
let transform = Matrix4::from_translation(translation) * cgmath::Matrix4::from_nonuniform_scale(scale.x, scale.y, scale.z);
for i in (0..model.indices.len()-4).step_by(3) {
let v0 = vertex2point(model.vertices[model.indices[i] as usize]);
let v1 = vertex2point(model.vertices[model.indices[i+1] as usize]);
let v2 = vertex2point(model.vertices[model.indices[i+2] as usize]);
let n0 = vertex2normal(model.vertices[model.indices[i] as usize]);
let n1 = vertex2normal(model.vertices[model.indices[i+1] as usize]);
let n2 = vertex2normal(model.vertices[model.indices[i+2] as usize]);
triangles.push(Triangle::new(
transform.transform_point(v0),
transform.transform_point(v1),
transform.transform_point(v2),
(n0 + n1 + n2).normalize(),
material.clone()));
}
println!("Model has {} triangles.", triangles.len());
println!("Building k-d tree with model's triangles...");
let triangles: Vec<Arc<Triangle>> = triangles.into_iter().map(Arc::new).collect();
Model {
material,
aa_bb: AABB::from_entities(triangles.iter().map(|a|a.as_ref())),
position,
tree: KDTree::new(triangles.clone()),
triangles
}
}
}
impl Entity for Model {
fn collide(&self, ray: &Ray) -> ColliderResult {
self.tree.collide(ray)
}
fn material(&self) -> Option<&Material> {
Some(&self.material)
}
fn bounding_box(&self) -> AABB {
self.aa_bb
}
fn position(&self) -> Point3<f64> {
Point3 {
x: self.position.x,
y: self.position.y,
z: self.position.z
}
}
fn translate(&mut self, vec: Vector3<f64>) {
for triangle in &self.triangles {
let triangle = Arc::as_ptr(triangle) as *mut Triangle;
unsafe { (*triangle).translate(vec); }
}
self.tree.translate_nodes(vec);
}
}
fn vertex2point(v: obj::Vertex) -> Point3<f64> {
Point3 {
x: v.position[0] as f64,
y: v.position[1] as f64,
z: v.position[2] as f64,
}
}
fn vertex2normal(v: obj::Vertex) -> Vector3<f64> {
Vector3 {
x: v.normal[0] as f64,
y: v.normal[1] as f64,
z: v.normal[2] as f64,
}.normalize()
}
| true |
82e47cdb49b3c3424d9b26ea7afac8efe24622d3
|
Rust
|
linnar/aoc2020
|
/d06/src/main.rs
|
UTF-8
| 695 | 3.03125 | 3 |
[] |
no_license
|
use std::collections::HashMap;
use std::fs;
fn main() {
let mut any: usize = 0;
let mut all: usize = 0;
fs::read_to_string("inputs/input_d06.txt")
.expect("File not found")
.split("\n\n")
.for_each(|x| {
let mut counter = HashMap::new();
let mut lines = 0;
for line in x.trim().lines() {
lines += 1;
for c in line.chars() {
*counter.entry(c).or_insert(0) += 1;
}
}
any += counter.len();
all += counter.values().filter(|x| **x == lines).count();
});
println!("any {}", any);
println!("all {}", all);
}
| true |
47db20b2a08c9f424bf6b0c2bbd4ae7b1e9ae55a
|
Rust
|
feather-rs/feather
|
/quill/api/src/entity.rs
|
UTF-8
| 4,468 | 3.21875 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
use libcraft_text::Text;
use std::{marker::PhantomData, ptr};
use quill_common::{Component, Pointer, PointerMut};
/// Unique internal ID of an entity.
///
/// Can be passed to [`crate::Game::entity`] to get an [`Entity`]
/// handle.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub struct EntityId(pub(crate) quill_common::EntityId);
/// Error returned by [`Entity::get`] when
/// the entity is missing a component.
#[derive(Debug, thiserror::Error)]
#[error("entity does not have component of type {0}")]
pub struct MissingComponent(&'static str);
/// A handle to an entity.
///
/// Allows access to the entity's components, like
/// position and UUID.
///
/// Use [`crate::Game::entity`] to get an `Entity` instance.
///
/// An `Entity` be sent or shared between threads. However,
/// an [`EntityId`] can.
#[derive(Debug)]
#[repr(C)]
pub struct Entity {
id: EntityId,
_not_send_sync: PhantomData<*mut ()>,
}
impl Entity {
pub(crate) fn new(id: EntityId) -> Self {
Self {
id,
_not_send_sync: PhantomData,
}
}
/// Gets a component of this entity. Returns
/// `Err(MissingComponent)` if the entity does not have this component.
///
/// # Examples
/// ```no_run
/// use quill::{Position, Entity};
/// # let entity: Entity = unreachable!();
/// let position = entity.get::<Position>().expect("entity has no position component");
/// ```
pub fn get<T: Component>(&self) -> Result<T, MissingComponent> {
let host_component = T::host_component();
unsafe {
let mut bytes_ptr = Pointer::new(ptr::null());
let mut bytes_len = 0u32;
quill_sys::entity_get_component(
self.id.0,
host_component,
PointerMut::new(&mut bytes_ptr),
PointerMut::new(&mut bytes_len),
);
if bytes_ptr.as_ptr().is_null() {
return Err(MissingComponent(std::any::type_name::<T>()));
}
let bytes = std::slice::from_raw_parts(bytes_ptr.as_ptr(), bytes_len as usize);
Ok(T::from_bytes_unchecked(bytes).0)
}
}
/// Inserts or replaces a component of this entity.
///
/// If the entity already has this component,
/// the component is overwritten.
pub fn insert<T: Component>(&self, component: T) {
let host_component = T::host_component();
let bytes = component.to_cow_bytes();
unsafe {
quill_sys::entity_set_component(
self.id.0,
host_component,
bytes.as_ptr().into(),
bytes.len() as u32,
);
}
}
/// Inserts an event to the entity.
///
/// If the entity already has this event,
/// the event is overwritten.
pub fn insert_event<T: Component>(&self, event: T) {
let host_component = T::host_component();
let bytes = event.to_cow_bytes();
unsafe {
quill_sys::entity_add_event(
self.id.0,
host_component,
bytes.as_ptr().into(),
bytes.len() as u32,
);
}
}
/// Sends the given message to this entity.
///
/// The message sends as a "system" message.
/// See [the wiki](https://wiki.vg/Chat) for more details.
pub fn send_message(&self, message: impl Into<Text>) {
let message = message.into().to_string();
unsafe {
quill_sys::entity_send_message(self.id.0, message.as_ptr().into(), message.len() as u32)
}
}
/// Sends the given title to this entity.
pub fn send_title(&self, title: &libcraft_text::Title) {
let title = serde_json::to_string(title).expect("failed to serialize Title");
unsafe {
quill_sys::entity_send_title(self.id.0, title.as_ptr().into(), title.len() as u32);
}
}
/// Hides the currently visible title for this entity, will do nothing if the there's no title
pub fn hide_title(&self) {
self.send_title(&libcraft_text::title::Title::HIDE);
}
/// Resets the currently visible title for this entity, will do nothing if there's no title
pub fn reset_title(&self) {
self.send_title(&libcraft_text::title::Title::RESET)
}
/// Gets the unique ID of this entity.
pub fn id(&self) -> EntityId {
self.id
}
}
| true |
1817fb0fd213e66bd7c8da0b76f17200b73293d6
|
Rust
|
doyoubi/undermoon
|
/src/common/config.rs
|
UTF-8
| 7,838 | 2.921875 | 3 |
[
"Apache-2.0"
] |
permissive
|
use serde::de::Error;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::collections::HashMap;
use std::str::FromStr;
use std::sync::atomic::{AtomicU64, Ordering};
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, Default)]
pub struct ClusterConfig {
#[serde(default)]
pub compression_strategy: CompressionStrategy,
#[serde(default)]
pub migration_config: MigrationConfig,
}
impl ClusterConfig {
pub fn set_field(&mut self, field: &str, value: &str) -> Result<(), ConfigError> {
let field = field.to_lowercase();
match field.as_str() {
"compression_strategy" => {
let strategy =
CompressionStrategy::from_str(value).map_err(|_| ConfigError::InvalidValue)?;
self.compression_strategy = strategy;
}
_ => {
if field.starts_with("migration_") {
let f = field
.split_once('_')
.map(|(_prefix, f)| f)
.ok_or(ConfigError::FieldNotFound)?;
return self.migration_config.set_field(f, value);
} else {
return Err(ConfigError::FieldNotFound);
}
}
}
Ok(())
}
pub fn to_str_map(&self) -> HashMap<String, String> {
vec![
(
"compression_strategy",
self.compression_strategy.to_str().to_string(),
),
(
"migration_max_migration_time",
self.migration_config.max_migration_time.to_string(),
),
(
"migration_max_blocking_time",
self.migration_config.max_blocking_time.to_string(),
),
(
"migration_scan_interval",
self.migration_config.scan_interval.to_string(),
),
(
"migration_scan_count",
self.migration_config.scan_count.to_string(),
),
]
.into_iter()
.map(|(k, v)| (k.to_string(), v))
.collect()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompressionStrategy {
Disabled = 0,
// Only allow SET, SETEX, PSETEX, SETNX, GET, GETSET , MGET, MSET, MSETNX commands for String data type
// as once compression is enabled other commands will get the wrong result.
SetGetOnly = 1,
// Allow all the String commands. User need to use lua script to
// bypass the compression.
AllowAll = 2,
}
impl Default for CompressionStrategy {
fn default() -> Self {
CompressionStrategy::Disabled
}
}
pub struct InvalidCompressionStr;
impl FromStr for CompressionStrategy {
type Err = InvalidCompressionStr;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let lowercase = s.to_lowercase();
match lowercase.as_str() {
"disabled" => Ok(Self::Disabled),
"set_get_only" => Ok(Self::SetGetOnly),
"allow_all" => Ok(Self::AllowAll),
_ => Err(InvalidCompressionStr),
}
}
}
impl CompressionStrategy {
pub fn to_str(self) -> &'static str {
match self {
Self::Disabled => "disabled",
Self::SetGetOnly => "set_get_only",
Self::AllowAll => "allow_all",
}
}
}
impl Serialize for CompressionStrategy {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str((*self).to_str())
}
}
impl<'de> Deserialize<'de> for CompressionStrategy {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
Self::from_str(&s)
.map_err(|_| D::Error::custom(format!("invalid compression strategy {}", s)))
}
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct MigrationConfig {
pub max_migration_time: u64,
pub max_blocking_time: u64,
pub scan_interval: u64,
pub scan_count: u64,
}
impl MigrationConfig {
fn set_field(&mut self, field: &str, value: &str) -> Result<(), ConfigError> {
let field = field.to_lowercase();
match field.as_str() {
"max_migration_time" => {
let v = value
.parse::<u64>()
.map_err(|_| ConfigError::InvalidValue)?;
self.max_migration_time = v;
}
"max_blocking_time" => {
let v = value
.parse::<u64>()
.map_err(|_| ConfigError::InvalidValue)?;
self.max_blocking_time = v;
}
"scan_interval" => {
let v = value
.parse::<u64>()
.map_err(|_| ConfigError::InvalidValue)?;
self.scan_interval = v;
}
"scan_count" => {
let v = value
.parse::<u64>()
.map_err(|_| ConfigError::InvalidValue)?;
if v == 0 {
return Err(ConfigError::InvalidValue);
}
self.scan_count = v;
}
_ => return Err(ConfigError::FieldNotFound),
}
Ok(())
}
}
impl Default for MigrationConfig {
fn default() -> Self {
Self {
max_migration_time: 3 * 60 * 60, // 3 hours
max_blocking_time: 10_000, // 10 seconds waiting for switch
scan_interval: 500, // 500 microseconds
scan_count: 16,
}
}
}
pub struct AtomicMigrationConfig {
max_migration_time: AtomicU64,
max_blocking_time: AtomicU64,
scan_interval: AtomicU64,
scan_count: AtomicU64,
}
impl Default for AtomicMigrationConfig {
fn default() -> Self {
Self::from_config(MigrationConfig::default())
}
}
impl AtomicMigrationConfig {
pub fn from_config(config: MigrationConfig) -> Self {
Self {
max_migration_time: AtomicU64::new(config.max_migration_time),
max_blocking_time: AtomicU64::new(config.max_blocking_time),
scan_interval: AtomicU64::new(config.scan_interval),
scan_count: AtomicU64::new(config.scan_count),
}
}
pub fn get_max_migration_time(&self) -> u64 {
self.max_migration_time.load(Ordering::SeqCst)
}
pub fn get_max_blocking_time(&self) -> u64 {
self.max_blocking_time.load(Ordering::SeqCst)
}
pub fn get_scan_interval(&self) -> u64 {
self.scan_interval.load(Ordering::SeqCst)
}
pub fn get_scan_count(&self) -> u64 {
self.scan_count.load(Ordering::SeqCst)
}
}
#[derive(Debug)]
pub enum ConfigError {
ReadonlyField,
FieldNotFound,
InvalidValue,
Forbidden,
}
impl ToString for ConfigError {
fn to_string(&self) -> String {
match self {
Self::ReadonlyField => "READONLY_FIELD".to_string(),
Self::FieldNotFound => "FIELD_NOT_FOUND".to_string(),
Self::InvalidValue => "INVALID_VALUE".to_string(),
Self::Forbidden => "FORBIDDEN".to_string(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_config_set_field() {
let mut migration_config = MigrationConfig::default();
migration_config.set_field("scan_count", "233").unwrap();
assert_eq!(migration_config.scan_count, 233);
let mut cluster_config = ClusterConfig::default();
cluster_config
.set_field("migration_scan_count", "666")
.unwrap();
assert_eq!(cluster_config.migration_config.scan_count, 666);
}
}
| true |
89d5749163246d5af6911c86e997253e5512f8dc
|
Rust
|
iCrawl/myrias
|
/src/router/create_container.rs
|
UTF-8
| 1,202 | 2.8125 | 3 |
[
"MIT"
] |
permissive
|
use log::info;
use rocket::{http::Status, post};
use rocket_contrib::json::Json;
use serde::Deserialize;
use crate::docker::Docker;
#[derive(Deserialize)]
pub struct CreateContainerInput {
language: String,
}
#[post("/create_container", format = "json", data = "<create>")]
pub fn index(create: Json<CreateContainerInput>) -> Status {
info!("Building container: myrias_{}", create.language);
Docker::start_container(&create.language);
info!("Built container: myrias_{}", create.language);
info!(
"Creating eval directory in container: myrias_{}",
create.language
);
Docker::exec(&[
"exec",
&format!("myrias_{}", create.language),
"mkdir",
"eval",
]);
info!(
"Created eval directory in container: myrias_{}",
create.language
);
info!(
"Chmod eval directory to 711 in container: myrias_{}",
create.language
);
Docker::exec(&[
"exec",
&format!("myrias_{}", create.language),
"chmod",
"711",
"eval",
]);
info!(
"Chmod' eval directory in container: myrias_{}",
create.language
);
Status::Created
}
| true |
f4170084c8e72529fede870701dd9b6cf756c5cd
|
Rust
|
AdamKinnell/AdventOfCode2018
|
/src/bin/day1_part1.rs
|
UTF-8
| 273 | 2.796875 | 3 |
[] |
no_license
|
use std::fs;
fn main() {
let input = fs::read_to_string("res/input/day1.txt")
.expect("Unable to read input");
let sum:i32 = input.split("\r\n")
.map(|x| x.parse::<i32>().unwrap())
.sum();
println!("Resulting Frequency: {}", sum);
}
| true |
b0b6a67e35d9616ca72e1c22416a4552a677a3fa
|
Rust
|
kahirokunn/atcoder
|
/history/arc065_a.rs
|
UTF-8
| 606 | 3.15625 | 3 |
[] |
no_license
|
use std::io::*;
use std::str::FromStr;
fn read<T: FromStr>() -> T {
let stdin = stdin();
let stdin = stdin.lock();
let token: String = stdin
.bytes()
.map(|c| c.expect("failed to read char") as char)
.skip_while(|c| c.is_whitespace())
.take_while(|c| !c.is_whitespace())
.collect();
token.parse().ok().expect("failed to parse token")
}
fn main() {
let patterns = ["eraser", "erase", "dreamer", "dream"];
let s = patterns.iter().fold(read::<String>(), |s, x| s.replace(x, ""));
println!("{}", if s.is_empty() { "YES" } else { "NO "});
}
| true |
427fd2cde3869c59022c91f7de93ca3459431675
|
Rust
|
skriems/muttmates
|
/src/fields.rs
|
UTF-8
| 2,456 | 2.640625 | 3 |
[
"Unlicense"
] |
permissive
|
/*
* TODO: add support for:
* "SOURCE" / "KIND" / "FN" / "N" / "NICKNAME"
* "PHOTO" / "BDAY" / "ANNIVERSARY" / "GENDER" / "ADR" / "TEL"
* "EMAIL" / "IMPP" / "LANG" / "TZ" / "GEO" / "TITLE" / "ROLE"
* "LOGO" / "ORG" / "MEMBER" / "RELATED" / "CATEGORIES"
* "NOTE" / "PRODID" / "REV" / "SOUND" / "UID" / "CLIENTPIDMAP"
* "URL" / "KEY" / "FBURL" / "CALADRURI" / "CALURI" / "XML"
* iana-token / x-name
*/
use std::fmt;
/// The `FN` field of a `VCard` is a required field
/// # Example
/// ```
/// use muttmates::fields::FN;
///
/// let field = FN::new("FN:Foo Bar");
/// assert_eq!(field.name, "Foo Bar" );
/// ```
#[derive(Debug, PartialEq)]
pub struct FN<'a> {
pub name: &'a str,
}
impl<'a> FN<'a> {
pub fn new(raw: &'a str) -> Self {
let splits: Vec<&str> = raw.split(':').collect();
FN { name: splits[1] }
}
}
impl<'a> fmt::Display for FN<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.name)
}
}
/// An Enum for various EMail types
/// TODO: please elaborate...
#[derive(Debug, PartialEq)]
pub enum EMailKind {
Home,
Work,
Other,
}
/// The `EMAIL` field
/// # Example
/// ```
/// use muttmates::fields::{EMail, EMailKind};
///
/// let email = EMail::new("EMAIL;TYPE=WORK:[email protected]");
/// assert_eq!(email.addr, "[email protected]");
/// assert_eq!(email.kind, EMailKind::Work);
/// ```
#[derive(Debug, PartialEq)]
pub struct EMail<'a> {
pub addr: &'a str,
pub kind: EMailKind,
pub pref: bool,
}
impl<'a> EMail<'a> {
pub fn new(raw: &'a str) -> Self {
let splits: Vec<&str> = raw.split(":").collect();
let (prefix, address) = match splits.as_slice() {
[prefix, address] => (prefix, address),
_ => unreachable!(),
};
let addr = address.trim();
let mut kind = EMailKind::Other;
if prefix.find("TYPE").is_some() || prefix.find("type").is_some() {
if prefix.contains("WORK") || prefix.contains("work") {
kind = EMailKind::Work;
} else if prefix.contains("HOME") || prefix.contains("home") {
kind = EMailKind::Home;
}
}
let pref = false;
EMail { addr, kind, pref }
}
fn parse(&self) -> String {
self.addr.to_string()
}
}
impl<'a> fmt::Display for EMail<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.parse())
}
}
| true |
4295a33c29164cf26a0cdc979693800f5593023b
|
Rust
|
tmt96/adventofcode2019
|
/day7/src/main.rs
|
UTF-8
| 7,973 | 3.015625 | 3 |
[
"MIT"
] |
permissive
|
use std::collections::VecDeque;
use std::fs::read_to_string;
use std::path::Path;
use itertools::Itertools;
enum ResultCode {
Output(i32),
Terminated,
}
enum Mode {
Position,
Intermediate,
}
impl Mode {
fn from_i32(val: i32) -> Self {
match val {
0 => Self::Position,
1 => Self::Intermediate,
mode => panic!("MOde must be either 0 or 1, receive {}", mode),
}
}
}
struct IntCodeComputer {
program: Vec<i32>,
input: VecDeque<i32>,
inst_pointer: usize,
}
impl IntCodeComputer {
fn new(program: &[i32], phase: i32) -> Self {
Self {
program: program.to_vec(),
input: VecDeque::from(vec![phase]),
inst_pointer: 0,
}
}
fn parse_instruction(&self) -> (i32, Mode, Mode) {
let inst = self.program[self.inst_pointer];
let opcode = inst % 100;
let mut inst = inst / 100;
let mode_1 = inst % 10;
inst /= 10;
let mode_2 = inst % 10;
(opcode, Mode::from_i32(mode_1), Mode::from_i32(mode_2))
}
fn get_val(&self, loc: usize, mode: Mode) -> i32 {
let res = self.program[loc];
match mode {
Mode::Intermediate => res,
Mode::Position => self.program[res as usize],
}
}
fn run_one_turn(&mut self, input: i32) -> ResultCode {
self.input.push_back(input);
while self.inst_pointer < self.program.len() {
let (opcode, mode_1, mode_2) = self.parse_instruction();
match opcode {
1 => {
let (fst, snd, dst) = (
self.get_val(self.inst_pointer + 1, mode_1),
self.get_val(self.inst_pointer + 2, mode_2),
self.program[self.inst_pointer + 3],
);
self.program[dst as usize] = fst + snd;
self.inst_pointer += 4;
}
2 => {
let (fst, snd, dst) = (
self.get_val(self.inst_pointer + 1, mode_1),
self.get_val(self.inst_pointer + 2, mode_2),
self.program[self.inst_pointer + 3],
);
self.program[dst as usize] = fst * snd;
self.inst_pointer += 4;
}
3 => {
let dst = self.program[self.inst_pointer + 1];
self.program[dst as usize] = self.input.pop_front().unwrap();
self.inst_pointer += 2;
}
4 => {
let output = self.get_val(self.inst_pointer + 1, mode_1);
self.inst_pointer += 2;
return ResultCode::Output(output);
}
5 => {
let (fst, snd) = (
self.get_val(self.inst_pointer + 1, mode_1),
self.get_val(self.inst_pointer + 2, mode_2),
);
self.inst_pointer = if fst != 0 {
snd as usize
} else {
self.inst_pointer + 3
}
}
6 => {
let (fst, snd) = (
self.get_val(self.inst_pointer + 1, mode_1),
self.get_val(self.inst_pointer + 2, mode_2),
);
self.inst_pointer = if fst == 0 {
snd as usize
} else {
self.inst_pointer + 3
}
}
7 => {
let (fst, snd, dst) = (
self.get_val(self.inst_pointer + 1, mode_1),
self.get_val(self.inst_pointer + 2, mode_2),
self.program[self.inst_pointer + 3],
);
self.program[dst as usize] = if fst < snd { 1 } else { 0 };
self.inst_pointer += 4;
}
8 => {
let (fst, snd, dst) = (
self.get_val(self.inst_pointer + 1, mode_1),
self.get_val(self.inst_pointer + 2, mode_2),
self.program[self.inst_pointer + 3],
);
self.program[dst as usize] = if fst == snd { 1 } else { 0 };
self.inst_pointer += 4;
}
99 => return ResultCode::Terminated,
opcode => panic!(
"Opcode must be 1, 2, 3, 4, 5, 6, 7, 8 or 99, receive {} at {}",
opcode, self.inst_pointer,
),
}
}
unreachable!()
}
fn run_program(&mut self, input: i32) -> i32 {
let mut input = input;
while let ResultCode::Output(i) = self.run_one_turn(input) {
input = i;
}
self.input[0]
}
}
fn cal_normal_thrust(phases: &[i32], program: &[i32]) -> i32 {
phases.iter().fold(0, |state, &phase| {
IntCodeComputer::new(program, phase).run_program(state)
})
}
fn cal_thurst_with_feedback(phases: &[i32], program: &[i32]) -> i32 {
let mut computers: Vec<_> = phases
.iter()
.map(|&phase| IntCodeComputer::new(program, phase))
.collect();
let mut input = 0;
for i in (0..computers.len()).cycle() {
match computers[i].run_one_turn(input) {
ResultCode::Output(i) => input = i,
ResultCode::Terminated => return input,
}
}
unreachable!()
}
fn read_input(filepath: &Path) -> std::io::Result<Vec<i32>> {
Ok(read_to_string(filepath)?
.split(',')
.filter_map(|s| s.trim().parse::<i32>().ok())
.collect())
}
fn part1(input: &[i32]) -> i32 {
(0..5)
.permutations(5)
.map(|perm| cal_normal_thrust(&perm, input))
.max()
.unwrap()
}
fn part2(input: &[i32]) -> i32 {
(5..10)
.permutations(5)
.map(|perm| cal_thurst_with_feedback(&perm, input))
.max()
.unwrap()
}
fn main() -> std::io::Result<()> {
let filepath = Path::new("./input/input.txt");
let input = read_input(filepath)?;
println!("part 1: {}", part1(&input));
println!("part 2: {}", part2(&input));
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn day7_test1() {
let code = vec![
3, 15, 3, 16, 1002, 16, 10, 16, 1, 16, 15, 15, 4, 15, 99, 0, 0,
];
let res = part1(&code);
assert_eq!(43210, res);
}
#[test]
fn day7_test2() {
let code = vec![
3, 23, 3, 24, 1002, 24, 10, 24, 1002, 23, -1, 23, 101, 5, 23, 23, 1, 24, 23, 23, 4, 23,
99, 0, 0,
];
let res = part1(&code);
assert_eq!(54321, res);
}
#[test]
fn day7_test3() {
let code = vec![
3, 31, 3, 32, 1002, 32, 10, 32, 1001, 31, -2, 31, 1007, 31, 0, 33, 1002, 33, 7, 33, 1,
33, 31, 31, 1, 32, 31, 31, 4, 31, 99, 0, 0, 0,
];
let res = part1(&code);
assert_eq!(65210, res);
}
#[test]
fn day7_test4() {
let code = vec![
3, 26, 1001, 26, -4, 26, 3, 27, 1002, 27, 2, 27, 1, 27, 26, 27, 4, 27, 1001, 28, -1,
28, 1005, 28, 6, 99, 0, 0, 5,
];
let res = part2(&code);
assert_eq!(139_629_729, res);
}
#[test]
fn day7_test5() {
let code = vec![
3, 52, 1001, 52, -5, 52, 3, 53, 1, 52, 56, 54, 1007, 54, 5, 55, 1005, 55, 26, 1001, 54,
-5, 54, 1105, 1, 12, 1, 53, 54, 53, 1008, 54, 0, 55, 1001, 55, 1, 55, 2, 53, 55, 53, 4,
53, 1001, 56, -1, 56, 1005, 56, 6, 99, 0, 0, 0, 0, 10,
];
let res = part2(&code);
assert_eq!(18216, res);
}
}
| true |
a33fe336c5a6dcbee54211c13282e98143601745
|
Rust
|
TanNgocDo/hbbft
|
/src/subset/subset.rs
|
UTF-8
| 6,665 | 2.796875 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
use std::collections::BTreeMap;
use std::sync::Arc;
use std::{fmt, result};
use derivative::Derivative;
use hex_fmt::HexFmt;
use log::debug;
use serde_derive::Serialize;
use super::proposal_state::{ProposalState, Step as ProposalStep};
use super::{Error, Message, MessageContent, Result};
use rand::Rand;
use {util, DistAlgorithm, NetworkInfo, NodeIdT, SessionIdT};
/// A `Subset` step, possibly containing several outputs.
pub type Step<N> = ::Step<Message<N>, SubsetOutput<N>, N>;
/// An output with an accepted contribution or the end of the set.
#[derive(Derivative, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[derivative(Debug)]
pub enum SubsetOutput<N> {
/// A contribution was accepted into the set.
Contribution(
N,
#[derivative(Debug(format_with = "util::fmt_hex"))] Vec<u8>,
),
/// The set is complete.
Done,
}
/// Subset algorithm instance
#[derive(Debug)]
pub struct Subset<N: Rand, S> {
/// Shared network information.
netinfo: Arc<NetworkInfo<N>>,
/// The session identifier.
session_id: S,
/// A map that assigns to each validator the progress of their contribution.
proposal_states: BTreeMap<N, ProposalState<N, S>>,
/// Whether the instance has decided on a value.
decided: bool,
}
impl<N: NodeIdT + Rand, S: SessionIdT> DistAlgorithm for Subset<N, S> {
type NodeId = N;
type Input = Vec<u8>;
type Output = SubsetOutput<N>;
type Message = Message<N>;
type Error = Error;
fn handle_input(&mut self, input: Self::Input) -> Result<Step<N>> {
self.propose(input)
}
fn handle_message(&mut self, sender_id: &N, message: Message<N>) -> Result<Step<N>> {
self.handle_message(sender_id, message)
}
fn terminated(&self) -> bool {
self.decided
}
fn our_id(&self) -> &Self::NodeId {
self.netinfo.our_id()
}
}
impl<N: NodeIdT + Rand, S: SessionIdT> Subset<N, S> {
/// Creates a new `Subset` instance with the given session identifier.
///
/// If multiple `Subset`s are instantiated within a single network, they must use different
/// session identifiers to foil replay attacks.
pub fn new(netinfo: Arc<NetworkInfo<N>>, session_id: S) -> Result<Self> {
let mut proposal_states = BTreeMap::new();
for (proposer_idx, proposer_id) in netinfo.all_ids().enumerate() {
let ba_id = BaSessionId {
subset_id: session_id.clone(),
proposer_idx: proposer_idx as u32,
};
proposal_states.insert(
proposer_id.clone(),
ProposalState::new(netinfo.clone(), ba_id, proposer_id.clone())?,
);
}
Ok(Subset {
netinfo,
session_id,
proposal_states,
decided: false,
})
}
/// Proposes a value for the subset.
///
/// Returns an error if we already made a proposal.
pub fn propose(&mut self, value: Vec<u8>) -> Result<Step<N>> {
if !self.netinfo.is_validator() {
return Ok(Step::default());
}
debug!("{} proposing {:0.10}", self, HexFmt(&value));
let prop_step = self
.proposal_states
.get_mut(self.netinfo.our_id())
.ok_or(Error::UnknownProposer)?
.propose(value)?;
let step = Self::convert_step(self.netinfo.our_id(), prop_step);
Ok(step.join(self.try_output()?))
}
/// Handles a message received from `sender_id`.
///
/// This must be called with every message we receive from another node.
pub fn handle_message(&mut self, sender_id: &N, msg: Message<N>) -> Result<Step<N>> {
let prop_step = self
.proposal_states
.get_mut(&msg.proposer_id)
.ok_or(Error::UnknownProposer)?
.handle_message(sender_id, msg.content)?;
let step = Self::convert_step(&msg.proposer_id, prop_step);
Ok(step.join(self.try_output()?))
}
/// Returns the number of validators from which we have already received a proposal.
pub fn received_proposals(&self) -> usize {
let received = |state: &&ProposalState<N, S>| state.received();
self.proposal_states.values().filter(received).count()
}
fn convert_step(proposer_id: &N, prop_step: ProposalStep<N>) -> Step<N> {
let from_p_msg = |p_msg: MessageContent| p_msg.with(proposer_id.clone());
let mut step = Step::default();
if let Some(value) = step.extend_with(prop_step, from_p_msg).pop() {
let contribution = SubsetOutput::Contribution(proposer_id.clone(), value);
step.output.push(contribution);
}
step
}
/// Returns the number of Binary Agreement instances that have decided "yes".
fn count_accepted(&self) -> usize {
let accepted = |state: &&ProposalState<N, S>| state.accepted();
self.proposal_states.values().filter(accepted).count()
}
/// Checks the voting and termination conditions: If enough proposals have been accepted, votes
/// "no" for the remaining ones. If all proposals have been decided, outputs `Done`.
fn try_output(&mut self) -> Result<Step<N>> {
if self.decided || self.count_accepted() < self.netinfo.num_correct() {
return Ok(Step::default());
}
let mut step = Step::default();
if self.count_accepted() == self.netinfo.num_correct() {
for (proposer_id, state) in &mut self.proposal_states {
step.extend(Self::convert_step(proposer_id, state.vote_false()?));
}
}
if self.proposal_states.values().all(ProposalState::complete) {
self.decided = true;
step.output.push(SubsetOutput::Done);
}
Ok(step)
}
}
impl<N: NodeIdT + Rand, S: SessionIdT> fmt::Display for Subset<N, S> {
fn fmt(&self, f: &mut fmt::Formatter) -> result::Result<(), fmt::Error> {
write!(f, "{:?} Subset({})", self.our_id(), self.session_id)
}
}
/// A session identifier for a `BinaryAgreement` instance run as a `Subset` sub-algorithm. It
/// consists of the `Subset` instance's own session ID, and the index of the proposer whose
/// contribution this `BinaryAgreement` is about.
#[derive(Clone, Debug, Serialize)]
pub struct BaSessionId<S> {
subset_id: S,
proposer_idx: u32,
}
impl<S: fmt::Display> fmt::Display for BaSessionId<S> {
fn fmt(&self, f: &mut fmt::Formatter) -> result::Result<(), fmt::Error> {
write!(
f,
"subset {}, proposer #{}",
self.subset_id, self.proposer_idx
)
}
}
| true |
19298fec8527e9374b0d2b589395d6f8892e243c
|
Rust
|
rust-onig/rust-onig
|
/onig/examples/listcap.rs
|
UTF-8
| 1,269 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
use onig::*;
fn ex(hay: &str, pattern: &str, syntax: &Syntax) {
let reg = Regex::with_options(pattern, RegexOptions::REGEX_OPTION_NONE, syntax).unwrap();
println!("number of captures: {}", reg.captures_len());
println!(
"number of capture histories: {}",
reg.capture_histories_len()
);
let mut region = Region::new();
let r = reg.search_with_options(
hay,
0,
hay.len(),
SearchOptions::SEARCH_OPTION_NONE,
Some(&mut region),
);
if let Some(pos) = r {
println!("match at {}", pos);
for (i, (start, end)) in region.iter().enumerate() {
println!("{}: ({}-{})", i, start, end);
}
region.tree_traverse(|i, (start, end), level| {
println!("{}{}: ({}-{})", " ".repeat(level as usize), i, start, end);
true
});
} else {
println!("search fail");
}
}
fn main() {
let mut syn = Syntax::default().clone();
syn.enable_operators(SyntaxOperator::SYNTAX_OPERATOR_ATMARK_CAPTURE_HISTORY);
ex(
"((())())",
"\\g<p>(?@<p>\\(\\g<s>\\)){0}(?@<s>(?:\\g<p>)*|){0}",
&syn,
);
ex("x00x00x00", "(?@x(?@\\d+))+", &syn);
ex("0123", "(?@.)(?@.)(?@.)(?@.)", &syn);
}
| true |
adad89a0baa9b84a5387f90d82a048619a4d45cb
|
Rust
|
mcy/sseq
|
/ext/crates/algebra/src/algebra/milnor_algebra.rs
|
UTF-8
| 56,199 | 2.625 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
use itertools::Itertools;
use rustc_hash::FxHashMap as HashMap;
use std::sync::Mutex;
use crate::algebra::combinatorics;
use crate::algebra::{Algebra, Bialgebra, GeneratedAlgebra};
use fp::prime::{integer_power, Binomial, BitflagIterator, ValidPrime};
use fp::vector::{FpVector, Slice, SliceMut};
use once::OnceVec;
#[cfg(feature = "json")]
use {crate::algebra::JsonAlgebra, serde::Deserialize, serde_json::value::Value};
use nom::{
branch::alt,
bytes::complete::tag,
character::complete::{char, digit1, space1},
combinator::map,
sequence::{delimited, pair},
IResult,
};
// This is here so that the Python bindings can use modules defined for AdemAlgebraT with their own algebra enum.
// In order for things to work AdemAlgebraT cannot implement Algebra.
// Otherwise, the algebra enum for our bindings will see an implementation clash.
pub trait MilnorAlgebraT: Send + Sync + Algebra {
fn milnor_algebra(&self) -> &MilnorAlgebra;
}
pub struct MilnorProfile {
pub truncated: bool,
pub q_part: u32,
pub p_part: PPart,
}
impl MilnorProfile {
pub fn is_trivial(&self) -> bool {
!self.truncated && self.q_part == !0 && self.p_part.is_empty()
}
}
#[derive(Default, Clone)]
pub struct QPart {
degree: i32,
q_part: u32,
}
#[cfg(feature = "odd-primes")]
pub type PPartEntry = u32;
#[cfg(not(feature = "odd-primes"))]
pub type PPartEntry = u8;
pub type PPart = Vec<PPartEntry>;
#[derive(Debug, Clone, Default)]
pub struct MilnorBasisElement {
pub q_part: u32,
pub p_part: PPart,
pub degree: i32,
}
impl MilnorBasisElement {
fn from_p(p: PPart, dim: i32) -> Self {
Self {
p_part: p,
q_part: 0,
degree: dim,
}
}
pub fn clone_into(&self, other: &mut Self) {
other.q_part = self.q_part;
other.degree = self.degree;
other.p_part.clear();
other.p_part.extend_from_slice(&self.p_part);
}
}
impl std::cmp::PartialEq for MilnorBasisElement {
fn eq(&self, other: &Self) -> bool {
#[cfg(feature = "odd-primes")]
return self.p_part == other.p_part && self.q_part == other.q_part;
#[cfg(not(feature = "odd-primes"))]
return self.p_part == other.p_part;
}
}
impl std::cmp::Eq for MilnorBasisElement {}
impl std::hash::Hash for MilnorBasisElement {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.p_part.hash(state);
#[cfg(feature = "odd-primes")]
self.q_part.hash(state);
}
}
impl std::fmt::Display for MilnorBasisElement {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
if self.degree == 0 {
write!(f, "1")?;
return Ok(());
}
if self.q_part != 0 {
let q_part = BitflagIterator::set_bit_iterator(self.q_part as u64)
.map(|idx| format!("Q_{}", idx))
.format(" ");
write!(f, "{}", q_part)?;
}
if !self.p_part.is_empty() {
if self.q_part != 0 {
write!(f, " ")?;
}
write!(f, "P({})", self.p_part.iter().format(", "))?;
}
Ok(())
}
}
// A basis element of a Milnor Algebra is of the form Q(E) P(R). Nore that deg P(R) is *always* a
// multiple of q = 2p - 2. So qpart_table is a vector of length (2p - 2), each containing a list of
// possible Q(E) of appropriate residue class mod q, sorted in increasing order of degree. On the
// other hand, ppart_table[i] consists of a list of possible P(R) of degree qi. When we construct a
// list of basis elements from ppart_table and qpart_table given a degree d, we iterate through the
// elements of qpart_table[d % q], and then for each element, we iterate through the appropriate
// entry in ppart_table of the right degree.
pub struct MilnorAlgebra {
pub profile: MilnorProfile,
lock: Mutex<()>,
p: ValidPrime,
#[cfg(feature = "odd-primes")]
generic: bool,
ppart_table: OnceVec<Vec<PPart>>,
qpart_table: Vec<OnceVec<QPart>>,
pub basis_table: OnceVec<Vec<MilnorBasisElement>>,
basis_element_to_index_map: OnceVec<HashMap<MilnorBasisElement, usize>>, // degree -> MilnorBasisElement -> index
#[cfg(feature = "cache-multiplication")]
multiplication_table: OnceVec<OnceVec<Vec<Vec<FpVector>>>>, // source_deg -> target_deg -> source_op -> target_op
}
impl std::fmt::Display for MilnorAlgebra {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "MilnorAlgebra(p={})", self.prime())
}
}
impl MilnorAlgebra {
pub fn new(p: ValidPrime) -> Self {
let profile = MilnorProfile {
truncated: false,
q_part: !0,
p_part: Vec::new(),
};
Self {
p,
#[cfg(feature = "odd-primes")]
generic: *p != 2,
profile,
lock: Mutex::new(()),
ppart_table: OnceVec::new(),
qpart_table: vec![OnceVec::new(); 2 * *p as usize - 2],
basis_table: OnceVec::new(),
basis_element_to_index_map: OnceVec::new(),
#[cfg(feature = "cache-multiplication")]
multiplication_table: OnceVec::new(),
}
}
#[inline]
pub fn generic(&self) -> bool {
#[cfg(feature = "odd-primes")]
{
self.generic
}
#[cfg(not(feature = "odd-primes"))]
{
false
}
}
pub fn q(&self) -> i32 {
if self.generic() {
2 * (*self.prime() as i32 - 1)
} else {
1
}
}
pub fn basis_element_from_index(&self, degree: i32, idx: usize) -> &MilnorBasisElement {
&self.basis_table[degree as usize][idx]
}
pub fn try_basis_element_to_index(&self, elt: &MilnorBasisElement) -> Option<usize> {
self.basis_element_to_index_map[elt.degree as usize]
.get(elt)
.copied()
}
pub fn basis_element_to_index(&self, elt: &MilnorBasisElement) -> usize {
self.try_basis_element_to_index(elt)
.unwrap_or_else(|| panic!("Didn't find element: {:?}", elt))
}
}
impl Algebra for MilnorAlgebra {
fn prime(&self) -> ValidPrime {
self.p
}
fn default_filtration_one_products(&self) -> Vec<(String, i32, usize)> {
let mut products = Vec::with_capacity(4);
let max_degree;
if self.generic() {
if self.profile.q_part & 1 != 0 {
products.push((
"a_0".to_string(),
MilnorBasisElement {
degree: 1,
q_part: 1,
p_part: vec![],
},
));
}
if (self.profile.p_part.is_empty() && !self.profile.truncated)
|| (!self.profile.p_part.is_empty() && self.profile.p_part[0] > 0)
{
products.push((
"h_0".to_string(),
MilnorBasisElement {
degree: (2 * (*self.prime()) - 2) as i32,
q_part: 0,
p_part: vec![1],
},
));
}
max_degree = (2 * (*self.prime()) - 2) as i32;
} else {
let mut max = 4;
if !self.profile.p_part.is_empty() {
max = std::cmp::min(4, self.profile.p_part[0]);
} else if self.profile.truncated {
max = 0;
}
for i in 0..max {
let degree = 1 << i; // degree is 2^hi
products.push((
format!("h_{}", i),
MilnorBasisElement {
degree,
q_part: 0,
p_part: vec![1 << i],
},
));
}
max_degree = 1 << 3;
}
self.compute_basis(max_degree + 1);
products
.into_iter()
.map(|(name, b)| (name, b.degree, self.basis_element_to_index(&b)))
.collect()
}
fn compute_basis(&self, max_degree: i32) {
let _lock = self.lock.lock().unwrap();
let next_degree = self.basis_table.len() as i32;
if max_degree < next_degree {
return;
}
self.compute_ppart(max_degree);
self.compute_qpart(next_degree, max_degree);
if self.generic() {
self.generate_basis_generic(next_degree, max_degree);
} else {
self.generate_basis_2(next_degree, max_degree);
}
// Populate hash map
for d in next_degree as usize..=max_degree as usize {
let basis = &self.basis_table[d];
let mut map = HashMap::default();
map.reserve(basis.len());
for (i, b) in basis.iter().enumerate() {
map.insert(b.clone(), i);
}
self.basis_element_to_index_map.push(map);
}
#[cfg(feature = "cache-multiplication")]
{
for d in 0..=max_degree as usize {
if self.multiplication_table.len() == d {
self.multiplication_table.push(OnceVec::new());
}
for e in self.multiplication_table[d].len()..=max_degree as usize - d {
self.multiplication_table[d].push(
(0..self.dimension(d as i32, -1))
.map(|i| {
(0..self.dimension(e as i32, -1))
.map(|j| {
let mut res = FpVector::new(
self.prime(),
self.dimension((d + e) as i32, -1),
);
self.multiply(
&mut res,
1,
&self.basis_table[d][i],
&self.basis_table[e][j],
);
res
})
.collect::<Vec<_>>()
})
.collect::<Vec<_>>(),
);
}
}
}
}
fn dimension(&self, degree: i32, _excess: i32) -> usize {
if degree < 0 {
return 0;
}
self.basis_table[degree as usize].len()
}
#[cfg(not(feature = "cache-multiplication"))]
fn multiply_basis_elements(
&self,
result: SliceMut,
coef: u32,
r_degree: i32,
r_idx: usize,
s_degree: i32,
s_idx: usize,
_excess: i32,
) {
self.multiply(
result,
coef,
&self.basis_table[r_degree as usize][r_idx],
&self.basis_table[s_degree as usize][s_idx],
);
}
#[cfg(feature = "cache-multiplication")]
fn multiply_basis_elements(
&self,
result: SliceMut,
coef: u32,
r_degree: i32,
r_idx: usize,
s_degree: i32,
s_idx: usize,
_excess: i32,
) {
result.shift_add(
&self.multiplication_table[r_degree as usize][s_degree as usize][r_idx][s_idx]
.as_slice(),
coef,
);
}
fn basis_element_to_string(&self, degree: i32, idx: usize) -> String {
format!("{}", self.basis_table[degree as usize][idx])
}
}
#[cfg(feature = "json")]
impl JsonAlgebra for MilnorAlgebra {
fn prefix(&self) -> &str {
"milnor"
}
fn json_to_basis(&self, json: &Value) -> anyhow::Result<(i32, usize)> {
let xi_degrees = combinatorics::xi_degrees(self.prime());
let tau_degrees = combinatorics::tau_degrees(self.prime());
let p_part: PPart;
let mut q_part = 0;
let mut degree = 0;
if self.generic() {
let (q_list, p_list): (Vec<u8>, PPart) = <_>::deserialize(json)?;
let q = self.q();
p_part = p_list;
for (i, &val) in p_part.iter().enumerate() {
degree += (val as i32) * xi_degrees[i] * q;
}
for k in q_list {
q_part |= 1 << k;
degree += tau_degrees[k as usize];
}
} else {
p_part = <_>::deserialize(json)?;
for (i, &val) in p_part.iter().enumerate() {
degree += (val as i32) * xi_degrees[i];
}
}
let m = MilnorBasisElement {
q_part,
p_part,
degree,
};
Ok((degree, self.basis_element_to_index(&m)))
}
fn json_from_basis(&self, degree: i32, index: usize) -> Value {
let b = self.basis_element_from_index(degree, index);
if self.generic() {
let mut q_part = b.q_part;
let mut q_list = Vec::with_capacity(q_part.count_ones() as usize);
while q_part != 0 {
let tz = q_part.trailing_zeros();
q_part ^= 1 << tz;
q_list.push(tz);
}
serde_json::to_value((q_list, &b.p_part)).unwrap()
} else {
serde_json::to_value(&b.p_part).unwrap()
}
}
}
impl GeneratedAlgebra for MilnorAlgebra {
// Same implementation as AdemAlgebra
fn string_to_generator<'a, 'b>(&'a self, input: &'b str) -> IResult<&'b str, (i32, usize)> {
let first = map(
alt((
delimited(char('P'), digit1, space1),
delimited(tag("Sq"), digit1, space1),
)),
|elt| {
let i = std::str::FromStr::from_str(elt).unwrap();
self.beps_pn(0, i)
},
);
let second = map(pair(char('b'), space1), |_| (1, 0));
alt((first, second))(input)
}
fn generator_to_string(&self, degree: i32, _idx: usize) -> String {
if self.generic() {
if degree == 1 {
"b".to_string()
} else {
format!("P{}", degree as u32 / (2 * (*self.prime()) - 2))
}
} else {
format!("Sq{}", degree)
}
}
fn generators(&self, degree: i32) -> Vec<usize> {
if degree == 0 {
return vec![];
}
if self.generic() && degree == 1 {
return vec![0]; // Q_0
}
let p = *self.prime();
let q = self.q() as u32;
let mut temp_degree = degree as u32;
if temp_degree % q != 0 {
return vec![];
}
temp_degree /= q;
let mut power = 0;
while temp_degree % p == 0 {
temp_degree /= p;
power += 1;
}
if temp_degree != 1 {
return vec![];
}
if (self.profile.p_part.is_empty() && self.profile.truncated)
|| (!self.profile.p_part.is_empty() && self.profile.p_part[0] <= power)
{
return vec![];
}
let idx = self.basis_element_to_index(&MilnorBasisElement {
degree,
q_part: 0,
p_part: vec![(degree as u32 / q) as PPartEntry],
});
return vec![idx];
}
fn decompose_basis_element(
&self,
degree: i32,
idx: usize,
) -> Vec<(u32, (i32, usize), (i32, usize))> {
let basis = &self.basis_table[degree as usize][idx];
// If qpart = 0, return self
if basis.q_part == 0 {
self.decompose_basis_element_ppart(degree, idx)
} else {
self.decompose_basis_element_qpart(degree, idx)
}
}
fn generating_relations(&self, degree: i32) -> Vec<Vec<(u32, (i32, usize), (i32, usize))>> {
if self.generic() && degree == 2 {
// beta^2 = 0 is an edge case
return vec![vec![(1, (1, 0), (1, 0))]];
}
let p = self.prime();
let inadmissible_pairs = combinatorics::inadmissible_pairs(p, self.generic(), degree);
let mut result = Vec::new();
for (x, b, y) in inadmissible_pairs {
let mut relation = Vec::new();
// Adem relation. Sometimes these don't exist because of profiles. Then just ignore it.
(|| {
let (first_degree, first_index) = self.try_beps_pn(0, x as PPartEntry)?;
let (second_degree, second_index) = self.try_beps_pn(b, y as PPartEntry)?;
relation.push((
*p - 1,
(first_degree, first_index),
(second_degree, second_index),
));
for e1 in 0..=b {
let e2 = b - e1;
// e1 and e2 determine where a bockstein shows up.
// e1 determines whether a bockstein shows up in front
// e2 determines whether a bockstein shows up in middle
// So our output term looks like b^{e1} P^{x+y-j} b^{e2} P^{j}
for j in 0..=x / *p {
let c = combinatorics::adem_relation_coefficient(p, x, y, j, e1, e2);
if c == 0 {
continue;
}
if j == 0 {
relation.push((
c,
self.try_beps_pn(e1, (x + y) as PPartEntry)?,
(e2 as i32, 0),
));
continue;
}
let first_sq = self.try_beps_pn(e1, (x + y - j) as PPartEntry)?;
let second_sq = self.try_beps_pn(e2, j as PPartEntry)?;
relation.push((c, first_sq, second_sq));
}
}
result.push(relation);
Some(())
})();
}
result
}
}
// Compute basis functions
impl MilnorAlgebra {
fn compute_ppart(&self, max_degree: i32) {
self.ppart_table.extend(0, |_| vec![Vec::new()]);
let p = *self.prime() as i32;
let q = if p == 2 { 1 } else { 2 * p - 2 };
let new_deg = max_degree / q;
let xi_degrees = combinatorics::xi_degrees(self.prime());
let mut profile_list = Vec::with_capacity(xi_degrees.len());
for i in 0..xi_degrees.len() {
if i < self.profile.p_part.len() {
profile_list.push(
(integer_power(*self.prime(), self.profile.p_part[i] as u32) - 1) as PPartEntry,
);
} else if self.profile.truncated {
profile_list.push(0);
} else {
profile_list.push(PPartEntry::MAX);
}
}
self.ppart_table.extend(new_deg as usize, |d| {
let d = d as i32;
let mut new_row = Vec::new(); // Improve this
for i in 0..xi_degrees.len() {
if xi_degrees[i] > d {
break;
}
if profile_list[i] == 0 {
continue;
}
let rem = (d - xi_degrees[i]) as usize;
for old in &self.ppart_table[rem] {
// ppart_table[rem] is arranged in increasing order of highest
// xi_i. If we get something too large, we may abort;
if old.len() > i + 1 {
break;
}
if old.len() == i + 1 && old[i] == profile_list[i] {
continue;
}
let mut new = old.clone();
if new.len() < i + 1 {
new.resize(i + 1, 0);
}
new[i] += 1;
new_row.push(new);
}
}
new_row
});
}
fn compute_qpart(&self, next_degree: i32, max_degree: i32) {
let q = (2 * (*self.prime()) - 2) as i32;
let profile = !self.profile.q_part;
if !self.generic() {
return;
}
let mut next_degree = next_degree;
if next_degree == 0 {
self.qpart_table[0].push_checked(
QPart {
degree: 0,
q_part: 0,
},
0,
);
next_degree = 1;
}
let tau_degrees = combinatorics::tau_degrees(self.prime());
let old_max_tau = tau_degrees
.iter()
.position(|d| *d > next_degree - 1)
.unwrap(); // Use expect instead
let new_max_tau = tau_degrees.iter().position(|d| *d > max_degree).unwrap();
let bit_string_min: u32 = 1 << old_max_tau;
let bit_string_max: u32 = 1 << new_max_tau;
let mut residue: i32 = (old_max_tau as i32) % q;
let mut total: i32 = tau_degrees[0..old_max_tau].iter().sum();
for bit_string in bit_string_min..bit_string_max {
// v has all the trailing zeros set. These are the bits that were set last time,
// but aren't set anymore because of a carry. Shift right 1 because ???1000 ==> ???0111 xor ???1000 = 0001111.
let mut v = (bit_string ^ (bit_string - 1)) >> 1;
let mut c: usize = 0; // We're going to get the new bit that is set into c.
while v != 0 {
v >>= 1; // Subtract off the degree of each of the lost entries
total -= tau_degrees[c];
c += 1;
}
total += tau_degrees[c];
residue += 1 - c as i32;
if bit_string & profile != 0 {
continue;
}
residue %= q;
if residue < 0 {
residue += q;
}
self.qpart_table[residue as usize].push(QPart {
degree: total,
q_part: bit_string,
});
}
}
fn generate_basis_generic(&self, next_degree: i32, max_degree: i32) {
let q = (2 * (*self.prime()) - 2) as usize;
for d in next_degree as usize..=max_degree as usize {
let mut new_table = Vec::new(); // Initialize size
for q_part in self.qpart_table[d % q].iter() {
// Elements in qpart_table are listed in increasing order in
// degree. Abort if degree too large.
if q_part.degree > d as i32 {
break;
}
for p_part in &self.ppart_table[(d - (q_part.degree as usize)) / q] {
new_table.push(MilnorBasisElement {
p_part: p_part.clone(),
q_part: q_part.q_part,
degree: d as i32,
});
}
}
// new_table.shrink_to_fit();
self.basis_table.push(new_table);
}
}
fn generate_basis_2(&self, next_degree: i32, max_degree: i32) {
for i in next_degree as usize..=max_degree as usize {
self.basis_table.push(
self.ppart_table[i]
.iter()
.map(|p| MilnorBasisElement::from_p(p.clone(), i as i32))
.collect(),
);
}
}
}
// Multiplication logic
impl MilnorAlgebra {
fn try_beps_pn(&self, e: u32, x: PPartEntry) -> Option<(i32, usize)> {
let q = self.q() as u32;
let degree = (q * x as u32 + e) as i32;
self.try_basis_element_to_index(&MilnorBasisElement {
degree,
q_part: e,
p_part: vec![x as PPartEntry],
})
.map(|index| (degree, index))
}
fn beps_pn(&self, e: u32, x: PPartEntry) -> (i32, usize) {
self.try_beps_pn(e, x).unwrap()
}
fn multiply_qpart(&self, m1: &MilnorBasisElement, f: u32) -> Vec<(u32, MilnorBasisElement)> {
let mut new_result: Vec<(u32, MilnorBasisElement)> = vec![(1, m1.clone())];
let mut old_result: Vec<(u32, MilnorBasisElement)> = Vec::new();
for k in BitflagIterator::set_bit_iterator(f as u64) {
let k = k as u32;
let pk = integer_power(*self.p, k) as PPartEntry;
std::mem::swap(&mut new_result, &mut old_result);
new_result.clear();
// We implement the formula
// P(R) Q_k = Q_k P^R + Q_{k+1} P(R - p^k e_1) + Q_{k+2} P(R - p^k e_2) +
// ... + Q_{k + i} P(R - p^k e_i) + ...
// where e_i is the vector with value 1 in entry i and 0 otherwise (in the above
// formula, the first xi is xi_1, hence the offset below). If R - p^k e_i has a
// negative entry, the term is 0.
//
// We also use the fact that Q_k Q_j = -Q_j Q_k
for (coef, term) in &old_result {
for i in 0..=term.p_part.len() {
// If there is already Q_{k+i} on the other side, the result is 0
if term.q_part & (1 << (k + i as u32)) != 0 {
continue;
}
// Check if R - p^k e_i < 0. Only do this from the first term onwards.
if i > 0 && term.p_part[i - 1] < pk {
continue;
}
let mut new_p = term.p_part.clone();
if i > 0 {
new_p[i - 1] -= pk;
}
// Now calculate the number of Q's we are moving past
let larger_q = (term.q_part >> (k + i as u32 + 1)).count_ones();
// If new_p ends with 0, drop them
while let Some(0) = new_p.last() {
new_p.pop();
}
// Now put everything together
let m = MilnorBasisElement {
p_part: new_p,
q_part: term.q_part | 1 << (k + i as u32),
degree: 0, // we don't really care about the degree here. The final degree of the whole calculation is known a priori
};
let c = if larger_q % 2 == 0 {
*coef
} else {
*coef * (*self.prime() - 1)
};
new_result.push((c, m));
}
}
}
new_result
}
pub fn multiply(
&self,
res: SliceMut,
coef: u32,
m1: &MilnorBasisElement,
m2: &MilnorBasisElement,
) {
self.multiply_with_allocation(res, coef, m1, m2, PPartAllocation::default());
}
pub fn multiply_with_allocation(
&self,
mut res: SliceMut,
coef: u32,
m1: &MilnorBasisElement,
m2: &MilnorBasisElement,
mut allocation: PPartAllocation,
) -> PPartAllocation {
let target_deg = m1.degree + m2.degree;
if self.generic() {
let m1f = self.multiply_qpart(m1, m2.q_part);
for (cc, basis) in m1f {
let mut multiplier = PPartMultiplier::<false>::new_from_allocation(
self.prime(),
&basis.p_part,
&m2.p_part,
allocation,
basis.q_part,
target_deg,
);
while let Some(c) = multiplier.next() {
let idx = self.basis_element_to_index(&multiplier.ans);
res.add_basis_element(idx, c * cc * coef);
}
allocation = multiplier.into_allocation()
}
} else {
let mut multiplier = PPartMultiplier::<false>::new_from_allocation(
self.prime(),
&m1.p_part,
&m2.p_part,
allocation,
0,
target_deg,
);
while let Some(c) = multiplier.next() {
let idx = self.basis_element_to_index(&multiplier.ans);
res.add_basis_element(idx, c * coef);
}
allocation = multiplier.into_allocation()
}
allocation
}
pub fn multiply_element_by_basis_with_allocation(
&self,
mut res: SliceMut,
coef: u32,
r_deg: i32,
r: Slice,
m2: &MilnorBasisElement,
mut allocation: PPartAllocation,
) -> PPartAllocation {
for (i, c) in r.iter_nonzero() {
allocation = self.multiply_with_allocation(
res.copy(),
coef * c,
self.basis_element_from_index(r_deg, i),
m2,
allocation,
);
}
allocation
}
}
#[derive(Debug, Default)]
struct Matrix2D {
cols: usize,
inner: PPart,
}
impl std::fmt::Display for Matrix2D {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
for i in 0..self.inner.len() / self.cols {
writeln!(f, "{:?}", &self[i][0..self.cols])?;
}
Ok(())
}
}
impl Matrix2D {
fn reset(&mut self, rows: usize, cols: usize) {
self.cols = cols;
self.inner.clear();
self.inner.resize(rows * cols, 0);
}
}
impl Matrix2D {
fn with_capacity(rows: usize, cols: usize) -> Self {
Self {
cols: 0,
inner: Vec::with_capacity(rows * cols),
}
}
}
impl std::ops::Index<usize> for Matrix2D {
type Output = [PPartEntry];
fn index(&self, row: usize) -> &Self::Output {
// Computing the end point is fairly expensive and only serves as a safety check...
&self.inner[row * self.cols..]
}
}
impl std::ops::IndexMut<usize> for Matrix2D {
fn index_mut(&mut self, row: usize) -> &mut Self::Output {
&mut self.inner[row * self.cols..]
}
}
/// The parts of a PPartMultiplier that involve heap allocation. This lets us reuse the allocation
/// across multiple different multipliers. Reusing the whole PPartMultiplier is finicky but doable
/// due to lifetime issues, but it appears to be less performant.
#[derive(Default)]
pub struct PPartAllocation {
m: Matrix2D,
#[cfg(feature = "odd-primes")]
diagonal: PPart,
p_part: PPart,
}
impl PPartAllocation {
/// This creates a PPartAllocation with enough capacity to handle mulitiply elements with
/// of total degree < 2^n - ε at p = 2.
pub fn with_capacity(n: usize) -> Self {
Self {
m: Matrix2D::with_capacity(n + 1, n),
#[cfg(feature = "odd-primes")]
diagonal: Vec::with_capacity(n),
// This size should be the number of diagonals. Even though the answer cannot be that
// long, we still insert zeros then pop them out later.
p_part: Vec::with_capacity(2 * n),
}
}
}
#[allow(non_snake_case)]
pub struct PPartMultiplier<'a, const MOD4: bool> {
p: ValidPrime,
M: Matrix2D,
r: &'a PPart,
rows: usize,
cols: usize,
diag_num: usize,
init: bool,
pub ans: MilnorBasisElement,
#[cfg(feature = "odd-primes")]
diagonal: PPart,
}
#[allow(non_snake_case)]
impl<'a, const MOD4: bool> PPartMultiplier<'a, MOD4> {
fn prime(&self) -> ValidPrime {
self.p
}
#[allow(clippy::ptr_arg)]
#[allow(unused_mut)] // Mut is only used with odd primes
pub fn new_from_allocation(
p: ValidPrime,
r: &'a PPart,
s: &'a PPart,
mut allocation: PPartAllocation,
q_part: u32,
degree: i32,
) -> Self {
if MOD4 {
assert_eq!(*p, 2);
}
let rows = r.len() + 1;
let cols = s.len() + 1;
let diag_num = r.len() + s.len();
#[cfg(feature = "odd-primes")]
{
allocation.diagonal.clear();
allocation.diagonal.reserve_exact(std::cmp::max(rows, cols));
}
let mut M = allocation.m;
M.reset(rows, cols);
for i in 1..rows {
M[i][0] = r[i - 1];
}
// This is somehow quite significantly faster than copy_from_slice
#[allow(clippy::manual_memcpy)]
for k in 1..cols {
M[0][k] = s[k - 1];
}
let ans = MilnorBasisElement {
q_part,
p_part: allocation.p_part,
degree,
};
PPartMultiplier {
#[cfg(feature = "odd-primes")]
diagonal: allocation.diagonal,
p,
M,
r,
rows,
cols,
diag_num,
ans,
init: true,
}
}
pub fn into_allocation(self) -> PPartAllocation {
PPartAllocation {
m: self.M,
#[cfg(feature = "odd-primes")]
diagonal: self.diagonal,
p_part: self.ans.p_part,
}
}
/// This compute the first l > k such that (sum + l) choose l != 0 mod p, stopping if we reach
/// max + 1. This is useful for incrementing the matrix.
///
/// TODO: Improve odd prime performance
fn next_val(&self, sum: PPartEntry, k: PPartEntry, max: PPartEntry) -> PPartEntry {
match *self.prime() {
2 => {
if MOD4 {
// x.count_ones() + y.count_ones() - (x + y).count_ones() is the number of
// carries when adding x to y.
//
// The p-adic valuation of (n + r) choose r is the number of carries when
// adding r to n in base p.
(k + 1..max + 1)
.find(|&l| {
sum & l == 0
|| (sum.count_ones() + l.count_ones()) - (sum + l).count_ones() == 1
})
.unwrap_or(max + 1)
} else {
((k | sum) + 1) & !sum
}
}
_ => (k + 1..max + 1)
.find(|&l| !PPartEntry::binomial_odd_is_zero(self.prime(), sum + l, l))
.unwrap_or(max + 1),
}
}
/// We have a matrix of the form
/// | s₁ s₂ s₃ ...
/// --------------------
/// r₁ |
/// r₂ | x_{ij}
/// r₃ |
///
/// We think of ourselves as modifiying the center pieces x_{ij}, while the r_i's and s_j's are
/// only there to ensure the x_{ij}'s don't get too big. The idea is to sweep through the
/// matrix row by row, from top-to-bottom, and left-to-right. In each pass, we find the first
/// entry that can be incremented. We then increment it and zero out all the entries that
/// appear before it. This will give us all valid entries.
fn update(&mut self) -> bool {
for i in 1..self.rows {
// total is sum x_{ij} p^j up to the jth column
let mut total = self.M[i][0];
let mut p_to_the_j = 1;
for j in 1..self.cols {
p_to_the_j *= *self.prime() as PPartEntry;
if total < p_to_the_j {
// We don't have enough weight left in the entries above this one in the column to increment this cell.
// Add the weight from this cell to the total, we can use it to increment a cell lower down.
total += self.M[i][j] * p_to_the_j;
continue;
}
let col_sum: PPartEntry = (0..i).map(|k| self.M[k][j]).sum();
if col_sum == 0 {
total += self.M[i][j] * p_to_the_j;
continue;
}
let max_inc = std::cmp::min(col_sum, total / p_to_the_j);
// Compute the sum of entries along the diagonal to the bottom-left
let mut sum = 0;
for c in (i + j + 1).saturating_sub(self.rows)..j {
sum += self.M[i + j - c][c];
}
// Find the next possible value we can increment M[i][j] to without setting the
// coefficient to 0. The coefficient is the multinomial coefficient of the
// diagonal, and if the multinomial coefficient of any subset is zero, so is the
// coefficient of the whole diagonal.
let next_val = self.next_val(sum, self.M[i][j], max_inc + self.M[i][j]);
let inc = next_val - self.M[i][j];
// The remaining obstacle to incrementing this entry is the column sum condition.
// For this, we only need a non-zero entry in the column j above row i.
if inc <= max_inc {
// If so, we found our next matrix.
for row in 1..i {
self.M[row][0] = self.r[row - 1];
for col in 1..self.cols {
self.M[0][col] += self.M[row][col];
self.M[row][col] = 0;
}
}
for col in 1..j {
self.M[0][col] += self.M[i][col];
self.M[i][col] = 0;
}
self.M[0][j] -= inc;
self.M[i][j] += inc;
self.M[i][0] = total - p_to_the_j * inc;
return true;
}
// All the cells above this one are zero so we didn't find our next matrix.
// Add the weight from this cell to the total, we can use it to increment a cell lower down.
total += self.M[i][j] * p_to_the_j;
}
}
false
}
}
impl<'a, const MOD4: bool> Iterator for PPartMultiplier<'a, MOD4> {
type Item = u32;
fn next(&mut self) -> Option<u32> {
let p = *self.prime() as PPartEntry;
'outer: loop {
self.ans.p_part.clear();
let mut coef = 1;
if self.init {
self.init = false;
for i in 1..std::cmp::min(self.cols, self.rows) {
if MOD4 {
coef *= PPartEntry::binomial4(self.M[i][0] + self.M[0][i], self.M[0][i]);
coef %= 4;
} else {
coef *= PPartEntry::binomial(
self.prime(),
self.M[i][0] + self.M[0][i],
self.M[0][i],
);
coef %= p;
}
if coef == 0 {
continue 'outer;
}
}
for &k in &self.M[0][1..self.cols] {
self.ans.p_part.push(k);
}
if self.rows > self.cols {
self.ans.p_part.resize(self.r.len(), 0);
}
for (i, &entry) in self.r.iter().enumerate() {
self.ans.p_part[i] += entry;
}
return Some(coef as u32);
} else if self.update() {
for diag_idx in 1..=self.diag_num {
let i_min = if diag_idx + 1 > self.cols {
diag_idx + 1 - self.cols
} else {
0
};
let i_max = std::cmp::min(1 + diag_idx, self.rows);
let mut sum = 0;
if *self.prime() == 2 {
if MOD4 {
for i in i_min..i_max {
let entry = self.M[i][diag_idx - i];
sum += entry;
if coef % 2 == 0 {
coef *= PPartEntry::binomial2(sum, entry);
} else {
coef *= PPartEntry::binomial4(sum, entry);
}
coef %= 4;
if coef == 0 {
continue 'outer;
}
}
} else {
let mut or = 0;
for i in i_min..i_max {
sum += self.M[i][diag_idx - i];
or |= self.M[i][diag_idx - i];
}
if sum != or {
continue 'outer;
}
}
} else {
#[cfg(feature = "odd-primes")]
{
self.diagonal.clear();
for i in i_min..i_max {
self.diagonal.push(self.M[i][diag_idx - i]);
sum += self.M[i][diag_idx - i];
}
coef *= PPartEntry::multinomial_odd(self.prime(), &mut self.diagonal);
coef %= p;
if coef == 0 {
continue 'outer;
}
}
}
self.ans.p_part.push(sum);
}
// If new_p ends with 0, drop them
while let Some(0) = self.ans.p_part.last() {
self.ans.p_part.pop();
}
return Some(coef as u32);
} else {
return None;
}
}
}
}
impl MilnorAlgebra {
fn decompose_basis_element_qpart(
&self,
degree: i32,
idx: usize,
) -> Vec<(u32, (i32, usize), (i32, usize))> {
let basis = &self.basis_table[degree as usize][idx];
// Look for left-most non-zero qpart
let i = basis.q_part.trailing_zeros();
// If the basis element is just Q_{k+1}, we decompose Q_{k+1} = P(p^k) Q_k - Q_k P(p^k).
if basis.q_part == 1 << i && basis.p_part.is_empty() {
let ppow = fp::prime::integer_power(*self.prime(), i - 1);
let q_degree = (2 * ppow - 1) as i32;
let p_degree = (ppow * (2 * (*self.prime()) - 2)) as i32;
let p_idx = self
.basis_element_to_index(&MilnorBasisElement::from_p(
vec![ppow as PPartEntry],
p_degree,
))
.to_owned();
let q_idx = self
.basis_element_to_index(&MilnorBasisElement {
q_part: 1 << (i - 1),
p_part: Vec::new(),
degree: q_degree,
})
.to_owned();
return vec![
(1, (p_degree, p_idx), (q_degree, q_idx)),
(*self.prime() - 1, (q_degree, q_idx), (p_degree, p_idx)),
];
}
// Otherwise, separate out the first Q_k.
let first_degree = combinatorics::tau_degrees(self.prime())[i as usize];
let second_degree = degree - first_degree;
let first_idx = self.basis_element_to_index(&MilnorBasisElement {
q_part: 1 << i,
p_part: Vec::new(),
degree: first_degree,
});
let second_idx = self.basis_element_to_index(&MilnorBasisElement {
q_part: basis.q_part ^ 1 << i,
p_part: basis.p_part.clone(),
degree: second_degree,
});
vec![(1, (first_degree, first_idx), (second_degree, second_idx))]
}
// use https://monks.scranton.edu/files/pubs/bases.pdf page 8
#[allow(clippy::useless_let_if_seq)]
fn decompose_basis_element_ppart(
&self,
degree: i32,
idx: usize,
) -> Vec<(u32, (i32, usize), (i32, usize))> {
let p = self.prime();
let pp = *self.prime() as PPartEntry;
let b = &self.basis_table[degree as usize][idx];
let first;
let second;
if b.p_part.len() > 1 {
let mut t1 = 0;
let mut pow = 1;
for r in &b.p_part {
t1 += r * pow;
pow *= pp;
}
first = self.beps_pn(0, t1);
let second_degree = degree - first.0;
let second_idx = self.basis_element_to_index(&MilnorBasisElement {
q_part: 0,
p_part: b.p_part[1..].to_vec(),
degree: second_degree,
});
second = (second_degree, second_idx);
} else {
// return vec![(1, (degree, idx), (0, 0))];
let sq = b.p_part[0];
let mut pow = 1;
{
let mut temp_sq = sq;
while temp_sq % pp == 0 {
temp_sq /= pp;
pow *= pp;
}
}
if sq == pow {
return vec![(1, (degree, idx), (0, 0))];
}
first = self.beps_pn(0, pow);
second = self.beps_pn(0, sq - pow);
}
let mut out_vec = FpVector::new(p, self.dimension(degree, -1));
self.multiply_basis_elements(
out_vec.as_slice_mut(),
1,
first.0,
first.1,
second.0,
second.1,
-1,
);
let mut result = Vec::new();
let c = out_vec.entry(idx);
assert!(c != 0);
out_vec.set_entry(idx, 0);
let c_inv = fp::prime::inverse(p, *p - c);
result.push((((*p - 1) * c_inv) % *p, first, second));
for (i, v) in out_vec.iter_nonzero() {
for (c, t1, t2) in self.decompose_basis_element_ppart(degree, i) {
result.push(((c_inv * c * v) % *p, t1, t2));
}
}
result
}
}
#[cfg(test)]
mod tests {
use super::*;
use expect_test::expect;
use rstest::rstest;
#[rstest(p, max_degree, case(2, 32), case(3, 106))]
#[trace]
fn test_milnor_basis(p: u32, max_degree: i32) {
let p = ValidPrime::new(p);
let algebra = MilnorAlgebra::new(p); //p != 2
algebra.compute_basis(max_degree);
for i in 1..max_degree {
let dim = algebra.dimension(i, -1);
for j in 0..dim {
let b = algebra.basis_element_from_index(i, j);
assert_eq!(algebra.basis_element_to_index(b), j);
let json = algebra.json_from_basis(i, j);
let new_b = algebra.json_to_basis(&json).unwrap();
assert_eq!(new_b, (i, j));
}
}
}
#[rstest(p, max_degree, case(2, 32), case(3, 106))]
#[trace]
fn test_milnor_decompose(p: u32, max_degree: i32) {
let p = ValidPrime::new(p);
let algebra = MilnorAlgebra::new(p);
algebra.compute_basis(max_degree);
for i in 1..max_degree {
let dim = algebra.dimension(i, -1);
let gens = algebra.generators(i);
// println!("i : {}, gens : {:?}", i, gens);
let mut out_vec = FpVector::new(p, dim);
for j in 0..dim {
if gens.contains(&j) {
continue;
}
for (coeff, (first_degree, first_idx), (second_degree, second_idx)) in
algebra.decompose_basis_element(i, j)
{
// print!("{} * {} * {} + ", coeff, algebra.basis_element_to_string(first_degree,first_idx), algebra.basis_element_to_string(second_degree, second_idx));
algebra.multiply_basis_elements(
out_vec.as_slice_mut(),
coeff,
first_degree,
first_idx,
second_degree,
second_idx,
-1,
);
}
assert!(
out_vec.entry(j) == 1,
"{} != {}",
algebra.basis_element_to_string(i, j),
algebra.element_to_string(i, out_vec.as_slice())
);
out_vec.set_entry(j, 0);
assert!(
out_vec.is_zero(),
"\n{} != {}",
algebra.basis_element_to_string(i, j),
algebra.element_to_string(i, out_vec.as_slice())
);
}
}
}
use crate::module::ModuleFailedRelationError;
#[rstest(p, max_degree, case(2, 32), case(3, 106))]
#[trace]
fn test_adem_relations(p: u32, max_degree: i32) {
let p = ValidPrime::new(p);
let algebra = MilnorAlgebra::new(p); // , p != 2
algebra.compute_basis(max_degree + 2);
let mut output_vec = FpVector::new(p, 0);
for i in 1..max_degree {
let output_dim = algebra.dimension(i, -1);
output_vec.set_scratch_vector_size(output_dim);
let relations = algebra.generating_relations(i);
println!("{:?}", relations);
for relation in relations {
for (coeff, (deg_1, idx_1), (deg_2, idx_2)) in &relation {
algebra.multiply_basis_elements(
output_vec.as_slice_mut(),
*coeff,
*deg_1,
*idx_1,
*deg_2,
*idx_2,
-1,
);
}
if !output_vec.is_zero() {
let mut relation_string = String::new();
for (coeff, (deg_1, idx_1), (deg_2, idx_2)) in &relation {
relation_string.push_str(&format!(
"{} * {} * {} + ",
*coeff,
&algebra.basis_element_to_string(*deg_1, *idx_1),
&algebra.basis_element_to_string(*deg_2, *idx_2)
));
}
relation_string.pop();
relation_string.pop();
relation_string.pop();
relation_string.pop();
relation_string.pop();
let value_string = algebra.element_to_string(i as i32, output_vec.as_slice());
panic!(
"{}",
ModuleFailedRelationError {
relation: relation_string,
value: value_string
}
);
}
}
}
}
#[test]
fn test_clone_into() {
let mut other = MilnorBasisElement::default();
let mut check = |a: &MilnorBasisElement| {
a.clone_into(&mut other);
assert_eq!(a, &other);
};
check(&MilnorBasisElement {
q_part: 3,
p_part: vec![3, 2],
degree: 12,
});
check(&MilnorBasisElement {
q_part: 1,
p_part: vec![3],
degree: 11,
});
check(&MilnorBasisElement {
q_part: 5,
p_part: vec![1, 3, 5, 2],
degree: 7,
});
check(&MilnorBasisElement {
q_part: 0,
p_part: vec![],
degree: 2,
});
}
#[test]
fn test_ppart_multiplier_2() {
let r = vec![1, 4];
let s = vec![2, 4];
let mut m = PPartMultiplier::<false>::new_from_allocation(
ValidPrime::new(2),
&r,
&s,
PPartAllocation::default(),
0,
0,
);
expect![[r#"
[0, 2, 4]
[1, 0, 0]
[4, 0, 0]
"#]]
.assert_eq(&m.M.to_string());
assert_eq!(m.next(), Some(1));
expect![[r#"
[0, 0, 4]
[1, 0, 0]
[0, 2, 0]
"#]]
.assert_eq(&m.M.to_string());
assert_eq!(m.next(), Some(1));
expect![[r#"
[0, 2, 3]
[1, 0, 0]
[0, 0, 1]
"#]]
.assert_eq(&m.M.to_string());
assert_eq!(m.next(), None);
}
#[test]
fn test_ppart_multiplier_3() {
let r = vec![3, 4];
let s = vec![1, 4];
let mut m = PPartMultiplier::<false>::new_from_allocation(
ValidPrime::new(3),
&r,
&s,
PPartAllocation::default(),
0,
0,
);
expect![[r#"
[0, 1, 4]
[3, 0, 0]
[4, 0, 0]
"#]]
.assert_eq(&m.M.to_string());
assert_eq!(m.next(), Some(1));
expect![[r#"
[0, 1, 4]
[3, 0, 0]
[4, 0, 0]
"#]]
.assert_eq(&m.M.to_string());
assert_eq!(m.next(), Some(2));
expect![[r#"
[0, 0, 4]
[3, 0, 0]
[1, 1, 0]
"#]]
.assert_eq(&m.M.to_string());
assert_eq!(m.next(), None);
}
}
impl MilnorAlgebra {
/// Returns `true` if the new element is not within the bounds
fn increment_p_part(element: &mut PPart, max: &[PPartEntry]) -> bool {
element[0] += 1;
for i in 0..element.len() - 1 {
if element[i] > max[i] {
element[i] = 0;
element[i + 1] += 1;
}
}
element.last().unwrap() > max.last().unwrap()
}
}
impl Bialgebra for MilnorAlgebra {
fn coproduct(&self, op_deg: i32, op_idx: usize) -> Vec<(i32, usize, i32, usize)> {
assert_eq!(*self.prime(), 2, "Coproduct at odd primes not supported");
if op_deg == 0 {
return vec![(0, 0, 0, 0)];
}
let xi_degrees = combinatorics::xi_degrees(self.prime());
let mut len = 1;
let p_part = &self.basis_element_from_index(op_deg, op_idx).p_part;
for i in p_part.iter() {
len *= i + 1;
}
let len = len as usize;
let mut result = Vec::with_capacity(len);
let mut cur_ppart: PPart = vec![0; p_part.len()];
loop {
let mut left_degree: i32 = 0;
for i in 0..cur_ppart.len() {
left_degree += cur_ppart[i] as i32 * xi_degrees[i];
}
let right_degree: i32 = op_deg - left_degree;
let mut left_ppart = cur_ppart.clone();
while let Some(0) = left_ppart.last() {
left_ppart.pop();
}
let mut right_ppart = cur_ppart
.iter()
.enumerate()
.map(|(i, v)| p_part[i] - *v)
.collect::<Vec<_>>();
while let Some(0) = right_ppart.last() {
right_ppart.pop();
}
let left_idx = self.basis_element_to_index(&MilnorBasisElement {
degree: left_degree,
q_part: 0,
p_part: left_ppart,
});
let right_idx = self.basis_element_to_index(&MilnorBasisElement {
degree: right_degree,
q_part: 0,
p_part: right_ppart,
});
result.push((left_degree, left_idx, right_degree, right_idx));
if Self::increment_p_part(&mut cur_ppart, p_part) {
break;
}
}
result
}
fn decompose(&self, op_deg: i32, op_idx: usize) -> Vec<(i32, usize)> {
vec![(op_deg, op_idx)]
}
}
| true |
b6147cb10867dc460fb653c1e58cee57e083e106
|
Rust
|
themasch/aoc-2020
|
/src/day04.rs
|
UTF-8
| 6,584 | 2.921875 | 3 |
[] |
no_license
|
use crate::*;
use std::io::BufRead;
#[derive(Debug)]
pub struct Input(Vec<Passport>);
#[derive(Debug)]
pub struct Passport {
byr: String,
iyr: String,
eyr: String,
hgt: String,
hcl: String,
ecl: String,
pid: String,
cid: Option<String>,
}
use std::collections::hash_map::RandomState;
use std::collections::HashMap;
use std::iter::FromIterator;
impl Passport {
fn try_create_from(input: Vec<(&str, &str)>) -> Option<Passport> {
let map: HashMap<&str, &str, RandomState> = HashMap::from_iter(input);
Some(Passport {
byr: map.get("byr").map(|&x| String::from(x))?,
iyr: map.get("iyr").map(|&x| String::from(x))?,
eyr: map.get("eyr").map(|&x| String::from(x))?,
hgt: map.get("hgt").map(|&x| String::from(x))?,
hcl: map.get("hcl").map(|&x| String::from(x))?,
ecl: map.get("ecl").map(|&x| String::from(x))?,
pid: map.get("pid").map(|&x| String::from(x))?,
cid: map.get("cid").map(|&x| String::from(x)),
})
}
}
impl<R: BufRead> ReadInput<R> for Input {
fn read(mut b: R) -> Result<Input, ()> {
let mut content = String::new();
b.read_to_string(&mut content).unwrap();
let vec = content
.replace("\r\n", "\n")
.split("\n\n")
.filter_map(|input| read_passport(input))
.collect();
Ok(Input(vec))
}
}
fn read_passport(input: &str) -> Option<Passport> {
let kv_pairs = input
.split_whitespace()
.filter_map(|pair| {
if pair.contains(':') {
let key_value: Vec<&str> = pair.split(':').collect();
Some((key_value[0], key_value[1]))
} else {
None
}
})
.collect();
Passport::try_create_from(kv_pairs)
}
pub struct FirstStep;
impl Solution for FirstStep {
type Input = Input;
type Output = usize;
fn solve(i: Input) -> Result<usize, ()> {
Ok(i.0.len())
}
}
enum HeightUnit {
Centimeter,
Inch,
}
struct Height {
amount: usize,
unit: HeightUnit,
}
impl Height {
fn as_cm(&self) -> f32 {
match self.unit {
HeightUnit::Centimeter => self.amount as f32,
HeightUnit::Inch => self.amount as f32 * 2.54,
}
}
}
use std::str::FromStr;
impl FromStr for Height {
type Err = ();
fn from_str(input: &str) -> Result<Height, ()> {
if input.ends_with("in") {
Ok(Height {
amount: input[0..input.len() - 2].parse().map_err(|_| ())?,
unit: HeightUnit::Inch,
})
} else if input.ends_with("cm") {
Ok(Height {
amount: input[0..input.len() - 2].parse().map_err(|_| ())?,
unit: HeightUnit::Centimeter,
})
} else {
Err(())
}
}
}
pub struct SecondStep;
impl Solution for SecondStep {
type Input = Input;
type Output = usize;
fn solve(i: Input) -> Result<usize, ()> {
let output =
i.0.iter()
.filter(|pp| {
pp.byr
.parse::<u16>()
.ok()
.map(|value| value >= 1920 && value <= 2002)
.unwrap_or(false)
})
.filter(|pp| {
pp.iyr
.parse::<u16>()
.ok()
.map(|value| value >= 2010 && value <= 2020)
.unwrap_or(false)
})
.filter(|pp| {
pp.eyr
.parse::<u16>()
.ok()
.map(|value| value >= 2020 && value <= 2030)
.unwrap_or(false)
})
.filter(|pp| {
pp.hgt
.parse::<Height>()
.ok()
.map(|value| value.as_cm() >= 150.0 && value.as_cm() <= 193.0)
.unwrap_or(false)
})
.filter(|pp| {
pp.hcl.as_str().starts_with('#')
&& pp.hcl[1..]
.chars()
.find(|&c| (c < '0' || c > '9') && (c < 'a' || c > 'f'))
.is_none()
})
.filter(|pp| {
let allowed_colors = vec!["amb", "blu", "brn", "gry", "grn", "hzl", "oth"];
allowed_colors.contains(&pp.ecl.as_str())
})
.filter(|pp| {
pp.pid.len() == 9 && pp.pid.chars().find(|&c| c < '0' || c > '9').is_none()
})
.count();
Ok(output)
}
}
#[cfg(test)]
mod test {
use super::*;
use std::io::BufReader;
static INPUT: &str = r#"ecl:gry pid:860033327 eyr:2020 hcl:#fffffd
byr:1937 iyr:2017 cid:147 hgt:183cm
iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884
hcl:#cfa07d byr:1929
hcl:#ae17e1 iyr:2013
eyr:2024
ecl:brn pid:760753108 byr:1931
hgt:179cm
hcl:#cfa07d eyr:2025 pid:166559648
iyr:2011 ecl:brn hgt:59in"#;
#[test]
fn test_read_passports() {
Input::read(BufReader::new(INPUT.as_bytes())).unwrap();
}
#[test]
fn test_step_1() {
let read = Input::read(BufReader::new(INPUT.as_bytes())).unwrap();
assert_eq!(Ok(2), FirstStep::solve(read));
}
#[test]
fn test_step_2_all_invalid() {
let local_input = r#"eyr:1972 cid:100
hcl:#18171d ecl:amb hgt:170 pid:186cm iyr:2018 byr:1926
iyr:2019
hcl:#602927 eyr:1967 hgt:170cm
ecl:grn pid:012533040 byr:1946
hcl:dab227 iyr:2012
ecl:brn hgt:182cm pid:021572410 eyr:2020 byr:1992 cid:277
hgt:59cm ecl:zzz
eyr:2038 hcl:74454a iyr:2023
pid:3556412378 byr:2007"#;
let read = Input::read(BufReader::new(local_input.as_bytes())).unwrap();
assert_eq!(Ok(0), SecondStep::solve(read));
}
#[test]
fn test_step_2_all_valid() {
let local_input = r#"pid:087499704 hgt:74in ecl:grn iyr:2012 eyr:2030 byr:1980
hcl:#623a2f
eyr:2029 ecl:blu cid:129 byr:1989
iyr:2014 pid:896056539 hcl:#a97842 hgt:165cm
hcl:#888785
hgt:164cm byr:2001 iyr:2015 cid:88
pid:545766238 ecl:hzl
eyr:2022
iyr:2010 hgt:158cm hcl:#b6652a ecl:blu byr:1944 eyr:2021 pid:093154719"#;
let read = Input::read(BufReader::new(local_input.as_bytes())).unwrap();
assert_eq!(Ok(4), SecondStep::solve(read));
}
}
| true |
cb56b3488a91cca856e978bc8913ae0651626968
|
Rust
|
ichn-hu/xterm-js-sys
|
/src/crossterm_support/mod.rs
|
UTF-8
| 3,809 | 3.5 | 4 |
[
"MIT"
] |
permissive
|
//! Supporting types for a xterm.js-backed backend for [crossterm].
//!
//! [crossterm]: docs.rs/crossterm
use super::xterm::Terminal;
use std::cell::Cell;
use std::fmt::{self, Debug};
use std::io::{Error as IoError, ErrorKind, Result as IoResult, Write};
use std::ops::Deref;
/// Wrapper for the [xterm.js terminal](Terminal) for use with [crossterm].
///
/// [crossterm]: docs.rs/crossterm
pub struct XtermJsCrosstermBackend<'a> {
/// The xterm.js terminal that this struct instance wraps.
pub terminal: &'a Terminal,
/// Internal buffer for data to write to the terminal.
///
/// This lets us make one big call to [`Terminal::write`] with a batch of
/// commands rather than many small calls.
buffer: Cell<Vec<u8>>,
}
impl<'a> Debug for XtermJsCrosstermBackend<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct(core::any::type_name::<Self>())
.field("terminal", &self.terminal)
.finish()
}
}
impl<'a> Deref for XtermJsCrosstermBackend<'a> {
type Target = Terminal;
fn deref(&self) -> &Terminal {
//! This will flush the internal buffer before providing the reference
//! to make sure that the order of operations is preserved.
self.flush_immutable().unwrap();
self.terminal
}
}
impl<'a> Drop for XtermJsCrosstermBackend<'a> {
fn drop(&mut self) {
self.flush().unwrap()
}
}
impl<'a> XtermJsCrosstermBackend<'a> {
/// Constructor for the wrapper type.
#[must_use]
pub fn new(terminal: &'a Terminal) -> Self {
Self::new_with_capacity(terminal, 0)
}
/// Like [`new`](XtermJsCrosstermBackend::new) except it also takes an
/// estimate for the size of the internal buffer.
///
/// This is useful if you have a good guess about how many bytes the
/// commands you're going to send will need.
#[must_use]
pub fn new_with_capacity(terminal: &'a Terminal, capacity: usize) -> Self {
Self {
terminal,
buffer: Cell::new(Vec::with_capacity(capacity)),
}
}
/// Writes a `String` directly to the underlying terminal, bypassing the
/// buffer.
///
/// This is useful for situations in which the commands being sent are
/// already buffered and the extra copy is undesired. Note that this will
/// flush the buffer first to preserve the order of commands.
///
/// # Errors
///
/// This should never actually error. For consistency with the [`Write`]
/// calls it results an [`io::Result`]
///
/// [`Write`]: std::io::Write
/// [`io::Result`]: std::io::Result
pub fn write_immediately(&mut self, commands: String) -> IoResult<()> {
self.flush()?;
self.terminal.write(commands);
Ok(())
}
/// A version of [`flush`](Write::flush) that takes an immutable reference
/// instead of a mutable one.
///
/// This exists because we want to flush the buffer in the [`Deref`] impl.
#[inline]
fn flush_immutable(&self) -> IoResult<()> {
// Can't call `self.buffer.flush()` here but since that's just a Vec,
// it's probably fine.
let s = String::from_utf8(self.buffer.replace(Vec::new()))
.map_err(|e| IoError::new(ErrorKind::Other, e))?;
self.terminal.write(s);
Ok(())
}
}
impl<'a> Write for XtermJsCrosstermBackend<'a> {
fn write(&mut self, buf: &[u8]) -> IoResult<usize> {
self.buffer.get_mut().write(buf)
}
fn flush(&mut self) -> IoResult<()> {
self.buffer.get_mut().flush()?;
self.flush_immutable()
}
}
impl<'a> From<&'a Terminal> for XtermJsCrosstermBackend<'a> {
fn from(terminal: &'a Terminal) -> Self {
Self::new(terminal)
}
}
| true |
a2c56d13d8ff5fdbd6b70c77544f6b05703fbc2b
|
Rust
|
dylanmckay/hmdee
|
/psvr/src/protocol.rs
|
UTF-8
| 1,362 | 3.703125 | 4 |
[
"MIT"
] |
permissive
|
//! The low-level protocol types.
/// The size of the command header.
pub const COMMAND_HEADER_SIZE: usize = 4;
/// The header for a command message.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct CommandHeader {
pub id: u8,
pub status: u8,
pub magic: u8,
pub length: u8,
}
#[derive(Clone)]
pub struct Command {
pub header: CommandHeader,
pub payload: Vec<u8>,
}
impl CommandHeader {
pub fn raw_bytes(&self) -> Vec<u8> {
vec![self.id, self.status, self.magic, self.length]
}
}
impl Command {
pub fn raw_bytes(&self) -> Vec<u8> {
let mut raw_bytes = Vec::new();
raw_bytes.extend(self.header.raw_bytes());
raw_bytes.extend(self.payload.iter());
raw_bytes
}
}
#[cfg(test)]
mod test {
use super::*;
use std::mem::size_of;
#[test]
fn command_header_size_matches_constant() {
assert_eq!(size_of::<CommandHeader>(), COMMAND_HEADER_SIZE);
}
#[test]
fn command_raw_bytes_is_correct() {
let command = Command {
header: CommandHeader {
id: 0x69,
status: 123,
magic: 88,
length: 5,
},
payload: vec![5,4,3,2,1],
};
assert_eq!(&[0x69, 123, 88, 5, 5, 4, 3, 2, 1], &command.raw_bytes()[..]);
}
}
| true |
f04624a81b914719792d4f95ba92714b40d6159b
|
Rust
|
TheLostLambda/zellij
|
/default-plugins/status-bar/src/first_line.rs
|
UTF-8
| 13,458 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
use ansi_term::ANSIStrings;
use zellij_tile::prelude::*;
use crate::color_elements;
use crate::{ColoredElements, LinePart};
struct CtrlKeyShortcut {
mode: CtrlKeyMode,
action: CtrlKeyAction,
}
impl CtrlKeyShortcut {
pub fn new(mode: CtrlKeyMode, action: CtrlKeyAction) -> Self {
CtrlKeyShortcut { mode, action }
}
}
enum CtrlKeyAction {
Lock,
Pane,
Tab,
Resize,
Scroll,
Quit,
Session,
}
enum CtrlKeyMode {
Unselected,
Selected,
Disabled,
}
impl CtrlKeyShortcut {
pub fn full_text(&self) -> String {
match self.action {
CtrlKeyAction::Lock => String::from("LOCK"),
CtrlKeyAction::Pane => String::from("PANE"),
CtrlKeyAction::Tab => String::from("TAB"),
CtrlKeyAction::Resize => String::from("RESIZE"),
CtrlKeyAction::Scroll => String::from("SCROLL"),
CtrlKeyAction::Quit => String::from("QUIT"),
CtrlKeyAction::Session => String::from("SESSION"),
}
}
pub fn letter_shortcut(&self) -> char {
match self.action {
CtrlKeyAction::Lock => 'g',
CtrlKeyAction::Pane => 'p',
CtrlKeyAction::Tab => 't',
CtrlKeyAction::Resize => 'r',
CtrlKeyAction::Scroll => 's',
CtrlKeyAction::Quit => 'q',
CtrlKeyAction::Session => 'o',
}
}
}
fn unselected_mode_shortcut(
letter: char,
text: &str,
palette: ColoredElements,
separator: &str,
) -> LinePart {
let prefix_separator = palette.unselected_prefix_separator.paint(separator);
let char_left_separator = palette.unselected_char_left_separator.paint(" <");
let char_shortcut = palette.unselected_char_shortcut.paint(letter.to_string());
let char_right_separator = palette.unselected_char_right_separator.paint(">");
let styled_text = palette.unselected_styled_text.paint(format!("{} ", text));
let suffix_separator = palette.unselected_suffix_separator.paint(separator);
LinePart {
part: ANSIStrings(&[
prefix_separator,
char_left_separator,
char_shortcut,
char_right_separator,
styled_text,
suffix_separator,
])
.to_string(),
len: text.chars().count() + 7, // 2 for the arrows, 3 for the char separators, 1 for the character, 1 for the text padding
}
}
fn selected_mode_shortcut(
letter: char,
text: &str,
palette: ColoredElements,
separator: &str,
) -> LinePart {
let prefix_separator = palette.selected_prefix_separator.paint(separator);
let char_left_separator = palette.selected_char_left_separator.paint(" <".to_string());
let char_shortcut = palette.selected_char_shortcut.paint(format!("{}", letter));
let char_right_separator = palette.selected_char_right_separator.paint(">".to_string());
let styled_text = palette.selected_styled_text.paint(format!("{} ", text));
let suffix_separator = palette.selected_suffix_separator.paint(separator);
LinePart {
part: ANSIStrings(&[
prefix_separator,
char_left_separator,
char_shortcut,
char_right_separator,
styled_text,
suffix_separator,
])
.to_string(),
len: text.chars().count() + 7, // 2 for the arrows, 3 for the char separators, 1 for the character, 1 for the text padding
}
}
fn disabled_mode_shortcut(text: &str, palette: ColoredElements, separator: &str) -> LinePart {
let prefix_separator = palette.disabled_prefix_separator.paint(separator);
let styled_text = palette.disabled_styled_text.paint(format!("{} ", text));
let suffix_separator = palette.disabled_suffix_separator.paint(separator);
LinePart {
part: format!("{}{}{}", prefix_separator, styled_text, suffix_separator),
len: text.chars().count() + 2 + 1, // 2 for the arrows, 1 for the padding in the end
}
}
fn selected_mode_shortcut_single_letter(
letter: char,
palette: ColoredElements,
separator: &str,
) -> LinePart {
let char_shortcut_text = format!(" {} ", letter);
let len = char_shortcut_text.chars().count() + 4; // 2 for the arrows, 2 for the padding
let prefix_separator = palette
.selected_single_letter_prefix_separator
.paint(separator);
let char_shortcut = palette
.selected_single_letter_char_shortcut
.paint(char_shortcut_text);
let suffix_separator = palette
.selected_single_letter_suffix_separator
.paint(separator);
LinePart {
part: ANSIStrings(&[prefix_separator, char_shortcut, suffix_separator]).to_string(),
len,
}
}
fn unselected_mode_shortcut_single_letter(
letter: char,
palette: ColoredElements,
separator: &str,
) -> LinePart {
let char_shortcut_text = format!(" {} ", letter);
let len = char_shortcut_text.chars().count() + 4; // 2 for the arrows, 2 for the padding
let prefix_separator = palette
.unselected_single_letter_prefix_separator
.paint(separator);
let char_shortcut = palette
.unselected_single_letter_char_shortcut
.paint(char_shortcut_text);
let suffix_separator = palette
.unselected_single_letter_suffix_separator
.paint(separator);
LinePart {
part: ANSIStrings(&[prefix_separator, char_shortcut, suffix_separator]).to_string(),
len,
}
}
fn full_ctrl_key(key: &CtrlKeyShortcut, palette: ColoredElements, separator: &str) -> LinePart {
let full_text = key.full_text();
let letter_shortcut = key.letter_shortcut();
match key.mode {
CtrlKeyMode::Unselected => unselected_mode_shortcut(
letter_shortcut,
&format!(" {}", full_text),
palette,
separator,
),
CtrlKeyMode::Selected => selected_mode_shortcut(
letter_shortcut,
&format!(" {}", full_text),
palette,
separator,
),
CtrlKeyMode::Disabled => disabled_mode_shortcut(
&format!(" <{}> {}", letter_shortcut, full_text),
palette,
separator,
),
}
}
fn single_letter_ctrl_key(
key: &CtrlKeyShortcut,
palette: ColoredElements,
separator: &str,
) -> LinePart {
let letter_shortcut = key.letter_shortcut();
match key.mode {
CtrlKeyMode::Unselected => {
unselected_mode_shortcut_single_letter(letter_shortcut, palette, separator)
}
CtrlKeyMode::Selected => {
selected_mode_shortcut_single_letter(letter_shortcut, palette, separator)
}
CtrlKeyMode::Disabled => {
disabled_mode_shortcut(&format!(" {}", letter_shortcut), palette, separator)
}
}
}
fn key_indicators(
max_len: usize,
keys: &[CtrlKeyShortcut],
palette: ColoredElements,
separator: &str,
) -> LinePart {
let mut line_part = LinePart::default();
for ctrl_key in keys {
let key = full_ctrl_key(ctrl_key, palette, separator);
line_part.part = format!("{}{}", line_part.part, key.part);
line_part.len += key.len;
}
if line_part.len < max_len {
return line_part;
}
line_part = LinePart::default();
for ctrl_key in keys {
let key = single_letter_ctrl_key(ctrl_key, palette, separator);
line_part.part = format!("{}{}", line_part.part, key.part);
line_part.len += key.len;
}
if line_part.len < max_len {
return line_part;
}
line_part = LinePart::default();
line_part
}
pub fn superkey(palette: ColoredElements, separator: &str) -> LinePart {
let prefix_text = " Ctrl +";
let prefix = palette.superkey_prefix.paint(prefix_text);
let suffix_separator = palette.superkey_suffix_separator.paint(separator);
LinePart {
part: ANSIStrings(&[prefix, suffix_separator]).to_string(),
len: prefix_text.chars().count(),
}
}
pub fn ctrl_keys(help: &ModeInfo, max_len: usize, separator: &str) -> LinePart {
let colored_elements = color_elements(help.palette);
match &help.mode {
InputMode::Locked => key_indicators(
max_len,
&[
CtrlKeyShortcut::new(CtrlKeyMode::Selected, CtrlKeyAction::Lock),
CtrlKeyShortcut::new(CtrlKeyMode::Disabled, CtrlKeyAction::Pane),
CtrlKeyShortcut::new(CtrlKeyMode::Disabled, CtrlKeyAction::Tab),
CtrlKeyShortcut::new(CtrlKeyMode::Disabled, CtrlKeyAction::Resize),
CtrlKeyShortcut::new(CtrlKeyMode::Disabled, CtrlKeyAction::Scroll),
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Session),
CtrlKeyShortcut::new(CtrlKeyMode::Disabled, CtrlKeyAction::Quit),
],
colored_elements,
separator,
),
InputMode::Resize => key_indicators(
max_len,
&[
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Lock),
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Pane),
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Tab),
CtrlKeyShortcut::new(CtrlKeyMode::Selected, CtrlKeyAction::Resize),
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Scroll),
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Session),
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Quit),
],
colored_elements,
separator,
),
InputMode::Pane => key_indicators(
max_len,
&[
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Lock),
CtrlKeyShortcut::new(CtrlKeyMode::Selected, CtrlKeyAction::Pane),
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Tab),
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Resize),
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Scroll),
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Session),
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Quit),
],
colored_elements,
separator,
),
InputMode::Tab | InputMode::RenameTab => key_indicators(
max_len,
&[
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Lock),
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Pane),
CtrlKeyShortcut::new(CtrlKeyMode::Selected, CtrlKeyAction::Tab),
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Resize),
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Scroll),
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Session),
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Quit),
],
colored_elements,
separator,
),
InputMode::Scroll => key_indicators(
max_len,
&[
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Lock),
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Pane),
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Tab),
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Resize),
CtrlKeyShortcut::new(CtrlKeyMode::Selected, CtrlKeyAction::Scroll),
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Session),
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Quit),
],
colored_elements,
separator,
),
InputMode::Normal => key_indicators(
max_len,
&[
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Lock),
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Pane),
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Tab),
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Resize),
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Scroll),
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Session),
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Quit),
],
colored_elements,
separator,
),
InputMode::Session => key_indicators(
max_len,
&[
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Lock),
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Pane),
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Tab),
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Resize),
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Scroll),
CtrlKeyShortcut::new(CtrlKeyMode::Selected, CtrlKeyAction::Session),
CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Quit),
],
colored_elements,
separator,
),
}
}
| true |
928003e694a01a32d47942cab9214b70b76f3cf3
|
Rust
|
rendaardy/optopodi
|
/src/util.rs
|
UTF-8
| 158 | 2.734375 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
pub fn percentage(numerator: u64, denominator: u64) -> u64 {
if denominator != 0 {
(numerator * 100) / denominator
} else {
0
}
}
| true |
9d001311482b528717de70cef0fd3e4afe0d4823
|
Rust
|
Mackirac/image_processing
|
/src/bit_manipulation/steganography.rs
|
UTF-8
| 2,962 | 3.25 | 3 |
[] |
no_license
|
use crate::{ ImageBuffer, Pixel };
use super::{ to_bin, to_dec, Bits };
#[derive(Debug)]
pub struct Cipher {
bits: usize,
filter: [bool; 8]
}
impl Cipher {
pub fn new (pattern: String) -> Result<Cipher, String> {
if pattern.len() != 8 { return Err("Invalid cipher pattern length".to_string()) }
let mut bits = 0;
let mut filter = [false; 8];
let mut pattern = pattern.chars();
for i in 0..8 {
let c = pattern.next_back();
if c == Some('1') {
bits += 1;
filter[i] = true
}
else if c != Some('0') { return Err("Invalid cipher pattern".to_string()) }
}
if bits == 0 { return Err("Empty cipher pattern".to_string()) }
Ok(Cipher { bits, filter })
}
fn hide_character <'a, P: Pixel<Subpixel=u8> + 'static>
(&self, character: u8, bits: &mut Bits<'a, P>)
{
for bit in to_bin(character).iter() {
loop {
match bits.next() {
None => return, // NO MORE BITS AVAILABLE ON THE IMAGE
Some(b) => {
if self.filter[b.px_bit] {
bits.set_current_bit(*bit);
break;
}
}
}
}
}
bits.set_current_byte();
}
pub fn hide <P: Pixel<Subpixel=u8> + 'static>
(&self, message: String, image: &mut ImageBuffer<P, Vec<u8>>)
-> Result<(), String>
{
let message = message.into_bytes();
if message.len() * 8 > image.len() * self.bits {
return Err("Image length insufficient for this message".to_string());
}
let mut bits = Bits::new(image);
for character in &message {
self.hide_character(*character, &mut bits);
}
self.hide_character(3, &mut bits);
Ok(())
}
fn seek_character <P: Pixel<Subpixel=u8> + 'static>
(&self, bits: &mut Bits<P>)
-> u8
{
let mut character = [false; 8];
let mut c_bit = 0;
while c_bit < 8 {
match bits.next() {
None => return 3,
Some(b) => {
if self.filter[b.px_bit] {
character[c_bit] = b.value;
c_bit += 1;
}
}
}
}
to_dec(character)
}
pub fn seek <P: Pixel<Subpixel=u8> + 'static>
(&self, image: &mut ImageBuffer<P, Vec<u8>>)
-> Result<String, String>
{
let mut buffer = Vec::new();
let mut bits = Bits::new(image);
loop {
match self.seek_character(&mut bits) {
3 => break,
c => buffer.push(c)
}
}
String::from_utf8(buffer).or(Err("No valid message found".to_string()))
}
}
| true |
5b63be5b385ff05ec6ce47f6b80aa53264604636
|
Rust
|
lnicola/fasteval
|
/tests/eval.rs
|
UTF-8
| 13,837 | 2.796875 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
use fasteval::{Evaler, Error, Slab, Cached, EmptyNamespace, CachedCallbackNamespace, Parser};
use fasteval::bool_to_f64;
use std::mem;
use std::collections::{BTreeMap, BTreeSet};
#[test]
fn eval() {
let mut slab = Slab::new();
let mut ns = BTreeMap::<String,f64>::new();
ns.insert("x".to_string(), 1.0);
ns.insert("y".to_string(), 2.0);
ns.insert("z".to_string(), 3.0);
// Sanity check:
assert_eq!(Parser::new().parse("3+3-3/3", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns).unwrap(), 5.0);
assert_eq!(Parser::new().parse("x+y+z", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns).unwrap(), 6.0);
assert_eq!(Parser::new().parse("x+y+z+a", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns), Err(Error::Undefined("a".to_string())));
}
#[test]
fn aaa_util() {
assert_eq!(bool_to_f64!(true), 1.0);
assert_eq!(bool_to_f64!(false), 0.0);
}
#[test]
fn aaa_aaa_sizes() {
eprintln!("sizeof(Slab):{}", mem::size_of::<Slab>());
assert!(mem::size_of::<Slab>()<2usize.pow(18)); // 256kB
}
#[test]
fn aaa_aab_single() {
let mut slab = Slab::new();
let mut ns = EmptyNamespace;
assert_eq!(Parser::new().parse("123.456", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns).unwrap(), 123.456f64);
}
#[test]
fn aaa_basics() {
let mut slab = Slab::new();
assert_eq!(
Parser::new().parse("12.34 + 43.21 + 11.11", &mut slab.ps).unwrap().from(&slab.ps).var_names(&slab),
BTreeSet::new());
let mut ns = EmptyNamespace;
assert_eq!(
Parser::new().parse("12.34 + 43.21 + 11.11", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(66.66));
assert_eq!(
Parser::new().parse("12.34 + 43.21 - 11.11", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(44.44));
assert_eq!(
Parser::new().parse("11.11 * 3", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(33.33));
assert_eq!(
Parser::new().parse("33.33 / 3", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(11.11));
assert_eq!(
Parser::new().parse("33.33 % 3", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(0.3299999999999983));
assert_eq!(
Parser::new().parse("1 and 2", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(2.0));
assert_eq!(
Parser::new().parse("1 && 2", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(2.0));
assert_eq!(
Parser::new().parse("2 or 0", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(2.0));
assert_eq!(
Parser::new().parse("2 || 0", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(2.0));
assert_eq!(
Parser::new().parse("1 > 0", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(1.0));
assert_eq!(
Parser::new().parse("1 < 0", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(0.0));
assert_eq!(
Parser::new().parse("+5.5", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(5.5));
assert_eq!(
Parser::new().parse("-5.5", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(-5.5));
assert_eq!(
Parser::new().parse("!5.5", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(0.0));
assert_eq!(
Parser::new().parse("!0", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(1.0));
assert_eq!(
Parser::new().parse("(3 * 3 + 3 / 3)", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(10.0));
assert_eq!(
Parser::new().parse("(3 * (3 + 3) / 3)", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(6.0));
assert_eq!(
Parser::new().parse("4.4 + -5.5", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(-1.0999999999999996));
assert_eq!(
Parser::new().parse("4.4 + +5.5", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(9.9));
assert_eq!(
Parser::new().parse("x + 1", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Err(Error::Undefined("x".to_string())));
let mut ns = CachedCallbackNamespace::new(|_,_| Some(3.0));
assert_eq!(
Parser::new().parse("x + 1", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(4.0));
assert_eq!(
Parser::new().parse("1.2 + int(3.4)", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(4.2));
assert_eq!(
Parser::new().parse("1.2 + ceil(3.4)", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(5.2));
assert_eq!(
Parser::new().parse("1.2 + floor(3.4)", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(4.2));
assert_eq!(
Parser::new().parse("1.2 + abs(-3.4)", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(4.6));
assert_eq!(
Parser::new().parse("1.2 + log(1)", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(1.2));
assert_eq!(
Parser::new().parse("1.2 + log(10)", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(2.2));
assert_eq!(
Parser::new().parse("1.2 + log(0)", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(std::f64::NEG_INFINITY));
assert!(Parser::new().parse("1.2 + log(-1)", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns).unwrap().is_nan());
assert_eq!(
Parser::new().parse("1.2 + round(3.4)", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(4.2));
assert_eq!(
Parser::new().parse("1.2 + round(0.5, 3.4)", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(4.7));
assert_eq!(
Parser::new().parse("1.2 + round(-3.4)", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(-1.8));
assert_eq!(
Parser::new().parse("1.2 + round(0.5, -3.4)", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(-2.3));
assert_eq!(
Parser::new().parse("1.2 + min(1,2,0,3.3,-1)", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(0.19999999999999996));
assert_eq!(
Parser::new().parse("1.2 + min(1)", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(2.2));
assert_eq!(
Parser::new().parse("1.2 + max(1,2,0,3.3,-1)", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(4.5));
assert_eq!(
Parser::new().parse("1.2 + max(1)", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(2.2));
assert_eq!(
Parser::new().parse(r#"12.34 + print ( 43.21, "yay" ) + 11.11"#, &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(66.66));
assert_eq!(
Parser::new().parse("e()", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(2.718281828459045));
assert_eq!(
Parser::new().parse("pi()", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(3.141592653589793));
assert_eq!(
Parser::new().parse("sin(pi()/2)", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(1.0));
assert_eq!(
Parser::new().parse("cos(pi()/2)", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(0.00000000000000006123233995736766));
assert_eq!(
Parser::new().parse("tan(pi()/4)", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(0.9999999999999999));
assert_eq!(
Parser::new().parse("asin(1)", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(1.5707963267948966));
assert_eq!(
Parser::new().parse("acos(0)", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(1.5707963267948966));
assert_eq!(
Parser::new().parse("atan(1)", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(0.7853981633974483));
assert_eq!(
Parser::new().parse("sinh(pi()/2)", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(2.3012989023072947));
assert_eq!(
Parser::new().parse("cosh(pi()/2)", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(2.5091784786580567));
assert_eq!(
Parser::new().parse("tanh(pi()/4)", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(0.6557942026326724));
}
//// Commented out until we bring CachedLayeredNamespace back.
// #[derive(Debug)]
// struct TestEvaler;
// impl Evaler for TestEvaler {
// fn _var_names(&self, _slab:&Slab, _dst:&mut BTreeSet<String>) {}
// fn eval(&self, _slab:&Slab, ns:&mut impl EvalNamespace) -> Result<f64,Error> {
// match ns.lookup("x", vec![], &mut String::new()) {
// Some(v) => Ok(v),
// None => Ok(1.23),
// }
// }
// }
//
// #[test]
// fn aaa_evalns_basics() {
// let slab = Slab::new();
// let mut ns = CachedLayeredNamespace::new(|_,_| Some(5.4321));
// assert_eq!({ ns.push(); let out=TestEvaler{}.eval(&slab, &mut ns); ns.pop(); out }.unwrap(), 5.4321);
// ns.create_cached("x".to_string(),1.111).unwrap();
// assert_eq!({ ns.push(); let out=TestEvaler{}.eval(&slab, &mut ns); ns.pop(); out }.unwrap(), 1.111);
// }
#[test]
fn corners() {
let mut slab = Slab::new();
let mut ns = EmptyNamespace;
assert_eq!(
format!("{:?}", Parser::new().parse("(-1) ^ 0.5", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns)),
"Ok(NaN)");
}
fn my_evalns_cb_function(_:&str, _:Vec<f64>) -> Option<f64> { None }
#[test]
fn evalns_cb_ownership() {
let _ns = CachedCallbackNamespace::new(my_evalns_cb_function);
let _ns = CachedCallbackNamespace::new(my_evalns_cb_function);
// Conclusion: You can pass a function pointer into a function that receives ownership.
let closure = |_:&str, _:Vec<f64>| None;
let _ns = CachedCallbackNamespace::new(closure);
let _ns = CachedCallbackNamespace::new(closure);
let x = 1.0;
let closure = |_:&str, _:Vec<f64>| Some(x);
let _ns = CachedCallbackNamespace::new(closure);
let _ns = CachedCallbackNamespace::new(closure);
let mut x = 1.0;
let closure = |_:&str, _:Vec<f64>| {
x+=1.0;
Some(x)
};
let _ns = CachedCallbackNamespace::new(closure);
//let _ns = CachedCallbackNamespace::new(closure); // Not allowed.
// Conclusion: Functions and Closures that don't mutate state are effectively Copy.
// Closures that mutate state aren't Copy.
// Note that the argument type (FnMut vs Fn) doesn't actually matter,
// just the implementation matters!
}
#[test]
fn custom_func() {
let mut slab = Slab::new();
let mut ns = CachedCallbackNamespace::new(|name,args| {
eprintln!("In CB: {}",name);
match name {
"x" => Some(1.0),
"y" => Some(2.0),
"z" => Some(3.0),
"foo" => {
Some(args.get(0).unwrap_or(&std::f64::NAN)*10.0)
}
"bar" => {
Some(args.get(0).unwrap_or(&std::f64::NAN) + args.get(1).unwrap_or(&std::f64::NAN))
}
_ => None,
}
});
assert_eq!(
Parser::new().parse("x + 1.5", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, {ns.cache_clear(); &mut ns}),
Ok(2.5));
assert_eq!(
Parser::new().parse("x() + 1.5", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, {ns.cache_clear(); &mut ns}),
Ok(2.5));
assert_eq!(
Parser::new().parse("x(1,2,3) + 1.5", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, {ns.cache_clear(); &mut ns}),
Ok(2.5));
eprintln!("I should see TWO x lookups, 1 y, and 1 z:");
assert_eq!(
Parser::new().parse("x(x,y,z) + 1.5", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, {ns.cache_clear(); &mut ns}),
Ok(2.5));
eprintln!("I should see TWO x lookups:");
assert_eq!(
Parser::new().parse("x(x,x,x) + 1.5", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, {ns.cache_clear(); &mut ns}),
Ok(2.5));
eprintln!("I should see TWO x lookups:");
assert_eq!(
Parser::new().parse("x(1.0) + x(1.1) + x(1.0) + x(1.1)", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, {ns.cache_clear(); &mut ns}),
Ok(4.0));
eprintln!("---------------------------");
assert_eq!(
Parser::new().parse("foo(1.23)", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, {ns.cache_clear(); &mut ns}),
Ok(12.3));
assert_eq!(
Parser::new().parse("bar(1.23, 3.21)", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, {ns.cache_clear(); &mut ns}),
Ok(4.4399999999999995));
assert_eq!(
format!("{:?}", Parser::new().parse("bar(1.23)", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, {ns.cache_clear(); &mut ns})),
"Ok(NaN)");
}
#[test]
#[cfg(feature="unsafe-vars")]
fn unsafe_var() {
let mut slab = Slab::new();
let mut ua = 1.23;
let mut ub = 4.56;
unsafe {
slab.ps.add_unsafe_var("ua".to_string(), &ua);
slab.ps.add_unsafe_var("ub".to_string(), &ub);
}
let mut ns = EmptyNamespace;
assert_eq!(
Parser::new().parse("ua + ub + 5", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(10.79));
ua+=1.0;
ub+=2.0;
assert_eq!(
Parser::new().parse("ua + ub + 5", &mut slab.ps).unwrap().from(&slab.ps).eval(&slab, &mut ns),
Ok(13.79));
let _ = (ua,ub); // Silence compiler warnings about variables not being read.
}
| true |
97113ef0e8950a6eba49f28bb8950cc031247ad5
|
Rust
|
saks/splitio.rs
|
/src/matcher.rs
|
UTF-8
| 1,515 | 3.015625 | 3 |
[] |
no_license
|
use serde::Deserialize;
#[derive(Debug, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Matcher {
matcher_type: MatcherType,
negate: bool,
whitelist_matcher_data: Option<WhitelistMatcherData>,
}
impl Matcher {
pub fn is_match(&self, key: &str) -> bool {
match self.matcher_type {
MatcherType::AllKeys => true,
MatcherType::Whitelist => match &self.whitelist_matcher_data {
Some(ref data) => data.whitelist.iter().any(|e| e == key),
None => false,
},
_ => {
unimplemented!("need to implement more matcher types");
}
}
}
}
// pub enum Matcher {
// AllKeys,
// Whitelist(Vec<String>),
// }
//
// impl Matcher {
// pub fn is_match(&self, key: &str) -> bool {
// match self {
// Matcher::AllKeys => true,
// Matcher::Whitelist(data) => data.iter().any(|&e| e == key),
// }
// }
// }
#[derive(Debug, Deserialize, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum MatcherType {
AllKeys,
InSegment,
Whitelist,
EqualTo,
GreaterThanOrEqualTo,
LessThanOrEqualTo,
Between,
EqualToSet,
ContainsAnyOfSet,
ContainsAllOfSet,
PartOfSet,
StartsWith,
EndsWith,
ContainsString,
InSplitTreatment,
EqualToBoolean,
MatchesString,
}
#[derive(Debug, Deserialize, Clone)]
pub struct WhitelistMatcherData {
whitelist: Vec<String>,
}
| true |
c0a17a06592959d20752cd683d7901cf8aa8b368
|
Rust
|
swc-project/swc
|
/crates/swc_ecma_transforms_compat/tests/es2015_duplicated_keys.rs
|
UTF-8
| 3,584 | 2.90625 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
use swc_ecma_parser::Syntax;
use swc_ecma_transforms_compat::es2015::duplicate_keys;
use swc_ecma_transforms_testing::test;
fn syntax() -> Syntax {
Default::default()
}
test!(
syntax(),
|_| duplicate_keys(),
issue_203,
r#"
const obj = {};
obj.prop = {
alpha: {
charlie: true
},
beta: {
charlie: true,
delta: true
}
};
"#,
r#"
const obj = {};
obj.prop = {
alpha: {
charlie: true
},
beta: {
charlie: true,
delta: true
}
};
"#
);
test!(
ignore,
syntax(),
|_| duplicate_keys(),
combination_dupes,
r#"var x = { a: 5, a: 6 };"#,
r#"var x = _define_property({
a: 5
}, "a", 6);"#
);
test!(
syntax(),
|_| duplicate_keys(),
combination_no_dupes,
r#"var x = { a: 5, b: 6 };"#,
r#"var x = { a: 5, b: 6 };"#
);
test!(
syntax(),
|_| duplicate_keys(),
dup_keys_both_quoted,
r#"var x = { "a\n b": 5, "a\n b": 6 };"#,
r#"var x = {
"a\n b": 5,
["a\n b"]: 6
};"#
);
test!(
syntax(),
|_| duplicate_keys(),
dup_keys_dupes,
r#"var x = { a: 5, a: 6 };"#,
r#"var x = {
a: 5,
["a"]: 6
};"#
);
test!(
syntax(),
|_| duplicate_keys(),
dup_keys_getter,
r#"var x = { a: 5, get a() {return 6;} };"#,
r#"var x = {
a: 5,
get ["a"]() {
return 6;
}
};"#
);
test!(
syntax(),
|_| duplicate_keys(),
dup_keys_getter_and_setter,
r#"var x = {
get a() {},
set a(x) {},
get a() {},
set a(x) {},
a: 3,
b: 4,
get b() {},
set b(x) {},
get c() {},
c: 5,
set c(x) {},
set d(x) {},
d: 6,
get d() {}
};"#,
r#"var x = {
get a() {},
set a(x) {},
get ["a"]() {},
set ["a"](x) {},
["a"]: 3,
b: 4,
get ["b"]() {},
set ["b"](x) {},
get c() {},
["c"]: 5,
set ["c"](x) {},
set d(x) {},
["d"]: 6,
get ["d"]() {}
};"#
);
test!(
syntax(),
|_| duplicate_keys(),
dup_keys_one_quoted,
r#"var x = { a: 5, "a": 6 };"#,
r#"var x = {
a: 5,
["a"]: 6
};"#
);
// duplicate_keys_getter
test!(
syntax(),
|_| duplicate_keys(),
duplicate_keys_getter,
r#"
var x = { a: 5, get a() {return 6;} };
"#,
r#"
var x = {
a: 5,
get ["a"]() {
return 6;
}
};
"#
);
// duplicate_keys_dupes
test!(
syntax(),
|_| duplicate_keys(),
duplicate_keys_dupes,
r#"
var x = { a: 5, a: 6 };
"#,
r#"
var x = {
a: 5,
["a"]: 6
};
"#
);
// duplicate_keys_both_quoted
test!(
syntax(),
|_| duplicate_keys(),
duplicate_keys_both_quoted,
r#"
var x = { "a\n b": 5, "a\n b": 6 };
"#,
r#"
var x = {
"a\n b": 5,
["a\n b"]: 6
};
"#
);
// duplicate_keys_no_dupes
test!(
syntax(),
|_| duplicate_keys(),
duplicate_keys_no_dupes,
r#"
var x = { a: 5, b: 6 };
"#,
r#"
var x = {
a: 5,
b: 6
};
"#
);
// duplicate_keys_getters_and_setters
test!(
syntax(),
|_| duplicate_keys(),
duplicate_keys_getters_and_setters,
r#"
var x = {
get a() {},
set a(x) {},
get a() {},
set a(x) {},
a: 3,
b: 4,
get b() {},
set b(x) {},
get c() {},
c: 5,
set c(x) {},
set d(x) {},
d: 6,
get d() {}
};
"#,
r#"
var x = {
get a() {},
set a(x) {},
get ["a"]() {},
set ["a"](x) {},
["a"]: 3,
b: 4,
get ["b"]() {},
set ["b"](x) {},
get c() {},
["c"]: 5,
set ["c"](x) {},
set d(x) {},
["d"]: 6,
get ["d"]() {}
};
"#
);
// duplicate_keys_one_quoted
test!(
syntax(),
|_| duplicate_keys(),
duplicate_keys_one_quoted,
r#"
var x = { a: 5, "a": 6 };
"#,
r#"
var x = {
a: 5,
["a"]: 6
};
"#
);
| true |
47e482d9b5f2876a106dc6dea7e46e5285487df6
|
Rust
|
JonathanVusich/monty_hall_simulator_rust
|
/src/main.rs
|
UTF-8
| 1,050 | 3.078125 | 3 |
[] |
no_license
|
extern crate rand;
use std::time::Duration;
use std::thread;
use rand::distributions::uniform::Uniform;
use rand::Rng;
use rand::thread_rng;
fn main() {
println!("{:?}", generate_successes(false, 100000000));
thread::sleep(Duration::from_secs(3));
}
fn generate_successes(user_switch: bool, iterations: usize) -> usize {
let static_door_set = [[0, 1, 1], [1, 0, 1], [0, 1, 1]];
let mut successes = 0;
let door_set = generate_vector(iterations);
let door_choice = generate_vector(iterations);
for x in 0..iterations {
if user_switch {
if static_door_set[door_set[x]][door_choice[x]] == 1 {
successes+=1;
}
} else {
if static_door_set[door_set[x]][door_choice[x]] == 0 {
successes+=1;
};
}
}
return successes;
}
fn generate_vector(iterations: usize) -> Vec<usize> {
let range = Uniform::new(0, 3);
let random_vec = thread_rng().sample_iter(&range).take(iterations).collect();
return random_vec;
}
| true |
92c51698b7fd36d54106cfd56edd6510565c05be
|
Rust
|
aggresss/playground-rust
|
/workbench/closure-demo/src/main.rs
|
UTF-8
| 162 | 3.0625 | 3 |
[
"MIT"
] |
permissive
|
fn two_times_impl() -> impl Fn(i32) -> i32 {
let i = 2;
move |j| j * i
}
fn main() {
let result = two_times_impl();
assert_eq!(result(2), 4);
}
| true |
dabe706c05ba2ad42334a20a4b276a6eae743ceb
|
Rust
|
saanuregh/bowot-rs
|
/src/commands/meta.rs
|
UTF-8
| 6,756 | 2.609375 | 3 |
[] |
no_license
|
use poise::serenity_prelude::{OAuth2Scope, Permissions};
use crate::{
types::{Error, PoiseContext},
utils::discord::{get_meta_info, get_rest_latency, reply_embed, MetaInfoResult},
};
/// Register application commands in this guild or globally
///
/// Run with no arguments to register in guild, run with argument "global" to
/// register globally.
#[poise::command(prefix_command, owners_only, hide_in_help)]
pub async fn register(ctx: PoiseContext<'_>, #[flag] global: bool) -> Result<(), Error> {
poise::samples::register_application_commands(ctx.into(), global).await?;
Ok(())
}
/// Show help menu
#[poise::command(prefix_command, track_edits, slash_command)]
pub async fn help(
ctx: PoiseContext<'_>,
#[description = "A specific command to show help about."] command: Option<String>,
) -> Result<(), Error> {
poise::samples::help(
ctx,
command.as_deref(),
"",
poise::samples::HelpResponseMode::Ephemeral,
)
.await?;
Ok(())
}
/// Sends information about the bot.
#[poise::command(slash_command)]
pub async fn about(ctx: PoiseContext<'_>) -> Result<(), Error> {
let discord_ctx = ctx.discord();
let channel_id = ctx.channel_id();
let rest_latency = get_rest_latency(discord_ctx, channel_id).await?;
let MetaInfoResult {
uptime,
memory_usage,
cpu_usage,
version,
hoster_tag,
hoster_id,
bot_name,
bot_icon,
num_guilds,
num_shards,
num_channels,
num_priv_channels,
} = get_meta_info(discord_ctx).await;
reply_embed(ctx, |e| {
e.title(format!("**{}** - v{}", bot_name, version));
e.url("https://github.com/saanuregh/bowot-rs");
e.description("General Purpose Discord Bot made in [Rust](https://www.rust-lang.org/) using [serenity.rs](https://github.com/serenity-rs/serenity)\nHaving any issues, just dm me 😊.");
e.field("Statistics:", format!("Shards: {}\nGuilds: {}\nChannels: {}\nPrivate Channels: {}", num_shards, num_guilds, num_channels, num_priv_channels), true);
e.field("Currently hosted by:", format!("Tag: {}\nID: {}", hoster_tag, hoster_id), true);
e.field("Latency:", format!("REST:\n`{}ms`", rest_latency), true);
e.field("CPU Usage:", format!("`{:.2} %`",cpu_usage), true);
e.field("Memory Usage:", format!("`{} KB`", memory_usage), true);
e.field("Uptime:", format!("`{}`", uptime), true);
e.thumbnail(bot_icon);
e
}).await?;
Ok(())
}
/// Sends the latency of the bot to the shards.
#[poise::command(slash_command)]
pub async fn ping(ctx: PoiseContext<'_>) -> Result<(), Error> {
let discord_ctx = ctx.discord();
let channel_id = ctx.channel_id();
let rest_latency = get_rest_latency(discord_ctx, channel_id).await?;
reply_embed(ctx, |e| {
e.title("Ping");
e.field("Latency:", format!("REST:\n`{}ms`", rest_latency), true);
e
})
.await?;
Ok(())
}
/// This command just sends an invite of the bot with the required permissions.
#[poise::command(slash_command)]
pub async fn invite(ctx: PoiseContext<'_>) -> Result<(), Error> {
let discord_ctx = ctx.discord();
let _p = vec![
Permissions::MANAGE_GUILD,
Permissions::MANAGE_ROLES,
Permissions::MANAGE_CHANNELS,
Permissions::KICK_MEMBERS,
Permissions::BAN_MEMBERS,
Permissions::CREATE_INVITE,
Permissions::MANAGE_WEBHOOKS,
Permissions::READ_MESSAGES,
Permissions::SEND_MESSAGES,
Permissions::MANAGE_MESSAGES,
Permissions::EMBED_LINKS,
Permissions::ATTACH_FILES,
Permissions::READ_MESSAGE_HISTORY,
Permissions::USE_EXTERNAL_EMOJIS,
Permissions::ADD_REACTIONS,
Permissions::SPEAK,
Permissions::CONNECT,
Permissions::USE_PRIVATE_THREADS,
Permissions::USE_PUBLIC_THREADS,
Permissions::USE_SLASH_COMMANDS,
];
let scopes = vec![OAuth2Scope::Bot, OAuth2Scope::ApplicationsCommands];
let mut permissions = Permissions::empty();
_p.iter().for_each(|&p| permissions.set(p, true));
let url = discord_ctx
.cache
.current_user()
.invite_url_with_oauth2_scopes(discord_ctx, permissions, &scopes)
.await?;
reply_embed(ctx, |e| {
e.title("Invite Link");
e.url(url);
e.description("__**Reason for each permission**__");
e.fields(vec![
("Manage Guild", "Be able to manage server.", true),
(
"Manage Roles",
"Be able to manage roles of server and members.",
true,
),
(
"Manage Channels",
"Be able to mute members on the channel without having to create a role for it.",
true,
),
("Kick Members", "Kick/GhostBan moderation command.", true),
("Ban Members", "Ban moderation command.", true),
("Create Invite", "Allow creation of rich invite.", true),
(
"Manage Webhooks",
"For all the commands that can be ran on a schedule, so it's more efficient.",
true,
),
(
"Read Messages",
"So the bot can read the messages to know when a command was invoked and such.",
true,
),
(
"Send Messages",
"So the bot can send the messages it needs to send.",
true,
),
(
"Manage Messages",
"Be able to manage messages, like for clear command.",
true,
),
(
"Embed Links",
"For the tags to be able to embed images.",
true,
),
(
"Attach Files",
"For the tags to be able to attach files.",
true,
),
(
"Read Message History",
"This is a required permission for every paginated command.",
true,
),
(
"Use External Emojis",
"For all the commands that use emojis for better emphasis.",
true,
),
(
"Add Reactions",
"To be able to add reactions for all the paginated commands.",
true,
),
(
"Speak",
"To be able to play music on that voice channel.",
true,
),
("Connect", "To be able to connect to a voice channel.", true),
]);
e
})
.await?;
Ok(())
}
| true |
06b8f8cca3f23381c522a1672bed18125d8821f4
|
Rust
|
Ionman64/OpenTill
|
/rust/src/template_manager.rs
|
UTF-8
| 3,647 | 2.6875 | 3 |
[] |
no_license
|
use utils as app;
use std::fs;
use std::path::{Path, PathBuf};
use std::fs::File;
use regex::Regex;
use std::io::Write;
use std::ops::Index;
use std::io::BufReader;
use std::io::BufRead;
pub fn process_templates_into_folder() {
let input_directory = app::get_home_dir().join("input_templates");
let directory = match fs::read_dir(input_directory) {
Ok(x) => x,
Err(x) => {
panic!("Could not read input templates directory: {}", x);
}
};
let regex_pattern = r#"<modal data-page="(.*)">"#;
let re = match Regex::new(regex_pattern) {
Ok(x) => x,
Err(x) => {
panic!("Could not compile regex, {}", x);
}
};
for dir_entry_result in directory {
let dir_entry = match dir_entry_result {
Ok(x) => x,
Err(x) => {
panic!("{}", x);
}
};
let path = dir_entry.path();
let extension = match Path::new(&path).extension() {
Some(x) => x,
None => {
continue;
}
};
let filename = match Path::new(&path).file_name() {
Some(x) => x,
None => {
continue;
}
};
match extension.to_os_string().to_str() {
Some(x) => {
if x == "hbs" {
let input_file = match File::open(&path) {
Ok(x) => x,
Err(x) => {
panic!("Could not read file {}", x);
}
};
let mut output_file = match File::create(app::get_app_dir().join("templates").join(filename)) {
Ok(x) => x,
Err(x) => {
panic!("Could not create file {}", x);
}
};
for unwrapped_line in BufReader::new(input_file).lines() {
let line = match unwrapped_line {
Ok(x) => x,
Err(x) => {
continue;
}
};
let cap = re.captures(&line);
let found_path = match cap {
Some(x) => x,
None => {
writeln!(output_file, "{}", &line);
continue;
}
};
let path = PathBuf::from(app::get_app_dir().join("input_templates").join(found_path.index(1).replace("/", &std::path::MAIN_SEPARATOR.to_string()).replace("\\", &std::path::MAIN_SEPARATOR.to_string())));
if path.exists() {
output_file.write(&app::read_all_lines(path).into_bytes());
}
else {
warn!("{} does not exist for inclusion into the template file", path.display());
}
}
match output_file.sync_all() {
Ok(x) => {},
Err(x) => {
panic!("{}", x);
}
}
}
else {
println!("not hbs {}", x);
}
}
None => {
panic!("Could not get OS extension, not valid UTF-8");
}
}
}
}
| true |
cb9ac72ecb471935a3bed4278b84078a606f9e4d
|
Rust
|
proelbtn/nitkc-lsm
|
/src/main.rs
|
UTF-8
| 2,301 | 3.203125 | 3 |
[] |
no_license
|
use std::env;
use std::fs::File;
use std::io::{BufRead, BufReader, Error};
type Data = (f64, f64);
type Matrix = Vec<Vec<f64>>;
fn read_dat(filename: &str) -> Result<Vec<Data>, Error> {
let mut vec = Vec::new();
let file = match File::open(filename) {
Ok(v) => v,
Err(v) => return Err(v)
};
let reader = BufReader::new(file);
for line in reader.lines() {
let data = line.unwrap()
.split(" ")
.map(|e| e.trim().parse::<f64>().unwrap())
.collect::<Vec<f64>>();
vec.push((data[0], data[1]))
}
return Ok(vec);
}
fn calc_neq(dim: usize, data: &Vec<Data>) -> (Matrix, Vec<f64>) {
let mut mat = vec![vec![0.0; dim]; dim];
let mut vec = vec![0.0; dim];
for &(x, y) in data.iter() {
let mut c1: f64 = 1.0;
for px in (0..dim).rev() {
let mut c2: f64 = c1;
for py in (0..dim).rev() {
mat[py][px] += c2;
if px == dim - 1 {
vec[py] += c2 * y;
}
c2 *= x;
}
c1 *= x;
}
}
return (mat, vec);
}
fn calc_lsm(dim: usize, data: &Vec<Data>) -> Vec<f64> {
let (mut mat, mut vec) = calc_neq(dim, data);
for i in 0..dim {
// mat[i][i]を1にする
vec[i] /= mat[i][i];
for x in (0..dim).rev() { mat[i][x] /= mat[i][i]; }
// mat[y][i]を0にする(i < y)
for y in (i + 1)..dim {
vec[y] -= vec[i] * mat[y][i];
for x in (i..dim).rev() { mat[y][x] -= mat[i][x] * mat[y][i]; }
}
}
for i in (0..dim).rev() {
for y in 0..i {
vec[y] -= mat[y][i] * vec[i];
mat[y][i] = 0.;
}
}
return vec;
}
fn main() {
let program: String = env::args().next().unwrap();
let args: Vec<String> = env::args().skip(1).collect();
if args.len() != 2 {
println!("Usage:");
println!(" {} [dimention] [.dat file]", program);
std::process::exit(1);
}
let dimention = args[0].trim().parse::<usize>().unwrap() + 1;
let filename = &args[1];
let data = read_dat(filename).unwrap();
let result = calc_lsm(dimention, &data);
result.iter().for_each(|v| print!("{:.3}\t", v));
}
| true |
4d34909c5cd56bbb71d4e90616036e9cb987e8b1
|
Rust
|
port-finance/anchor
|
/lang/syn/src/codegen/program/common.rs
|
UTF-8
| 2,635 | 2.5625 | 3 |
[
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] |
permissive
|
use crate::parser;
use crate::{IxArg, State};
use heck::CamelCase;
use quote::quote;
// Namespace for calculating state instruction sighash signatures.
pub const SIGHASH_STATE_NAMESPACE: &str = "state";
// Namespace for calculating instruction sighash signatures for any instruction
// not affecting program state.
pub const SIGHASH_GLOBAL_NAMESPACE: &str = "global";
// We don't technically use sighash, because the input arguments aren't given.
// Rust doesn't have method overloading so no need to use the arguments.
// However, we do namespace methods in the preeimage so that we can use
// different traits with the same method name.
pub fn sighash(namespace: &str, name: &str) -> [u8; 8] {
let preimage = format!("{}:{}", namespace, name);
let mut sighash = [0u8; 8];
sighash.copy_from_slice(&crate::hash::hash(preimage.as_bytes()).to_bytes()[..8]);
sighash
}
pub fn sighash_ctor() -> [u8; 8] {
sighash(SIGHASH_STATE_NAMESPACE, "new")
}
pub fn generate_ix_variant(name: String, args: &[IxArg]) -> proc_macro2::TokenStream {
let ix_arg_names: Vec<&syn::Ident> = args.iter().map(|arg| &arg.name).collect();
let ix_name_camel: proc_macro2::TokenStream = {
let n = name.to_camel_case();
n.parse().unwrap()
};
if args.is_empty() {
quote! {
#ix_name_camel
}
} else {
quote! {
#ix_name_camel {
#(#ix_arg_names),*
}
}
}
}
pub fn generate_ctor_args(state: &State) -> Vec<syn::Pat> {
generate_ctor_typed_args(state)
.iter()
.map(|pat_ty| *pat_ty.pat.clone())
.collect()
}
pub fn generate_ctor_typed_args(state: &State) -> Vec<syn::PatType> {
state
.ctor_and_anchor
.as_ref()
.map(|(ctor, _anchor_ident)| {
ctor.sig
.inputs
.iter()
.filter_map(|arg: &syn::FnArg| match arg {
syn::FnArg::Typed(pat_ty) => {
let mut arg_str = parser::tts_to_string(&pat_ty.ty);
arg_str.retain(|c| !c.is_whitespace());
if arg_str.starts_with("Context<") {
return None;
}
Some(pat_ty.clone())
}
_ => {
if !state.is_zero_copy {
panic!("Cannot pass self as parameter")
}
None
}
})
.collect()
})
.unwrap_or_default()
}
| true |
d61ea102047a15fa2dd1e4c2f607a23b4d10e55c
|
Rust
|
input-output-hk/chain-libs
|
/chain-impl-mockchain/src/leadership/mod.rs
|
UTF-8
| 19,414 | 2.546875 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
use crate::{
block::{BlockDate, BlockVersion, Header},
certificate::PoolId,
chaintypes::ConsensusType,
date::Epoch,
key::BftLeaderId,
ledger::Ledger,
stake::StakeDistribution,
};
use chain_crypto::{Ed25519, RistrettoGroup2HashDh, SecretKey, SumEd25519_12};
use chain_time::era::TimeEra;
pub mod bft;
pub mod genesis;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ErrorKind {
Failure,
NoLeaderForThisSlot,
IncompatibleBlockVersion,
IncompatibleLeadershipMode,
InvalidLeader,
InvalidLeaderSignature,
InvalidLeaderProof,
InvalidBlockMessage,
InvalidStateUpdate,
VrfNonceIsEmptyButNotSupposedTo,
}
#[derive(Debug)]
pub struct Error {
kind: ErrorKind,
cause: Option<Box<dyn std::error::Error + Send + Sync>>,
}
/// Verification type for when validating a block
#[derive(Debug)]
pub enum Verification {
Success,
Failure(Error),
}
macro_rules! try_check {
($x:expr) => {
if $x.failure() {
return $x;
}
};
}
pub struct BftLeader {
pub sig_key: SecretKey<Ed25519>,
}
impl From<SecretKey<Ed25519>> for Leader {
fn from(secret_key: SecretKey<Ed25519>) -> Self {
Leader {
bft_leader: Some(BftLeader {
sig_key: secret_key,
}),
genesis_leader: None,
}
}
}
pub struct GenesisLeader {
pub node_id: PoolId,
pub sig_key: SecretKey<SumEd25519_12>,
pub vrf_key: SecretKey<RistrettoGroup2HashDh>,
}
pub struct Leader {
pub bft_leader: Option<BftLeader>,
pub genesis_leader: Option<GenesisLeader>,
}
#[allow(clippy::large_enum_variant)]
pub enum LeaderOutput {
None,
Bft(BftLeaderId),
GenesisPraos(PoolId, genesis::Witness),
}
pub enum LeadershipConsensus {
Bft(bft::LeadershipData),
GenesisPraos(genesis::LeadershipData),
}
/// Leadership represent a given epoch and their associated leader or metadata.
pub struct Leadership {
// Specific epoch where the leadership apply
epoch: Epoch,
// Give the closest parameters associated with date keeping given a leadership
era: TimeEra,
// Consensus specific metadata required for verifying/evaluating leaders
inner: LeadershipConsensus,
}
impl LeadershipConsensus {
#[inline]
fn verify_version(&self, block_version: BlockVersion) -> Verification {
match self {
LeadershipConsensus::Bft(_) if block_version == BlockVersion::Ed25519Signed => {
Verification::Success
}
LeadershipConsensus::GenesisPraos(_) if block_version == BlockVersion::KesVrfproof => {
Verification::Success
}
_ => Verification::Failure(Error::new(ErrorKind::IncompatibleBlockVersion)),
}
}
#[inline]
fn verify_leader(&self, block_header: &Header) -> Verification {
match self {
LeadershipConsensus::Bft(bft) => bft.verify(block_header),
LeadershipConsensus::GenesisPraos(genesis_praos) => genesis_praos.verify(block_header),
}
}
#[inline]
fn is_leader(&self, leader: &Leader, date: BlockDate) -> LeaderOutput {
match self {
LeadershipConsensus::Bft(bft) => match leader.bft_leader {
Some(ref bft_leader) => {
let bft_leader_id = bft.get_leader_at(date);
if bft_leader_id == bft_leader.sig_key.to_public().into() {
LeaderOutput::Bft(bft_leader_id)
} else {
LeaderOutput::None
}
}
None => LeaderOutput::None,
},
LeadershipConsensus::GenesisPraos(genesis_praos) => match leader.genesis_leader {
None => LeaderOutput::None,
Some(ref gen_leader) => {
match genesis_praos.leader(&gen_leader.node_id, &gen_leader.vrf_key, date) {
Ok(Some(witness)) => {
LeaderOutput::GenesisPraos(gen_leader.node_id.clone(), witness)
}
_ => LeaderOutput::None,
}
}
},
}
}
}
impl Leadership {
pub fn new(epoch: Epoch, ledger: &Ledger) -> Self {
let inner = match ledger.settings.consensus_version {
ConsensusType::Bft => LeadershipConsensus::Bft(
bft::LeadershipData::new(ledger.settings.bft_leaders.clone()).unwrap(),
),
ConsensusType::GenesisPraos => {
LeadershipConsensus::GenesisPraos(genesis::LeadershipData::new(
epoch,
ledger.get_stake_distribution(),
ledger.delegation.clone(),
ledger.settings.consensus_nonce.clone(),
ledger.settings.active_slots_coeff,
))
}
};
Leadership {
epoch,
era: ledger.era.clone(),
inner,
}
}
/// get the epoch associated to the `Leadership`
#[inline]
pub fn epoch(&self) -> Epoch {
self.epoch
}
pub fn stake_distribution(&self) -> Option<&StakeDistribution> {
match &self.inner {
LeadershipConsensus::Bft(_) => None,
LeadershipConsensus::GenesisPraos(inner) => Some(inner.distribution()),
}
}
/// Create a Block date given a leadership and a relative epoch slot
///
/// # Panics
///
/// If the slot index is not valid given the leadership, out of bound date
pub fn date_at_slot(&self, slot_id: u32) -> BlockDate {
assert!(slot_id < self.era.slots_per_epoch());
BlockDate {
epoch: self.epoch(),
slot_id,
}
}
/// get the TimeEra associated to the `Leadership`
#[inline]
pub fn era(&self) -> &TimeEra {
&self.era
}
/// get the consensus associated with the `Leadership`
pub fn consensus(&self) -> &LeadershipConsensus {
&self.inner
}
/// Verify whether this header has been produced by a leader that fits with the leadership
///
pub fn verify(&self, block_header: &Header) -> Verification {
try_check!(self.inner.verify_version(block_header.block_version()));
try_check!(self.inner.verify_leader(block_header));
Verification::Success
}
/// Test that the given leader object is able to create a valid block for the leadership
/// at a given date.
pub fn is_leader_for_date(&self, leader: &Leader, date: BlockDate) -> LeaderOutput {
self.inner.is_leader(leader, date)
}
}
impl Verification {
#[inline]
pub fn into_error(self) -> Result<(), Error> {
match self {
Verification::Success => Ok(()),
Verification::Failure(err) => Err(err),
}
}
#[inline]
pub fn success(&self) -> bool {
matches!(self, Verification::Success)
}
#[inline]
pub fn failure(&self) -> bool {
!self.success()
}
}
impl Error {
pub fn new(kind: ErrorKind) -> Self {
Error { kind, cause: None }
}
pub fn new_<E>(kind: ErrorKind, cause: E) -> Self
where
E: std::error::Error + Send + Sync + 'static,
{
Error {
kind,
cause: Some(Box::new(cause)),
}
}
}
impl std::fmt::Display for ErrorKind {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
ErrorKind::Failure => write!(f, "The current state of the leader selection is invalid"),
ErrorKind::NoLeaderForThisSlot => write!(f, "No leader available for this block date"),
ErrorKind::IncompatibleBlockVersion => {
write!(f, "The block Version is incompatible with LeaderSelection.")
}
ErrorKind::IncompatibleLeadershipMode => {
write!(f, "Incompatible leadership mode (the proof is invalid)")
}
ErrorKind::InvalidLeader => write!(f, "Block has unexpected block leader"),
ErrorKind::InvalidLeaderSignature => write!(f, "Block signature is invalid"),
ErrorKind::InvalidLeaderProof => write!(f, "Block proof is invalid"),
ErrorKind::InvalidBlockMessage => write!(f, "Invalid block message"),
ErrorKind::InvalidStateUpdate => write!(f, "Invalid State Update"),
ErrorKind::VrfNonceIsEmptyButNotSupposedTo => write!(f, "Vrf Nonce is empty"),
}
}
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
if let Some(cause) = &self.cause {
write!(f, "{}: {}", self.kind, cause)
} else {
write!(f, "{}", self.kind)
}
}
}
impl std::error::Error for Error {
fn cause(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.cause
.as_ref()
.map(|cause| -> &(dyn std::error::Error + 'static) { cause.as_ref() })
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::fragment::Contents;
use crate::header::ChainLength;
use crate::header::HeaderBuilderNew;
use crate::testing::data::AddressData;
use crate::testing::ConfigBuilder;
use crate::testing::LedgerBuilder;
use crate::testing::TestGen;
use chain_crypto::PublicKey;
pub fn generate_ledger_with_bft_leaders_count(count: usize) -> (Vec<BftLeaderId>, Ledger) {
let leaders: Vec<PublicKey<Ed25519>> = TestGen::leaders_pairs()
.take(count)
.map(|x| x.key().to_public())
.collect();
generate_ledger_with_bft_leaders(leaders)
}
pub fn generate_ledger_with_bft_leaders(
leaders: Vec<PublicKey<Ed25519>>,
) -> (Vec<BftLeaderId>, Ledger) {
let leaders: Vec<BftLeaderId> = leaders.into_iter().map(BftLeaderId).collect();
let config = ConfigBuilder::new().with_leaders(&leaders);
let test_ledger = LedgerBuilder::from_config(config)
.build()
.expect("cannot build ledger");
(leaders, test_ledger.ledger)
}
pub fn generate_header_for_leader(leader_key: SecretKey<Ed25519>, slot_id: u32) -> Header {
HeaderBuilderNew::new(BlockVersion::Ed25519Signed, &Contents::empty())
.set_parent(&TestGen::hash(), ChainLength(slot_id))
.set_date(BlockDate { epoch: 0, slot_id })
.into_bft_builder()
.unwrap()
.sign_using(&leader_key)
.generalize()
}
#[test]
fn consensus_verify_version_for_bft() {
let ledger = TestGen::ledger();
let data = bft::LeadershipData::new(ledger.settings.bft_leaders)
.expect("Couldn't build leadership data");
let bft_leadership_consensus = LeadershipConsensus::Bft(data);
assert!(bft_leadership_consensus
.verify_version(BlockVersion::Ed25519Signed)
.success());
assert!(bft_leadership_consensus
.verify_version(BlockVersion::KesVrfproof)
.failure());
assert!(bft_leadership_consensus
.verify_version(BlockVersion::Genesis)
.failure());
}
#[test]
fn consensus_leader_for_bft() {
let leader_key = AddressData::generate_key_pair::<Ed25519>();
let (_, ledger) = generate_ledger_with_bft_leaders(vec![leader_key.public_key().clone()]);
let leadership_data = bft::LeadershipData::new(ledger.settings.bft_leaders)
.expect("leaders ids collection is empty");
let bft_leadership_consensus = LeadershipConsensus::Bft(leadership_data);
let header = generate_header_for_leader(leader_key.private_key().clone(), 0);
assert!(bft_leadership_consensus.verify_leader(&header).success());
}
#[test]
fn is_leader_for_bft_correct() {
let leaders_count = 5;
let leaders_keys: Vec<SecretKey<Ed25519>> =
TestGen::secret_keys().take(leaders_count).collect();
let (leaders, ledger) =
generate_ledger_with_bft_leaders(leaders_keys.iter().map(|x| x.to_public()).collect());
let leadership_data = bft::LeadershipData::new(ledger.settings.bft_leaders)
.expect("leaders ids collection is empty");
let bft_leadership_consensus = LeadershipConsensus::Bft(leadership_data);
for leader_index in 0..leaders_count {
let leader_output = bft_leadership_consensus.is_leader(
&leaders_keys[leader_index].clone().into(),
BlockDate {
epoch: 0,
slot_id: leader_index as u32,
},
);
if let LeaderOutput::Bft(actual_leader) = leader_output {
assert_eq!(leaders[leader_index].clone(), actual_leader);
} else {
panic!("wrong leader at index: {}", leader_index);
}
}
}
#[test]
fn is_leader_for_bft_negative() {
let leaders_count = 5;
let leaders_keys: Vec<SecretKey<Ed25519>> =
TestGen::secret_keys().take(leaders_count).collect();
let (_, ledger) =
generate_ledger_with_bft_leaders(leaders_keys.iter().map(|x| x.to_public()).collect());
let leadership_data = bft::LeadershipData::new(ledger.settings.bft_leaders)
.expect("leaders ids collection is empty");
let bft_leadership_consensus = LeadershipConsensus::Bft(leadership_data);
for leader in leaders_keys.iter().take(leaders_count - 1).cloned() {
let _leader_output = bft_leadership_consensus.is_leader(
&leader.into(),
BlockDate {
epoch: 0,
slot_id: leaders_count as u32,
},
);
assert!(matches!(LeaderOutput::None, _leader_output));
}
}
#[test]
fn is_leader_empty() {
let ledger = TestGen::ledger();
let leadership_data = bft::LeadershipData::new(ledger.settings.bft_leaders)
.expect("leaders ids collection is empty");
let bft_leadership_consensus = LeadershipConsensus::Bft(leadership_data);
let leader = Leader {
bft_leader: None,
genesis_leader: None,
};
let _leader_output = bft_leadership_consensus.is_leader(
&leader,
BlockDate {
epoch: 0,
slot_id: 0,
},
);
assert!(matches!(LeaderOutput::None, _leader_output));
}
#[test]
fn consensus_verify_version_for_praos() {
let ledger = TestGen::ledger();
let data = genesis::LeadershipData::new(
0,
ledger.get_stake_distribution(),
ledger.delegation.clone(),
ledger.settings.consensus_nonce,
ledger.settings.active_slots_coeff,
);
let gen_leadership_consensus = LeadershipConsensus::GenesisPraos(data);
assert!(gen_leadership_consensus
.verify_version(BlockVersion::Ed25519Signed)
.failure());
assert!(gen_leadership_consensus
.verify_version(BlockVersion::KesVrfproof)
.success());
assert!(gen_leadership_consensus
.verify_version(BlockVersion::Genesis)
.failure());
}
#[test]
#[should_panic]
fn ledership_getters_bft_slot_no_negative() {
let test_ledger = LedgerBuilder::from_config(
ConfigBuilder::new()
.with_consensus_version(ConsensusType::Bft)
.with_slots_per_epoch(60),
)
.build()
.unwrap();
let leadership = Leadership::new(0, &test_ledger.ledger);
leadership.date_at_slot(61);
}
#[test]
fn ledership_getters_bft() {
let epoch = 0;
let slot_id = 1;
let test_ledger = LedgerBuilder::from_config(
ConfigBuilder::new()
.with_consensus_version(ConsensusType::Bft)
.with_slots_per_epoch(60),
)
.build()
.unwrap();
let leadership = Leadership::new(epoch, &test_ledger.ledger);
assert_eq!(leadership.epoch(), epoch);
assert_eq!(
leadership.date_at_slot(slot_id),
BlockDate { epoch: 0, slot_id }
);
assert_eq!(leadership.stake_distribution(), None);
}
#[test]
fn ledership_getters_praos() {
let epoch = 0;
let slot_id = 1;
let test_ledger = LedgerBuilder::from_config(
ConfigBuilder::new()
.with_consensus_version(ConsensusType::GenesisPraos)
.with_slots_per_epoch(60),
)
.build()
.unwrap();
let leadership = Leadership::new(epoch, &test_ledger.ledger);
assert_eq!(leadership.epoch(), epoch);
assert_eq!(
leadership.date_at_slot(slot_id),
BlockDate { epoch: 0, slot_id }
);
assert_eq!(
leadership.stake_distribution(),
Some(&test_ledger.ledger.get_stake_distribution())
);
}
#[test]
fn leadership_is_leader_for_date() {
let leaders_count = 5;
let leaders_keys: Vec<SecretKey<Ed25519>> =
TestGen::secret_keys().take(leaders_count).collect();
let leaders: Vec<BftLeaderId> = leaders_keys
.iter()
.map(|x| BftLeaderId(x.to_public()))
.collect();
let config = ConfigBuilder::new()
.with_leaders(&leaders)
.with_consensus_version(ConsensusType::Bft)
.with_slots_per_epoch(60);
let test_ledger = LedgerBuilder::from_config(config)
.build()
.expect("cannot build ledger");
let leadership = Leadership::new(0, &test_ledger.ledger);
for leader_index in 0..leaders_count {
let leader_output = leadership.is_leader_for_date(
&leaders_keys[leader_index].clone().into(),
BlockDate {
epoch: 0,
slot_id: leader_index as u32,
},
);
if let LeaderOutput::Bft(actual_leader) = leader_output {
assert_eq!(leaders[leader_index].clone(), actual_leader);
} else {
panic!("wrong leader at index: {}", leader_index);
}
}
}
#[test]
fn leadership_verify() {
let leaders_count = 5usize;
let leaders_keys: Vec<SecretKey<Ed25519>> =
TestGen::secret_keys().take(leaders_count).collect();
let leaders: Vec<BftLeaderId> = leaders_keys.iter().map(|x| x.to_public().into()).collect();
let config = ConfigBuilder::new()
.with_leaders(&leaders)
.with_consensus_version(ConsensusType::Bft)
.with_slots_per_epoch(60);
let test_ledger = LedgerBuilder::from_config(config)
.build()
.expect("cannot build ledger");
let leadership = Leadership::new(0, &test_ledger.ledger);
for (i, key) in leaders_keys.iter().cloned().enumerate() {
let header = generate_header_for_leader(key, i as u32);
assert!(leadership.verify(&header).success());
}
}
}
| true |
2e80bf9a335b46d6cd0cb1d02e40878f8772c109
|
Rust
|
rick68/rust-trace
|
/libcore/ops/trait_Mul/mul.rs
|
UTF-8
| 3,466 | 3.28125 | 3 |
[
"MIT"
] |
permissive
|
#![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::ops::Mul;
#[derive(Copy, Clone)]
struct A<T> {
value: T
}
impl Mul for A<T> {
type Output = A<T>;
fn mul(self, rhs: A<T>) -> Self::Output {
A { value: self.value * rhs.value }
}
}
// pub trait Mul<RHS=Self> {
// /// The resulting type after applying the `*` operator
// #[stable(feature = "rust1", since = "1.0.0")]
// type Output;
//
// /// The method for the `*` operator
// #[stable(feature = "rust1", since = "1.0.0")]
// fn mul(self, rhs: RHS) -> Self::Output;
// }
// macro_rules! forward_ref_binop {
// (impl $imp:ident, $method:ident for $t:ty, $u:ty) => {
// #[unstable(feature = "core",
// reason = "recently added, waiting for dust to settle")]
// impl<'a> $imp<$u> for &'a $t {
// type Output = <$t as $imp<$u>>::Output;
//
// #[inline]
// fn $method(self, other: $u) -> <$t as $imp<$u>>::Output {
// $imp::$method(*self, other)
// }
// }
//
// #[unstable(feature = "core",
// reason = "recently added, waiting for dust to settle")]
// impl<'a> $imp<&'a $u> for $t {
// type Output = <$t as $imp<$u>>::Output;
//
// #[inline]
// fn $method(self, other: &'a $u) -> <$t as $imp<$u>>::Output {
// $imp::$method(self, *other)
// }
// }
//
// #[unstable(feature = "core",
// reason = "recently added, waiting for dust to settle")]
// impl<'a, 'b> $imp<&'a $u> for &'b $t {
// type Output = <$t as $imp<$u>>::Output;
//
// #[inline]
// fn $method(self, other: &'a $u) -> <$t as $imp<$u>>::Output {
// $imp::$method(*self, *other)
// }
// }
// }
// }
// macro_rules! mul_impl {
// ($($t:ty)*) => ($(
// #[stable(feature = "rust1", since = "1.0.0")]
// impl Mul for $t {
// type Output = $t;
//
// #[inline]
// fn mul(self, other: $t) -> $t { self * other }
// }
//
// forward_ref_binop! { impl Mul, mul for $t, $t }
// )*)
// }
// mul_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
type T = i32;
macro_rules! mul_test {
($($t:ty)*) => ($({
let a: $t = 17 as $t;
let b: $t = 4 as $t;
{
let result: $t = a.mul(b);
assert_eq!(result, 68 as $t);
}
{
let result: $t = a * b;
assert_eq!(result, 68 as $t);
}
let c: &$t = &(10 as $t);
{
let result: $t = c * b;
assert_eq!(result, 40 as $t);
}
{
let result: $t = b * c;
assert_eq!(result, 40 as $t);
}
{
let result: $t = c * c;
assert_eq!(result, 100 as $t);
}
})*)
}
#[test]
fn mul_test1() {
let a: A<T> = A { value: 17 };
let b: A<T> = A { value: 4 };
{
let result: A<T> = a.mul(b);
assert_eq!(result.value, 68);
}
{
let result: A<T> = a * b;
assert_eq!(result.value, 68);
}
}
#[test]
fn mul_test2() {
mul_test! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 };
}
}
| true |
7c7798576001034709fa6f4e7e2c89b185722b92
|
Rust
|
chromium/chromium
|
/third_party/rust/rstest/v0_17/crate/tests/resources/rstest/dump_debug_compact.rs
|
UTF-8
| 1,153 | 2.8125 | 3 |
[
"MIT",
"Apache-2.0",
"BSD-3-Clause",
"GPL-1.0-or-later",
"LGPL-2.0-or-later"
] |
permissive
|
use rstest::*;
#[derive(Debug)]
struct A {}
#[fixture]
fn fu32() -> u32 {
42
}
#[fixture]
fn fstring() -> String {
"A String".to_string()
}
#[fixture]
fn ftuple() -> (A, String, i32) {
(A {}, "A String".to_string(), -12)
}
#[rstest(::trace)]
fn single_fail(fu32: u32, fstring: String, ftuple: (A, String, i32)) {
assert!(false);
}
#[rstest]
fn no_trace_single_fail(fu32: u32, fstring: String, ftuple: (A, String, i32)) {
assert!(false);
}
#[rstest(u, s, t,
case(42, "str", ("ss", -12)),
case(24, "trs", ("tt", -24))
::trace
)]
fn cases_fail(u: u32, s: &str, t: (&str, i32)) {
assert!(false);
}
#[rstest(u, s, t,
case(42, "str", ("ss", -12)),
case(24, "trs", ("tt", -24))
)]
fn no_trace_cases_fail(u: u32, s: &str, t: (&str, i32)) {
assert!(false);
}
#[rstest(
u => [1, 2],
s => ["rst", "srt"],
t => [("SS", -12), ("TT", -24)]
::trace
)]
fn matrix_fail(u: u32, s: &str, t: (&str, i32)) {
assert!(false);
}
#[rstest(
u => [1, 2],
s => ["rst", "srt"],
t => [("SS", -12), ("TT", -24)]
)]
fn no_trace_matrix_fail(u: u32, s: &str, t: (&str, i32)) {
assert!(false);
}
| true |
2b1ddea77fd9394248ad200f9962679dcb0d0606
|
Rust
|
Axect/Rust
|
/Tutorial/binary_search/src/main.rs
|
UTF-8
| 387 | 2.5625 | 3 |
[] |
no_license
|
use std::cmp::Ordering;
use peroxide::fuga::*;
fn main() {
let a = seq(0, 10, 1);
let b = gen_range(&a);
let x = 11f64;
let bs = b.binary_search_by(|r| {
if r.contains(&x) {
Ordering::Equal
} else if r.start > x {
Ordering::Greater
} else {
Ordering::Less
}
});
println!("{:?}", bs);
}
| true |
9b809e4f7bd0c0702ae7b75c03a9609bf0a21b8f
|
Rust
|
dlon/nftnl-rs
|
/nftnl/src/expr/immediate.rs
|
UTF-8
| 3,674 | 2.953125 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
use super::Expression;
use libc;
use nftnl_sys::{self as sys, libc::{c_char, c_void}};
use std::{ffi::{CStr, CString}, mem::size_of_val};
/// An immediate expression. Used to set immediate data.
/// Verdicts are handled separately by [Verdict].
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct Immediate<T> {
pub data: T,
}
impl<T> Expression for Immediate<T> {
fn to_expr(&self) -> *mut sys::nftnl_expr {
unsafe {
let expr = try_alloc!(sys::nftnl_expr_alloc(
b"immediate\0" as *const _ as *const c_char
));
sys::nftnl_expr_set_u32(
expr,
sys::NFTNL_EXPR_IMM_DREG as u16,
libc::NFT_REG_1 as u32,
);
sys::nftnl_expr_set(
expr,
sys::NFTNL_EXPR_IMM_DATA as u16,
&self.data as *const _ as *const c_void,
size_of_val(&self.data) as u32,
);
expr
}
}
}
#[macro_export]
macro_rules! nft_expr_immediate {
(data $value:expr) => {
$crate::expr::Immediate { data: $value }
};
}
/// A verdict expression. In the background actually an "Immediate" expression in nftnl terms,
/// but here it's simplified to only represent a verdict.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum Verdict {
/// Silently drop the packet.
Drop,
/// Accept the packet and let it pass.
Accept,
Queue,
Continue,
Break,
Jump {
chain: CString,
},
Goto {
chain: CString,
},
Return,
}
impl Verdict {
fn verdict_const(&self) -> i32 {
match *self {
Verdict::Drop => libc::NF_DROP,
Verdict::Accept => libc::NF_ACCEPT,
Verdict::Queue => libc::NF_QUEUE,
Verdict::Continue => libc::NFT_CONTINUE,
Verdict::Break => libc::NFT_BREAK,
Verdict::Jump { .. } => libc::NFT_JUMP,
Verdict::Goto { .. } => libc::NFT_GOTO,
Verdict::Return => libc::NFT_RETURN,
}
}
fn chain(&self) -> Option<&CStr> {
match *self {
Verdict::Jump { ref chain } => Some(chain.as_c_str()),
Verdict::Goto { ref chain } => Some(chain.as_c_str()),
_ => None,
}
}
}
impl Expression for Verdict {
fn to_expr(&self) -> *mut sys::nftnl_expr {
unsafe {
let expr = try_alloc!(sys::nftnl_expr_alloc(
b"immediate\0" as *const _ as *const c_char
));
sys::nftnl_expr_set_u32(
expr,
sys::NFTNL_EXPR_IMM_DREG as u16,
libc::NFT_REG_VERDICT as u32,
);
if let Some(chain) = self.chain() {
sys::nftnl_expr_set_str(expr, sys::NFTNL_EXPR_IMM_CHAIN as u16, chain.as_ptr());
}
sys::nftnl_expr_set_u32(
expr,
sys::NFTNL_EXPR_IMM_VERDICT as u16,
self.verdict_const() as u32,
);
expr
}
}
}
#[macro_export]
macro_rules! nft_expr_verdict {
(drop) => {
$crate::expr::Verdict::Drop
};
(accept) => {
$crate::expr::Verdict::Accept
};
(queue) => {
$crate::expr::Verdict::Queue
};
(continue) => {
$crate::expr::Verdict::Continue
};
(break) => {
$crate::expr::Verdict::Break
};
(jump $chain:expr) => {
$crate::expr::Verdict::Jump { chain: $chain }
};
(goto $chain:expr) => {
$crate::expr::Verdict::Goto { chain: $chain }
};
(return) => {
$crate::expr::Verdict::Return
};
}
| true |
309b57b59140943ed167eccc39a129fcfb741ef2
|
Rust
|
pbzweihander/rust-trending-discord
|
/src/config.rs
|
UTF-8
| 791 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
use crate::{Error, Repo};
#[derive(Clone, Deserialize, Debug)]
pub struct Config {
pub redis_url: String,
pub webhook_url: String,
pub post_ttl: usize,
pub fetch_interval: usize,
pub post_interval: usize,
pub blacklist: Blacklist,
}
#[derive(Clone, Deserialize, Debug)]
pub struct Blacklist {
pub names: Vec<String>,
pub authors: Vec<String>,
}
impl Config {
pub fn from_file(filename: &str) -> Result<Self, Error> {
let mut settings = configc::Config::default();
settings.merge(configc::File::with_name(filename))?;
Ok(settings.try_into()?)
}
}
impl Blacklist {
pub fn is_listed(&self, repo: &Repo) -> bool {
self.authors.iter().any(|a| &repo.author == a) || self.names.iter().any(|n| &repo.name == n)
}
}
| true |
b4254fb9aa7036770ca7d6219c7681cb480db89c
|
Rust
|
toddself/edit-text
|
/oatie/src/doc.rs
|
UTF-8
| 1,673 | 2.53125 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
//! Defines document types, operation types, and cursor types.
use serde::de::{
self,
SeqAccess,
Visitor,
};
use serde::ser::SerializeSeq;
use serde::{
Deserialize,
Deserializer,
Serialize,
Serializer,
};
use std::collections::HashMap;
use std::fmt;
use std::ops::Range;
use std::sync::atomic::AtomicUsize;
use std::sync::Arc;
// Re-exports
pub use super::place::*;
pub use super::string::*;
pub type Attrs = HashMap<String, String>;
pub type DocSpan = Vec<DocElement>;
pub type DelSpan = Vec<DelElement>;
pub type AddSpan = Vec<AddElement>;
pub type CurSpan = Vec<CurElement>;
pub type Op = (DelSpan, AddSpan);
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum DocElement {
DocChars(DocString),
DocGroup(Attrs, DocSpan),
}
pub use self::DocElement::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Doc(pub Vec<DocElement>);
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum DelElement {
DelSkip(usize),
DelWithGroup(DelSpan),
DelChars(usize),
DelGroup(DelSpan),
DelStyles(usize, StyleSet),
// TODO Implement these
// DelGroupAll,
// DelMany(usize),
// DelObject,
}
pub use self::DelElement::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum AddElement {
AddSkip(usize),
AddWithGroup(AddSpan),
AddChars(DocString),
AddGroup(Attrs, AddSpan),
AddStyles(usize, StyleMap),
}
pub use self::AddElement::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum CurElement {
CurSkip(usize),
CurWithGroup(CurSpan),
CurGroup,
CurChar,
}
pub use self::CurElement::*;
| true |
c6da6ac6602cae40f99454aaa60659334939ec2e
|
Rust
|
jsimonrichard/sudoku-solver
|
/src/main.rs
|
UTF-8
| 1,185 | 2.859375 | 3 |
[] |
no_license
|
use clap::{Arg,App};
mod puzzle;
mod parse_puzzle;
mod solve;
fn main() {
/*
A rather slow sudoku solver
*/
// Parse program arguments
let matches = App::new("SudokuSolver")
.version("0.1.0")
.author("J. Simon Richard <[email protected]>")
.about("Solves a sudoku grid lazily (puzzle in the style of the puzzles
at http://lipas.uwasa.fi/~timan/sudoku/)")
.arg(Arg::with_name("file")
.short("f")
.long("file")
.takes_value(true)
.required(false)
.help("Get a puzzle from a file"))
.get_matches();
// Get the puzzle
let my_puzzle;
if matches.is_present("file") {
// Get puzzle from file
my_puzzle = parse_puzzle::puzzle_from_file(
matches.value_of("file").unwrap()
); // Read the contents of the file
} else {
// Get data from stdin
my_puzzle = parse_puzzle::puzzle_from_stdin();
};
// Solve the puzzle
let solved_puzzle = solve::solve(my_puzzle);
// Print the puzzle
puzzle::print_puzzle(&solved_puzzle);
}
| true |
4ac18dde3fe82c3a9c66a1d0825e4950f8f6c57e
|
Rust
|
Tarrask/hue.rs
|
/src/disco.rs
|
UTF-8
| 1,457 | 2.53125 | 3 |
[] |
no_license
|
use crate::{HueError, HueError::DiscoveryError};
use serde_json::{Map, Value};
use std::net::IpAddr;
pub fn discover_hue_bridge() -> Result<IpAddr, HueError> {
let n_upnp_result = discover_hue_bridge_n_upnp();
if n_upnp_result.is_err() {
discover_hue_bridge_upnp()
} else {
n_upnp_result
}
}
pub fn discover_hue_bridge_n_upnp() -> Result<IpAddr, HueError> {
let objects: Vec<Map<String, Value>> =
reqwest::blocking::get("https://discovery.meethue.com/")?.json()?;
if objects.len() == 0 {
Err(DiscoveryError {
msg: "expected non-empty array".into(),
})?
}
let ref object = objects[0];
let ip = object.get("internalipaddress").ok_or(DiscoveryError {
msg: "Expected internalipaddress".into(),
})?;
Ok(ip
.as_str()
.ok_or(DiscoveryError {
msg: "expect a string in internalipaddress".into(),
})?
.parse()?)
}
pub fn discover_hue_bridge_upnp() -> Result<IpAddr, HueError> {
// use 'IpBridge' as a marker and a max duration of 5s as per
// https://developers.meethue.com/develop/application-design-guidance/hue-bridge-discovery/
Ok(
ssdp_probe::ssdp_probe_v4(br"IpBridge", 1, std::time::Duration::from_secs(5))?
.first()
.map(|it| it.to_owned().into())
.ok_or(DiscoveryError {
msg: "could not find bridge".into(),
})?,
)
}
| true |
c5bccc3f192d998a1372dc9dd979dd68dfad0334
|
Rust
|
liusongde/rftp
|
/src/connect.rs
|
UTF-8
| 7,001 | 3.015625 | 3 |
[
"MIT"
] |
permissive
|
use crate::utils::{ErrorKind, Result};
use base64;
use dirs::home_dir;
use rpassword::prompt_password_stdout;
use std::collections::HashSet;
use std::io::{stdin, stdout, Write};
use std::net::TcpStream;
/// Create an authenticated `ssh2::Session`.
pub fn create_session(
destination: &str,
username: &str,
port: Option<&str>,
verbose: bool,
) -> Result<ssh2::Session> {
let tcp = if let Some(port) = port {
let port = port.parse::<u16>().or(Err(ErrorKind::InvalidPortNumber))?;
if verbose {
println!("Attempting to connect to {}:{}.", destination, port);
}
TcpStream::connect((destination, port))?
} else {
if verbose {
println!("Attempting to connect to {}.", destination);
}
TcpStream::connect(destination).unwrap_or(TcpStream::connect((destination, 22))?)
};
let port = tcp.peer_addr()?.port();
let mut session = ssh2::Session::new()?;
session.set_timeout(10000);
session.set_compress(true);
session.set_tcp_stream(tcp);
session.handshake()?;
let session = authenticate_host(session, destination, port, verbose)?;
let session = authenticate_session(session, username)?;
if verbose {
println!("Connected to host {}@{}:{}.", username, destination, port);
}
Ok(session)
}
/// Authenticate the identity of the host by checking the host key in `~/.ssh/known_hosts`.
fn authenticate_host(
session: ssh2::Session,
destination: &str,
port: u16,
verbose: bool,
) -> Result<ssh2::Session> {
let mut known_hosts = session.known_hosts()?;
let known_hosts_path = home_dir()
.ok_or(ErrorKind::UnableToFindHomeDirectory)?
.join(".ssh/known_hosts");
known_hosts.read_file(&known_hosts_path, ssh2::KnownHostFileKind::OpenSSH)?;
let (key, key_type) = session.host_key().ok_or(ErrorKind::HostKeyNotFound)?;
match known_hosts.check_port(destination, port, key) {
ssh2::CheckResult::Match => {
if verbose {
println!(
"Host key for {}:{} matches entry in {:?}.",
destination, port, known_hosts_path
);
}
Ok(session)
}
ssh2::CheckResult::NotFound => {
let fingerprint = session
.host_key_hash(ssh2::HashType::Sha256)
.map(|hash| ("SHA256", hash))
.or_else(|| {
session
.host_key_hash(ssh2::HashType::Sha1)
.map(|hash| ("SHA128", hash))
})
.map(|(hash_type, fingerprint)| {
format!("{}:{}", hash_type, base64::encode(fingerprint))
})
.ok_or(ErrorKind::HostFingerprintNotFound)?;
println!(
"No matching host key for {}:{} was not found in {:?}.",
destination, port, known_hosts_path
);
println!("Fingerprint: {}", fingerprint);
print!("Would you like to add it (yes/no)? ");
stdout().flush()?;
let mut input = String::new();
stdin().read_line(&mut input)?;
match input.trim().as_ref() {
"Y" | "y" | "YES" | "Yes" | "yes" => {
known_hosts.add(destination, key, "", key_type.into())?;
known_hosts.write_file(&known_hosts_path, ssh2::KnownHostFileKind::OpenSSH)?;
Ok(session)
}
_ => Err(ErrorKind::HostAuthenticationError(
destination.to_string(),
port,
)),
}
}
ssh2::CheckResult::Mismatch => {
eprintln!("####################################################");
eprintln!("# WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! #");
eprintln!("####################################################");
Err(ErrorKind::MismatchedFingerprint)
}
ssh2::CheckResult::Failure => Err(ErrorKind::HostFileCheckError),
}
}
/// Authenticate the session using a password or public key.
fn authenticate_session(session: ssh2::Session, username: &str) -> Result<ssh2::Session> {
let mut has_entered_password = false;
for _ in 0..3 {
if session.authenticated() {
break;
}
let auth_methods: HashSet<&str> = session.auth_methods(username)?.split(",").collect();
if auth_methods.contains("publickey") {
session.userauth_agent(username).ok();
}
if !has_entered_password && !session.authenticated() && auth_methods.contains("password") {
authenticate_with_password(&session, username)?;
// We only want to prompt the user for a password for one round.
has_entered_password = true;
}
// if !session.authenticated() && auth_methods.contains("keyboard-interactive") {
// // TODO: Need to test.
// struct Prompter;
// impl ssh2::KeyboardInteractivePrompt for Prompter {
// fn prompt(
// &mut self,
// _username: &str,
// instructions: &str,
// prompts: &[ssh2::Prompt],
// ) -> Vec<String> {
// prompts
// .iter()
// .map(|p| {
// println!("{}", instructions);
// if p.echo {
// let mut input = String::new();
// if stdin().read_line(&mut input).is_ok() {
// input
// } else {
// String::new()
// }
// } else {
// prompt_password_stdout(&p.text).unwrap_or_else(|_| String::new())
// }
// })
// .collect()
// }
// }
// let mut prompter = Prompter;
// session.userauth_keyboard_interactive(username, &mut prompter)?;
// }
}
if session.authenticated() {
Ok(session)
} else {
Err(ErrorKind::UserAuthenticationError(username.to_string()))
}
}
/// Attempt to authenticate the session by prompting the user for a password three times.
fn authenticate_with_password(session: &ssh2::Session, username: &str) -> Result<()> {
for _ in 0..3 {
let password = prompt_password_stdout("🔐 Password: ")?;
if session.userauth_password(username, &password).is_ok() {
return Ok(());
} else {
eprintln!("❌ Permission denied, please try again.");
}
}
Err(ErrorKind::UserAuthenticationError(username.to_string()))
}
| true |
8b0ff29612a25822ffeed874c646a33178eacb84
|
Rust
|
skerkewitz/advent_of_code_2020
|
/src/main_day21.rs
|
UTF-8
| 4,224 | 2.9375 | 3 |
[
"MIT"
] |
permissive
|
use std::collections::{HashMap, HashSet};
use lazy_static::lazy_static;
use regex::Regex;
use crate::utils;
type Ingredient = String;
type Allergen = String;
type IngredientList = Vec<Ingredient>;
type IngredientSet = HashSet<Ingredient>;
type AllergenList = Vec<Allergen>;
type AllergenSet = HashSet<Allergen>;
lazy_static! { static ref RE: Regex = Regex::new(r"^(.*) \(contains (.*)\)$").unwrap(); }
fn solve(input: &Vec<(HashSet<String>, HashSet<String>)>) -> (IngredientSet, HashMap<Ingredient, Allergen>, HashMap<Allergen, Ingredient>) {
let mut data = input.clone();
let mut ingrediants_with_no_allergen = HashSet::new() as IngredientSet;
let mut ingrediants_allergens_map = HashMap::new() as HashMap<Ingredient, Allergen>;
let mut allergens_ingredients_map = HashMap::new() as HashMap<Allergen, Ingredient>;
loop {
let ingredients_set = data.iter().map(|x| x.0.clone()).flatten().collect::<IngredientSet>();
step_solve(&data, ingredients_set, &mut ingrediants_with_no_allergen, &mut ingrediants_allergens_map, &mut allergens_ingredients_map);
// simplify by removing already solved items
data = data.iter()
.map(|x| {
let mut ingredients = x.0.clone();
ingrediants_with_no_allergen.iter().for_each(|i| { ingredients.remove(i); });
ingrediants_allergens_map.keys().for_each(|k| { ingredients.remove(k); });
let mut allergens = x.1.clone();
allergens_ingredients_map.keys().for_each(|k| {allergens.remove(k);});
(ingredients, allergens)
})
.filter(|x| !x.0.is_empty() && !x.1.is_empty())
.collect();
if data.is_empty() { break; }
}
(ingrediants_with_no_allergen, ingrediants_allergens_map, allergens_ingredients_map)
}
fn step_solve(data: &Vec<(HashSet<String>, HashSet<String>)>, ingredients_set: HashSet<String>, ingrediants_with_no_allergen: &mut HashSet<String>, ingrediants_allergens_map: &mut HashMap<String, String>, allergens_ingredients_map: &mut HashMap<String, String>) {
for ingredient in ingredients_set {
let possible_allergens = data.iter()
.filter(|x| x.0.contains(&ingredient))
.map(|x| x.1.clone()).flatten().collect::<AllergenSet>();
let ingredient_matches = possible_allergens.iter()
.cloned()
.filter(|possible_allergen| {
data.iter()
.filter(|x| x.1.contains(possible_allergen))
.all(|x| x.0.contains(&ingredient))
})
.collect::<AllergenSet>();
if ingredient_matches.is_empty() {
ingrediants_with_no_allergen.insert(ingredient.clone());
} else if ingredient_matches.len() == 1 {
let allergen = ingredient_matches.iter().next().unwrap();
ingrediants_allergens_map.insert(ingredient.clone(), allergen.to_owned());
allergens_ingredients_map.insert(allergen.to_owned(), ingredient.clone());
}
}
}
pub fn main() -> std::io::Result<()> {
fn parse_line(s: &String) -> (IngredientSet, AllergenSet) {
let matches = RE.captures(s).unwrap();
let ingredients = matches.get(1).unwrap().as_str().split(" ").map(|s| s.to_string()).collect::<IngredientSet>();
let allergen = matches.get(2).unwrap().as_str().split(", ").map(|s| s.to_string()).collect::<AllergenSet>();
(ingredients, allergen)
}
let data = utils::read_lines_from_file("inputs/day21/input.txt")?.iter()
.map(parse_line)
.collect::<Vec<(IngredientSet, AllergenSet)>>();
/* Solve the list */
let solution = solve(&data);
let result1 = solution.0.iter()
.map(|ingredient| data.iter().filter(|x| x.0.contains(ingredient)).count())
.sum::<usize>();
println!("Result day21 part1: {}", result1);
let mut allergens = solution.2.keys().cloned().collect::<AllergenList>();
allergens.sort();
let result2 = allergens.iter()
.map(|allergen| solution.2.get(allergen).unwrap())
.cloned().collect::<IngredientList>().join(",");
println!("Result day21 part2: {}", result2);
Ok(())
}
| true |
9160c19a5ddd51135355e617397796a3791ae897
|
Rust
|
h4hany/leetcode
|
/python_solutions/896.monotonic-array.rs
|
UTF-8
| 2,448 | 3.234375 | 3 |
[] |
no_license
|
/*
* @lc app=leetcode id=896 lang=rust
*
* [896] Monotonic Array
*
* https://leetcode.com/problems/monotonic-array/description/
*
* algorithms
* Easy (56.80%)
* Total Accepted: 82.2K
* Total Submissions: 144.6K
* Testcase Example: '[1,2,2,3]'
*
* An array is monotonic if it is either monotone increasing or monotone
* decreasing.
*
* An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array
* A is monotone decreasing if for all i <= j, A[i] >= A[j].
*
* Return true if and only if the given array A is monotonic.
*
*
*
*
*
*
*
* Example 1:
*
*
* Input: [1,2,2,3]
* Output: true
*
*
*
* Example 2:
*
*
* Input: [6,5,4,4]
* Output: true
*
*
*
* Example 3:
*
*
* Input: [1,3,2]
* Output: false
*
*
*
* Example 4:
*
*
* Input: [1,2,4,5]
* Output: true
*
*
*
* Example 5:
*
*
* Input: [1,1,1]
* Output: true
*
*
*
*
* Note:
*
*
* 1 <= A.length <= 50000
* -100000 <= A[i] <= 100000
*
*
*
*
*
*
*
*/
impl Solution {
pub fn is_monotonic(a: Vec<i32>) -> bool {
let (mut inc, mut dec) = (true, true);
for i in 0..a.len()-1{
inc &= a[i] <= a[i+1];
dec &= a[i] >= a[i+1];
}
inc || dec
}
}
// pub structSolution;
use std::collections::HashMap;
use std::collections::HashSet;
use std::fmt::Debug;
use std::hash::Hash;
use std::iter::FromIterator;
// use std::collections::VecDeque;
// use std::collections::BTreeMap;
#[allow(dead_code)]
pub fn print_map<K: Debug + Eq + Hash, V: Debug>(map: &HashMap<K, V>) {
for (k, v) in map.iter() {
println!("{:?}: {:?}", k, v);
}
}
#[allow(dead_code)]
pub fn say_vec(nums: Vec<i32>){
println!("{:?}", nums);
}
#[allow(dead_code)]
pub fn char_frequency(s: String) -> HashMap<char, i32> {
let mut res:HashMap<char, i32> = HashMap::new();
for c in s.chars(){
*res.entry(c).or_insert(0) += 1;
}
res
}
#[allow(dead_code)]
pub fn vec_counter(arr: Vec<i32>) -> HashMap<i32, i32> {
let mut c = HashMap::new();
for n in arr { *c.entry(n).or_insert(0) += 1; }
c
}
#[allow(dead_code)]
pub fn vec_to_hashset(arr: Vec<i32>) -> HashSet<i32> {
HashSet::from_iter(arr.iter().cloned())
}
#[allow(dead_code)]
pub fn int_to_char(n: i32) -> char {
// Convert number 0 to a, 1 to b, ...
assert!(n >= 0 && n <= 25);
(n as u8 + 'a' as u8) as char
}
| true |
4bb77cede0fbe64caf30f70c52f90e65a972ecf3
|
Rust
|
solana-labs/solana
|
/accounts-db/src/stake_rewards.rs
|
UTF-8
| 3,594 | 2.75 | 3 |
[
"Apache-2.0"
] |
permissive
|
//! Code for stake and vote rewards
use {
crate::{accounts_db::IncludeSlotInHash, storable_accounts::StorableAccounts},
solana_sdk::{
account::AccountSharedData, clock::Slot, pubkey::Pubkey, reward_type::RewardType,
},
};
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, AbiExample, Clone, Copy)]
pub struct RewardInfo {
pub reward_type: RewardType,
/// Reward amount
pub lamports: i64,
/// Account balance in lamports after `lamports` was applied
pub post_balance: u64,
/// Vote account commission when the reward was credited, only present for voting and staking rewards
pub commission: Option<u8>,
}
#[derive(AbiExample, Debug, Serialize, Deserialize, Clone, PartialEq)]
pub struct StakeReward {
pub stake_pubkey: Pubkey,
pub stake_reward_info: RewardInfo,
pub stake_account: AccountSharedData,
}
impl StakeReward {
pub fn get_stake_reward(&self) -> i64 {
self.stake_reward_info.lamports
}
}
/// allow [StakeReward] to be passed to `StoreAccounts` directly without copies or vec construction
impl<'a> StorableAccounts<'a, AccountSharedData> for (Slot, &'a [StakeReward], IncludeSlotInHash) {
fn pubkey(&self, index: usize) -> &Pubkey {
&self.1[index].stake_pubkey
}
fn account(&self, index: usize) -> &AccountSharedData {
&self.1[index].stake_account
}
fn slot(&self, _index: usize) -> Slot {
// per-index slot is not unique per slot when per-account slot is not included in the source data
self.target_slot()
}
fn target_slot(&self) -> Slot {
self.0
}
fn len(&self) -> usize {
self.1.len()
}
fn include_slot_in_hash(&self) -> IncludeSlotInHash {
self.2
}
}
#[cfg(feature = "dev-context-only-utils")]
use {
rand::Rng,
solana_sdk::{
account::WritableAccount,
rent::Rent,
signature::{Keypair, Signer},
},
solana_stake_program::stake_state,
solana_vote_program::vote_state,
};
// These functions/fields are only usable from a dev context (i.e. tests and benches)
#[cfg(feature = "dev-context-only-utils")]
impl StakeReward {
pub fn new_random() -> Self {
let mut rng = rand::thread_rng();
let rent = Rent::free();
let validator_pubkey = solana_sdk::pubkey::new_rand();
let validator_stake_lamports = 20;
let validator_staking_keypair = Keypair::new();
let validator_voting_keypair = Keypair::new();
let validator_vote_account = vote_state::create_account(
&validator_voting_keypair.pubkey(),
&validator_pubkey,
10,
validator_stake_lamports,
);
let validator_stake_account = stake_state::create_account(
&validator_staking_keypair.pubkey(),
&validator_voting_keypair.pubkey(),
&validator_vote_account,
&rent,
validator_stake_lamports,
);
Self {
stake_pubkey: Pubkey::new_unique(),
stake_reward_info: RewardInfo {
reward_type: RewardType::Staking,
lamports: rng.gen_range(1..200),
post_balance: 0, /* unused atm */
commission: None, /* unused atm */
},
stake_account: validator_stake_account,
}
}
pub fn credit(&mut self, amount: u64) {
self.stake_reward_info.lamports = amount as i64;
self.stake_reward_info.post_balance += amount;
self.stake_account.checked_add_lamports(amount).unwrap();
}
}
| true |
3da2ba47311e2006ac2166870173230fd148a059
|
Rust
|
apache/incubator-teaclave-sgx-sdk
|
/sgx_tstd/src/sync/mpsc/spsc_queue.rs
|
UTF-8
| 10,395 | 2.96875 | 3 |
[
"BSD-3-Clause",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License..
//! A single-producer single-consumer concurrent queue
//!
//! This module contains the implementation of an SPSC queue which can be used
//! concurrently between two threads. This data structure is safe to use and
//! enforces the semantics that there is one pusher and one popper.
// https://www.1024cores.net/home/lock-free-algorithms/queues/unbounded-spsc-queue
use core::cell::UnsafeCell;
use core::ptr;
use crate::boxed::Box;
use crate::sync::atomic::{AtomicPtr, AtomicUsize, Ordering};
use super::cache_aligned::CacheAligned;
// Node within the linked list queue of messages to send
struct Node<T> {
// FIXME: this could be an uninitialized T if we're careful enough, and
// that would reduce memory usage (and be a bit faster).
// is it worth it?
value: Option<T>, // nullable for re-use of nodes
cached: bool, // This node goes into the node cache
next: AtomicPtr<Node<T>>, // next node in the queue
}
/// The single-producer single-consumer queue. This structure is not cloneable,
/// but it can be safely shared in an Arc if it is guaranteed that there
/// is only one popper and one pusher touching the queue at any one point in
/// time.
pub struct Queue<T, ProducerAddition = (), ConsumerAddition = ()> {
// consumer fields
consumer: CacheAligned<Consumer<T, ConsumerAddition>>,
// producer fields
producer: CacheAligned<Producer<T, ProducerAddition>>,
}
struct Consumer<T, Addition> {
tail: UnsafeCell<*mut Node<T>>, // where to pop from
tail_prev: AtomicPtr<Node<T>>, // where to pop from
cache_bound: usize, // maximum cache size
cached_nodes: AtomicUsize, // number of nodes marked as cacheable
addition: Addition,
}
struct Producer<T, Addition> {
head: UnsafeCell<*mut Node<T>>, // where to push to
first: UnsafeCell<*mut Node<T>>, // where to get new nodes from
tail_copy: UnsafeCell<*mut Node<T>>, // between first/tail
addition: Addition,
}
unsafe impl<T: Send, P: Send + Sync, C: Send + Sync> Send for Queue<T, P, C> {}
unsafe impl<T: Send, P: Send + Sync, C: Send + Sync> Sync for Queue<T, P, C> {}
impl<T> Node<T> {
fn new() -> *mut Node<T> {
Box::into_raw(box Node {
value: None,
cached: false,
next: AtomicPtr::new(ptr::null_mut::<Node<T>>()),
})
}
}
impl<T, ProducerAddition, ConsumerAddition> Queue<T, ProducerAddition, ConsumerAddition> {
/// Creates a new queue. With given additional elements in the producer and
/// consumer portions of the queue.
///
/// Due to the performance implications of cache-contention,
/// we wish to keep fields used mainly by the producer on a separate cache
/// line than those used by the consumer.
/// Since cache lines are usually 64 bytes, it is unreasonably expensive to
/// allocate one for small fields, so we allow users to insert additional
/// fields into the cache lines already allocated by this for the producer
/// and consumer.
///
/// This is unsafe as the type system doesn't enforce a single
/// consumer-producer relationship. It also allows the consumer to `pop`
/// items while there is a `peek` active due to all methods having a
/// non-mutable receiver.
///
/// # Arguments
///
/// * `bound` - This queue implementation is implemented with a linked
/// list, and this means that a push is always a malloc. In
/// order to amortize this cost, an internal cache of nodes is
/// maintained to prevent a malloc from always being
/// necessary. This bound is the limit on the size of the
/// cache (if desired). If the value is 0, then the cache has
/// no bound. Otherwise, the cache will never grow larger than
/// `bound` (although the queue itself could be much larger.
pub unsafe fn with_additions(
bound: usize,
producer_addition: ProducerAddition,
consumer_addition: ConsumerAddition,
) -> Self {
let n1 = Node::new();
let n2 = Node::new();
(*n1).next.store(n2, Ordering::Relaxed);
Queue {
consumer: CacheAligned::new(Consumer {
tail: UnsafeCell::new(n2),
tail_prev: AtomicPtr::new(n1),
cache_bound: bound,
cached_nodes: AtomicUsize::new(0),
addition: consumer_addition,
}),
producer: CacheAligned::new(Producer {
head: UnsafeCell::new(n2),
first: UnsafeCell::new(n1),
tail_copy: UnsafeCell::new(n1),
addition: producer_addition,
}),
}
}
/// Pushes a new value onto this queue. Note that to use this function
/// safely, it must be externally guaranteed that there is only one pusher.
pub fn push(&self, t: T) {
unsafe {
// Acquire a node (which either uses a cached one or allocates a new
// one), and then append this to the 'head' node.
let n = self.alloc();
assert!((*n).value.is_none());
(*n).value = Some(t);
(*n).next.store(ptr::null_mut(), Ordering::Relaxed);
(**self.producer.head.get()).next.store(n, Ordering::Release);
*(&self.producer.head).get() = n;
}
}
unsafe fn alloc(&self) -> *mut Node<T> {
// First try to see if we can consume the 'first' node for our uses.
if *self.producer.first.get() != *self.producer.tail_copy.get() {
let ret = *self.producer.first.get();
*self.producer.0.first.get() = (*ret).next.load(Ordering::Relaxed);
return ret;
}
// If the above fails, then update our copy of the tail and try
// again.
*self.producer.0.tail_copy.get() = self.consumer.tail_prev.load(Ordering::Acquire);
if *self.producer.first.get() != *self.producer.tail_copy.get() {
let ret = *self.producer.first.get();
*self.producer.0.first.get() = (*ret).next.load(Ordering::Relaxed);
return ret;
}
// If all of that fails, then we have to allocate a new node
// (there's nothing in the node cache).
Node::new()
}
/// Attempts to pop a value from this queue. Remember that to use this type
/// safely you must ensure that there is only one popper at a time.
pub fn pop(&self) -> Option<T> {
unsafe {
// The `tail` node is not actually a used node, but rather a
// sentinel from where we should start popping from. Hence, look at
// tail's next field and see if we can use it. If we do a pop, then
// the current tail node is a candidate for going into the cache.
let tail = *self.consumer.tail.get();
let next = (*tail).next.load(Ordering::Acquire);
if next.is_null() {
return None;
}
assert!((*next).value.is_some());
let ret = (*next).value.take();
*self.consumer.0.tail.get() = next;
if self.consumer.cache_bound == 0 {
self.consumer.tail_prev.store(tail, Ordering::Release);
} else {
let cached_nodes = self.consumer.cached_nodes.load(Ordering::Relaxed);
if cached_nodes < self.consumer.cache_bound && !(*tail).cached {
self.consumer.cached_nodes.store(cached_nodes, Ordering::Relaxed);
(*tail).cached = true;
}
if (*tail).cached {
self.consumer.tail_prev.store(tail, Ordering::Release);
} else {
(*self.consumer.tail_prev.load(Ordering::Relaxed))
.next
.store(next, Ordering::Relaxed);
// We have successfully erased all references to 'tail', so
// now we can safely drop it.
let _: Box<Node<T>> = Box::from_raw(tail);
}
}
ret
}
}
/// Attempts to peek at the head of the queue, returning `None` if the queue
/// has no data currently
///
/// # Warning
/// The reference returned is invalid if it is not used before the consumer
/// pops the value off the queue. If the producer then pushes another value
/// onto the queue, it will overwrite the value pointed to by the reference.
pub fn peek(&self) -> Option<&mut T> {
// This is essentially the same as above with all the popping bits
// stripped out.
unsafe {
let tail = *self.consumer.tail.get();
let next = (*tail).next.load(Ordering::Acquire);
if next.is_null() { None } else { (*next).value.as_mut() }
}
}
pub fn producer_addition(&self) -> &ProducerAddition {
&self.producer.addition
}
pub fn consumer_addition(&self) -> &ConsumerAddition {
&self.consumer.addition
}
}
impl<T, ProducerAddition, ConsumerAddition> Drop for Queue<T, ProducerAddition, ConsumerAddition> {
fn drop(&mut self) {
unsafe {
let mut cur = *self.producer.first.get();
while !cur.is_null() {
let next = (*cur).next.load(Ordering::Relaxed);
let _n: Box<Node<T>> = Box::from_raw(cur);
cur = next;
}
}
}
}
| true |
d16a55167ba932efb99b6a535e8540be17c21e44
|
Rust
|
roblass/learning
|
/rust/chapter_3/control_flow/src/main.rs
|
UTF-8
| 1,468 | 3.875 | 4 |
[] |
no_license
|
use std::io;
fn main() {
println!("Give me a number: ");
let mut x = String::new();
io::stdin().read_line(&mut x);
let x: usize = x.trim().parse().expect("wtf");
if x <= 5 {
println!("It's too small");
}else{
println!("It's big enough");
}
let even = if x % 2 == 0 {true} else {false};
if even {
println!("It is even!");
} else {
println!("It is odd!");
}
let odd = x % 2 == 1;
if odd {
println!("It is odd!");
} else {
println!("It is even!");
}
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2
}
};
println!("It's {result}, which is {counter} * 2");
let mut i = 0;
while i < 10 {
let mut j = 0;
while j < i {
print!("*");
j = j + 1;
}
println!("");
i = i + 1;
}
let months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
];
for month in months {
println!("It's {month}!");
}
for number in (1..10).rev() {
println!("t-minus {number} and counting");
}
println!("Blast off!");
for number in 1..10 {
println!("{number} since launch");
}
}
| true |
ea7091c842d7eac0a9d0e5fad1b59c283f4fbbbd
|
Rust
|
noshi91/n91lib_rs
|
/src/other/cmp_assign.rs
|
UTF-8
| 389 | 2.953125 | 3 |
[
"CC0-1.0"
] |
permissive
|
pub trait MinAssign: Ord + Sized {
fn min_assign(&mut self, rhs: Self) {
if *self > rhs {
*self = rhs;
}
}
}
impl<T> MinAssign for T where T: Ord + Sized {}
pub trait MaxAssign: Ord + Sized {
fn max_assign(&mut self, rhs: Self) {
if *self < rhs {
*self = rhs;
}
}
}
impl<T> MaxAssign for T where T: Ord + Sized {}
| true |
c67f4616b3e22adf4654c4a5348dd320785f0ab1
|
Rust
|
Itorius/AoC-2020
|
/Day3/day3.rs
|
UTF-8
| 1,180 | 3.296875 | 3 |
[] |
no_license
|
use std::fs;
use std::ops::Deref;
use std::borrow::Borrow;
pub(crate) fn run() {
let contents = fs::read_to_string("/home/itorius/Development/AoC/Day3/input.txt").expect("Something went wrong reading the file");
let split: Vec<&str> = contents.lines().collect();
let width = split[0].chars().count();
let height = split.len();
let mut array: Vec<Vec<char>> = Vec::new();
for (i, str) in split.iter().enumerate() {
let line: Vec<char> = (*str).chars().collect();
array.push(line);
}
let temp1 = GetTreesForSlope(array.borrow(), 1, 1);
let temp2 = GetTreesForSlope(array.borrow(), 3, 1);
let temp3 = GetTreesForSlope(array.borrow(), 5, 1);
let temp4 = GetTreesForSlope(array.borrow(), 7, 1);
let temp5 = GetTreesForSlope(array.borrow(), 1, 2);
let sum: u64 = temp1 * temp2 * temp3 * temp4 * temp5;
println!("{0}", sum)
}
fn GetTreesForSlope(array: &Vec<Vec<char>>, traverseX: usize, traverseY: usize) -> u64 {
let mut posX = 0;
let mut posY = 0;
let height = array.len();
let width = array[0].len();
let mut sum = 0;
while posY < height {
if array[posY][posX % width] == '#' {
sum += 1;
}
posX += traverseX;
posY += traverseY;
}
sum
}
| true |
4cd1c6620cfb5df4fbcf33a95218b28daab46d8e
|
Rust
|
jacksonriley/aoc2020
|
/src/bin/02.rs
|
UTF-8
| 2,496 | 3.609375 | 4 |
[] |
no_license
|
use std::time::Instant;
#[macro_use]
extern crate serde_scan;
#[derive(Debug, Eq, PartialEq)]
struct PasswordRule<'a> {
lower: usize,
upper: usize,
letter: char,
password: &'a str,
}
impl<'a> PasswordRule<'a> {
fn from_str(line: &'a str) -> Option<Self> {
let parse_result: Result<(usize, usize, char, &str), _> = scan!("{}-{} {}: {}" <- line);
match parse_result {
Ok(parsed) => Some(Self {
lower: parsed.0,
upper: parsed.1,
letter: parsed.2,
password: parsed.3,
}),
Err(_) => None,
}
}
fn is_valid1(&self) -> bool {
let num_instances = self.password.chars().filter(|&c| c == self.letter).count();
(self.lower..=self.upper).contains(&num_instances)
}
fn is_valid2(&self) -> bool {
// Exactly one of the numbered positions must correspond to the
// letter, so use the XOR operator, ^.
(self.password.chars().nth(self.lower - 1) == Some(self.letter))
^ (self.password.chars().nth(self.upper - 1) == Some(self.letter))
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let now = Instant::now();
let input = std::fs::read_to_string("input/02")?;
let passwords = parse_input(&input);
println!("Part 1: {}", part_one(&passwords));
println!("Part 2: {}", part_two(&passwords));
println!("Time: {}µs", now.elapsed().as_micros());
Ok(())
}
fn parse_input(input: &str) -> Vec<PasswordRule> {
input.lines().filter_map(PasswordRule::from_str).collect()
}
fn part_one(passwords: &[PasswordRule]) -> usize {
passwords.iter().filter(|p| p.is_valid1()).count()
}
fn part_two(passwords: &[PasswordRule]) -> usize {
passwords.iter().filter(|p| p.is_valid2()).count()
}
#[test]
fn test_examples() {
let input = "1-3 a: abcde
1-3 b: cdefg
2-9 c: ccccccccc";
let expected = vec![
PasswordRule {
lower: 1,
upper: 3,
letter: 'a',
password: "abcde",
},
PasswordRule {
lower: 1,
upper: 3,
letter: 'b',
password: "cdefg",
},
PasswordRule {
lower: 2,
upper: 9,
letter: 'c',
password: "ccccccccc",
},
];
assert_eq!(parse_input(&input), expected);
assert_eq!(part_one(&expected), 2);
assert_eq!(part_two(&expected), 1);
}
| true |
b3c802cb90594de176c5d1247a700246cd2a30cd
|
Rust
|
abhyuditjain/aoc2020
|
/src/day6.rs
|
UTF-8
| 1,128 | 2.90625 | 3 |
[] |
no_license
|
use aoc_runner_derive::{aoc, aoc_generator};
use std::collections::HashSet;
#[aoc_generator(day6)]
pub fn input_generator(input: &str) -> Vec<Vec<String>> {
input
.split("\n\n")
.map(|group_answers| group_answers.lines().map(|str| str.to_string()).collect())
.collect()
}
#[aoc(day6, part1)]
pub fn solve_part1(input: &[Vec<String>]) -> usize {
input
.iter()
.map(|group_answers| {
group_answers
.iter()
.flat_map(|answer| answer.chars())
.collect::<HashSet<_>>()
.len()
})
.sum()
}
#[aoc(day6, part2)]
pub fn solve_part2(input: &[Vec<String>]) -> usize {
input
.iter()
.map(|group_answers| {
let answers = group_answers
.iter()
.map(|row| row.chars().collect::<HashSet<_>>())
.collect::<Vec<_>>();
let mut in_all = answers[0].clone();
for a in &answers[1..] {
in_all.retain(|ch| a.contains(ch));
}
in_all.len()
})
.sum()
}
| true |
6ff45c34cd072659286a2c2c0a6ef3b9baa0d6b6
|
Rust
|
Tarnadas/smmdb-api
|
/crates/smmdb-db/src/collections.rs
|
UTF-8
| 552 | 2.84375 | 3 |
[] |
no_license
|
pub enum Collections {
Courses,
CourseData,
Courses2,
Course2Data,
Accounts,
Votes,
Meta,
}
impl Collections {
pub fn as_str(&self) -> &str {
match *self {
Collections::Courses => "courses",
Collections::CourseData => "courseData",
Collections::Courses2 => "courses2",
Collections::Course2Data => "course2Data",
Collections::Accounts => "accounts",
Collections::Votes => "votes",
Collections::Meta => "meta",
}
}
}
| true |
a11f881c4f8da334f1b26ee898e8b65140c1046f
|
Rust
|
eranfu/leetcode
|
/examples/502_ipo.rs
|
UTF-8
| 1,602 | 3.578125 | 4 |
[] |
no_license
|
//! [502. IPO](https://leetcode-cn.com/problems/ipo/)
use std::cmp::Ordering;
use std::collections::BinaryHeap;
#[derive(PartialEq, Eq)]
struct Pair(i32, i32);
impl PartialOrd<Self> for Pair {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Pair {
fn cmp(&self, other: &Self) -> Ordering {
match self.0.cmp(&other.0) {
Ordering::Equal => other.1.cmp(&self.1),
not_equal => not_equal,
}
}
}
impl Solution {
pub fn find_maximized_capital(k: i32, mut w: i32, profits: Vec<i32>, capital: Vec<i32>) -> i32 {
let mut pairs: BinaryHeap<_> = profits
.iter()
.zip(capital.iter())
.map(|(&profit, &capital)| Pair(profit, capital))
.collect();
let mut temp = vec![];
let mut i = 0;
while i < k {
let mut found = false;
while let Some(top) = pairs.pop() {
if top.1 <= w {
pairs.extend(temp.drain(..));
w += top.0;
found = true;
break;
} else {
temp.push(top);
}
}
if !found {
break;
}
i += 1;
}
w
}
}
struct Solution;
fn main() {
assert_eq!(
Solution::find_maximized_capital(2, 0, vec![1, 2, 3], vec![0, 1, 1]),
4
);
assert_eq!(
Solution::find_maximized_capital(3, 0, vec![1, 2, 3], vec![0, 1, 2]),
6
);
}
| true |
4fd69a9478f236aeed7daf64bf2c4e8fdb1a15b9
|
Rust
|
fiveseven-lambda/jackdaw5
|
/src/pos.rs
|
UTF-8
| 3,175 | 4.125 | 4 |
[] |
no_license
|
use std::fmt::{self, Debug, Display, Formatter};
use std::ops::Add;
// 文字の位置(何行目,何文字目)を 0-indexed で表す.
// Ord の derive は (line, column) の辞書式順序(メンバの宣言順)
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct CharPos {
line: usize,
column: usize,
}
// 半開区間
#[derive(Clone)]
pub struct Pos {
start: CharPos,
end: CharPos,
}
// new
impl CharPos {
pub fn new(line: usize, column: usize) -> CharPos {
CharPos { line: line, column: column }
}
}
impl Pos {
pub fn new(start: CharPos, end: CharPos) -> Pos {
debug_assert!((start.line, start.column) <= (end.line, end.column));
Pos { start: start, end: end }
}
}
// Display, Debug
impl Display for CharPos {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}:{}", self.line + 1, self.column + 1)
}
}
impl Debug for CharPos {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}:{}", self.line, self.column)
}
}
impl Display for Pos {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(
f,
"{}:{}-{}:{}",
self.start.line + 1,
self.start.column + 1,
self.end.line + 1,
self.end.column
)
}
}
impl Debug for Pos {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "[{:?}, {:?})", self.start, self.end)
}
}
// 順序あり足し算
impl Add<Pos> for Pos {
type Output = Pos;
fn add(self, other: Pos) -> Pos {
debug_assert!((self.end.line, self.end.column) <= (other.start.line, other.start.column));
Pos::new(self.start, other.end)
}
}
impl Add<Option<Pos>> for Pos {
type Output = Pos;
fn add(self, right: Option<Pos>) -> Pos {
match right {
Some(right) => self + right,
None => self,
}
}
}
impl Add<Pos> for Option<Pos> {
type Output = Pos;
fn add(self, right: Pos) -> Pos {
match self {
Some(left) => left + right,
None => right,
}
}
}
#[cfg(test)]
impl CharPos {
pub fn into_inner(self) -> (usize, usize) {
(self.line, self.column)
}
}
#[cfg(test)]
impl Pos {
pub fn into_inner(self) -> std::ops::RangeInclusive<(usize, usize)> {
self.start.into_inner()..=self.end.into_inner()
}
}
#[test]
fn test_add() {
let left = || Pos::new(CharPos::new(2, 3), CharPos::new(2, 6)); // 2 行目の 3 から 6 文字目
let right = || Pos::new(CharPos::new(5, 1), CharPos::new(5, 4)); // 5 行目の 1 から 4 文字目
// 合わせると, 2 行目の 3 文字目から 5 行目の 4 文字目までになる
assert_eq!((left() + right()).into_inner(), (2, 3)..=(5, 4));
// 片方が Option でも同じ
assert_eq!((left() + Some(right())).into_inner(), (2, 3)..=(5, 4));
assert_eq!((Some(left()) + right()).into_inner(), (2, 3)..=(5, 4));
// 片方が None なら何も変わらない
assert_eq!((left() + None).into_inner(), (2, 3)..=(2, 6));
assert_eq!((None + right()).into_inner(), (5, 1)..=(5, 4));
}
| true |
8ae01c97014f4dc74d7ebfe5976aa561086a0bd5
|
Rust
|
Banyango/rust-blockchain
|
/src/miner.rs
|
UTF-8
| 4,769 | 3.328125 | 3 |
[] |
no_license
|
use super::block::Block;
use crypto::sha2::Sha256;
use crypto::digest::Digest;
use pad::{PadStr, Alignment};
pub fn calculate_hash(block: &Block) -> String {
let record = [block.index.to_string(), block.timestamp.clone(), block.bpm.to_string(), block.prev_hash.clone(), block.nonce.clone()].concat();
let mut hasher = Sha256::new();
hasher.input_str(&record);
hasher.result_str()
}
pub fn is_hash_valid(hash:&String, difficulty: i64) -> bool {
let prefix = "".pad(difficulty as usize, '0', Alignment::Right, true);
hash.starts_with(&prefix)
}
pub fn is_block_valid(new_block: &Block, old_block: &Block) -> bool {
if old_block.index+1 != new_block.index {
return false;
}
if old_block.hash.as_ref().expect("Hash is null").as_str() != new_block.prev_hash {
return false;
}
let hash = calculate_hash(&new_block);
if !new_block.hash.is_some() {
return false;
}
if hash != new_block.hash.as_ref().unwrap().as_str() {
println!("blocks dont match...");
return false;
}
true
}
pub fn generate_block(old_block: &Block, bpm: i64, difficulty: i64) -> Result<Block, String> {
println!("Generating Block...");
let mut block = Block {
index: old_block.index + 1,
timestamp: time::get_time().sec.to_string(),
bpm: bpm,
prev_hash:old_block.hash.clone().expect("Previous Hash is null"),
hash:None,
difficulty:difficulty,
nonce:String::from(""),
};
let mut i = 0;
loop {
let hex = format!("{:x}", i);
block.nonce = hex;
let hash = calculate_hash(&block);
if !is_hash_valid(&hash, difficulty) {
println!("{} do more work",hash);
std::thread::sleep(std::time::Duration::from_secs(1));
} else {
println!("{} hash found",hash);
block.hash = Some(hash);
break;
}
i+=1;
}
Ok(block)
}
// this function would be used when networking is hooked up.
#[allow(dead_code)]
pub fn should_replace_chain(new_blocks: &[Block], old_blocks: &[Block]) -> bool {
if new_blocks.len() > old_blocks.len() {
return true;
}
false
}
#[cfg(test)]
mod tests {
use super::*;
use super::super::block::Block;
use pad::{PadStr, Alignment};
#[test]
fn test_is_hash_valid() {
assert_eq!(is_hash_valid(&String::from("0011"), 1), true);
}
#[test]
fn test_prefix() {
let prefix = "".pad(1, '0', Alignment::Right, true);
assert_eq!(prefix, "0");
}
#[test]
fn test_is_block_valid_index_wrong() {
let old = Block {
index:2,
..Default::default()
};
let new = Block {
index:1,
..Default::default()
};
assert_eq!(is_block_valid(&new, &old), false);
}
#[test]
fn test_is_block_valid_prev_hash_not_equal_to_hash() {
let old = Block {
index:0,
hash:Some(String::from("1")),
..Default::default()
};
let new = Block {
index:1,
prev_hash:String::from("2"),
..Default::default()
};
assert_eq!(is_block_valid(&new, &old), false);
}
#[test]
fn test_is_block_valid_new_hash_is_none() {
let old = Block {
index:0,
hash:Some(String::from("1")),
..Default::default()
};
let new = Block {
index:1,
hash:None,
..Default::default()
};
assert_eq!(is_block_valid(&new, &old), false);
}
#[test]
fn test_is_hash_valid_invalid_hash() {
let hash = String::from("1asdf9823f90a23f23f");
assert_eq!(is_hash_valid(&hash, 1), false, "hash with 0 leading 0 should be invalid on 1 difficulty");
let hash = String::from("1asdf9823f90a23f23f");
assert_eq!(is_hash_valid(&hash, 2), false, "hash with 0 leading 0 should be invalid on 2 difficulty");
let hash = String::from("01asdf9823f90a23f23f");
assert_eq!(is_hash_valid(&hash, 2), false, "hash with 1 leading 0 should be invalid on 2 difficulty");
}
#[test]
fn test_is_hash_valid_valid_hash() {
let hash = String::from("01asdf9823f90a23f23f");
assert_eq!(is_hash_valid(&hash, 1), true, "hash with 1 leading 0 should be valid on 1 difficulty");
let hash = String::from("00sdf9823f90a23f23f");
assert_eq!(is_hash_valid(&hash, 2), true, "hash with 2 leading 0 should be valid on 2 difficulty");
}
}
| true |
739b4af8e2f5053ec0431339fefd90ceef3f0327
|
Rust
|
HarveyHunt/streampager
|
/src/refresh.rs
|
UTF-8
| 2,722 | 3.609375 | 4 |
[
"MIT"
] |
permissive
|
//! Track screen refresh regions.
use bit_set::BitSet;
use std::cmp::{max, min};
/// Tracks which parts of the screen need to be refreshed.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) enum Refresh {
/// Nothing to render.
None,
/// The range of lines from `start`..`end` must be rendered.
Range(usize, usize),
/// The lines in the bitset must be rendered.
Lines(BitSet),
/// The whole screen must be rendered.
All,
}
impl Refresh {
/// Add a range of lines to the lines that must be rendered.
pub(crate) fn add_range(&mut self, start: usize, end: usize) {
match *self {
Refresh::None => *self = Refresh::Range(start, end),
Refresh::Range(s, e) => {
if start > e || s > end {
let mut b = BitSet::new();
b.extend(s..e);
b.extend(start..end);
*self = Refresh::Lines(b);
} else {
*self = Refresh::Range(min(start, s), max(end, e));
}
}
Refresh::Lines(ref mut b) => {
b.extend(start..end);
}
Refresh::All => {}
}
}
/// Rotate the range of lines upwards (towards 0). Lines that roll past
/// 0 are dropped.
pub(crate) fn rotate_range_up(&mut self, step: usize) {
match *self {
Refresh::None | Refresh::All => {}
Refresh::Range(s, e) => {
if step > e {
*self = Refresh::None;
} else {
*self = Refresh::Range(s.saturating_sub(step), e - step);
}
}
Refresh::Lines(ref b) => {
let mut new_b = BitSet::new();
for line in b.iter() {
if line >= step {
new_b.insert(line - step);
}
}
if new_b.is_empty() {
*self = Refresh::None;
} else {
*self = Refresh::Lines(new_b)
}
}
}
}
/// Rotate the range of lines downwards (away from 0).
pub(crate) fn rotate_range_down(&mut self, step: usize) {
match *self {
Refresh::None | Refresh::All => {}
Refresh::Range(s, e) => {
*self = Refresh::Range(s + step, e + step);
}
Refresh::Lines(ref b) => {
let mut new_b = BitSet::new();
for line in b.iter() {
new_b.insert(line + step);
}
*self = Refresh::Lines(new_b)
}
}
}
}
| true |
d7816f103984d39408a714e756066cb0ad491b57
|
Rust
|
nick-parker/rust-trimesh
|
/src/mesh.rs
|
UTF-8
| 1,673 | 3.09375 | 3 |
[] |
no_license
|
use tri::Tri;
use stlerror::StlError;
use std::fmt;
///A mesh which maintains information about Tris' neighbors to allow
///rapid traversal.
pub type Neighbors<'a> = [Option<&'a Tri>; 3];
pub struct Mesh<'a>{
pub ts : &'a Vec<Tri>,
pub ns : Vec<Neighbors<'a>>
}
impl<'a> Mesh<'a>{
pub fn new (ref ts : &'a Vec<Tri>)-> Result<Mesh<'a>, StlError>{
let mut ns : Vec<Neighbors<'a>> = Vec::with_capacity(ts.len());
for _ in 0..ts.len() { ns.push([None,None,None])};
for (i, t) in ts.iter().enumerate(){
for (j, u) in ts.iter().enumerate().filter(|x| x.0>i) {
let vs = t.vs;
let verts = (u.has_point(vs.0),u.has_point(vs.1),u.has_point(vs.2));
match verts {
(true,true,true) => return Err(StlError::BadStl(
"Identical Tris found in mesh.".to_string())),
(true,true,false) => ns[i][0] = Some(&u),
(false,true,true) => ns[i][1] = Some(&u),
(true,false,true) => ns[i][2] = Some(&u),
_ => continue //Tris share a vertex, which we don't care about.
}
let vs2 = u.vs;
let verts2 = (t.has_point(vs2.0),t.has_point(vs2.1),t.has_point(vs2.2));
match verts2 {
(true,true,true) => return Err(StlError::BadStl(
"Identical Tris found in mesh.".to_string())),
(true,true,false) => ns[j][0] = Some(&t),
(false,true,true) => ns[j][1] = Some(&t),
(true,false,true) => ns[j][2] = Some(&t),
_ => continue //Tris share a vertex, which we don't care about.
}
}
}
Ok(Mesh{ts: ts, ns: ns})
}
}
impl<'a> fmt::Display for Mesh<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Mesh: {:?}", self.ts)
}
}
//Crossing edges: (edge x line) x new normal
| true |
a82a86ea1d515a5d741c0f70c6eaab2e409fe5aa
|
Rust
|
KaiserY/trpl-zh-cn
|
/listings/ch18-patterns-and-matching/listing-18-19/src/main.rs
|
UTF-8
| 237 | 3.265625 | 3 |
[
"MIT"
] |
permissive
|
fn main() {
// ANCHOR: here
let numbers = (2, 4, 8, 16, 32);
match numbers {
(first, _, third, _, fifth) => {
println!("Some numbers: {first}, {third}, {fifth}")
}
}
// ANCHOR_END: here
}
| true |
daa825e85a424a8a54d201c4ba50b9a3788998ee
|
Rust
|
OliverUv/rltk_rs
|
/bracket-terminal/src/hal/wasm/events/keyboard.rs
|
UTF-8
| 5,654 | 3.015625 | 3 |
[
"MIT"
] |
permissive
|
use super::super::VirtualKeyCode;
/// Provides a global variable for keyboard events to be written to. I'm not really
/// a fan of using globals, but it was hard to find an alternative given the separation
/// between the web-side and the wasm side.
pub static mut GLOBAL_KEY: Option<VirtualKeyCode> = None;
/// Global for handling modifier key-state.
pub static mut GLOBAL_MODIFIERS: (bool, bool, bool) = (false, false, false);
/// Handler for on_key events from the browser. Sets the global variables, which are then
/// referenced by the main loop.
pub fn on_key(key: web_sys::KeyboardEvent) {
//super::console::log("Key Event");
unsafe {
if key.get_modifier_state("Shift") {
GLOBAL_MODIFIERS.0 = true;
}
if key.get_modifier_state("Control") {
GLOBAL_MODIFIERS.1 = true;
}
if key.get_modifier_state("Alt") {
GLOBAL_MODIFIERS.2 = true;
}
let code = key.key_code();
match code {
8 => GLOBAL_KEY = Some(VirtualKeyCode::Back),
9 => GLOBAL_KEY = Some(VirtualKeyCode::Tab),
13 => GLOBAL_KEY = Some(VirtualKeyCode::Return),
20 => GLOBAL_KEY = Some(VirtualKeyCode::Capital),
27 => GLOBAL_KEY = Some(VirtualKeyCode::Escape),
32 => GLOBAL_KEY = Some(VirtualKeyCode::Space),
33 => GLOBAL_KEY = Some(VirtualKeyCode::PageUp),
34 => GLOBAL_KEY = Some(VirtualKeyCode::PageDown),
35 => GLOBAL_KEY = Some(VirtualKeyCode::End),
36 => GLOBAL_KEY = Some(VirtualKeyCode::Home),
37 => GLOBAL_KEY = Some(VirtualKeyCode::Left),
38 => GLOBAL_KEY = Some(VirtualKeyCode::Up),
39 => GLOBAL_KEY = Some(VirtualKeyCode::Right),
40 => GLOBAL_KEY = Some(VirtualKeyCode::Down),
45 => GLOBAL_KEY = Some(VirtualKeyCode::Insert),
46 => GLOBAL_KEY = Some(VirtualKeyCode::Delete),
48 => GLOBAL_KEY = Some(VirtualKeyCode::Key0),
49 => GLOBAL_KEY = Some(VirtualKeyCode::Key1),
50 => GLOBAL_KEY = Some(VirtualKeyCode::Key2),
51 => GLOBAL_KEY = Some(VirtualKeyCode::Key3),
52 => GLOBAL_KEY = Some(VirtualKeyCode::Key4),
53 => GLOBAL_KEY = Some(VirtualKeyCode::Key5),
54 => GLOBAL_KEY = Some(VirtualKeyCode::Key6),
55 => GLOBAL_KEY = Some(VirtualKeyCode::Key7),
56 => GLOBAL_KEY = Some(VirtualKeyCode::Key8),
57 => GLOBAL_KEY = Some(VirtualKeyCode::Key9),
65 => GLOBAL_KEY = Some(VirtualKeyCode::A),
66 => GLOBAL_KEY = Some(VirtualKeyCode::B),
67 => GLOBAL_KEY = Some(VirtualKeyCode::C),
68 => GLOBAL_KEY = Some(VirtualKeyCode::D),
69 => GLOBAL_KEY = Some(VirtualKeyCode::E),
70 => GLOBAL_KEY = Some(VirtualKeyCode::F),
71 => GLOBAL_KEY = Some(VirtualKeyCode::G),
72 => GLOBAL_KEY = Some(VirtualKeyCode::H),
73 => GLOBAL_KEY = Some(VirtualKeyCode::I),
74 => GLOBAL_KEY = Some(VirtualKeyCode::J),
75 => GLOBAL_KEY = Some(VirtualKeyCode::K),
76 => GLOBAL_KEY = Some(VirtualKeyCode::L),
77 => GLOBAL_KEY = Some(VirtualKeyCode::M),
78 => GLOBAL_KEY = Some(VirtualKeyCode::N),
79 => GLOBAL_KEY = Some(VirtualKeyCode::O),
80 => GLOBAL_KEY = Some(VirtualKeyCode::P),
81 => GLOBAL_KEY = Some(VirtualKeyCode::Q),
82 => GLOBAL_KEY = Some(VirtualKeyCode::R),
83 => GLOBAL_KEY = Some(VirtualKeyCode::S),
84 => GLOBAL_KEY = Some(VirtualKeyCode::T),
85 => GLOBAL_KEY = Some(VirtualKeyCode::U),
86 => GLOBAL_KEY = Some(VirtualKeyCode::V),
87 => GLOBAL_KEY = Some(VirtualKeyCode::W),
88 => GLOBAL_KEY = Some(VirtualKeyCode::X),
89 => GLOBAL_KEY = Some(VirtualKeyCode::Y),
90 => GLOBAL_KEY = Some(VirtualKeyCode::Z),
97 => GLOBAL_KEY = Some(VirtualKeyCode::Numpad1),
98 => GLOBAL_KEY = Some(VirtualKeyCode::Numpad2),
99 => GLOBAL_KEY = Some(VirtualKeyCode::Numpad3),
100 => GLOBAL_KEY = Some(VirtualKeyCode::Numpad4),
101 => GLOBAL_KEY = Some(VirtualKeyCode::Numpad5),
102 => GLOBAL_KEY = Some(VirtualKeyCode::Numpad6),
103 => GLOBAL_KEY = Some(VirtualKeyCode::Numpad7),
104 => GLOBAL_KEY = Some(VirtualKeyCode::Numpad8),
105 => GLOBAL_KEY = Some(VirtualKeyCode::Numpad9),
106 => GLOBAL_KEY = Some(VirtualKeyCode::Multiply),
107 => GLOBAL_KEY = Some(VirtualKeyCode::Add),
109 => GLOBAL_KEY = Some(VirtualKeyCode::Subtract),
111 => GLOBAL_KEY = Some(VirtualKeyCode::Divide),
186 => GLOBAL_KEY = Some(VirtualKeyCode::Semicolon),
187 => GLOBAL_KEY = Some(VirtualKeyCode::Equals),
188 => GLOBAL_KEY = Some(VirtualKeyCode::Comma),
189 => GLOBAL_KEY = Some(VirtualKeyCode::Minus),
190 => GLOBAL_KEY = Some(VirtualKeyCode::Period),
191 => GLOBAL_KEY = Some(VirtualKeyCode::Slash),
192 => GLOBAL_KEY = Some(VirtualKeyCode::Grave),
219 => GLOBAL_KEY = Some(VirtualKeyCode::LBracket),
220 => GLOBAL_KEY = Some(VirtualKeyCode::Backslash),
221 => GLOBAL_KEY = Some(VirtualKeyCode::RBracket),
222 => GLOBAL_KEY = Some(VirtualKeyCode::Apostrophe),
_ => {
GLOBAL_KEY = None;
crate::console::log(&format!("Keycode: {}", code));
}
}
}
}
| true |
9937bfac23e8daf821fde7e3ec54dfe75eb13c85
|
Rust
|
gdoct/rustvm
|
/src/instructions/bvs.rs
|
UTF-8
| 394 | 2.53125 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
use crate::traits::{ Instruction, VirtualCpu };
use crate::types::{ Byte };
/// BvsRel: BVS relative
pub struct BvsRel { }
impl Instruction for BvsRel {
fn opcode (&self) -> &'static str { "BVS"}
fn hexcode(&self) -> Byte { 0x70 }
fn execute(&self, _cpu: &mut dyn VirtualCpu) -> std::io::Result<()> {
panic!("opcode BVS (Bvs) not implemented!");
// Ok(())
}
}
| true |
adec507865b75039c8c8f37c2e1aa075673ef1bc
|
Rust
|
adventofcode/2015solutions
|
/day12/p2a.rs
|
UTF-8
| 1,190 | 3.328125 | 3 |
[] |
no_license
|
//! This file is in the [cargo-script][1] format.
//!
//! [1]: https://github.com/DanielKeep/cargo-script
//!
//! ```cargo
//! [dependencies]
//! serde = "^0.6"
//! serde_json = "^0.6"
//! ```
extern crate serde;
extern crate serde_json;
use serde_json::{Value, from_reader};
use std::io;
fn sum_value(val: &Value) -> i64 {
match val {
&Value::I64(i) => i,
&Value::U64(u) => u as i64,
&Value::F64(f) => f as i64,
&Value::Array(ref arr) => {
let mut sum = 0;
for item in arr.iter() {
sum += sum_value(&item);
}
sum
},
&Value::Object(ref obj) => {
let mut sum = 0;
for (_, item) in obj.iter() {
if Some("red") == item.as_string() {
return 0;
}
sum += sum_value(&item);
}
sum
},
_ => 0,
}
}
fn main() {
let stdin = io::stdin();
let stdin = stdin.lock();
let input: Value = from_reader(stdin)
.expect("the input should be properly formatted");
let sum = sum_value(&input);
println!("Sum: {}", sum);
}
| true |
95086faeed9b396d0733fe3c27c421564512cc87
|
Rust
|
Mereep/advent_of_code_2020_rust
|
/src/day12/solution.rs
|
UTF-8
| 2,092 | 3.640625 | 4 |
[] |
no_license
|
use crate::files;
use std::num;
struct Point(i64, i64);
struct Ship {
position: Point,
angle: i32
}
impl Ship {
fn new(position: Option<Point>, angle: Option<i32>) -> Ship {
Ship {
position: position.unwrap_or_else(|| Point (0,0)),
angle: angle.unwrap_or_else(|| 90),
}
}
fn move_ship(&mut self, instruction: &str) {
let cmd = &instruction[0..1];
let distance = (&instruction[1..]).parse::<i64>().expect(
&format!("Couldn't parse {} as number", &instruction[1..]));
// println!("Command {}, distance {}", cmd, distance);
match cmd {
"N" => self.position.1 += distance,
"S" => self.position.1 -= distance,
"W" => self.position.0 -= distance,
"E" => self.position.0 += distance,
"L" => {
self.angle = (self.angle - distance as i32);
if self.angle < 0 {self.angle+= 360}
},
"R" => self.move_ship(&format!("L{}", 360 - distance)),
"F" => {
match self.angle {
90 => self.position.0 += distance,
180 => self.position.1 -= distance,
270 => self.position.0 -= distance,
0 => self.position.1 += distance,
_ => panic!("Illegal angle {}", self.angle)
}
},
_ => panic!("Unknown command {}", instruction)
}
}
}
pub fn task1() {
let data = get_input_data();
let lines = files::str_to_lines(data);
let mut ship = Ship::new(
None,None
);
for line in &lines {
ship.move_ship(&line);
}
println!("Position of ship: {}, {}; Manhatten distance: {}",
ship.position.0,
ship.position.1,
ship.position.0.abs() + ship.position.1.abs())
}
/// Reads the file into the binary
fn get_input_data() -> &'static str {
return include_str!("input.txt");
}
| true |
553c0207a378e509ad213150b2c61aa50f054de0
|
Rust
|
wdv4758h/sleep_sort
|
/src/lib.rs
|
UTF-8
| 493 | 2.78125 | 3 |
[] |
no_license
|
use std::{sync, thread};
// use std::time::Duration;
pub fn sleep_sort<I: Iterator<Item=u32>>(nums: I) -> Vec<u32> {
let (tx, rx) = sync::mpsc::channel();
let threads = nums.map(|n| {
let tx = tx.clone();
thread::spawn(move || {
// thread::sleep(Duration::new(0, n*1000000));
thread::sleep_ms(n); // deprecated
tx.send(n).unwrap();
})
}).collect::<Vec<_>>();
rx.iter().take(threads.len()).collect::<Vec<_>>()
}
| true |
0da553a80bbee542484929b13b251a6d3d0423bb
|
Rust
|
forkkit/semaphore
|
/general/src/types/traits.rs
|
UTF-8
| 4,101 | 3.53125 | 4 |
[
"MIT"
] |
permissive
|
use std::fmt::Debug;
use crate::types::{Annotated, MetaMap, MetaTree, Value};
/// A value that can be empty.
pub trait Empty {
/// Returns whether this value is empty.
fn is_empty(&self) -> bool;
/// Returns whether this value is empty or all of its descendants are empty.
///
/// This only needs to be implemented for containers by calling `Empty::is_deep_empty` on all
/// children. The default implementation calls `Empty::is_empty`.
///
/// For containers of `Annotated` elements, this must call `Annotated::skip_serialization`.
#[inline]
fn is_deep_empty(&self) -> bool {
self.is_empty()
}
}
/// Defines behavior for skipping the serialization of fields.
///
/// This behavior is configured via the `skip_serialization` attribute on fields of structs. It is
/// passed as parameter to `ToValue::skip_serialization` of the corresponding field.
///
/// The default for fields in derived structs is `SkipSerialization::Null(true)`, which will skips
/// `null` values under the field recursively. Newtype structs (`MyType(T)`) and enums pass through
/// to their inner type and variant, respectively.
///
/// ## Example
///
/// ```ignore
/// #[derive(Debug, Empty, ToValue)]
/// struct Helper {
/// #[metastructure(skip_serialization = "never")]
/// items: Annotated<Array<String>>,
/// }
/// ```
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum SkipSerialization {
/// Serialize all values. Missing values will be serialized as `null`.
Never,
/// Do not serialize `null` values but keep empty collections.
///
/// If the `bool` flag is set to `true`, this applies to all descendants recursively; if it is
/// set to `false`, this only applies to direct children and does not propagate down.
Null(bool),
/// Do not serialize empty objects as indicated by the `Empty` trait.
///
/// If the `bool` flag is set to `true`, this applies to all descendants recursively; if it is
/// set to `false`, this only applies to direct children and does not propagate down.
Empty(bool),
}
impl SkipSerialization {
/// Returns the serialization behavior for child elements.
///
/// Shallow behaviors - `Null(false)` and `Empty(false)` - propagate as `Never`, all others
/// remain the same. This allows empty containers to be skipped while their contents will
/// serialize with `null` values.
pub fn descend(self) -> Self {
match self {
SkipSerialization::Null(false) => SkipSerialization::Never,
SkipSerialization::Empty(false) => SkipSerialization::Never,
other => other,
}
}
}
impl Default for SkipSerialization {
fn default() -> Self {
SkipSerialization::Null(true)
}
}
/// Implemented for all meta structures.
pub trait FromValue: Debug {
/// Creates a meta structure from an annotated boxed value.
fn from_value(value: Annotated<Value>) -> Annotated<Self>
where
Self: Sized;
}
/// Implemented for all meta structures.
pub trait ToValue: Debug + Empty {
/// Boxes the meta structure back into a value.
fn to_value(self) -> Value
where
Self: Sized;
/// Extracts children meta map out of a value.
fn extract_child_meta(&self) -> MetaMap
where
Self: Sized,
{
Default::default()
}
/// Efficiently serializes the payload directly.
fn serialize_payload<S>(&self, s: S, behavior: SkipSerialization) -> Result<S::Ok, S::Error>
where
Self: Sized,
S: serde::Serializer;
/// Extracts the meta tree out of annotated value.
///
/// This should not be overridden by implementators, instead `extract_child_meta`
/// should be provided instead.
fn extract_meta_tree(value: &Annotated<Self>) -> MetaTree
where
Self: Sized,
{
MetaTree {
meta: value.1.clone(),
children: match value.0 {
Some(ref value) => ToValue::extract_child_meta(value),
None => Default::default(),
},
}
}
}
| true |
d570299ac560769875cc38ee1a7918efa3c0ad46
|
Rust
|
hamadakafu/kyopro
|
/src/bin/typical90_36.rs
|
UTF-8
| 1,218 | 2.765625 | 3 |
[] |
no_license
|
#![allow(clippy::comparison_chain)]
#![allow(clippy::collapsible_if)]
use std::cmp::Reverse;
use std::cmp::{max, min};
use std::collections::{BTreeSet, HashMap, HashSet};
use itertools::Itertools;
use whiteread::parse_line;
const ten97: usize = 1000_000_007;
/// 2の逆元 mod ten97.割りたいときに使う
const inv2ten97: u128 = 500_000_004;
fn main() {
let (n, q): (usize, usize) = parse_line().unwrap();
let mut xx: Vec<isize> = vec![];
let mut yy: Vec<isize> = vec![];
for _ in 0..n {
let (x, y): (isize, isize) = parse_line().unwrap();
xx.push(x - y);
yy.push(x + y);
}
let xmin = *xx.iter().min().unwrap() as isize;
let xmax = *xx.iter().max().unwrap() as isize;
let ymin = *yy.iter().min().unwrap() as isize;
let ymax = *yy.iter().max().unwrap() as isize;
for _ in 0..q {
let q: usize = parse_line().unwrap();
println!(
"{}",
vec![
(xx[q - 1] - xmin).abs(),
(xx[q - 1] - xmax).abs(),
(yy[q - 1] - ymin).abs(),
(yy[q - 1] - ymax).abs()
]
.iter()
.max()
.unwrap()
);
}
}
| true |
a41f71d480cee18d7c9901a705c207d92d171b46
|
Rust
|
jmjoy/async-wg
|
/src/lib.rs
|
UTF-8
| 4,524 | 3.171875 | 3 |
[
"Unlicense"
] |
permissive
|
//! # async-wg
//!
//! Async version WaitGroup for RUST.
//!
//! ## Examples
//!
//! ```rust, no_run
//! #[tokio::main]
//! async fn main() {
//! use async_wg::WaitGroup;
//!
//! // Create a new wait group.
//! let wg = WaitGroup::new();
//!
//! for _ in 0..10 {
//! let wg = wg.clone();
//! // Add count n.
//! wg.add(1).await;
//!
//! tokio::spawn(async move {
//! // Do some work.
//!
//! // Done count 1.
//! wg.done().await;
//! });
//! }
//!
//! // Wait for done count is equal to add count.
//! wg.await;
//! }
//! ```
//!
//! ## Benchmarks
//!
//! Simple benchmark comparison run on github actions.
//!
//! Code: [benchs/main.rs](https://github.com/jmjoy/async-wg/blob/master/benches/main.rs)
//!
//! ```text
//! test bench_join_handle ... bench: 34,485 ns/iter (+/- 18,969)
//! test bench_wait_group ... bench: 36,916 ns/iter (+/- 7,555)
//! ```
//!
//! ## License
//!
//! The Unlicense.
//!
use futures_util::lock::Mutex;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll, Waker};
#[derive(Clone)]
/// Enables multiple tasks to synchronize the beginning or end of some computation.
pub struct WaitGroup {
inner: Arc<Inner>,
}
struct Inner {
count: Mutex<isize>,
waker: Mutex<Option<Waker>>,
}
impl WaitGroup {
/// Creates a new wait group and returns the single reference to it.
///
/// # Examples
/// ```rust
/// use async_wg::WaitGroup;
/// let wg = WaitGroup::new();
/// ```
pub fn new() -> WaitGroup {
WaitGroup {
inner: Arc::new(Inner {
count: Mutex::new(0),
waker: Mutex::new(None),
}),
}
}
/// Add count n.
///
/// # Panic
/// 1. The argument `delta` must be a positive number (> 0).
/// 2. The max count must be less than `isize::max_value()` / 2.
pub async fn add(&self, delta: isize) {
if delta <= 0 {
panic!("The argument `delta` of wait group `add` must be a positive number");
}
let mut count = self.inner.count.lock().await;
*count += delta;
if *count >= isize::max_value() / 2 {
panic!("wait group count is too large");
}
}
/// Done count 1.
pub async fn done(&self) {
let mut count = self.inner.count.lock().await;
*count -= 1;
if *count <= 0 {
if let Some(waker) = &*self.inner.waker.lock().await {
waker.clone().wake();
}
}
}
/// Get the inner count of `WaitGroup`, the primary count is `0`.
pub async fn count(&self) -> isize {
*self.inner.count.lock().await
}
}
impl Future for WaitGroup {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
let mut count = self.inner.count.lock();
let pin_count = Pin::new(&mut count);
if let Poll::Ready(count) = pin_count.poll(cx) {
if *count <= 0 {
return Poll::Ready(());
}
}
drop(count);
let mut waker = self.inner.waker.lock();
let pin_waker = Pin::new(&mut waker);
if let Poll::Ready(mut waker) = pin_waker.poll(cx) {
*waker = Some(cx.waker().clone());
}
Poll::Pending
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
#[should_panic]
async fn add_zero() {
let wg = WaitGroup::new();
wg.add(0).await;
}
#[tokio::test]
#[should_panic]
async fn add_neg_one() {
let wg = WaitGroup::new();
wg.add(-1).await;
}
#[tokio::test]
#[should_panic]
async fn add_very_max() {
let wg = WaitGroup::new();
wg.add(isize::max_value()).await;
}
#[tokio::test]
async fn add() {
let wg = WaitGroup::new();
wg.add(1).await;
wg.add(10).await;
assert_eq!(*wg.inner.count.lock().await, 11);
}
#[tokio::test]
async fn done() {
let wg = WaitGroup::new();
wg.done().await;
wg.done().await;
assert_eq!(*wg.inner.count.lock().await, -2);
}
#[tokio::test]
async fn count() {
let wg = WaitGroup::new();
assert_eq!(wg.count().await, 0);
wg.add(10).await;
assert_eq!(wg.count().await, 10);
wg.done().await;
assert_eq!(wg.count().await, 9);
}
}
| true |
9c871c0be538f772c6a626812cd11bdd1be3362d
|
Rust
|
milancio42/joinkit
|
/tests/hash_join.rs
|
UTF-8
| 4,706 | 3.046875 | 3 |
[
"MIT"
] |
permissive
|
extern crate joinkit;
use std::collections::HashSet;
use joinkit::Joinkit;
use joinkit::EitherOrBoth::{Left, Both, Right};
#[test]
fn inner_fused() {
let a = (0..3).zip(0..3);
let b = (2..5).zip(2..5);
let mut it = a.hash_join_inner(b);
assert_eq!(it.next(), Some((2, vec![2])));
assert_eq!(it.next(), None);
}
#[test]
fn inner_fused_inv() {
let a = (2..5).zip(2..5);
let b = (0..3).zip(0..3);
let mut it = a.hash_join_inner(b);
assert_eq!(it.next(), Some((2, vec![2])));
assert_eq!(it.next(), None);
}
#[test]
fn left_excl_fused() {
let a = (0..3).zip(0..3);
let b = (2..5).zip(2..5);
let mut it = a.hash_join_left_excl(b);
assert_eq!(it.next(), Some(0));
assert_eq!(it.next(), Some(1));
assert_eq!(it.next(), None);
}
#[test]
fn left_excl_fused_inv() {
let a = (2..5).zip(2..5);
let b = (0..3).zip(0..3);
let mut it = a.hash_join_left_excl(b);
assert_eq!(it.next(), Some(3));
assert_eq!(it.next(), Some(4));
assert_eq!(it.next(), None);
}
#[test]
fn left_outer_fused() {
let a = (0..3).zip(0..3);
let b = (2..5).zip(2..5);
let mut it = a.hash_join_left_outer(b);
assert_eq!(it.next(), Some(Left(0)));
assert_eq!(it.next(), Some(Left(1)));
assert_eq!(it.next(), Some(Both(2, vec![2])));
assert_eq!(it.next(), None);
}
#[test]
fn left_outer_fused_inv() {
let a = (2..5).zip(2..5);
let b = (0..3).zip(0..3);
let mut it = a.hash_join_left_outer(b);
assert_eq!(it.next(), Some(Both(2, vec![2])));
assert_eq!(it.next(), Some(Left(3)));
assert_eq!(it.next(), Some(Left(4)));
assert_eq!(it.next(), None);
}
#[test]
fn right_excl_fused() {
let a = (0..3).zip(0..3);
let b = (2..5).zip(2..5);
let mut it = a.hash_join_right_excl(b);
let right_values: HashSet<Vec<u64>> = it.by_ref().take(2).collect();
assert!(right_values.contains(&vec![3]));
assert!(right_values.contains(&vec![4]));
assert_eq!(it.next(), None);
}
#[test]
fn right_excl_fused_inv() {
let a = (2..5).zip(2..5);
let b = (0..3).zip(0..3);
let mut it = a.hash_join_right_excl(b);
let right_values: HashSet<Vec<u64>> = it.by_ref().take(2).collect();
assert!(right_values.contains(&vec![0]));
assert!(right_values.contains(&vec![1]));
assert_eq!(it.next(), None);
}
#[test]
fn right_outer_fused() {
let a = (0..3).zip(0..3);
let b = (2..5).zip(2..5);
let mut it = a.hash_join_right_outer(b);
assert_eq!(it.next(), Some(Both(2, vec![2])));
let right_values: HashSet<Vec<u64>> = it.by_ref()
.take(2)
.map(|e| match e {
Right(r) => return r,
_ => panic!("Expected Right variant"),
})
.collect();
assert!(right_values.contains(&vec![3]));
assert!(right_values.contains(&vec![4]));
assert_eq!(it.next(), None);
}
#[test]
fn right_outer_fused_inv() {
let a = (2..5).zip(2..5);
let b = (0..3).zip(0..3);
let mut it = a.hash_join_right_outer(b);
assert_eq!(it.next(), Some(Both(2, vec![2])));
let right_values: HashSet<Vec<u64>> = it.by_ref()
.take(2)
.map(|e| match e {
Right(r) => return r,
_ => panic!("Expected Right variant"),
})
.collect();
assert!(right_values.contains(&vec![0]));
assert!(right_values.contains(&vec![1]));
assert_eq!(it.next(), None);
}
#[test]
fn full_outer_fused() {
let a = (0..3).zip(0..3);
let b = (2..5).zip(2..5);
let mut it = a.hash_join_full_outer(b);
assert_eq!(it.next(), Some(Left(0)));
assert_eq!(it.next(), Some(Left(1)));
assert_eq!(it.next(), Some(Both(2, vec![2])));
let right_values: HashSet<Vec<u64>> = it.by_ref()
.take(2)
.map(|e| match e {
Right(r) => return r,
_ => panic!("Expected Right variant"),
})
.collect();
assert!(right_values.contains(&vec![3]));
assert!(right_values.contains(&vec![4]));
assert_eq!(it.next(), None);
}
#[test]
fn full_outer_fused_inv() {
let a = (2..5).zip(2..5);
let b = (0..3).zip(0..3);
let mut it = a.hash_join_full_outer(b);
assert_eq!(it.next(), Some(Both(2, vec![2])));
assert_eq!(it.next(), Some(Left(3)));
assert_eq!(it.next(), Some(Left(4)));
let right_values: HashSet<Vec<u64>> = it.by_ref()
.take(2)
.map(|e| match e {
Right(r) => return r,
_ => panic!("Expected Right variant"),
})
.collect();
assert!(right_values.contains(&vec![0]));
assert!(right_values.contains(&vec![1]));
assert_eq!(it.next(), None);
}
| true |
b326b7d8791c4a51a92ad5e134892a7c1e3a66b5
|
Rust
|
marco-c/gecko-dev-wordified
|
/third_party/rust/http/src/byte_str.rs
|
UTF-8
| 1,990 | 3.125 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"Apache-2.0"
] |
permissive
|
use
bytes
:
:
Bytes
;
use
std
:
:
{
ops
str
}
;
#
[
derive
(
Debug
Clone
Eq
PartialEq
Ord
PartialOrd
Hash
)
]
pub
(
crate
)
struct
ByteStr
{
/
/
Invariant
:
bytes
contains
valid
UTF
-
8
bytes
:
Bytes
}
impl
ByteStr
{
#
[
inline
]
pub
fn
new
(
)
-
>
ByteStr
{
ByteStr
{
/
/
Invariant
:
the
empty
slice
is
trivially
valid
UTF
-
8
.
bytes
:
Bytes
:
:
new
(
)
}
}
#
[
inline
]
pub
const
fn
from_static
(
val
:
&
'
static
str
)
-
>
ByteStr
{
ByteStr
{
/
/
Invariant
:
val
is
a
str
so
contains
vaid
UTF
-
8
.
bytes
:
Bytes
:
:
from_static
(
val
.
as_bytes
(
)
)
}
}
#
[
inline
]
/
/
/
#
#
Panics
/
/
/
In
a
debug
build
this
will
panic
if
bytes
is
not
valid
UTF
-
8
.
/
/
/
/
/
/
#
#
Safety
/
/
/
bytes
must
contain
valid
UTF
-
8
.
In
a
release
build
it
is
undefined
/
/
/
behaviour
to
call
this
with
bytes
that
is
not
valid
UTF
-
8
.
pub
unsafe
fn
from_utf8_unchecked
(
bytes
:
Bytes
)
-
>
ByteStr
{
if
cfg
!
(
debug_assertions
)
{
match
str
:
:
from_utf8
(
&
bytes
)
{
Ok
(
_
)
=
>
(
)
Err
(
err
)
=
>
panic
!
(
"
ByteStr
:
:
from_utf8_unchecked
(
)
with
invalid
bytes
;
error
=
{
}
bytes
=
{
:
?
}
"
err
bytes
)
}
}
/
/
Invariant
:
assumed
by
the
safety
requirements
of
this
function
.
ByteStr
{
bytes
:
bytes
}
}
}
impl
ops
:
:
Deref
for
ByteStr
{
type
Target
=
str
;
#
[
inline
]
fn
deref
(
&
self
)
-
>
&
str
{
let
b
:
&
[
u8
]
=
self
.
bytes
.
as_ref
(
)
;
/
/
Safety
:
the
invariant
of
bytes
is
that
it
contains
valid
UTF
-
8
.
unsafe
{
str
:
:
from_utf8_unchecked
(
b
)
}
}
}
impl
From
<
String
>
for
ByteStr
{
#
[
inline
]
fn
from
(
src
:
String
)
-
>
ByteStr
{
ByteStr
{
/
/
Invariant
:
src
is
a
String
so
contains
valid
UTF
-
8
.
bytes
:
Bytes
:
:
from
(
src
)
}
}
}
impl
<
'
a
>
From
<
&
'
a
str
>
for
ByteStr
{
#
[
inline
]
fn
from
(
src
:
&
'
a
str
)
-
>
ByteStr
{
ByteStr
{
/
/
Invariant
:
src
is
a
str
so
contains
valid
UTF
-
8
.
bytes
:
Bytes
:
:
copy_from_slice
(
src
.
as_bytes
(
)
)
}
}
}
impl
From
<
ByteStr
>
for
Bytes
{
fn
from
(
src
:
ByteStr
)
-
>
Self
{
src
.
bytes
}
}
| true |
0c0a09383c6687816ce43c1262252db9206bc32a
|
Rust
|
mozilla/gecko-dev
|
/third_party/rust/icu_locid/src/subtags/variants.rs
|
UTF-8
| 3,507 | 3.078125 | 3 |
[
"LicenseRef-scancode-unicode",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
// This file is part of ICU4X. For terms of use, please see the file
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
use super::Variant;
use crate::helpers::ShortSlice;
use alloc::vec::Vec;
use core::ops::Deref;
/// A list of variants (examples: `["macos", "posix"]`, etc.)
///
/// [`Variants`] stores a list of [`Variant`] subtags in a canonical form
/// by sorting and deduplicating them.
///
/// # Examples
///
/// ```
/// use icu::locid::{subtags::Variants, subtags_variant as variant};
///
/// let mut v = vec![variant!("posix"), variant!("macos")];
/// v.sort();
/// v.dedup();
///
/// let variants: Variants = Variants::from_vec_unchecked(v);
/// assert_eq!(variants.to_string(), "macos-posix");
/// ```
#[derive(Default, Debug, PartialEq, Eq, Clone, Hash, PartialOrd, Ord)]
pub struct Variants(ShortSlice<Variant>);
impl Variants {
/// Returns a new empty list of variants. Same as [`default()`](Default::default()), but is `const`.
///
/// # Examples
///
/// ```
/// use icu::locid::subtags::Variants;
///
/// assert_eq!(Variants::new(), Variants::default());
/// ```
#[inline]
pub const fn new() -> Self {
Self(ShortSlice::new())
}
/// Creates a new [`Variants`] set from a single [`Variant`].
///
/// # Examples
///
/// ```
/// use icu::locid::{subtags::Variants, subtags_variant as variant};
///
/// let variants = Variants::from_variant(variant!("posix"));
/// ```
#[inline]
pub const fn from_variant(variant: Variant) -> Self {
Self(ShortSlice::new_single(variant))
}
/// Creates a new [`Variants`] set from a [`Vec`].
/// The caller is expected to provide sorted and deduplicated vector as
/// an input.
///
/// # Examples
///
/// ```
/// use icu::locid::{subtags::Variants, subtags_variant as variant};
///
/// let mut v = vec![variant!("posix"), variant!("macos")];
/// v.sort();
/// v.dedup();
///
/// let variants = Variants::from_vec_unchecked(v);
/// ```
///
/// Notice: For performance- and memory-constrained environments, it is recommended
/// for the caller to use [`binary_search`](slice::binary_search) instead of [`sort`](slice::sort)
/// and [`dedup`](Vec::dedup()).
pub fn from_vec_unchecked(input: Vec<Variant>) -> Self {
Self(ShortSlice::from(input))
}
/// Empties the [`Variants`] list.
///
/// Returns the old list.
///
/// # Examples
///
/// ```
/// use icu::locid::{subtags::Variants, subtags_variant as variant};
///
/// let mut v = vec![variant!("posix"), variant!("macos")];
/// v.sort();
/// v.dedup();
///
/// let mut variants: Variants = Variants::from_vec_unchecked(v);
///
/// assert_eq!(variants.to_string(), "macos-posix");
///
/// variants.clear();
///
/// assert_eq!(variants, Variants::default());
/// ```
pub fn clear(&mut self) -> Self {
core::mem::take(self)
}
pub(crate) fn for_each_subtag_str<E, F>(&self, f: &mut F) -> Result<(), E>
where
F: FnMut(&str) -> Result<(), E>,
{
self.deref().iter().map(|t| t.as_str()).try_for_each(f)
}
}
impl_writeable_for_subtag_list!(Variants, "macos", "posix");
impl Deref for Variants {
type Target = [Variant];
fn deref(&self) -> &[Variant] {
self.0.as_slice()
}
}
| true |
ab986fb867cbb18e9a5952d1f827c8e8f93c44f5
|
Rust
|
gitter-badger/jolimail
|
/server/src/model/template/update.rs
|
UTF-8
| 2,385 | 2.953125 | 3 |
[] |
no_license
|
use crate::error::ServerError;
use crate::model::template::Template;
use deadpool_postgres::Client;
use serde::{Deserialize, Serialize};
use tokio_postgres::types::ToSql;
use uuid::Uuid;
use super::COLUMNS;
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct TemplateUpdate {
pub id: Uuid,
pub title: Option<String>,
pub description: Option<String>,
pub current_version_id: Option<Uuid>,
}
impl TemplateUpdate {
pub async fn save(&self, client: &Client) -> Result<Option<Template>, ServerError> {
debug!("save template {}", self.id);
let mut params: Vec<&(dyn ToSql + Sync)> = vec![&self.id];
let mut changes = vec!["updated_at = now()".to_string()];
if let Some(title) = self.title.as_ref() {
params.push(title);
changes.push(format!("title = ${}", params.len()));
}
if let Some(description) = self.description.as_ref() {
params.push(description);
changes.push(format!("description = ${}", params.len()));
}
if let Some(current_version_id) = self.current_version_id.as_ref() {
params.push(current_version_id);
changes.push(format!("current_version_id = ${}", params.len()));
}
let stmt = format!(
"UPDATE templates SET {} WHERE id = $1 RETURNING {}",
changes.join(", "),
COLUMNS.as_str()
);
let stmt = client.prepare(stmt.as_str()).await?;
let rows = client.query(&stmt, ¶ms).await?;
Ok(rows.first().map(Template::from))
}
}
#[cfg(test)]
pub mod tests {
use super::*;
use crate::service::database::client::tests::POOL;
#[allow(dead_code)]
pub async fn update_template(
id: &Uuid,
title: Option<String>,
description: Option<String>,
current_version_id: Option<Uuid>,
) -> Option<Template> {
let client = POOL.get().await.unwrap();
let body = TemplateUpdate {
id: id.clone(),
title: title.clone(),
description: description.clone(),
current_version_id: current_version_id.clone(),
};
body.save(&client).await.unwrap()
}
pub async fn set_template_version(id: &Uuid, version_id: &Uuid) -> Option<Template> {
update_template(id, None, None, Some(version_id.clone())).await
}
}
| true |
680ba7ef18adfcd98e8bcc2a34ba732518752f88
|
Rust
|
archer884/cfjungle
|
/src/lib.rs
|
UTF-8
| 956 | 2.859375 | 3 |
[] |
no_license
|
use serde::{Serialize, Serializer, Deserialize, Deserializer};
use std::fmt::{self, Debug};
static TEMPLATE_FORMAT_VERSION: &str = "2010-09-09";
#[derive(Debug)]
pub struct Template {
name: String,
}
impl Serialize for Template {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
#[derive(Serialize)]
#[allow(non_snake_case)]
struct InternalTemplate<'t> {
AWSTemplateFormatVersion: &'t str,
name: &'t str,
}
let serialization_template = InternalTemplate {
AWSTemplateFormatVersion: TEMPLATE_FORMAT_VERSION,
name: &self.name,
};
serialization_template.serialize(serializer)
}
}
#[derive(Copy, Clone)]
pub enum TemplateFormatVersion {
Version2010,
}
impl Debug for TemplateFormatVersion {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(TEMPLATE_FORMAT_VERSION)
}
}
| true |
0e880af0285e43e26ca8cd9bac906501e37aeb34
|
Rust
|
elijaharita/ascii-snake
|
/src/main.rs
|
UTF-8
| 7,558 | 3.46875 | 3 |
[] |
no_license
|
extern crate crossterm;
extern crate rand;
use crossterm::{cursor, terminal, QueueableCommand};
use rand::{prelude::*, thread_rng};
use std::io::{prelude::*, stdin, stdout};
use std::sync::mpsc::{channel, Receiver};
use std::thread;
type SnakeVal = i32;
fn main() {
use std::time::{Duration, Instant};
// Create game
let mut game = Game::new(16, 16);
// Start alternate terminal view and disable cursor to prepare for drawing
stdout()
.queue(terminal::EnterAlternateScreen)
.unwrap()
.queue(cursor::Hide)
.unwrap()
.flush()
.unwrap();
terminal::enable_raw_mode().unwrap();
// Game loop timing information
let tick_rate: f32 = 10.0;
let mut last_game_update = Instant::now();
// Spawn control input channel
let input_channel = spawn_input_channel();
let mut direction_input = Direction::Up;
// Game loop
loop {
// Process input
if let Ok(direction) = input_channel.try_recv() {
direction_input = direction;
}
// If the fixed time step has passed, perform the next update
let now = Instant::now();
if now - last_game_update > Duration::from_secs_f32(1.0 / tick_rate) {
last_game_update = now;
// Set the direction to the latest input
let _ = game.set_direction(direction_input);
// Update
game.update();
// Clear terminal and render
stdout()
.queue(terminal::Clear(terminal::ClearType::All))
.unwrap()
.queue(cursor::MoveTo(0, 0))
.unwrap();
game.render_ascii();
// Stop running the game loop if the player died
if !game.alive() {
println!("You died!");
std::thread::sleep(Duration::from_secs(1));
break;
}
}
}
// Reset terminal to original state
stdout()
.queue(terminal::LeaveAlternateScreen)
.unwrap()
.queue(cursor::Show)
.unwrap()
.flush()
.unwrap();
terminal::disable_raw_mode().unwrap();
}
fn spawn_input_channel() -> Receiver<Direction> {
let (tx, rx) = channel::<Direction>();
thread::spawn(move || loop {
let mut buf = [0u8; 1];
stdin().read_exact(&mut buf).unwrap();
tx.send(match buf[0] as char {
'w' => Direction::Up,
's' => Direction::Down,
'a' => Direction::Left,
'd' => Direction::Right,
_ => continue,
})
.unwrap();
});
rx
}
// The board containing the snake and food
struct Game {
width: i32,
height: i32,
tiles: Vec<Vec<Tile>>, // tiles[x][y]
direction: Direction,
alive: bool,
length: i32,
head_x: i32,
head_y: i32,
}
impl Game {
// Create a world with the specified size
fn new(width: i32, height: i32) -> Self {
let mut new = Self {
width,
height,
tiles: vec![vec![Tile::Empty; height as usize]; width as usize],
direction: Direction::Up,
alive: true,
length: 3,
head_x: width / 2,
head_y: height / 2,
};
new.spawn_food();
new
}
// Set the snake's direction
// Returns an error if direction is opposite to current direction
fn set_direction(&mut self, direction: Direction) -> Result<(), ()> {
if direction == self.direction.opposite() {
Err(())
} else {
self.direction = direction;
Ok(())
}
}
fn alive(&self) -> bool {
self.alive
}
fn update(&mut self) {
// Move head
match self.direction {
Direction::Up => self.head_y -= 1,
Direction::Down => self.head_y += 1,
Direction::Left => self.head_x -= 1,
Direction::Right => self.head_x += 1,
}
// Check for out of bounds
if self.head_x < 0
|| self.head_x >= self.width
|| self.head_y < 0
|| self.head_y >= self.height
{
// Die if out of bounds
self.alive = false;
return;
}
// Check for collision
match self.tiles[self.head_x as usize][self.head_y as usize] {
Tile::Snake(_) => {
// Die if collided
self.alive = false;
return;
}
Tile::Food => {
// Eat
self.length += 1;
self.spawn_food();
self.tiles[self.head_x as usize][self.head_y as usize] = Tile::Snake(0);
}
Tile::Empty => {
// Set head position to snake tile
self.tiles[self.head_x as usize][self.head_y as usize] = Tile::Snake(0);
}
}
// Update the grid's snake values
for x in 0..self.width {
for y in 0..self.height {
match self.tiles[x as usize][y as usize] {
Tile::Snake(val) => {
self.tiles[x as usize][y as usize] = if val >= self.length {
Tile::Empty
} else {
Tile::Snake(val + 1)
}
}
_ => (),
}
}
}
}
fn spawn_food(&mut self) {
loop {
let tile = &mut self.tiles[thread_rng().gen_range(0, self.width) as usize]
[thread_rng().gen_range(0, self.height) as usize];
if *tile == Tile::Empty {
*tile = Tile::Food;
break;
}
}
}
fn render_ascii(&self) {
// Top border
stdout().write(" ".as_bytes()).unwrap();
for _x in 0..self.width {
stdout().write("--".as_bytes()).unwrap();
}
stdout().write("\n".as_bytes()).unwrap();
for y in 0..self.height {
// Left border
stdout().write("| ".as_bytes()).unwrap();
// Tiles
for x in 0..self.width {
stdout()
.write(self.tiles[x as usize][y as usize].ascii_rep().as_bytes())
.unwrap();
}
// Right border
stdout().write(" |\n".as_bytes()).unwrap();
}
// Bottom border
stdout().write(" ".as_bytes()).unwrap();
for _x in 0..self.width {
stdout().write("--".as_bytes()).unwrap();
}
stdout().write("\n".as_bytes()).unwrap();
}
}
// Snake direction controls
#[derive(Clone, Copy, PartialEq, Eq)]
enum Direction {
Up,
Down,
Left,
Right,
}
impl Direction {
// Get the opposite direction
fn opposite(self) -> Self {
match self {
Direction::Up => Direction::Down,
Direction::Down => Direction::Up,
Direction::Left => Direction::Right,
Direction::Right => Direction::Left,
}
}
}
// Possible states of a tile
#[derive(Clone, Copy, PartialEq, Eq)]
enum Tile {
Empty,
Food,
Snake(SnakeVal),
}
impl Tile {
// Get a two-character ASCII representation
fn ascii_rep(self) -> &'static str {
match self {
Tile::Empty => " ",
Tile::Food => "><",
Tile::Snake(_) => "██",
}
}
}
| true |
1a2a21aefc3ebc10502f750a911ccf2c190b931c
|
Rust
|
przygienda/rust-http2
|
/src/misc.rs
|
UTF-8
| 826 | 3.1875 | 3 |
[
"MIT"
] |
permissive
|
use std::any::Any;
use std::fmt;
#[allow(dead_code)]
pub struct BsDebug<'a>(pub &'a [u8]);
impl<'a> fmt::Debug for BsDebug<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(fmt, "b\"")?;
let u8a: &[u8] = self.0;
for &c in u8a {
// ASCII printable
if c >= 0x20 && c < 0x7f {
write!(fmt, "{}", c as char)?;
} else {
write!(fmt, "\\x{:02x}", c)?;
}
}
write!(fmt, "\"")?;
Ok(())
}
}
pub fn any_to_string(any: Box<Any + Send + 'static>) -> String {
if any.is::<String>() {
*any.downcast::<String>().unwrap()
} else if any.is::<&str>() {
(*any.downcast::<&str>().unwrap()).to_owned()
} else {
"unknown any".to_owned()
}
}
| true |
1566998f2b9d4531ad682859f6d78ad13491c641
|
Rust
|
johnwstanford/vxi11
|
/src/rpc/tcp_clients.rs
|
UTF-8
| 2,085 | 2.546875 | 3 |
[] |
no_license
|
extern crate byteorder;
use std::io::{self, Read, Write, Error, ErrorKind};
use std::net::{TcpStream, ToSocketAddrs};
use byteorder::{BigEndian, WriteBytesExt, ReadBytesExt};
use crate::xdr;
use super::xdr_unpack;
pub struct TcpClient {
pub stream: TcpStream,
pub prog: u32,
pub vers: u32,
pub lastxid: u32,
pub packer: xdr::Packer,
pub unpacker: xdr::Unpacker,
}
impl TcpClient {
pub fn connect<A: ToSocketAddrs>(addr: A, prog: u32, vers: u32) -> io::Result<Self> {
let packer = xdr::Packer::new();
let unpacker = xdr::Unpacker::new();
Ok(Self{ stream: TcpStream::connect(addr)?, prog, vers, lastxid: 0, packer, unpacker })
}
pub fn do_call(&mut self) -> io::Result<()> {
let call:Vec<u8> = self.packer.get_buf()?;
if call.len() > 0 {
let header:u32 = call.len() as u32 | 0x80000000;
let mut send_bytes:Vec<u8> = vec![];
send_bytes.write_u32::<BigEndian>(header)?;
send_bytes.extend_from_slice(&call);
self.stream.write_all(&send_bytes)?;
}
'outer: loop {
let mut reply:Vec<u8> = vec![];
let mut last:bool = false;
while !last {
let x:u32 = self.stream.read_u32::<BigEndian>()?;
last = (x & 0x80000000) != 0;
let n:u32 = x & 0x7fffffff;
let mut frag:Vec<u8> = Vec::with_capacity(n as usize);
let mut buff:[u8; 4] = [0; 4];
while frag.len() < n as usize {
self.stream.read_exact(&mut buff)?;
frag.extend_from_slice(&buff);
}
reply.append(&mut frag);
}
// Load the response into the unpacker and make sure the xid matches
self.unpacker.reset(&reply);
let (xid, _) = xdr_unpack::unpack_replyheader(&mut self.unpacker)?;
if xid == self.lastxid {
// Packet from the present
return Ok(());
} else if xid < self.lastxid {
// Packet from the past
continue 'outer;
} else {
// Packet from the future?
return Err(Error::new(ErrorKind::Other, "Somehow got a packet from the future"));
}
}
}
}
| true |
dddd7c2616053a0e1b86e415029617a503f5c754
|
Rust
|
GuilhermoReadonly/asteroids
|
/src/lib.rs
|
UTF-8
| 1,798 | 2.703125 | 3 |
[] |
no_license
|
pub mod constants;
pub mod inputs;
pub mod objects;
pub mod state;
use crate::{constants::*, state::*};
use ggez::{
event, graphics,
nalgebra::{Point2, Vector2},
Context, GameResult,
};
use log::info;
pub type SpeedVector = Vector2<f32>;
pub type SpeedScalar = f32;
pub type SpeedAngle = f32;
pub type PositionVector = Vector2<f32>;
pub type Point = Point2<f32>;
pub type Direction = f32;
pub type DirectionVector = Vector2<f32>;
pub type Mass = f32;
pub type Force = f32;
pub type Life = f32;
pub struct MainState {
state: Box<dyn StateWithTransition>,
}
impl MainState {
pub fn new() -> MainState {
info!("Let the party rocks !");
MainState {
state: Box::new(StartScreen::new()),
}
}
}
impl event::EventHandler for MainState {
fn update(&mut self, ctx: &mut Context) -> GameResult<()> {
while ggez::timer::check_update_time(ctx, GAME_FPS) {
self.state.update(ctx);
}
if let Some(new_state) = self.state.transition(ctx) {
self.state = new_state
};
Ok(())
}
fn draw(&mut self, ctx: &mut Context) -> GameResult<()> {
graphics::clear(ctx, graphics::BLACK);
self.state.draw(ctx)?;
graphics::present(ctx)?;
Ok(())
}
// Handle key events. These just map keyboard events
// and alter our input state appropriately.
fn key_down_event(
&mut self,
ctx: &mut Context,
keycode: event::KeyCode,
keymod: event::KeyMods,
repeat: bool,
) {
self.state.key_down_event(ctx, keycode, keymod, repeat);
}
fn key_up_event(&mut self, ctx: &mut Context, keycode: event::KeyCode, keymod: event::KeyMods) {
self.state.key_up_event(ctx, keycode, keymod);
}
}
| true |
c7aab0f7f56906960158ac845914bab917ae31bb
|
Rust
|
cargo-crates/orm-rs
|
/src/nodes/node_column.rs
|
UTF-8
| 2,216 | 3.203125 | 3 |
[] |
no_license
|
use serde_json::{Value as JsonValue};
use crate::nodes::NodeAble;
use crate::methods::full_column_name;
#[derive(Clone, Debug)]
pub struct NodeColumn {
condition: JsonValue
}
impl NodeColumn {
pub fn new(condition: JsonValue) -> Self {
Self {
condition
}
}
fn get_full_column_names(&self, table_name: &str) -> Vec<String> {
let mut vec = vec![];
match self.get_condition() {
JsonValue::Object(condition) => {
for key in condition.keys() {
let full_column_name = full_column_name(key, table_name);
vec.push(full_column_name);
}
},
JsonValue::Array(condition) => {
for json_value in condition.iter() {
match json_value {
JsonValue::Object(json_value) => {
for key in json_value.keys() {
let full_column_name = full_column_name(key, table_name);
vec.push(full_column_name);
}
},
JsonValue::String(key) => {
let full_column_name = full_column_name(key, table_name);
vec.push(full_column_name);
},
_ => ()
}
}
},
_ => ()
}
vec
}
}
impl NodeAble for NodeColumn {
fn get_condition(&self) -> &JsonValue {
&self.condition
}
fn to_value(&self, table_name: &str) -> Vec<String> {
self.get_full_column_names(table_name)
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn get_full_column_names() {
let node_column = NodeColumn::new(json!(["name", "age"]));
assert_eq!(node_column.get_full_column_names("users"), vec!["`users`.`name`", "`users`.`age`"]);
}
#[test]
fn to_value() {
let node_column = NodeColumn::new(json!(["name", "age"]));
assert_eq!(node_column.to_value("users"), vec!["`users`.`name`", "`users`.`age`"]);
}
}
| true |
72df5bd370a31047e985f22933cfc75bf9e14df6
|
Rust
|
ia7ck/competitive-programming
|
/AtCoder/abc251/src/bin/c/main.rs
|
UTF-8
| 561 | 2.78125 | 3 |
[] |
no_license
|
use proconio::input;
use std::cmp::Reverse;
use std::collections::HashSet;
fn main() {
input! {
n: usize,
st: [(String, u32); n],
};
let mut ti = Vec::new(); // original
let mut seen = HashSet::new();
for (i, (s, t)) in st.iter().enumerate() {
if seen.contains(s) {
continue;
}
seen.insert(s);
ti.push((*t, i));
}
ti.sort_by_key(|&(t, i)| (Reverse(t), i));
assert!(ti.len() >= 1);
let (t, ans) = ti[0];
eprintln!("t = {}", t);
println!("{}", ans + 1);
}
| true |
8c742e6527a41a33aac7af75226e5d5a0a9d8f3d
|
Rust
|
j-richey/open_ttt_lib
|
/examples/ai_difficulties.rs
|
UTF-8
| 7,903 | 3.25 | 3 |
[
"MIT"
] |
permissive
|
//! Example showing the different AI difficulties.
use rand::Rng;
use std::fmt;
use std::io;
use std::io::prelude::*;
use std::time;
use open_ttt_lib::{ai, game};
const INSTRUCTIONS: &str = r#"
AI Difficulty Examples
======================
This example shows how the different AI difficulties compare. AI opponents using
various difficulties play a series of games. The generated table shows the
percentage of wins, losses, and cat's games for each difficulty compared to the
None difficulty which places marks randomly and the Unbeatable difficulty which
never makes a mistake.
This example also demonstrates how to create custom difficulties. Try modifying
the `should_evaluate_node()` function and see how it compares to the builtin
difficulties.
Note: this example runs significantly faster with the --release flag: e.g:
$ cargo run --release --example ai_difficulties
"#;
// The number of games to play for each battle. More games gives a more accurate
// representation of how the difficulties compare, but takes longer to run.
const NUM_GAMES: i32 = 100;
// Custom difficulty's should evaluate node function. Modify this function to
// experiment with custom difficulties.
fn should_evaluate_node(depth: i32) -> bool {
if depth == 0 {
true
} else {
let evaluate_node_probability = 0.8;
rand::thread_rng().gen_bool(evaluate_node_probability)
}
}
fn main() {
println!("{}", INSTRUCTIONS);
print_table_header();
evaluate_difficulty(ai::Difficulty::None);
evaluate_difficulty(ai::Difficulty::Easy);
evaluate_difficulty(ai::Difficulty::Medium);
evaluate_difficulty(ai::Difficulty::Hard);
evaluate_difficulty(ai::Difficulty::Custom(should_evaluate_node));
evaluate_difficulty(ai::Difficulty::Unbeatable);
}
// Compares the provided difficulty to the reference difficulties. The results
// are printed to the screen.
fn evaluate_difficulty(difficulty: ai::Difficulty) {
let difficulty_name = get_difficulty_name(&difficulty);
let none_scores = battle(difficulty, ai::Difficulty::None);
let unbeatable_scores = battle(difficulty, ai::Difficulty::Unbeatable);
print_table_row(
difficulty_name,
&none_scores.to_string(),
&unbeatable_scores.to_string(),
);
}
// Has AI opponents of the provided difficulties play a series of games counting
// the wins for each player. Depending on the number of games being played, this
// function might take a while, so the progress of the battle is occasionally
// printed.
fn battle(
player_x_difficulty: ai::Difficulty,
player_o_difficulty: ai::Difficulty,
) -> BattleScores {
// The game logic ensures each opponent takes turns taking the first move,
// thus start_next_game() is used instead of creating a new game once the
// game is over.
let mut game = game::Game::new();
let player_x_name = get_difficulty_name(&player_x_difficulty);
let player_x = ai::Opponent::new(player_x_difficulty);
let player_o_name = get_difficulty_name(&player_o_difficulty);
let player_o = ai::Opponent::new(player_o_difficulty);
let mut scores = BattleScores::new();
let mut last_print_progress_time = time::Instant::now();
while scores.total_games() < NUM_GAMES {
// Play one turn of the either getting asking one of the AI players to
// pick a position or if the game is over updating the scores and starting
// the next game.
match game.state() {
game::State::PlayerXMove => {
let position = player_x.get_move(&game).unwrap();
game.do_move(position).unwrap();
}
game::State::PlayerOMove => {
let position = player_o.get_move(&game).unwrap();
game.do_move(position).unwrap();
}
game::State::PlayerXWin(_) => {
scores.player_x_wins += 1;
game.start_next_game();
}
game::State::PlayerOWin(_) => {
scores.player_o_wins += 1;
game.start_next_game();
}
game::State::CatsGame => {
scores.cats_games += 1;
game.start_next_game();
}
};
print_battle_progress(
scores.total_games(),
player_x_name,
player_o_name,
&mut last_print_progress_time,
);
}
scores
}
// Prints the table's header.
fn print_table_header() {
println!("{:10} {:^18} {:^18}", "Difficulty", "None", "Unbeatable");
println!("{:=<10} {:=<18} {:=<18}", "", "", "");
}
// Prints a row of the table.
fn print_table_row(col_1: &str, col_2: &str, col_3: &str) {
println!("{:10} {:18} {:18}", col_1, col_2, col_3);
}
// Occasionally prints the progress of a battle.
fn print_battle_progress(
games_played: i32,
player_x_name: &str,
player_o_name: &str,
last_update_time: &mut time::Instant,
) {
// The time between updates is set so users can see the program is making
// progress but so it does not go so fast that the display is just a blur.
const UPDATE_INTERVAL: time::Duration = time::Duration::from_millis(100);
if last_update_time.elapsed() >= UPDATE_INTERVAL {
// Create a description of the progress using the player names abd
// number of games played.
let battle_progress = games_played as f64 / NUM_GAMES as f64;
let progress_text = format!(
"{} vs. {} game {} of {}, ({:.0}%)",
player_x_name,
player_o_name,
games_played,
NUM_GAMES,
battle_progress * 100.0
);
// Print the progress text. The text is padded with spaces and ended with
// a carriage return so old progress text is overwritten with new text.
// Also, the standard output is flushed so the user sees the text we
// printed instead of it getting stuck in the buffer.
print!("{:50}\r", progress_text);
let _ignored_result = io::stdout().flush();
*last_update_time = time::Instant::now();
}
}
// Gets the name of a provided AI difficulty.
fn get_difficulty_name(difficulty: &ai::Difficulty) -> &str {
match difficulty {
ai::Difficulty::None => "None",
ai::Difficulty::Easy => "Easy",
ai::Difficulty::Medium => "Medium",
ai::Difficulty::Hard => "Hard",
ai::Difficulty::Unbeatable => "Unbeatable",
ai::Difficulty::Custom(_) => "Custom",
}
}
// Holds the battle's scores and provides convenience methods for calculating
// the percentage of wins or cats games.
struct BattleScores {
player_x_wins: i32,
player_o_wins: i32,
cats_games: i32,
}
impl BattleScores {
fn new() -> Self {
BattleScores {
player_x_wins: 0,
player_o_wins: 0,
cats_games: 0,
}
}
fn total_games(&self) -> i32 {
self.player_x_wins + self.player_o_wins + self.cats_games
}
fn player_x_win_percent(&self) -> f64 {
self.calculate_percent(self.player_x_wins)
}
fn player_o_win_percent(&self) -> f64 {
self.calculate_percent(self.player_o_wins)
}
fn cats_game_percent(&self) -> f64 {
self.calculate_percent(self.cats_games)
}
fn calculate_percent(&self, value: i32) -> f64 {
if self.total_games() > 0 {
let fraction = value as f64 / self.total_games() as f64;
fraction * 100.0
} else {
0.0
}
}
}
impl fmt::Display for BattleScores {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{:3.0}% - {:3.0}% - {:3.0}%",
self.player_x_win_percent(),
self.player_o_win_percent(),
self.cats_game_percent()
)?;
Ok(())
}
}
| true |
97f4222e355158beeb5fb69700dac159d7387bcb
|
Rust
|
Kerollmops/slice-group-by
|
/src/linear_str_group/mod.rs
|
UTF-8
| 5,346 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
macro_rules! str_group_by_wrapped {
(struct $name:ident, $elem:ty) => {
impl<'a> $name<'a> {
#[inline]
pub fn as_str(&self) -> &str {
self.0.as_str()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
#[inline]
pub fn remainder_len(&self) -> usize {
self.0.remainder_len()
}
}
impl<'a> std::iter::Iterator for $name<'a> {
type Item = $elem;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
fn last(self) -> Option<Self::Item> {
self.0.last()
}
}
impl<'a> DoubleEndedIterator for $name<'a> {
#[inline]
fn next_back(&mut self) -> Option<Self::Item> {
self.0.next_back()
}
}
impl<'a> std::iter::FusedIterator for $name<'a> { }
}
}
mod linear_str_group;
mod linear_str_group_by;
mod linear_str_group_by_key;
pub use self::linear_str_group::{LinearStrGroup, LinearStrGroupMut};
pub use self::linear_str_group_by::{LinearStrGroupBy, LinearStrGroupByMut};
pub use self::linear_str_group_by_key::{LinearStrGroupByKey, LinearStrGroupByKeyMut};
fn str_as_ptr(string: &str) -> *const u8 {
string.as_bytes().as_ptr()
}
fn str_as_mut_ptr(string: &mut str) -> *mut u8 {
unsafe { string.as_bytes_mut().as_mut_ptr() }
}
unsafe fn str_from_raw_parts<'a>(data: *const u8, len: usize) -> &'a str {
let slice = std::slice::from_raw_parts(data, len);
std::str::from_utf8_unchecked(slice)
}
unsafe fn str_from_raw_parts_mut<'a>(data: *mut u8, len: usize) -> &'a mut str {
let slice = std::slice::from_raw_parts_mut(data, len);
std::str::from_utf8_unchecked_mut(slice)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn str_easy() {
let string = "aaaabbbbbaacccc";
let mut iter = LinearStrGroup::new(string);
assert_eq!(iter.next(), Some("aaaa"));
assert_eq!(iter.next(), Some("bbbbb"));
assert_eq!(iter.next(), Some("aa"));
assert_eq!(iter.next(), Some("cccc"));
assert_eq!(iter.next(), None);
}
#[test]
fn str_mut_easy() {
let mut string = String::from("aaaabbbbbaacccc");
let mut iter = LinearStrGroupMut::new(&mut string);
assert_eq!(iter.next().map(|s| &*s), Some("aaaa"));
assert_eq!(iter.next().map(|s| &*s), Some("bbbbb"));
assert_eq!(iter.next().map(|s| &*s), Some("aa"));
assert_eq!(iter.next().map(|s| &*s), Some("cccc"));
assert_eq!(iter.next(), None);
}
#[test]
fn str_kanji() {
let string = "包包饰饰与与钥钥匙匙扣扣";
let mut iter = LinearStrGroup::new(string);
assert_eq!(iter.next(), Some("包包"));
assert_eq!(iter.next(), Some("饰饰"));
assert_eq!(iter.next(), Some("与与"));
assert_eq!(iter.next(), Some("钥钥"));
assert_eq!(iter.next(), Some("匙匙"));
assert_eq!(iter.next(), Some("扣扣"));
assert_eq!(iter.next(), None);
}
fn is_cjk(c: char) -> bool {
(c >= '\u{2e80}' && c <= '\u{2eff}') ||
(c >= '\u{2f00}' && c <= '\u{2fdf}') ||
(c >= '\u{3040}' && c <= '\u{309f}') ||
(c >= '\u{30a0}' && c <= '\u{30ff}') ||
(c >= '\u{3100}' && c <= '\u{312f}') ||
(c >= '\u{3200}' && c <= '\u{32ff}') ||
(c >= '\u{3400}' && c <= '\u{4dbf}') ||
(c >= '\u{4e00}' && c <= '\u{9fff}') ||
(c >= '\u{f900}' && c <= '\u{faff}')
}
#[test]
fn str_ascii_cjk() {
let string = "abc包包bbccdd饰饰";
let mut iter = LinearStrGroupBy::new(string, |a, b| is_cjk(a) == is_cjk(b));
assert_eq!(iter.next(), Some("abc"));
assert_eq!(iter.next(), Some("包包"));
assert_eq!(iter.next(), Some("bbccdd"));
assert_eq!(iter.next(), Some("饰饰"));
assert_eq!(iter.next(), None);
}
#[test]
fn str_rev_easy() {
let string = "aaaabbbbbaacccc";
let mut iter = LinearStrGroup::new(string).rev();
assert_eq!(iter.next(), Some("cccc"));
assert_eq!(iter.next(), Some("aa"));
assert_eq!(iter.next(), Some("bbbbb"));
assert_eq!(iter.next(), Some("aaaa"));
assert_eq!(iter.next(), None);
}
#[test]
fn str_mut_rev_easy() {
let mut string = String::from("aaaabbbbbaacccc");
let mut iter = LinearStrGroupMut::new(&mut string).rev();
assert_eq!(iter.next().map(|s| &*s), Some("cccc"));
assert_eq!(iter.next().map(|s| &*s), Some("aa"));
assert_eq!(iter.next().map(|s| &*s), Some("bbbbb"));
assert_eq!(iter.next().map(|s| &*s), Some("aaaa"));
assert_eq!(iter.next(), None);
}
#[test]
fn str_rev_ascii_cjk() {
let string = "abc包包bbccdd饰饰";
let mut iter = LinearStrGroupBy::new(string, |a, b| is_cjk(a) == is_cjk(b)).rev();
assert_eq!(iter.next(), Some("饰饰"));
assert_eq!(iter.next(), Some("bbccdd"));
assert_eq!(iter.next(), Some("包包"));
assert_eq!(iter.next(), Some("abc"));
assert_eq!(iter.next(), None);
}
}
| true |
b15f2dd0a1478ae0b6015384bc99fbad4b0ec122
|
Rust
|
brotheryeska/domain_try
|
/src/pages/applications/apis/settings.rs
|
UTF-8
| 5,541 | 2.765625 | 3 |
[] |
no_license
|
use yew::prelude::*;
use yew_router::components::RouterAnchor;
use crate::app::AppRoute;
use super::quickstart::Quickstart;
use super::tab_settings::TabSettings;
pub enum Content {
Quickstart,
Settings
}
pub struct ApisSettings {
content: Content,
link: ComponentLink<Self>
}
pub enum Msg {
ChangeContent(Content)
}
impl Component for ApisSettings {
type Message = Msg;
type Properties = ();
fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
ApisSettings {
content: Content::Quickstart,
link
}
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::ChangeContent(content) => {
self.content = content;
true
}
}
}
fn change(&mut self, _: Self::Properties) -> ShouldRender {
false
}
fn view(&self) -> Html {
type Anchor = RouterAnchor<AppRoute>;
html! {
<div
class="py-5 px-4 m-auto"
style="max-width: 1048px; font-size:14px;"
>
<Anchor
route=AppRoute::ApisHome{ tenant_id: String::from("testing_id") }
classes="text-decoration-none domain-link-dark"
>
<i class="bi bi-arrow-left me-2"></i>
{"Back to Apis"}
</Anchor>
<div
class="d-flex mb-5 mt-3"
>
<div
style="flex: 0 0 auto; width: 64px; height: 64px; background-color: #eff0f2;"
class="d-flex justify-content-center align-items-center rounded me-4"
>
<i class="bi bi-server fs-3"></i>
</div>
<div
class="d-flex flex-column"
>
<h2>{"Testing Name"}</h2>
<div
class="text-muted"
>
<span
class="me-4"
>
{"Custom API"}
</span>
<span>
{"Identifier"}
</span>
<span
class="rounded ms-2"
style="
background-color: #eff0f2;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
font-size: 14px;
padding: 2px 6px;
font-family: 'Roboto Mono', monospace;
"
>
{"https://test-api/"}
</span>
</div>
</div>
</div>
<div
class="mb-4"
>
<ul class="nav nav-tabs">
<li
onclick=self.link.callback(|_| Msg::ChangeContent(Content::Quickstart))
class="nav-item"
>
<a
// class="nav-link active"
class={
match self.content {
Content::Quickstart => "nav-link active",
_ => "nav-link"
}
}
aria-current="page"
href="#"
>
{"Quick Start"}</a>
</li>
<li
onclick=self.link.callback(|_| Msg::ChangeContent(Content::Settings))
class="nav-item">
<a
// class="nav-link"
class={
match self.content {
Content::Settings => "nav-link active",
_ => "nav-link"
}
}
href="#">{"Settings"}</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">{"Permissions"}</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">{"Machine to Machine Applications"}</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">{"Test"}</a>
</li>
</ul>
</div>
// <Quickstart/>
// <TabSettings/>
{
match self.content {
Content::Quickstart => html! { <Quickstart/> },
Content::Settings => html! { <TabSettings/> }
}
}
</div>
}
}
}
| true |
055d6960670563d31035bc492158346be36e67e3
|
Rust
|
j-rock/sports3dgame
|
/src/lib/entity/physical_world.rs
|
UTF-8
| 1,329 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
use app::StatusOr;
use controls::KeyboardControls;
use dimensions::time::DeltaTime;
use entity::{
Athlete,
Ball,
HexGrid,
};
use glm;
use nalgebra;
use nphysics3d;
pub struct PhysicalWorld {
athlete: Athlete,
ball: Ball,
hex_grid: HexGrid,
world: nphysics3d::world::World<f32>,
}
impl PhysicalWorld {
pub fn new() -> StatusOr<PhysicalWorld> {
let mut world = nphysics3d::world::World::new();
world.set_gravity(nalgebra::Vector3::new(0.0, -50.00, 0.0));
let hex_grid = HexGrid::new(&mut world)?;
Ok(PhysicalWorld {
athlete: Athlete::new()?,
ball: Ball::new()?,
hex_grid,
world,
})
}
pub fn update(&mut self, keyboard: &KeyboardControls, dt: DeltaTime) {
// Pre-physics step
self.athlete.update(dt, keyboard, &mut self.world);
self.ball.update(dt, &mut self.world);
self.hex_grid.update(dt);
// Apply physics
self.world.step(dt.as_f32_seconds());
// Post-physics step
self.athlete.apply_physics();
self.ball.apply_physics();
}
pub fn draw(&self, projection_view: &glm::Mat4) {
self.athlete.draw(projection_view);
self.ball.draw(projection_view);
self.hex_grid.draw(projection_view);
}
}
| true |
3a361bd82df02b701c5039535d6ee9896f4ead44
|
Rust
|
IThawk/rust-project
|
/rust-master/src/test/ui/match/match-range-fail.rs
|
UTF-8
| 545 | 2.6875 | 3 |
[
"Apache-2.0",
"MIT",
"LicenseRef-scancode-other-permissive",
"BSD-3-Clause",
"BSD-2-Clause",
"NCSA"
] |
permissive
|
fn main() {
match "wow" {
"bar" ..= "foo" => { }
};
//~^^ ERROR only char and numeric types are allowed in range
//~| start type: &'static str
//~| end type: &'static str
match "wow" {
10 ..= "what" => ()
};
//~^^ ERROR only char and numeric types are allowed in range
//~| start type: {integer}
//~| end type: &'static str
match 5 {
'c' ..= 100 => { }
_ => { }
};
//~^^^ ERROR mismatched types
//~| expected type `{integer}`
//~| found type `char`
}
| true |
ca0ddf519ea2dcc74111507a0ff20f1f28ba1283
|
Rust
|
kitty7756/contagion
|
/src/simulation/state.rs
|
UTF-8
| 4,126 | 2.859375 | 3 |
[] |
no_license
|
use crate::core::vector::*;
use crate::core::scalar::Scalar;
use crate::core::geo::polygon::*;
use crate::simulation::ai::path::Path;
use std::collections::HashSet;
#[derive(Clone)]
pub struct State {
pub entities: Vec<Entity>,
pub buildings: Vec<Polygon>,
pub building_outlines: Vec<Polygon>,
pub selection: HashSet<usize>,
pub projectiles: Vec<Projectile>,
pub rng: rand_xorshift::XorShiftRng,
}
pub const ENTITY_RADIUS: Scalar = 0.5;
pub const ENTITY_DRAG: Scalar = 1.0;
#[derive(Clone)]
pub struct Entity {
pub position: Vector2,
pub velocity: Vector2,
pub facing_angle: Scalar,
pub behaviour: Behaviour,
}
impl Entity {
pub fn get_facing_normal(&self) -> Vector2 {
Vector2::from_angle(self.facing_angle)
}
pub fn look_along_angle(&mut self, angle: Scalar, delta_time: Scalar) {
let delta_theta = (angle - self.facing_angle) % 6.28;
let angular_deviation = if delta_theta < 3.14 { delta_theta } else { delta_theta - 6.28 };
self.facing_angle += delta_time * angular_deviation;
}
pub fn look_along_vector(&mut self, vector: Vector2, delta_time: Scalar) {
self.look_along_angle(vector.angle(), delta_time);
}
pub fn look_at_point(&mut self, point: Vector2, delta_time: Scalar) {
self.look_along_vector(point - self.position, delta_time);
}
pub fn accelerate_along_vector(&mut self, vector: Vector2, delta_time: Scalar, force: Scalar) {
self.look_along_vector(vector, delta_time);
self.velocity += delta_time * force * vector.normalize();
}
}
pub const COP_MOVEMENT_FORCE: Scalar = 1.5;
pub const CIVILIAN_MOVEMENT_FORCE: Scalar = 1.0;
pub const ZOMBIE_MOVEMENT_FORCE: Scalar = 1.6;
pub const COP_RELOAD_COOLDOWN: Scalar = 4.0;
pub const COP_AIM_TIME_MEAN: Scalar = 1.0;
// Used only for log normal distribution, and we're presently using exponential distribution
// pub const COP_AIM_TIME_STD_DEV: Scalar = 1.0;
pub const COP_ANGULAR_ACCURACY_STD_DEV: Scalar = 0.1;
pub const COP_MAGAZINE_CAPACITY: i64 = 6;
pub const ZOMBIE_SIGHT_RADIUS: f64 = 30.0;
pub const ZOMBIE_SIGHT_RADIUS_SQUARE: f64 = ZOMBIE_SIGHT_RADIUS * ZOMBIE_SIGHT_RADIUS;
pub const HUMAN_SIGHT_RADIUS: f64 = 40.0;
pub const HUMAN_SIGHT_RADIUS_SQUARE: f64 = HUMAN_SIGHT_RADIUS * HUMAN_SIGHT_RADIUS;
pub const COP_SIGHT_RADIUS: f64 = 50.0;
pub const COP_SIGHT_RADIUS_SQUARE: f64 = COP_SIGHT_RADIUS * COP_SIGHT_RADIUS;
#[derive(Clone, PartialEq)]
pub enum Behaviour {
Cop {
rounds_in_magazine: i64,
// state: CopState
// A stack of the cop's states
// - The current state is the state on top of the stack
// - When the cop finishes with a state that state is popped from the stack
// - If there are no states in the stack, the cop is idle
state_stack: Vec<CopState>
},
Dead,
Human,
Zombie {
state: ZombieState
}
}
pub const COP_MIN_DISTANCE_FROM_WAYPOINT_SQUARED: Scalar = 0.2;
#[derive(Clone, PartialEq, Debug)]
pub enum CopState {
Aiming {
aim_time_remaining: Scalar,
target_index: usize,
},
Moving {
waypoint: Vector2,
mode: MoveMode,
path: Option<Path>
},
Reloading {
reload_time_remaining: Scalar,
},
AttackingZombie {
target_index: usize,
path: Option<Path>,
},
}
#[derive(Clone, PartialEq)]
pub enum ZombieState {
Chasing {
target_index: usize
},
Moving {
waypoint: Vector2
},
Roaming
}
pub const PROJECTILE_DRAG: Scalar = 1.0;
#[derive(Copy, Clone, PartialEq)]
pub struct Projectile {
pub position: Vector2,
pub velocity: Vector2,
pub kind: ProjectileKind,
}
pub const BULLET_RADIUS: Scalar = 0.12;
pub const BULLET_SPEED: Scalar = 40.0;
pub const BULLET_SPEED_MIN: Scalar = 10.0;
pub const BULLET_SPAWN_DISTANCE_MULTIPLIER: Scalar = 1.25;
pub const CASING_SPEED: Scalar = 1.0;
#[derive(Copy, Clone, PartialEq)]
pub enum ProjectileKind {
Bullet,
Casing,
}
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum MoveMode {
Moving,
Sprinting
}
| true |
521009cdc7a0a56772f7c0717cb1a30da780ef1b
|
Rust
|
lpil/exercism
|
/rust/sum-of-multiples/src/lib.rs
|
UTF-8
| 295 | 3.3125 | 3 |
[] |
no_license
|
pub fn sum_of_multiples(n: usize, factors: &Vec<usize>) -> usize {
(1..n)
.into_iter()
.filter(|x| is_multiple(factors, x))
.fold(0, |acc, x| x + acc)
}
fn is_multiple(factors: &Vec<usize>, num: &usize) -> bool {
factors.iter().any(|factor| num % factor == 0)
}
| true |
83105183984699cf73efabcff43a21c703ba800d
|
Rust
|
rustwasm/wasm-bindgen
|
/crates/web-sys/tests/wasm/html_element.rs
|
UTF-8
| 4,429 | 2.890625 | 3 |
[
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
use wasm_bindgen::prelude::*;
use wasm_bindgen_test::*;
use web_sys::HtmlElement;
#[wasm_bindgen(module = "/tests/wasm/element.js")]
extern "C" {
fn new_html() -> HtmlElement;
}
#[wasm_bindgen_test]
fn test_html_element() {
let element = new_html();
assert!(element.is_instance_of::<HtmlElement>());
assert_eq!(element.title(), "", "Shouldn't have a title");
element.set_title("boop");
assert_eq!(element.title(), "boop", "Should have a title");
assert_eq!(element.lang(), "", "Shouldn't have a lang");
element.set_lang("en-us");
assert_eq!(element.lang(), "en-us", "Should have a lang");
assert_eq!(element.dir(), "", "Shouldn't have a dir");
element.set_dir("ltr");
assert_eq!(element.dir(), "ltr", "Should have a dir");
assert_eq!(element.inner_text(), "", "Shouldn't have inner_text");
element.set_inner_text("hey");
assert_eq!(element.inner_text(), "hey", "Should have inner_text");
assert!(!element.hidden(), "Shouldn't be hidden");
element.set_hidden(true);
assert!(element.hidden(), "Should be hidden");
assert_eq!(
element.class_list().get(0),
None,
"Shouldn't have class at index 0"
);
element.class_list().add_2("a", "b").unwrap();
assert_eq!(
element.class_list().get(0).unwrap(),
"a",
"Should have class at index 0"
);
assert_eq!(
element.class_list().get(1).unwrap(),
"b",
"Should have class at index 1"
);
assert_eq!(
element.class_list().get(2),
None,
"Shouldn't have class at index 2"
);
assert_eq!(element.dataset().get("id"), None, "Shouldn't have data-id");
element.dataset().set("id", "123").unwrap();
assert_eq!(
element.dataset().get("id").unwrap(),
"123",
"Should have data-id"
);
assert_eq!(
element.style().get(0),
None,
"Shouldn't have style property name at index 0"
);
element
.style()
.set_property("background-color", "red")
.unwrap();
assert_eq!(
element.style().get(0).unwrap(),
"background-color",
"Should have style property at index 0"
);
assert_eq!(
element
.style()
.get_property_value("background-color")
.unwrap(),
"red",
"Should have style property"
);
// TODO add a click handler here
element.click();
assert_eq!(element.tab_index(), -1, "Shouldn't be tab_index");
element.set_tab_index(1);
assert_eq!(element.tab_index(), 1, "Should be tab_index");
// TODO add a focus handler here
assert_eq!(element.focus().unwrap(), (), "No result");
// TODO add a blur handler here
assert_eq!(element.blur().unwrap(), (), "No result");
assert_eq!(element.access_key(), "", "Shouldn't have a access_key");
element.set_access_key("a");
assert_eq!(element.access_key(), "a", "Should have a access_key");
// TODO add test for access_key_label
assert!(!element.draggable(), "Shouldn't be draggable");
element.set_draggable(true);
assert!(element.draggable(), "Should be draggable");
assert_eq!(
element.content_editable(),
"inherit",
"Shouldn't have a content_editable"
);
element.set_content_editable("true");
assert_eq!(
element.content_editable(),
"true",
"Should be content_editable"
);
assert!(element.is_content_editable(), "Should be content_editable");
element.set_spellcheck(false);
assert!(!element.spellcheck(), "Shouldn't be spellchecked");
element.set_spellcheck(true);
assert!(element.spellcheck(), "Should be spellchecked");
// TODO verify case where we have an offset_parent
match element.offset_parent() {
None => assert!(true, "Shouldn't have an offset_parent set"),
_ => assert!(false, "Shouldn't have a offset_parent set"),
};
// TODO verify when we have offsets
assert_eq!(element.offset_top(), 0, "Shouldn't have an offset_top yet");
assert_eq!(
element.offset_left(),
0,
"Shouldn't have an offset_left yet"
);
assert_eq!(
element.offset_width(),
0,
"Shouldn't have an offset_width yet"
);
assert_eq!(
element.offset_height(),
0,
"Shouldn't have an offset_height yet"
);
}
| true |
cd90b2f92ed0a9cac6060175783aa6b217200a62
|
Rust
|
richard-dennehy/raytracer_rs
|
/src/ppm_writer/tests.rs
|
UTF-8
| 2,943 | 3.125 | 3 |
[] |
no_license
|
use super::*;
mod unit_tests {
use super::*;
use crate::core::Colour;
use std::num::NonZeroU16;
#[test]
fn should_generate_correct_header() {
let ppm = write_ppm(
&Canvas::new(NonZeroU16::new(5).unwrap(), NonZeroU16::new(3).unwrap()).unwrap(),
);
let header = ppm
.lines()
.take(3)
.map(|line| format!("{}\n", line))
.collect::<String>();
assert_eq!(header, "P3\n5 3\n255\n");
}
#[test]
fn should_generate_correct_pixel_data() {
let mut canvas =
Canvas::new(NonZeroU16::new(5).unwrap(), NonZeroU16::new(3).unwrap()).unwrap();
canvas.set(0, 0, Colour::new(1.5, 0.0, 0.0));
canvas.set(2, 1, Colour::new(0.0, 0.5, 0.0));
canvas.set(4, 2, Colour::new(-0.5, 0.0, 1.0));
let ppm = write_ppm(&canvas);
let pixel_data = ppm
.lines()
.skip(3)
.map(|line| format!("{}\n", line))
.collect::<String>();
assert_eq!(
pixel_data,
"255 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 128 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 255
"
);
}
#[test]
fn ppm_colour_value_should_clamp_negative_colour_values_to_0() {
assert_eq!(ppm_colour_value(-1.0), 0);
}
#[test]
fn ppm_colour_value_should_clamp_colour_values_greater_than_1_f64_to_255() {
assert_eq!(ppm_colour_value(2.0), MAX_COLOUR_VALUE);
}
#[test]
fn ppm_colour_value_should_convert_1_f64_to_255() {
assert_eq!(ppm_colour_value(1.0), MAX_COLOUR_VALUE);
}
#[test]
fn ppm_colour_value_should_convert_0_f64_to_0() {
assert_eq!(ppm_colour_value(0.0), 0);
}
#[test]
fn ppm_colour_value_should_convert_0_5_f64_to_128() {
assert_eq!(ppm_colour_value(0.5), 128);
}
#[test]
fn should_limit_line_length_to_70() {
let mut canvas =
Canvas::new(NonZeroU16::new(10).unwrap(), NonZeroU16::new(2).unwrap()).unwrap();
for x in 0..10 {
for y in 0..2 {
canvas.set(x, y, Colour::new(1.0, 0.8, 0.6))
}
}
let ppm = write_ppm(&canvas);
let pixel_data = ppm
.lines()
.skip(3)
.map(|line| format!("{}\n", line))
.collect::<String>();
assert_eq!(
pixel_data,
"255 204 153 255 204 153 255 204 153 255 204 153 255 204 153 255 204
153 255 204 153 255 204 153 255 204 153 255 204 153
255 204 153 255 204 153 255 204 153 255 204 153 255 204 153 255 204
153 255 204 153 255 204 153 255 204 153 255 204 153
"
);
}
#[test]
fn should_end_ppm_with_newline() {
let ppm = write_ppm(
&Canvas::new(NonZeroU16::new(5).unwrap(), NonZeroU16::new(3).unwrap()).unwrap(),
);
assert_eq!(ppm.chars().last(), Some('\n'))
}
}
| true |
115b215ae349da9735a44d630953af21cbe0a43a
|
Rust
|
xjump/speedy
|
/src/readable.rs
|
UTF-8
| 1,986 | 2.984375 | 3 |
[
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
use std::io::{
self,
Read
};
use crate::reader::Reader;
use crate::context::Context;
use crate::endianness::Endianness;
struct StreamReader< C: Context, S: Read > {
context: C,
reader: S
}
impl< 'a, C: Context, S: Read > Reader< 'a, C > for StreamReader< C, S > {
#[inline(always)]
fn read_bytes( &mut self, output: &mut [u8] ) -> io::Result< () > {
self.reader.read_exact( output )
}
#[inline(always)]
fn context( &self ) -> &C {
&self.context
}
#[inline(always)]
fn context_mut( &mut self ) -> &mut C {
&mut self.context
}
}
impl< C: Context, S: Read > StreamReader< C, S > {
#[inline]
fn deserialize< 'a, T: Readable< 'a, C > >( context: C, reader: S ) -> io::Result< T > {
let mut reader = StreamReader { context, reader };
T::read_from( &mut reader )
}
}
pub trait Readable< 'a, C: Context >: Sized {
fn read_from< R: Reader< 'a, C > >( reader: &mut R ) -> io::Result< Self >;
#[inline]
fn minimum_bytes_needed() -> usize {
0
}
#[inline]
fn read_from_buffer( context: C, mut buffer: &'a [u8] ) -> io::Result< Self > {
StreamReader::deserialize( context, &mut buffer )
}
#[inline]
fn read_from_buffer_owned( context: C, mut buffer: &[u8] ) -> io::Result< Self > {
StreamReader::deserialize( context, &mut buffer )
}
#[inline]
fn read_from_stream< S: Read >( context: C, stream: S ) -> io::Result< Self > {
StreamReader::deserialize( context, stream )
}
// Since specialization is not stable yet we do it this way.
#[doc(hidden)]
#[inline(always)]
fn speedy_is_primitive() -> bool {
false
}
#[doc(hidden)]
#[inline]
unsafe fn speedy_slice_as_bytes_mut( _: &mut [Self] ) -> &mut [u8] {
panic!();
}
#[doc(hidden)]
#[inline]
fn speedy_convert_slice_endianness( _: Endianness, _: &mut [Self] ) {
panic!()
}
}
| true |
7f611921587aed124e4fa512752d91fc792029f6
|
Rust
|
onlyafly/macaroon
|
/src/ast.rs
|
UTF-8
| 8,540 | 3 | 3 |
[
"MIT"
] |
permissive
|
use back::env::SmartEnv;
use back::eval::NodeResult;
use back::runtime_error::RuntimeError;
use loc::Loc;
use std::cell::RefCell;
use std::cmp::Ordering;
use std::fmt;
use std::fmt::{Display, Formatter};
use std::ops::Deref;
use std::rc::Rc;
#[derive(PartialEq, Debug, Clone)]
pub enum Val {
Nil,
Error(String),
Number(i32),
Character(String),
StringVal(String),
Symbol(String),
Boolean(bool),
Routine(RoutineObj),
Primitive(PrimitiveObj),
List(Vec<Node>),
Writer(WriterObj),
Reader(ReaderObj),
Environment(SmartEnv),
Cell(CellObj),
}
impl Display for Val {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Val::Nil => write!(f, "nil"),
Val::Error(ref s) => write!(f, "#error<{}>", s),
Val::Number(n) => write!(f, "{}", n),
Val::StringVal(ref s) => write!(f, "\"{}\"", s),
Val::Character(ref s) => match s.as_ref() {
"\n" => write!(f, r"\newline"),
_ => write!(f, r"\{}", s),
},
Val::Symbol(ref s) => write!(f, "{}", s),
Val::List(ref children) => {
let mut v = Vec::new();
for child in children {
v.push(format!("{}", child.val));
}
write!(f, "({})", &v.join(" "))
}
Val::Boolean(false) => write!(f, "false"),
Val::Boolean(true) => write!(f, "true"),
Val::Routine(RoutineObj {
routine_type: RoutineType::Function,
name: None,
..
}) => write!(f, "#function"),
Val::Routine(RoutineObj {
routine_type: RoutineType::Function,
name: Some(s),
..
}) => write!(f, "#function<{}>", s),
Val::Routine(RoutineObj {
routine_type: RoutineType::Macro,
name: None,
..
}) => write!(f, "#macro"),
Val::Routine(RoutineObj {
routine_type: RoutineType::Macro,
name: Some(s),
..
}) => write!(f, "#macro<{}>", s),
Val::Primitive(PrimitiveObj { name, .. }) => write!(f, "#primitive<{}>", name),
Val::Writer(..) => write!(f, "#writer"),
Val::Reader(..) => write!(f, "#reader"),
Val::Environment(env) => write!(f, "#environment<{}>", env.borrow().name),
Val::Cell(obj) => write!(f, "(cell {})", obj),
}
}
}
impl Val {
pub fn type_name(&self) -> Result<String, RuntimeError> {
let out = match self {
Val::Nil => "nil",
Val::Error(..) => "error",
Val::Number(..) => "number",
Val::StringVal(..) => "string",
Val::Character(..) => "char",
Val::Symbol(..) => "symbol",
Val::List(..) => "list",
Val::Boolean(..) => "boolean",
Val::Routine(..) => "function",
Val::Primitive(..) => "primitive",
Val::Writer(..) => "writer",
Val::Reader(..) => "reader",
Val::Environment(..) => "environment",
Val::Cell(..) => "cell",
};
Ok(out.to_string())
}
}
impl PartialOrd for Val {
fn partial_cmp(&self, other: &Val) -> Option<Ordering> {
use self::Val::*;
match (self, other) {
(Number(a), Number(b)) => a.partial_cmp(b),
_ => None,
}
}
}
#[derive(Debug, Clone)]
pub struct Node {
pub val: Val,
pub loc: Loc,
}
impl Node {
pub fn new(val: Val, loc: Loc) -> Self {
Node { val, loc }
}
pub fn as_print_friendly_string(&self) -> String {
match self.val {
Val::StringVal(ref s) => format!("{}", s),
Val::Character(ref s) => format!("{}", s),
ref v => format!("{}", v), // Use Display's fmt for everything else
}
}
pub fn as_host_number(&self) -> Result<i32, RuntimeError> {
match self.val {
Val::Number(i) => Ok(i),
_ => Err(RuntimeError::UnexpectedValue(
"number".to_string(),
self.val.clone(),
self.loc.clone(),
)),
}
}
pub fn as_host_boolean(&self) -> Result<bool, RuntimeError> {
match self.val {
Val::Nil => Ok(false),
Val::Boolean(b) => Ok(b),
_ => Ok(true),
}
}
/* TODO
pub fn as_host_vector(&self) -> Result<bool, RuntimeError> {
match self {
&Val::Nil => Ok(false),
&Val::Boolean(b) => Ok(b),
_ => Ok(true),
}
} */
pub fn coll_len(self) -> Result<usize, RuntimeError> {
match self.val {
Val::Nil => Ok(0),
Val::StringVal(s) => Ok(s.chars().count()),
Val::List(children) => Ok(children.len()),
v => Err(RuntimeError::CannotGetLengthOfNonCollection(v, self.loc)),
}
}
pub fn coll_cons(self, elem: Node) -> Result<Node, RuntimeError> {
let loc = self.loc;
match self.val {
Val::Nil => Ok(Node::new(Val::List(vec![elem]), loc)),
Val::StringVal(s) => {
let loc = elem.loc;
let out = match elem.val {
Val::Character(c) => format!("{}{}", c, s),
v => return Err(RuntimeError::CannotConsNonCharacterOntoString(v, loc)),
};
Ok(Node::new(Val::StringVal(out), loc))
}
Val::List(mut children) => {
children.insert(0, elem);
Ok(Node::new(Val::List(children), loc))
}
v => Err(RuntimeError::CannotConsOntoNonCollection(v, loc)),
}
}
fn coll_children(self) -> Result<Vec<Node>, RuntimeError> {
let loc = self.loc;
match self.val {
Val::Nil => Ok(Vec::new()),
Val::StringVal(s) => Ok(s
.chars()
.map(|c| Node::new(Val::Character(format!("{}", c)), loc.clone()))
.collect()),
Val::List(children) => Ok(children),
v => Err(RuntimeError::CannotGetChildrenOfNonCollection(
"append".to_string(),
v,
loc,
)),
}
}
pub fn coll_append(self, other: Node) -> Result<Node, RuntimeError> {
match self.val {
Val::Nil => Ok(other),
Val::StringVal(s) => {
let output = format!("{}{}", s, other.as_print_friendly_string());
Ok(Node::new(Val::StringVal(output), self.loc))
}
Val::List(mut children) => {
let mut other_children = other.coll_children()?;
children.append(&mut other_children);
Ok(Node::new(Val::List(children), self.loc))
}
v => Err(RuntimeError::CannotAppendOnto(v, self.loc)),
}
}
}
// By implementing manually, we ensure that the metadata (loc, etc) is not checked
// for equality
impl PartialEq for Node {
fn eq(&self, other: &Node) -> bool {
self.val == other.val
}
}
impl Deref for Node {
type Target = Val;
fn deref(&self) -> &Val {
&self.val
}
}
#[derive(PartialEq, Debug, Clone)]
pub enum RoutineType {
Function,
Macro,
}
#[derive(PartialEq, Debug, Clone)]
pub struct RoutineObj {
pub name: Option<String>,
pub params: Vec<Node>,
pub body: Box<Node>,
pub lexical_env: SmartEnv,
pub routine_type: RoutineType,
}
pub type PrimitiveFnPointer = fn(SmartEnv, Node, Vec<Node>) -> NodeResult;
#[derive(PartialEq, Debug, Clone)]
pub struct PrimitiveObj {
pub name: String,
pub f: PrimitiveFnPointer,
pub min_arity: isize,
pub max_arity: isize,
}
#[derive(PartialEq, Debug, Clone)]
pub enum WriterObj {
Sink,
Standard,
Buffer(Rc<RefCell<Vec<u8>>>),
}
#[derive(PartialEq, Debug, Clone)]
pub struct ReaderObj {
pub reader_function: fn() -> Result<String, String>,
}
#[derive(PartialEq, Debug, Clone)]
pub struct CellObj {
pub contents: Rc<RefCell<Node>>,
}
impl CellObj {
pub fn new(n: Node) -> Self {
CellObj {
contents: Rc::new(RefCell::new(n)),
}
}
}
impl Display for CellObj {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}", self.contents.borrow_mut().val)
}
}
| true |
e3706019ad0f349107a58282c19055c2c062bc08
|
Rust
|
leontoeides/google_maps
|
/src/roads/status.rs
|
UTF-8
| 6,713 | 3.21875 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
//! The `"status"` field within the Roads API response object contains the
//! status of the request, and may contain debugging information to help you
//! track down why the Roads API is not working.
use crate::roads::error::Error;
use phf::phf_map;
use serde::{Deserialize, Serialize, Deserializer};
// -----------------------------------------------------------------------------
/// Indicates the status of the response.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub enum Status {
/// 1. Your API key is not valid or was not included in the request. Please
/// ensure that you've included the entire key, and that you've enabled the
/// API for this key.
///
/// 2. Your request contained invalid arguments. The most likely causes of this
/// error are:
///
/// * A problem with your path parameter.
/// * Please ensure you have at least 1, and fewer than 100 points. Each
/// point should be a pair of numbers separated by a comma, such as:
/// `48.409114,-123.369158`. Points should be separated by a pipe: '|'.
/// * Your request included an invalid `placeId`.
/// * Your request included both `placeId`s and a `path`. Only one of these
/// parameters may be specified for each request.
/// This error will not be returned if a `placeId` is passed for a road
/// which no longer exists, or for a place which is not a road.
#[serde(alias = "INVALID_ARGUMENT")]
InvalidArgument,
/// The request was denied for one or more of the following reasons:
///
/// * The API key is missing or invalid.
/// * Billing has not been enabled on your account.
/// * A self-imposed usage cap has been exceeded.
/// * The provided method of payment is no longer valid (for example, a
/// credit card has expired).
///
/// In order to use Google Maps Platform products, billing must be enabled
/// on your account, and all requests must include a valid API key. To fix
/// this, take the following steps:
///
/// * [Get an API key](https://developers.google.com/maps/documentation/roads/errors?hl=en#new-key)
/// * [Enable billing](https://console.cloud.google.com/project/_/billing/enable)
/// on your account.
/// * [Adjust your usage cap](https://developers.google.com/maps/documentation/roads/errors?hl=en#usage-cap)
/// to increase your daily limit (if applicable).
#[serde(alias = "PERMISSION_DENIED")]
PermissionDenied,
/// Ensure that you are sending requests to `https://roads.googleapis.com/`
/// and not `http://roads.googleapis.com/`.
#[serde(alias = "NOT_FOUND")]
NotFound,
/// You have exceeded the request limit that you configured in the Google
/// Cloud Platform Console. This limit is typically set as requests per day,
/// requests per 100 seconds, and requests per 100 seconds per user. This
/// limit should be configured to prevent a single or small group of users
/// from exhausting your daily quota, while still allowing reasonable access
/// to all users. See Capping API Usage to configure these limits.
#[serde(alias = "RESOURCE_EXHAUSTED")]
ResourceExhausted,
} // struct
// -----------------------------------------------------------------------------
impl<'de> Deserialize<'de> for Status {
/// Manual implementation of `Deserialize` for `serde`. This will take
/// advantage of the `phf`-powered `TryFrom` implementation for this type.
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let string = String::deserialize(deserializer)?;
match Status::try_from(string.as_str()) {
Ok(variant) => Ok(variant),
Err(error) => Err(serde::de::Error::custom(error.to_string()))
} // match
} // fn
} // impl
// -----------------------------------------------------------------------------
impl std::convert::From<&Status> for String {
/// Converts a `Status` enum to a `String` that contains a status
/// code.
fn from(status: &Status) -> String {
match status {
Status::InvalidArgument => String::from("INVALID_ARGUMENT"),
Status::PermissionDenied => String::from("PERMISSION_DENIED"),
Status::NotFound => String::from("NOT_FOUND"),
Status::ResourceExhausted => String::from("RESOURCE_EXHAUSTED"),
} // match
} // fn
} // impl
// -----------------------------------------------------------------------------
static STATUSES_BY_CODE: phf::Map<&'static str, Status> = phf_map! {
"INVALID_ARGUMENT" => Status::InvalidArgument,
"PERMISSION_DENIED" => Status::PermissionDenied,
"NOT_FOUND" => Status::NotFound,
"RESOURCE_EXHAUSTED" => Status::ResourceExhausted,
};
impl std::convert::TryFrom<&str> for Status {
// Error definitions are contained in the
// `google_maps\src\roads\error.rs` module.
type Error = crate::roads::error::Error;
/// Gets a `Status` enum from a `String` that contains a valid status
/// code.
fn try_from(status_code: &str) -> Result<Self, Self::Error> {
STATUSES_BY_CODE
.get(status_code)
.cloned()
.ok_or_else(|| Error::InvalidStatusCode(status_code.to_string()))
} // fn
} // impl
impl std::str::FromStr for Status {
// Error definitions are contained in the
// `google_maps\src\roads\error.rs` module.
type Err = crate::roads::error::Error;
/// Gets a `Status` enum from a `String` that contains a valid status
/// code.
fn from_str(status_code: &str) -> Result<Self, Self::Err> {
STATUSES_BY_CODE
.get(status_code)
.cloned()
.ok_or_else(|| Error::InvalidStatusCode(status_code.to_string()))
} // fn
} // impl
// -----------------------------------------------------------------------------
impl std::default::Default for Status {
/// Returns a reasonable default variant for the `Status` enum type.
fn default() -> Self {
Status::InvalidArgument
} // fn
} // impl
// -----------------------------------------------------------------------------
impl std::fmt::Display for Status {
/// Formats a `Status` enum into a string that is presentable to the end
/// user.
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Status::InvalidArgument => write!(f, "Invalid Argument"),
Status::PermissionDenied => write!(f, "Permission Denied"),
Status::NotFound => write!(f, "Not Found"),
Status::ResourceExhausted => write!(f, "Resource Exhausted"),
} // match
} // fn
} // impl
| true |
1e9799c98fcb7ceb5556580ec73c595cc53451bb
|
Rust
|
biryukovmaxim/peer
|
/src/config.rs
|
UTF-8
| 2,534 | 3.015625 | 3 |
[] |
no_license
|
use crate::errors::PeerError;
use clap::{App, Arg};
#[derive(Debug, Clone)]
pub struct Config {
pub my_address: String,
pub known_peer_address: Option<String>,
pub period: u64,
pub broadcast_size: usize,
}
impl Config {
pub fn read_config() -> Result<Self, PeerError> {
let mut config = Config {
my_address: "".to_string(),
known_peer_address: None,
period: 0,
broadcast_size: 0,
};
let matches = App::new("")
.about("simple p2p app")
.arg(
Arg::with_name("port")
.long("port")
.help("port on which the application will run")
.takes_value(true)
.required(true),
)
.arg(
Arg::with_name("period")
.long("period")
.value_name("X")
.help("every X second the peer will send gossip message to another known peers")
.takes_value(true)
.required(true),
)
.arg(
Arg::with_name("connect")
.long("connect")
.short("c")
.value_name("ipaddress>:<port")
.help("connect to first known peer")
.takes_value(true),
)
.arg(
Arg::with_name("broadcast_size")
.help("the maximum number of messages the Peer can retain at any given time")
.short("bs")
.takes_value(true)
.default_value("10"),
)
.get_matches();
match matches.value_of("port") {
Some(port) => config.my_address = format!("127.0.0.1:{}", port),
None => return Err(PeerError::ReadConfig("port is required".to_string())),
}
match matches.value_of("connect") {
Some(peer) => config.known_peer_address = Some(format!("127.0.0.1:{}", peer)),
None => config.known_peer_address = None,
}
match matches.value_of("broadcast_size") {
Some(size) => config.broadcast_size = size.parse::<usize>().unwrap_or(10),
None => config.broadcast_size = 10,
}
match matches.value_of("period") {
Some(size) => config.period = size.parse::<u64>().unwrap_or(10),
None => config.period = 10,
}
Ok(config)
}
}
| true |
fda6d31429818a48aded74a3e98ab07b79d2e6c5
|
Rust
|
nikhilkalige/stm32f411-bsp
|
/src/led.rs
|
UTF-8
| 641 | 3.078125 | 3 |
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
//! User LEDs
use stm32f411::{GPIOA, RCC};
/// Green LED (PA5)
pub struct Green;
/// Initializes the user LED
pub fn init(gpioa: &GPIOA, rcc: &RCC) {
// power on GPIOA
rcc.ahb1enr.modify(|_, w| w.gpioaen().set_bit());
// configure PA5 as output
unsafe {
gpioa.moder.write(|w| w.moder5().bits(1));
}
gpioa.bsrr.write(|w| w.bs5().set_bit());
}
impl Green {
/// Turns the LED on
pub fn on(&self) {
unsafe { (*GPIOA.get()).bsrr.write(|w| w.br5().set_bit()) }
}
/// Turns the LED off
pub fn off(&self) {
unsafe { (*GPIOA.get()).bsrr.write(|w| w.bs5().set_bit()) }
}
}
| true |
91c0cd4634bd47468594a68e4438e974d89d87ef
|
Rust
|
fifth-postulate/esche.rs
|
/eschers/src/rendering/mod.rs
|
UTF-8
| 3,560 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
//! Turning a `Rendering` into an SVG.
pub mod canvas;
use itertools::Itertools;
use svg::node::element as Svg;
use svg::node::Node;
use svg::Document;
use picture::Rendering;
use shape::Shape;
type Bounds = (f64, f64);
/// Create an SVG document from a `Rendering`
pub fn to_svg(bounds: Bounds, rendering: &Rendering) -> Document {
let mut document = Document::new().set("viewbox", (0.0, 0.0, bounds.0, bounds.1));
let mut group = Svg::Group::new().set(
"transform",
format!("scale(1,-1) translate(0,{})", -bounds.1),
);
for (shape, style) in rendering {
match shape {
Shape::Line(line_start, line_end) => {
let mut node = Svg::Line::new()
.set("x1", line_start.x)
.set("y1", line_start.y)
.set("x2", line_end.x)
.set("y2", line_end.y);
node.assign("stroke", "black");
node.assign("stroke-width", style.stroke_width);
node.assign("fill", "none");
group.append(node);
}
Shape::PolyLine(points) => {
let points = points
.iter()
.map(|point| format!("{},{}", point.x, point.y))
.join(" ");
let mut node = Svg::Polyline::new().set("points", points);
node.assign("stroke", "black");
node.assign("stroke-width", style.stroke_width);
node.assign("fill", "none");
group.append(node);
}
Shape::Polygon(points) => {
let points = points
.iter()
.map(|point| format!("{},{}", point.x, point.y))
.join(" ");
let mut node = Svg::Polygon::new().set("points", points);
node.assign("stroke", "black");
node.assign("stroke-width", style.stroke_width);
node.assign("fill", "none");
group.append(node);
}
Shape::Curve(p1, p2, p3, p4) => {
let d = format!(
"M{} {} C{} {}, {} {}, {} {}",
p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y,
);
let mut node = Svg::Path::new().set("d", d);
node.assign("stroke", "black");
node.assign("stroke-width", style.stroke_width);
node.assign("fill", "none");
group.append(node);
}
Shape::Path(start, cntrls) => {
let controls = cntrls
.iter()
.map(|control| {
format!(
"C{} {}, {} {}, {} {}",
control.mid_point1.x,
control.mid_point1.y,
control.mid_point2.x,
control.mid_point2.y,
control.end_point.x,
control.end_point.y,
)
}).join(" ");
let d = format!("M{},{} {}", start.x, start.y, controls);
let mut node = Svg::Path::new().set("d", d);
node.assign("stroke", "black");
node.assign("stroke-width", style.stroke_width);
node.assign("fill", "none");
group.append(node);
}
}
}
document.append(group);
document
}
| true |
fb9eca0b3f5d2dcda54fd070917ff1d4bb9bb865
|
Rust
|
RicoGit/rust-alg
|
/src/leetcode/contains_duplicate.rs
|
UTF-8
| 279 | 2.765625 | 3 |
[] |
no_license
|
//! 217. Contains Duplicate
impl Solution {
pub fn contains_duplicate(nums: Vec<i32>) -> bool {
let size = nums.len();
nums.into_iter()
.collect::<std::collections::HashSet<i32>>()
.len()
!= size
}
}
struct Solution;
| true |
7add5e3c25fef4aabbe0b8b8601bc960d39d0716
|
Rust
|
or17191/texlab
|
/src/syntax/latex/ast.rs
|
UTF-8
| 8,256 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
use crate::syntax::text::{Span, SyntaxNode};
use itertools::Itertools;
use lsp_types::Range;
use std::sync::Arc;
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum LatexTokenKind {
Word,
Command,
Math,
Comma,
BeginGroup,
EndGroup,
BeginOptions,
EndOptions,
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct LatexToken {
pub span: Span,
pub kind: LatexTokenKind,
}
impl LatexToken {
pub fn new(span: Span, kind: LatexTokenKind) -> Self {
Self { span, kind }
}
pub fn text(&self) -> &str {
&self.span.text
}
}
impl SyntaxNode for LatexToken {
fn range(&self) -> Range {
self.span.range()
}
}
#[derive(Debug, PartialEq, Eq, Clone, Default)]
pub struct LatexRoot {
pub children: Vec<LatexContent>,
}
impl LatexRoot {
pub fn new(children: Vec<LatexContent>) -> Self {
Self { children }
}
}
impl SyntaxNode for LatexRoot {
fn range(&self) -> Range {
if self.children.is_empty() {
Range::new_simple(0, 0, 0, 0)
} else {
Range::new(
self.children[0].start(),
self.children[self.children.len() - 1].end(),
)
}
}
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum LatexContent {
Group(Arc<LatexGroup>),
Command(Arc<LatexCommand>),
Text(Arc<LatexText>),
Comma(Arc<LatexComma>),
Math(Arc<LatexMath>),
}
impl LatexContent {
pub fn accept<T: LatexVisitor>(&self, visitor: &mut T) {
match self {
LatexContent::Group(group) => visitor.visit_group(Arc::clone(&group)),
LatexContent::Command(command) => visitor.visit_command(Arc::clone(&command)),
LatexContent::Text(text) => visitor.visit_text(Arc::clone(&text)),
LatexContent::Comma(comma) => visitor.visit_comma(Arc::clone(&comma)),
LatexContent::Math(math) => visitor.visit_math(Arc::clone(&math)),
}
}
}
impl SyntaxNode for LatexContent {
fn range(&self) -> Range {
match self {
LatexContent::Group(group) => group.range(),
LatexContent::Command(command) => command.range(),
LatexContent::Text(text) => text.range(),
LatexContent::Comma(comma) => comma.range(),
LatexContent::Math(math) => math.range(),
}
}
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum LatexGroupKind {
Group,
Options,
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct LatexGroup {
pub range: Range,
pub left: LatexToken,
pub children: Vec<LatexContent>,
pub right: Option<LatexToken>,
pub kind: LatexGroupKind,
}
impl LatexGroup {
pub fn new(
left: LatexToken,
children: Vec<LatexContent>,
right: Option<LatexToken>,
kind: LatexGroupKind,
) -> Self {
let end = if let Some(ref right) = right {
right.end()
} else if !children.is_empty() {
children[children.len() - 1].end()
} else {
left.end()
};
Self {
range: Range::new(left.start(), end),
left,
children,
right,
kind,
}
}
}
impl SyntaxNode for LatexGroup {
fn range(&self) -> Range {
self.range
}
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct LatexCommand {
pub range: Range,
pub name: LatexToken,
pub options: Vec<Arc<LatexGroup>>,
pub args: Vec<Arc<LatexGroup>>,
pub groups: Vec<Arc<LatexGroup>>,
}
impl LatexCommand {
pub fn new(
name: LatexToken,
options: Vec<Arc<LatexGroup>>,
args: Vec<Arc<LatexGroup>>,
) -> Self {
let groups: Vec<Arc<LatexGroup>> = args
.iter()
.chain(options.iter())
.sorted_by_key(|group| group.range.start)
.map(Arc::clone)
.collect();
let end = if let Some(group) = groups.last() {
group.end()
} else {
name.end()
};
Self {
range: Range::new(name.start(), end),
name,
options,
args,
groups,
}
}
pub fn short_name_range(&self) -> Range {
Range::new_simple(
self.name.start().line,
self.name.start().character + 1,
self.name.end().line,
self.name.end().character,
)
}
pub fn extract_text(&self, index: usize) -> Option<&LatexText> {
if self.args.len() > index && self.args[index].children.len() == 1 {
if let LatexContent::Text(ref text) = self.args[index].children[0] {
Some(text)
} else {
None
}
} else {
None
}
}
pub fn extract_word(&self, index: usize) -> Option<&LatexToken> {
let text = self.extract_text(index)?;
if text.words.len() == 1 {
Some(&text.words[0])
} else {
None
}
}
pub fn has_word(&self, index: usize) -> bool {
self.extract_word(index).is_some()
}
pub fn extract_comma_separated_words(&self, index: usize) -> Vec<&LatexToken> {
let mut words = Vec::new();
for child in &self.args[index].children {
if let LatexContent::Text(text) = child {
for word in &text.words {
words.push(word);
}
}
}
words
}
pub fn has_comma_separated_words(&self, index: usize) -> bool {
if self.args.len() <= index {
return false;
}
for node in &self.args[index].children {
match node {
LatexContent::Text(_) | LatexContent::Comma(_) => (),
LatexContent::Command(_) | LatexContent::Group(_) | LatexContent::Math(_) => {
return false;
}
}
}
true
}
}
impl SyntaxNode for LatexCommand {
fn range(&self) -> Range {
self.range
}
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct LatexText {
pub range: Range,
pub words: Vec<LatexToken>,
}
impl LatexText {
pub fn new(words: Vec<LatexToken>) -> Self {
Self {
range: Range::new(words[0].start(), words[words.len() - 1].end()),
words,
}
}
}
impl SyntaxNode for LatexText {
fn range(&self) -> Range {
self.range
}
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct LatexComma {
pub token: LatexToken,
}
impl LatexComma {
pub fn new(token: LatexToken) -> Self {
Self { token }
}
}
impl SyntaxNode for LatexComma {
fn range(&self) -> Range {
self.token.range()
}
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct LatexMath {
pub token: LatexToken,
}
impl LatexMath {
pub fn new(token: LatexToken) -> Self {
Self { token }
}
}
impl SyntaxNode for LatexMath {
fn range(&self) -> Range {
self.token.range()
}
}
pub trait LatexVisitor {
fn visit_root(&mut self, root: Arc<LatexRoot>);
fn visit_group(&mut self, group: Arc<LatexGroup>);
fn visit_command(&mut self, command: Arc<LatexCommand>);
fn visit_text(&mut self, text: Arc<LatexText>);
fn visit_comma(&mut self, comma: Arc<LatexComma>);
fn visit_math(&mut self, math: Arc<LatexMath>);
}
pub struct LatexWalker;
impl LatexWalker {
pub fn walk_root<T: LatexVisitor>(visitor: &mut T, root: Arc<LatexRoot>) {
for child in &root.children {
child.accept(visitor);
}
}
pub fn walk_group<T: LatexVisitor>(visitor: &mut T, group: Arc<LatexGroup>) {
for child in &group.children {
child.accept(visitor);
}
}
pub fn walk_command<T: LatexVisitor>(visitor: &mut T, command: Arc<LatexCommand>) {
for arg in &command.groups {
visitor.visit_group(Arc::clone(&arg));
}
}
pub fn walk_text<T: LatexVisitor>(_visitor: &mut T, _text: Arc<LatexText>) {}
pub fn walk_comma<T: LatexVisitor>(_visitor: &mut T, _comma: Arc<LatexComma>) {}
pub fn walk_math<T: LatexVisitor>(_visitor: &mut T, _math: Arc<LatexMath>) {}
}
| true |
0983d54d5af8543e272d604cd99be2ca3967caba
|
Rust
|
YetSiawYeung/advent_of_code_2019
|
/src/day3.rs
|
UTF-8
| 10,733 | 3.09375 | 3 |
[
"MIT"
] |
permissive
|
use std::num::ParseIntError;
#[cfg(test)]
const X_LEN: usize = 1000;
#[cfg(not(test))]
const X_LEN: usize = 35000;
#[cfg(test)]
const Y_LEN: usize = 1000;
#[cfg(not(test))]
const Y_LEN: usize = 35000;
pub fn get_man_dist() -> Option<u32> {
// Part A
let mut input = include_str!("../input/day3.txt").lines();
let first = input.next()?;
let second = input.next()?;
Some(get_closest_intersection(first, second).ok()?)
}
pub fn get_shortest_dist() -> Option<u32> {
// Part B
let mut input = include_str!("../input/day3.txt").lines();
let first = input.next()?;
let second = input.next()?;
Some(get_shortest_intersection(first, second).ok()?)
}
fn get_closest_intersection(first: &str, second: &str) -> Result<u32, ParseMovementErr> {
use Movement::*;
use VisitedBy::*;
let first: Vec<Movement> = first
.split(',')
.map(|x| x.trim().parse())
.collect::<Result<_, _>>()?;
let second: Vec<Movement> = second
.split(',')
.map(|x| x.trim().parse())
.collect::<Result<_, _>>()?;
let mut grid = vec![[Neither; X_LEN]; Y_LEN];
let central_port = ((X_LEN / 2) as u32, (Y_LEN / 2) as u32);
let mut current = central_port;
first.iter().for_each(|m| match m {
Up(x) => {
for i in 1..=*x {
grid[(current.1 + i) as usize][current.0 as usize] = First;
}
current = (current.0, current.1 + x);
}
Down(x) => {
for i in 1..=*x {
grid[(current.1 - i) as usize][current.0 as usize] = First;
}
current = (current.0, current.1 - x);
}
Left(x) => {
for i in 1..=*x {
grid[current.1 as usize][(current.0 - i) as usize] = First;
}
current = (current.0 - x, current.1);
}
Right(x) => {
for i in 1..=*x {
grid[current.1 as usize][(current.0 + i) as usize] = First;
}
current = (current.0 + x, current.1);
}
});
let mut current = central_port;
second.iter().for_each(|m| match m {
Up(x) => {
for i in 1..=*x {
if grid[(current.1 + i) as usize][current.0 as usize] == First {
grid[(current.1 + i) as usize][current.0 as usize] = Both
};
}
current = (current.0, current.1 + x);
}
Down(x) => {
for i in 1..=*x {
if grid[(current.1 - i) as usize][current.0 as usize] == First {
grid[(current.1 - i) as usize][current.0 as usize] = Both
};
}
current = (current.0, current.1 - x);
}
Left(x) => {
for i in 1..=*x {
if grid[current.1 as usize][(current.0 - i) as usize] == First {
grid[current.1 as usize][(current.0 - i) as usize] = Both
};
}
current = (current.0 - x, current.1);
}
Right(x) => {
for i in 1..=*x {
if grid[current.1 as usize][(current.0 + i) as usize] == First {
grid[current.1 as usize][(current.0 + i) as usize] = Both
};
}
current = (current.0 + x, current.1);
}
});
let mut shortest_dist = std::u32::MAX;
for (y, row) in grid.iter().enumerate().take(Y_LEN) {
for (x, cell) in row.iter().enumerate().take(X_LEN) {
if *cell == VisitedBy::Both && (x as u32, y as u32) != central_port {
let dist = manhattan_distance((x as u32, y as u32), central_port);
if dist < shortest_dist {
shortest_dist = dist;
}
}
}
}
Ok(shortest_dist)
}
fn get_shortest_intersection(first: &str, second: &str) -> Result<u32, ParseMovementErr> {
use Movement::*;
use VisitDistance::*;
let first = first
.split(',')
.map(|x| x.trim().parse())
.collect::<Result<Vec<_>, _>>()?;
let second = second
.split(',')
.map(|x| x.trim().parse())
.collect::<Result<Vec<_>, _>>()?;
let mut grid = vec![[Neither; X_LEN]; Y_LEN];
let central_port = ((X_LEN / 2) as u32, (Y_LEN / 2) as u32);
let mut current = central_port;
let mut travelled = 0;
first.iter().for_each(|m| match m {
Up(x) => {
for i in 1..=*x {
grid[(current.1 + i) as usize][current.0 as usize] = First(travelled + i);
}
current = (current.0, current.1 + x);
travelled += x;
}
Down(x) => {
for i in 1..=*x {
grid[(current.1 - i) as usize][current.0 as usize] = First(travelled + i);
}
current = (current.0, current.1 - x);
travelled += x;
}
Left(x) => {
for i in 1..=*x {
grid[current.1 as usize][(current.0 - i) as usize] = First(travelled + i);
}
current = (current.0 - x, current.1);
travelled += x;
}
Right(x) => {
for i in 1..=*x {
grid[current.1 as usize][(current.0 + i) as usize] = First(travelled + i);
}
current = (current.0 + x, current.1);
travelled += x;
}
});
let mut current = central_port;
let mut travelled = 0;
second.iter().for_each(|m| match m {
Up(x) => {
for i in 1..=*x {
if grid[(current.1 + i) as usize][current.0 as usize].is_first() {
grid[(current.1 + i) as usize][current.0 as usize] = Both(
travelled
+ i
+ grid[(current.1 + i) as usize][current.0 as usize].get_dist(),
)
};
}
current = (current.0, current.1 + x);
travelled += x;
}
Down(x) => {
for i in 1..=*x {
if grid[(current.1 - i) as usize][current.0 as usize].is_first() {
grid[(current.1 - i) as usize][current.0 as usize] = Both(
travelled
+ i
+ grid[(current.1 - i) as usize][current.0 as usize].get_dist(),
)
};
}
current = (current.0, current.1 - x);
travelled += x;
}
Left(x) => {
for i in 1..=*x {
if grid[current.1 as usize][(current.0 - i) as usize].is_first() {
grid[current.1 as usize][(current.0 - i) as usize] = Both(
travelled
+ i
+ grid[current.1 as usize][(current.0 - i) as usize].get_dist(),
)
};
}
current = (current.0 - x, current.1);
travelled += x;
}
Right(x) => {
for i in 1..=*x {
if grid[current.1 as usize][(current.0 + i) as usize].is_first() {
grid[current.1 as usize][(current.0 + i) as usize] = Both(
travelled
+ i
+ grid[current.1 as usize][(current.0 + i) as usize].get_dist(),
)
};
}
current = (current.0 + x, current.1);
travelled += x;
}
});
let mut shortest_dist = std::u32::MAX;
for (y, row) in grid.iter().enumerate().take(Y_LEN) {
for (x, cell) in row.iter().enumerate().take(X_LEN) {
if cell.is_both() && (x as u32, y as u32) != central_port {
let dist = cell.get_dist();
if dist < shortest_dist {
shortest_dist = dist;
}
}
}
}
Ok(shortest_dist)
}
fn manhattan_distance(first: (u32, u32), second: (u32, u32)) -> u32 {
abs_dist(first.0, second.0) + abs_dist(first.1, second.1)
}
fn abs_dist(first: u32, second: u32) -> u32 {
if first > second {
first - second
} else {
second - first
}
}
#[derive(Debug)]
enum Movement {
Up(u32),
Down(u32),
Left(u32),
Right(u32),
}
#[derive(Debug, PartialEq)]
struct ParseMovementErr {}
impl std::str::FromStr for Movement {
type Err = ParseMovementErr;
fn from_str(s: &str) -> Result<Self, Self::Err> {
use Movement::*;
match s.chars().next().ok_or(ParseMovementErr {})? {
'U' => Ok(Up(s[1..].parse().map_err(|_err| Self::Err {})?)),
'D' => Ok(Down(s[1..].parse().map_err(|_err| Self::Err {})?)),
'L' => Ok(Left(s[1..].parse().map_err(|_err| Self::Err {})?)),
'R' => Ok(Right(s[1..].parse().map_err(|_err| Self::Err {})?)),
_ => Err(Self::Err {}),
}
}
}
#[derive(Clone, Copy, PartialEq)]
enum VisitedBy {
Neither,
First,
Both,
}
#[derive(Clone, Copy, PartialEq)]
enum VisitDistance {
Neither,
First(u32),
Both(u32),
}
impl VisitDistance {
fn is_both(self) -> bool {
match self {
VisitDistance::Both(_) => true,
_ => false,
}
}
fn is_first(self) -> bool {
match self {
VisitDistance::First(_) => true,
_ => false,
}
}
fn get_dist(self) -> u32 {
match self {
VisitDistance::Neither => 0,
VisitDistance::First(x) => x,
VisitDistance::Both(x) => x,
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_closest() {
assert_eq!(
get_closest_intersection(
"R75,D30,R83,U83,L12,D49,R71,U7,L72",
"U62,R66,U55,R34,D71,R55,D58,R83"
),
Ok(159)
);
assert_eq!(
get_closest_intersection(
"R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51",
"U98,R91,D20,R16,D67,R40,U7,R15,U6,R7"
),
Ok(135)
);
}
#[test]
fn test_shortest() {
assert_eq!(
get_shortest_intersection(
"R75,D30,R83,U83,L12,D49,R71,U7,L72",
"U62,R66,U55,R34,D71,R55,D58,R83"
),
Ok(610)
);
assert_eq!(
get_shortest_intersection(
"R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51",
"U98,R91,D20,R16,D67,R40,U7,R15,U6,R7"
),
Ok(410)
);
}
}
| true |
3c048ac24b04887a0345f7ced1e3a0f19fa56117
|
Rust
|
zhao1jin4/vscode_rust_workspace
|
/rustc_basic/src/read_stdin.rs
|
UTF-8
| 455 | 3.3125 | 3 |
[] |
no_license
|
use std::io;
fn main() {
//vscode 不能从标准输入 ,只能用命令行才行
//Settings->Run Code configuration -> 复选 Run In Terminal 组下的唯一的一个Wheter to run code in Integerated Terminal -> ctrl+s保存 测试不行???
println!("Please input your guess.");
let mut guess = String::new();
io::stdin().read_line(&mut guess)
.expect("Failed to read line");
println!("You guessed: {}", guess);
}
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.