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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
eb8bea912112514d4a7c49ab52ee5c12d44c5c62 | Rust | favilo/kompression | /src/error.rs | UTF-8 | 251 | 2.609375 | 3 | [] | no_license | #[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("I/O error")]
IoError(#[from] std::io::Error),
#[error("Incomplete code, need {0} more bits")]
Incomplete(usize),
#[error("Bad Code received: {0}")]
BadCode(u16),
}
| true |
bb415080f4d1540c92058e381781f47d82c53a0b | Rust | durran/bson-rust | /src/bson.rs | UTF-8 | 6,060 | 3.25 | 3 | [] | no_license | /// The BSON enum.
use document::Document;
/// The enum for all valid BSON types.
#[derive(Clone, Debug, PartialEq)]
pub enum Bson {
Double(f64), // 0x01
String(String), // 0x02
Document(Document), // 0x03
Array(Vec<Bson>), // 0x04
Binary(u8, Vec<u8>), // 0x05
Undefined, // 0x06
Boolean(boo... | true |
14ca7bacf7b5c9915ff5b51333989a95d3b91183 | Rust | TheLortex/ReactiveRS | /src/engine/process.rs | UTF-8 | 20,655 | 3.25 | 3 | [] | no_license | use super::Runtime;
use super::continuation::Continuation;
use std::sync::{Arc, Mutex};
use super::signal::*;
use super::signal::signal_runtime::ValueRuntime;
use std::thread;
/// A reactive process.
pub trait Process: 'static + Send {
/// The value created by the process.
type Value;
/// Executes the rea... | true |
c29846524af49c411425d8cfe73c718effc15e82 | Rust | Tookmund/RustLife | /src/main.rs | UTF-8 | 604 | 2.671875 | 3 | [] | no_license | use std::io::{self, Write};
use std::{thread, time};
mod conways;
fn main() {
println!("Begin");
let mut con = conways::Life::new(32, 80);
con.populate();
loop {
for r in 0..con.rows {
for c in 0..con.cols {
if con.is_alive(r, c) {
print!("+");
... | true |
07ccfe9e6bb86c9d1bee442a69e5c4ceb5e28c8e | Rust | Gowee/intray | /src/error.rs | UTF-8 | 759 | 2.875 | 3 | [
"MIT"
] | permissive | use std::io;
#[derive(Debug, Fail)]
pub enum Error {
#[fail(display = "I/O Error: {}", _0)]
Io(#[fail(cause)] io::Error),
#[fail(display = "The file token is invalid.")]
InvalidFileToken,
#[fail(display = "The chunk index is invalid.")]
InvalidChunkIndex,
#[fail(display = "The chunk has alr... | true |
d401297c5682be321c63637a0b34bff9484959ba | Rust | MartensCedric/rusty-chip | /src/main.rs | UTF-8 | 522 | 2.609375 | 3 | [
"MIT"
] | permissive | use std::env;
use std::process;
mod chip8;
mod chip8_sdl2_gui;
mod chip8_util;
fn main() {
let args: Vec<String> = env::args().collect();
let config = chip8_sdl2_gui::Config::new(&args).unwrap_or_else(|err| {
eprintln!("Problem with arguments: {}", err);
process::exit(1);
});
match c... | true |
08846c9100dfa4eda8fe6d273396387252767f60 | Rust | InteractiveComputerGraphics/higher_order_embedded_fem | /fenris/src/geometry/polymesh.rs | UTF-8 | 34,220 | 2.921875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | use std::cmp::{max, min};
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::error::Error;
use std::fmt;
use std::fmt::Display;
use std::hash::Hash;
use itertools::Itertools;
use nalgebra::allocator::Allocator;
use nalgebra::{DefaultAllocator, DimName, Point, Point3, RealField, Scalar, Vector3, U2, U3};
use... | true |
04234dd91f8d820a5a16248278f863668b485fc5 | Rust | aconley/Algorithms | /TAOCP/Implementations/taocp/src/backtracking/langford.rs | UTF-8 | 7,397 | 3.1875 | 3 | [
"MIT"
] | permissive | // Finds Langford pairs using backtracking.
// TODO: Halve the amount of work by computing mirror.
#[derive(PartialEq, Eq, Debug)]
enum IteratorState {
New,
Ready,
Done,
}
#[derive(Debug)]
pub struct LangfordIterator {
// Range of values is [1..n]
n: u8,
// Current solution array. The second... | true |
f1fad22c1701e1566de95de27337799051ac8250 | Rust | RaineForest/FateExtraSolver | /src/action_count.rs | UTF-8 | 5,355 | 3.203125 | 3 | [] | no_license |
use action::Action;
use std::fmt;
use std::ops::Add;
pub struct ActionCount {
attacks: u32,
guards: u32,
breaks: u32,
specials: u32
}
impl fmt::Display for ActionCount {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.fmt(f)
}
}
impl fmt::Debug for ActionCount {
fn f... | true |
731e4e036386e0548c5f18cdebf3f3a613bb50f5 | Rust | twitter/rustcommon | /waterfall/examples/simulator.rs | UTF-8 | 3,634 | 2.859375 | 3 | [
"Apache-2.0"
] | permissive | // Copyright 2019 Twitter, Inc.
// Licensed under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
use heatmap::*;
use rand::thread_rng;
use rand_distr::*;
use rustcommon_logger::*;
use rustcommon_waterfall::*;
fn main() {
let log = LogBuilder::new()
.output(Box::new(Stdout::n... | true |
cf7e00c5c03586a0ce109cafb5407192a16b9edb | Rust | k124k3n/competitive-programming-answer | /aizuonlinejudge/0257.rs | UTF-8 | 825 | 3.3125 | 3 | [
"MIT"
] | permissive | /*input
0 1 0
*/
macro_rules! read_line_vec {
() => {
read_line!()
.split_whitespace()
.map(|x| x.parse().unwrap())
.collect()
};
($delimiter:expr) => {
read_line!()
.split($delimiter)
.map(|x| x.parse().unwrap())
.colle... | true |
84b46c913d2341253e17a8735092a713e2dfb89c | Rust | uuhan/Accepted | /src/core/operation.rs | UTF-8 | 6,555 | 2.984375 | 3 | [
"MIT"
] | permissive | use std::fmt::Debug;
use crate::core::CoreBuffer;
use crate::core::Cursor;
use std::ops::{Bound, RangeBounds};
pub struct OperationArg<'a, B: CoreBuffer> {
pub core_buffer: &'a mut B,
pub cursor: &'a mut Cursor,
}
pub trait Operation<B: CoreBuffer>: Debug {
fn perform(&mut self, arg: OperationArg<B>) ->... | true |
c510f71e7aedc5493151fac74818829ff2e42d55 | Rust | watashi/AlgoLib | /Tree/HeavyLightDecomposition/HeavyLightDecomposition.rs | UTF-8 | 3,571 | 2.953125 | 3 | [] | no_license | pub struct TreeDecomposition {
root: usize,
parent: Vec<usize>,
size: Vec<usize>,
// invariant: chain[start[i]][index[i]] == i
start: Vec<usize>,
index: Vec<usize>,
chain: Vec<Vec<usize>>,
// invariant: id[ts[i]] == i
id: Vec<usize>,
ts: Vec<usize>, // timestamp, index used in Se... | true |
1cfff9a9ab9337026397a5d748175df4578af638 | Rust | zhenkyle/ta-rs | /benches/indicators.rs | UTF-8 | 1,970 | 2.625 | 3 | [
"MIT"
] | permissive | #[macro_use]
extern crate bencher;
extern crate ta;
use bencher::Bencher;
use rand::Rng;
use ta::indicators::{
BollingerBands, ChandelierExit, EfficiencyRatio, ExponentialMovingAverage, FastStochastic,
KeltnerChannel, Maximum, Minimum, MoneyFlowIndex, MovingAverageConvergenceDivergence,
OnBalanceVolume, Pe... | true |
1b450de98a3911896b035e308b88e0e6827cf084 | Rust | rust-lang/rust | /tests/ui/methods/call_method_unknown_pointee.rs | UTF-8 | 1,059 | 2.890625 | 3 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"BSD-2-Clause",
"LicenseRef-scancode-unicode",
"MIT",
"LicenseRef-scancode-other-permissive"
] | permissive | // edition: 2018
// tests that the pointee type of a raw pointer must be known to call methods on it
// see also: `tests/ui/editions/edition-raw-pointer-method-2018.rs`
fn main() {
let val = 1_u32;
let ptr = &val as *const u32;
unsafe {
let _a: i32 = (ptr as *const _).read();
//~^ ERROR ca... | true |
dabdbc5dce768f38729f96c81ec06e4d1180e59e | Rust | juanibiapina/sub | /src/parser.rs | UTF-8 | 3,444 | 3.0625 | 3 | [
"MIT"
] | permissive | extern crate regex;
use regex::Regex;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
fn extract_initial_comment_block(path: &Path) -> String {
let file = File::open(path).unwrap();
let mut lines = Vec::new();
for line in BufReader::new(file).lines() {
let line = line... | true |
26215bcccd8a6a97f9657fdd7fc84a0a04daf349 | Rust | axross/rust-example-api-server | /src/main.rs | UTF-8 | 1,475 | 2.640625 | 3 | [
"MIT"
] | permissive | #![feature(proc_macro_hygiene, decl_macro)]
#[macro_use] extern crate rocket;
use clap::Clap;
use rocket::config::{Config, Environment, LoggingLevel};
mod common;
mod repository;
mod route;
/// Example Web API implementation written in Rust.
#[derive(Clap)]
#[clap(version = "0.0.1", author = "Kohei Asai <yo@kohei.d... | true |
e839110ad7cafbdab4c261a06b0687181cf6a935 | Rust | Trouv/alchemy | /src/lib.rs | UTF-8 | 628 | 2.765625 | 3 | [
"Apache-2.0"
] | permissive | pub mod alchemy;
#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)]
pub enum AppState {
Brewing,
}
pub mod utils {
use std::collections::HashSet;
pub fn reduce_reverse_pairs<T>(pairs: HashSet<(T, T)>) -> HashSet<(T, T)>
where
T: std::hash::Hash + Eq + Clone,
{
pairs
.i... | true |
993e6e8aec9fdd62d1beea702db34359c11b9dc9 | Rust | 05storm26/xi_glium | /glium_text/src/lib.rs | UTF-8 | 23,111 | 2.984375 | 3 | [
"MIT"
] | permissive | /*!
This crate allows you to easily write text.
Usage:
```no_run
# extern crate glium;
# extern crate glium_text;
# extern crate cgmath;
# fn main() {
# let display: glium::Display = unsafe { std::mem::uninitialized() };
// The `TextSystem` contains the shaders and elements used for text display.
let system = glium_... | true |
66bbe6969fc4ab521f1007495e46c058743229bf | Rust | vaporyorg/gp-gas-estimation | /src/gasnow.rs | UTF-8 | 6,512 | 2.921875 | 3 | [] | no_license | use super::{linear_interpolation, GasPriceEstimating, Transport};
use anyhow::{anyhow, Result};
use futures::lock::Mutex;
use std::{
convert::TryInto,
future::Future,
time::{Duration, Instant},
};
// Gas price estimation with https://www.gasnow.org/ , api at https://taichi.network/#gasnow .
const API_URI:... | true |
cf8ab2cde460dbcf78b1651008ac88171daef97d | Rust | vnetserg/pathfind_demo | /src/pywrappers.rs | UTF-8 | 1,365 | 2.703125 | 3 | [] | no_license | use py::builtins::tuple::PyTupleRef;
use py::pyobject::{BorrowValue, PyIterable, PyObjectRef, PyResult, TryFromObject};
use rustpython_vm as py;
////////////////////////////////////////////////////////////////////////////////
pub struct PyVecWrapper<T: TryFromObject>(pub Vec<T>);
impl<T: TryFromObject> TryFromObject... | true |
87e7e3984184f416d8cd08d74ba1fef210875688 | Rust | Playfloor/leveldb | /tests/iterator.rs | UTF-8 | 2,852 | 3.046875 | 3 | [
"MIT"
] | permissive | use utils::{open_database,tmpdir,db_put_simple};
use leveldb::iterator::Iterable;
use leveldb::iterator::LevelDBIterator;
use leveldb::options::{ReadOptions};
#[test]
fn test_iterator() {
let tmp = tmpdir("iter");
let database = &mut open_database(tmp.path(), true);
db_put_simple(database, 1, &[1]);
db_put_sim... | true |
4b9b1787c878422110f9ec688fcd813149644b61 | Rust | 1010Tom/itchysats | /daemon/src/payout_curve.rs | UTF-8 | 27,568 | 2.65625 | 3 | [] | no_license | use std::fmt;
use crate::model::{Leverage, Price, Usd};
use crate::payout_curve::curve::Curve;
use anyhow::{Context, Result};
use bdk::bitcoin;
use itertools::Itertools;
use maia::{generate_payouts, Payout};
use ndarray::prelude::*;
use num::{FromPrimitive, ToPrimitive};
use rust_decimal::Decimal;
mod basis;
mod basi... | true |
8be5fbe7a1793f3ecfa10326acf4d7f752b736ed | Rust | mcbridejc/pd-driver-messages | /src/messages.rs | UTF-8 | 9,592 | 3.0625 | 3 | [] | no_license | use core::convert::TryFrom;
use super::alloc::vec::Vec;
use super::error::ParseError;
pub const ELECTRODE_ENABLE_ID: u8 = 0;
pub const DRIVE_ENABLE_ID: u8 = 1;
pub const BULK_CAPACITANCE_ID: u8 = 2;
pub const ACTIVE_CAPACITANCE_ID: u8 = 3;
pub const COMMAND_ACK_ID: u8 = 4;
pub const MOVE_STEPPER_ID: u8 = 5;
#[derive(... | true |
bcafed9b4a3c57739151b01c736c815a3cb3a6ff | Rust | y-yagi/til | /leetcode/kth-largest-element-in-an-array/rust/src/lib.rs | UTF-8 | 1,093 | 3.546875 | 4 | [] | no_license | #[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
assert_eq!(Solution::find_kth_largest(vec![3, 2, 1, 5, 6, 4], 2), 5);
assert_eq!(
Solution::find_kth_largest(vec![3, 2, 3, 1, 2, 4, 5, 5, 6], 4),
4
);
}
}
struct Solution {}
impl Solution {
... | true |
9983eb89b18c006a4e6b8c74fae0f669bb657dd3 | Rust | jonmsawyer/uva-online-judge | /Problem Set Volumes (100...1999)/Volume 1 (100-199)/102 - Ecological Bin Packing/rust/src/lib.rs | UTF-8 | 14,206 | 3.765625 | 4 | [
"MIT"
] | permissive | //! `rust` crate
//!
//! Author: Jonathan Sawyer <jonmsawyer[at]gmail.com>
//!
//! Date: 2020-06-06
use std::io;
/// `Bin` enum. Has three variants, `Bin::One`, `Bin::Two`,
/// and `Bin::Three`. Each variant holds a 3-tuple of unsigned
/// integers. The first element in each bin corresponds to the
/// color Brown. Th... | true |
726d24b274b23051ef9c4742271e9d135d1bcbdd | Rust | n-my/pingcap-talent-plan | /kvs/src/lib.rs | UTF-8 | 1,142 | 3.921875 | 4 | [
"MIT"
] | permissive | #![deny(missing_docs)]
//! A simple key/value store.
use std::collections::HashMap;
/// The KvStore stores key/value pairs in memory.
///
/// Example
/// ```rust
/// use kvs::KvStore;
/// let mut store = KvStore::new();
/// store.set("foo".to_owned(), "bar".to_owned());
/// let value = store.get("foo".to_owned());
///... | true |
5c188fcc604709fbeb921039dca98ba4ac582dad | Rust | droundy/david-set | /src/lib.rs | UTF-8 | 2,091 | 3.5 | 4 | [] | no_license | //! david-set contains a few collections that are optimized to scale
//! in size well for small numbers of elements, while still scaling
//! well in time (and size) for numbers of elements. We have two set types:
//!
//! 1. `Set` is basically interchangeable with `HashSet`, although it
//! does require that its ele... | true |
63542bd0639dd03cddc38c3d2d09c10a674c2a09 | Rust | drewtato/aoc2019 | /days/day18/src/main.rs | UTF-8 | 5,113 | 2.625 | 3 | [] | no_license | const DAY: &str = "inputs/day18.txt";
// use itertools::Itertools;
use std::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd, Reverse};
use std::collections::{BinaryHeap, HashMap, HashSet};
use std::fs::read_to_string;
use std::rc::Rc;
fn main() {
let mut tunnels: Vec<Vec<u8>> = read_to_string(DAY)
.unwrap()
.trim(... | true |
be45b6362a1ca61b29525166a47c3ce87717f898 | Rust | JohnTitor/crates.io | /conduit-axum/src/conduit.rs | UTF-8 | 1,935 | 2.625 | 3 | [
"Apache-2.0",
"MIT"
] | permissive | use axum::async_trait;
use axum::body::Bytes;
use axum::extract::FromRequest;
use hyper::Body;
use std::error::Error;
use std::io::Cursor;
use std::ops::{Deref, DerefMut};
use crate::fallback::check_content_length;
use crate::response::AxumResponse;
use crate::server_error_response;
pub use http::{header, Extensions, ... | true |
137232519404bede0e9542b5d5dc906cfa2b8819 | Rust | mmueller/advent2017 | /src/util/infinite_grid.rs | UTF-8 | 3,336 | 3.703125 | 4 | [] | no_license | use util::grid::IPos;
use std::ops::{Index,IndexMut};
/* An infinite 2-dimensional grid where every position has default value until
* it is set otherwise. */
#[derive(Clone)]
pub struct InfiniteGrid<T: Clone> {
rows: Vec<Vec<T>>,
default: T
}
impl<T: Clone> InfiniteGrid<T> {
pub fn new(default: T) -> In... | true |
58b24e646f55b7924b254b42c7ffc801493ef2fe | Rust | nebbles/rust-sandbox | /src/arrays.rs | UTF-8 | 1,114 | 4.21875 | 4 | [] | no_license | // Arrays are fixed length of elements of a single type.
use std::mem; // brings mem into the current namespace
pub fn run() {
let numbers: [i32; 5] = [1,2,3,4,5];
let mut other_numbers: [i32; 5] = [1,2,3,4,5]; // made mutable
other_numbers[2] = 20;
println!("{:?}", numbers);
println!("{:?}", ot... | true |
f310a640190620ac1f2c17b1f5afa4ccc4d9d6c4 | Rust | optozorax/olymp | /templates/src/to_include/permutations.rs | UTF-8 | 632 | 2.734375 | 3 | [] | no_license | // Iterates over all permutation of array
// Make it iterator is impossible because of lack of GAT and therefore StreamingIterator
fn permutations<T, F: FnMut(&[T])>(a: &mut [T], mut f: F) {
fn helper<T, F: FnMut(&[T])>(k: usize, a: &mut [T], f: &mut F) {
if k == 1 {
f(a);
} else {
... | true |
16b60a926ee085d0703c191021ddc6a8c81b845b | Rust | Chris-F5/SPGE | /src/cell_storage/storage/masked_array_storage.rs | UTF-8 | 1,398 | 2.875 | 3 | [] | no_license | use crate::cell_storage::{CellMask, CellPos, Tag, TagStorage};
use crate::WORLD_CELL_COUNT;
pub struct MaskedArrayStorage<T>
where
T: Tag,
{
mask: CellMask,
cells: [T; WORLD_CELL_COUNT as usize],
}
impl<T> Default for MaskedArrayStorage<T>
where
T: Tag,
{
fn default() -> MaskedArrayStorage<T> {
... | true |
72e8912ce6038d1cd25b6d9322d34905ab923501 | Rust | SeiteAlexMH/Rust-small-projects | /fibonacci2.rs | UTF-8 | 636 | 3.78125 | 4 | [] | no_license | use std::io;
fn main() {
let mut even: u64 =0;
let mut odd: u64 = 1;
println!("What fibonacci number would you like?");
let mut number = String::new();
io::stdin().read_line(&mut number)
.expect("Failed to read line");
let number: u32 = match number.trim().parse(){
Ok(num) => num,
Err(_) => 0,
};
if num... | true |
6369902053a0ac308c85fd48ca597e6a8e0a8a34 | Rust | pingzing/oxide-skies | /src/weather_structs.in.rs | UTF-8 | 2,269 | 2.640625 | 3 | [
"MIT"
] | permissive | pub mod location {
#[derive(Serialize, Deserialize, Debug)]
pub struct Location {
pub ip: String,
pub country_code: String,
pub country_name: String,
pub region_code: String,
pub region_name: String,
pub city: String,
pub zip_code: String,
pub tim... | true |
a2762f7943270f93b91c723c2cb76802acc05ed5 | Rust | fitzgen/synth-loop-free-prog | /examples/brahma.rs | UTF-8 | 24,156 | 2.734375 | 3 | [] | no_license | use structopt::*;
use synth_loop_free_prog::{Result as SynthResult, *};
macro_rules! benchmarks {
( $($name:ident,)* ) => {
vec![
$(
(stringify!($name), $name as _),
)*
]
}
}
fn main() {
env_logger::init();
let mut opts = Options::from_args();
... | true |
f13af45e4bd107712dfc50c27172141d8ae30a18 | Rust | KatsuyaKikuchi/programming_contest_rust | /src/VirtualContest/graph/012.rs | UTF-8 | 2,267 | 3.078125 | 3 | [] | no_license | use proconio::input;
use std::collections::BinaryHeap;
use std::cmp::Reverse;
struct UnionFind {
parent: Vec<usize>,
rank: Vec<i32>,
}
impl UnionFind {
fn new(n: usize) -> Self {
UnionFind {
parent: (0..n).map(|i| i).collect(),
rank: vec![0; n],
}
}
fn find... | true |
474e5760def595a75bd5b06b0a2fedaba4309e7f | Rust | jpastuszek/asn-tools | /src/bin/asn-update.rs | UTF-8 | 3,525 | 2.828125 | 3 | [
"MIT"
] | permissive | use asn_db::*;
use asn_tools::default_database_cache_path;
use cotton::prelude::*;
use flate2::read::GzDecoder;
use reqwest::Url;
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::str::FromStr;
fn cache_db(asn_db: &Db, db_file_path: &Path) -> Result<(), Problem> {
in_context_of(
&format!("st... | true |
df4770e4fc528c8f5589f355eb096c9bdaa66b70 | Rust | linsinn/yet-another-ray-tracing | /src/vec3.rs | UTF-8 | 4,680 | 3.171875 | 3 | [] | no_license | use std::ops;
use std::convert::{TryFrom, TryInto};
use crate::utils::{random_double, random_double_range};
use std::iter::Sum;
#[derive(Copy, Clone, Debug, Default)]
pub struct Vec3 {
pub e: [f64; 3]
}
impl Sum for Vec3 {
fn sum<I: Iterator<Item=Self>>(iter: I) -> Self {
let mut ret = Self::new(0, 0, 0);
for i... | true |
c25871872262387450c26c326dec486e2e582e7c | Rust | kloss-os/kloss | /src/memory/paging/mod.rs | UTF-8 | 12,265 | 3.03125 | 3 | [] | no_license | /// Purpose of these submudules is to create a recursive page table hierarchy
/// with four levels of pagetables in it.
/// To acomplish this a enum Hierarchy to differentiate between the top three
/// levels and the fourth. As a result of this we can extract the addresses stored
/// in the first three levels then jump... | true |
16648e590b0675eb00eae42c952ea3edf25571bc | Rust | rksm/adventofcode | /2021/rust/src/day6.rs | UTF-8 | 4,442 | 3.1875 | 3 | [
"MIT"
] | permissive | use crate::input;
use anyhow::Result;
use itertools::Itertools;
fn test_input() -> &'static str {
"3,4,3,1,2"
}
#[derive(Debug)]
struct LanternFish {
age: u64,
}
impl LanternFish {
fn new(n: u64) -> Self {
Self { age: n }
}
fn day_passed(&mut self, new_fish: &mut Vec<LanternFish>) {
... | true |
68d9b514b7cacf4a4570cada590d00b339282e32 | Rust | tustvold/rust-playground | /lib/telemetry/src/lib.rs | UTF-8 | 5,176 | 2.890625 | 3 | [] | no_license | #[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate prometheus;
use std::convert::Infallible;
use std::future::Future;
use prometheus::{Encoder, Histogram, HistogramVec, IntCounter, IntCounterVec, TextEncoder};
lazy_static! {
static ref SUCCESS: IntCounterVec = register_int_counter_vec!(
"su... | true |
2570be13b460a63939fe610b604eae1f7f6cd38e | Rust | liamzdenek/rust-game-prototype | /components/backend_traits/entity_thread.rs | UTF-8 | 1,805 | 2.828125 | 3 | [] | no_license | use std::sync::mpsc::{channel,Sender,Receiver};
use super::environment_thread::Environment;
use std::result;
use common::{EntityId,Position,ChanError,EntityDataMutation,Cell};
pub type Result<T> = result::Result<T, Error>;
pub type EntityThread = Sender<EntityThreadMsg>;
#[derive(Debug)]
pub enum Error {
UnknownE... | true |
9eee1c6f99b71dadf1d9472ba91ea297c7daec5b | Rust | wllgrnt/advent-of-code-2019 | /day_7/src/main.rs | UTF-8 | 18,995 | 3.203125 | 3 | [
"MIT"
] | permissive | // Day 7
use std::error::Error;
use std::fs;
use std::process;
fn main() {
let input_filename = "input.txt";
if let Err(e) = run(input_filename) {
println!("Application error: {}", e);
process::exit(1);
}
}
fn run(filename: &str) -> Result<(), Box<dyn Error>> {
// Read the input file
... | true |
e24f734a61512d900f06d7ee7839b56aec852e0f | Rust | gitter-badger/ibm-cloud-sdk | /sdk/ibm-watson-assistant-v2/src/models/message_response.rs | UTF-8 | 1,772 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive | /*
* Watson Assistant v2
*
* The IBM Watson™ Assistant service combines machine learning, natural language understanding, and an integrated dialog editor to create conversation flows between your apps and your users. The Assistant v2 API provides runtime methods your client application can use to send user in... | true |
3bf68bee1d69d83dfe5c05581c24008002e57e82 | Rust | sorokya/eo | /src/net/server_sequencer.rs | UTF-8 | 1,656 | 2.890625 | 3 | [
"MIT"
] | permissive | use rand::Rng;
use crate::data::{EOChar, EOInt, EOShort};
#[derive(Debug, Default)]
pub struct ServerSequencer {
sequence_start: EOInt,
upcoming_sequence_start: EOInt,
sequence: EOInt,
}
impl ServerSequencer {
pub fn init_new_sequence(&mut self) {
let mut rng = rand::thread_rng();
sel... | true |
27e385b6592eb418d5ae68f884afc1a69f8e574f | Rust | dailypipsgxj/timely-dataflow | /src/progress/count_map.rs | UTF-8 | 1,731 | 3.328125 | 3 | [
"MIT"
] | permissive | use std::default::Default;
// could be updated to be an Enum { Vec<(T, i64)>, HashMap<T, i64> } in the fullness of time
#[derive(Clone, Debug)]
pub struct CountMap<T> {
pub updates: Vec<(T, i64)>
}
impl<T> Default for CountMap<T> {
fn default() -> CountMap<T> { CountMap { updates: Vec::new() } }
}
impl<T:Eq+... | true |
489f80a6f906e5af4b9e90a2df49154f320b9914 | Rust | l1h3r/scarab | /src/contracts/core/blob.rs | UTF-8 | 4,578 | 2.640625 | 3 | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | use wasmlib::MapKey;
use wasmlib::ScBaseContext;
use wasmlib::ScFuncContext;
use wasmlib::ScHash;
use wasmlib::ScImmutableBytes;
use wasmlib::ScImmutableMap;
use wasmlib::ScMutableMap;
use wasmlib::ScViewContext;
use wasmlib::CORE_BLOB;
use wasmlib::CORE_BLOB_FUNC_STORE_BLOB;
use wasmlib::CORE_BLOB_PARAM_FIELD;
use was... | true |
499b9039a58528df6bc33ada1c0e69ce4893f701 | Rust | l4l/trace-anal | /src/main.rs | UTF-8 | 1,351 | 2.578125 | 3 | [] | no_license | extern crate itertools;
#[macro_use]
mod parsing;
mod cfg;
use cfg::Cfg;
mod trace;
use trace::Bb;
mod graph;
mod base;
use std::env;
use std::fs::File;
use std::io::{Read, stdout};
use std::fmt;
impl fmt::Display for Cfg {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut prnt = format!("Cf... | true |
7debde7502b182ffb90ba1482bfecfdb9beda94d | Rust | AdamStepan/rust-elf | /src/main.rs | UTF-8 | 2,463 | 2.796875 | 3 | [] | no_license | mod dynamic;
mod error;
mod file;
mod interpret;
mod notes;
mod program;
mod reader;
mod relocs;
mod section;
mod symbols;
mod version;
mod elf;
use std::path::PathBuf;
use structopt::StructOpt;
use anyhow::Result;
use elf::Elf;
#[derive(Debug, StructOpt)]
struct DisplayOptions {
#[structopt(
short = "a",... | true |
3cc00fc81f7ca8aadb196f7bbc186374c8ea5991 | Rust | cympfh/rust-etude | /20/test.rs | UTF-8 | 406 | 3.046875 | 3 | [] | no_license | #[cfg(test)]
mod test {
fn gcd(a:i32, b:i32) -> i32 {
if b == 0 {
a
} else {
gcd(b, a%b)
}
}
#[test]
fn gcd_positive_test() {
assert!(gcd(3, 5) == 1);
assert!(gcd(2, 5) == 1);
assert!(gcd(3, 21) == 3);
}
#[test]
#[shou... | true |
a55391f5cc09660b8ead9892ae9a62723b625b17 | Rust | ArthurEnglebert/rust-chat | /webservice/src/db/messages/heap/mod.rs | UTF-8 | 979 | 2.609375 | 3 | [] | no_license | use std::collections::LinkedList;
use crate::db::messages::MessageRepository;
use chat_model::message::message::Message;
use itertools::Itertools;
use chrono::Local;
static mut MESSAGES : LinkedList<Message> = LinkedList::new();
pub struct HeapMessageRepository {
}
impl HeapMessageRepository {
pub fn new() -> He... | true |
323b31c3f35a621abb5939dd2bfcf5e2a6a6c729 | Rust | felipehfs/Rust-Learning | /abs.rs | UTF-8 | 169 | 2.90625 | 3 | [] | no_license | // The program return the number module
fn abs(x: f64) -> f64 {
if x > 0.0 {
x
} else {
-x
}
}
fn main() {
println!("{}", abs(-1.0));
}
| true |
f067c6f4d5795d94c1d8d080f907196668b1d747 | Rust | santi698/retail_manager | /backend/domain/src/repositories/email_and_password_identity_repository.rs | UTF-8 | 1,176 | 2.609375 | 3 | [] | no_license | use async_trait::async_trait;
use sqlx::{postgres::PgRow, PgPool, Row};
use crate::{EmailAndPasswordIdentity, EmailAndPasswordIdentityRepository, RepositoryError};
#[derive(Debug)]
pub struct PostgresEmailAndPasswordIdentityRepository {
pool: PgPool,
}
impl PostgresEmailAndPasswordIdentityRepository {
pub fn... | true |
367a48ba515b9232c1bec23f8c50f9418e496196 | Rust | Andrew-xj/rust-demo | /Chapter 3/lesson-3-5_control-flow/src/main.rs | UTF-8 | 966 | 4.4375 | 4 | [] | no_license | fn main() {
// if expression
let number = 3;
if number < 5 {
println!("condition was true");
}
else {
println!("condition was false");
}
let testif = if number == 3 { 5 } else { 6 };
// let testif = if number == 3 { 5 } else { "6" }; // error
println!("the value of... | true |
2e873ee6133b223328fcc0e5a0fcb30396b493a7 | Rust | fabmeyer/learning-rust | /iflet/src/main.rs | UTF-8 | 250 | 3.09375 | 3 | [] | no_license | fn main() {
let some_u8_value = Some(0u8);
// similiar to match but without exhausting search
if let Some(3) = some_u8_value {
println!("three");
// use else as fallback
} else {
println!("not three");
}
}
| true |
517bee1fd285bbddb9e9405f96d718fa00c9fd62 | Rust | ackintosh/sandbox | /rust/leetcode/src/subtract_the_product_and_sum_of_digits_of_an_integer.rs | UTF-8 | 718 | 3.65625 | 4 | [] | no_license | // https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/
struct Solution;
impl Solution {
pub fn subtract_product_and_sum(n: i32) -> i32 {
let string = n.to_string();
let mut product = 0;
let mut sum = 0;
for (i, s) in string.split("").filter(|s| !s.i... | true |
0a0cd4a02674a255c3bc79842f9d48af36fd9b1f | Rust | kuririn246/sabun_data_model | /sabun_maker/src/imp/intf/c_qv_str.rs | UTF-8 | 3,266 | 3.09375 | 3 | [] | no_license | use crate::imp::structs::qv::Qv;
use std::ptr::null;
/// &参照を露出してしまうと、それが生きている間にwriteしたら当然UB(undefined behavior)になる。
/// 参照を見せないために、RustではStringのCopyを行う
/// 対してCからは、ポインタを介してアクセスする分にはUBにならないのでコピーしない(そもそもコピーしても破棄するのが大変・・・
///
/// 生ポインタを持つ構造体はSendでもSyncでもないので、マルチスレッドで使われる心配はしなくていい。この方式ではマルチスレッド対応は無理
/// (まあ使う側がreadとwrite... | true |
54991c3f1624f5d2ee1b2de51a4ac90eefac4151 | Rust | Luro02/borrow_trait | /src/borrow_ref_mut.rs | UTF-8 | 4,245 | 3.609375 | 4 | [
"Apache-2.0",
"MIT"
] | permissive | use core::cell::{RefCell, RefMut};
use core::ops::DerefMut;
/// A trait for mutably borrowing data.
///
/// The `borrow` function returns an mutable reference to `Self::Target`.
/// ```
/// use std::ops::DerefMut;
/// use std::cell::RefCell;
/// use borrow_trait::{ BorrowRefMut };
///
/// fn takes_bound<T>(value: &T)
... | true |
2b222c0a788a8167155f775dd82dd3ec8131a8b7 | Rust | Hexilee/BronzeDB | /bronzedb-sled-db-server/src/engine_impl.rs | UTF-8 | 2,886 | 2.875 | 3 | [
"MIT"
] | permissive | use bronzedb_engine::{Engine, Scanner};
use bronzedb_util::status::{Error, StatusCode};
use bronzedb_util::types::{Entry, Key};
use sled::Db;
use std::path;
#[derive(Debug)]
pub struct EngineError {
inner: sled::Error,
}
impl EngineError {
pub fn new(err: sled::Error) -> Self {
Self { inner: err }
... | true |
3ecb4b81e6e54d2c8997098d6b9725274ba4b60b | Rust | HyberionBrew/gpc4_ss21 | /winder/src/lang/ast.rs | UTF-8 | 8,270 | 2.984375 | 3 | [] | no_license | use super::lexer::Position;
use super::lexer::Token;
//use super::interpreter::Interpreter;
use super::staticcheck::*;
//use super::compiler::*;
use crate::lang::compiler::{CompilableStat, CompilableExpr};
/* Traits */
pub trait Statement : CheckableStat + CompilableStat {
fn to_json_string(&self) -> String {
... | true |
e756d1237abd76b41b640512c16b6da96d2a8e04 | Rust | coqsucker/kravanenn | /src/coq/checker/inductive.rs | UTF-8 | 1,183 | 2.90625 | 3 | [] | no_license | use coq::checker::environ::{
Env,
};
use coq::checker::reduction::{
ConvResult,
};
use ocaml::values::{
Constr,
Ind,
PUniverses,
};
/// Extracting an inductive type from a construction
impl Constr {
/// This API is weird; it mutates self in place. This is done in order to allow the argument
... | true |
a610d56a6ffe5b692b25efe8147c4dd6b4156810 | Rust | kshefchek/aoc-2019-rust | /day3/src/main.rs | UTF-8 | 2,744 | 3.15625 | 3 | [] | no_license | use std::fs::File;
use std::path::Path;
use std::result::Result;
use std::collections::HashSet;
use std::collections::HashMap;
use std::iter::FromIterator;
use std::io::{BufRead, BufReader, Error};
fn main() {
let (first_wire, second_wire) = get_directions().unwrap();
let first_coords = directions_to_coords(&... | true |
a4be0afd68b5a5d4e14db2f0da40be9249942d76 | Rust | iCodeIN/saffron | /saffron/examples/describe.rs | UTF-8 | 492 | 3.03125 | 3 | [
"BSD-3-Clause"
] | permissive | //! Prints a description of the given cron expression
use saffron::parse::{CronExpr, English};
fn main() {
let args: Vec<String> = std::env::args().collect();
match args
.get(1)
.map(|s| s.as_str().parse::<CronExpr>())
.transpose()
{
Ok(Some(cron)) => println!("{}", cron.de... | true |
6aafd9cf5ade8b546693f13dfc09b317ead899e1 | Rust | pepijno/raytracer-rust | /src/material.rs | UTF-8 | 2,302 | 3.25 | 3 | [] | no_license | extern crate overload;
use overload::overload;
use std::ops; // <- don't forget this or you'll get nasty errors
#[derive(Debug, Copy, Clone)]
pub struct Color {
r: f32,
g: f32,
b: f32,
}
impl Color {
pub fn black() -> Self {
Self {
r: 0.0,
g: 0.0,
b: 0.0,
... | true |
4f75fa72c085448b638bd4fa22b78e0c3c0eb31d | Rust | ives9638/parquet2 | /src/encoding/delta_byte_array/decoder.rs | UTF-8 | 2,310 | 2.875 | 3 | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | use super::super::delta_bitpacked;
use super::super::delta_length_byte_array;
/// Decodes according to [Delta strings](https://github.com/apache/parquet-format/blob/master/Encodings.md#delta-strings-delta_byte_array--7),
/// prefixes, lengths and values
/// # Implementation
/// This struct does not allocate on the hea... | true |
713b7cc033a5d16d52b73eddaee0225b3b035553 | Rust | mblesel/eve_industry_terminal | /src/utils.rs | UTF-8 | 1,235 | 3.109375 | 3 | [] | no_license | use yaml_rust::{YamlLoader, Yaml, YamlEmitter};
use std::io::{self,Write};
use std::fs;
pub fn load_yaml(filepath: &str) -> Vec<Yaml>
{
let yaml_file = fs::read_to_string(filepath)
.expect("Cannot read yaml file");
YamlLoader::load_from_str(&yaml_file)
.expect("Cannot deserialize yaml file")
}
... | true |
61afe94b44c1590f452f082972cec51f79dc07ce | Rust | matt-williams/tokio-memcache | /src/request.rs | UTF-8 | 15,635 | 2.734375 | 3 | [] | no_license | use std::str;
use std::str::FromStr;
use nom::digit;
use ::parse_utils::is_key_char;
#[derive(Debug)]
pub enum Request {
Set{key: String, value: Vec<u8>, flags: u16, expiry: u32, noreply: bool},
Add{key: String, value: Vec<u8>, flags: u16, expiry: u32, noreply: bool},
Replace{key: String, value: Vec<u8>, ... | true |
9e1a839fe1aaa7421652a587479dd4d5ddf91f1b | Rust | tkygtr6/tutorials | /Rust-practice/ITP1_1_C.rs | UTF-8 | 323 | 2.8125 | 3 | [] | no_license | fn main() {
let mut line = String::new();
std::io::stdin().read_line(&mut line).unwrap();
let nums = line
.trim()
.split_whitespace()
.map(|c| c.parse::<u32>().unwrap())
.collect::<Vec<_>>();
let a = nums[0];
let b = nums[1];
println!("{} {}", a * b, (a + b) * 2);... | true |
fb93291d82631482b82377ee63a3baf2310050a8 | Rust | Ten0/sentry-rust | /sentry-core/src/integrations/log.rs | UTF-8 | 9,453 | 3.234375 | 3 | [
"Apache-2.0"
] | permissive | //! Adds support for automatic breadcrumb capturing from logs.
//!
//! **Feature:** `with_log` (*disabled by default*)
//!
//! The `log` crate is supported in two ways. First events can be captured as
//! breadcrumbs for later, secondly error events can be logged as events to
//! Sentry. By default anything above `In... | true |
5aad2ba8e608d90184340aafd3a0ad9fa99dcc31 | Rust | ra2003/IRust | /src/irust/raw_terminal.rs | UTF-8 | 3,062 | 2.828125 | 3 | [
"MIT"
] | permissive | use super::IRustError;
use crossterm::{cursor::*, queue, style::*, terminal::*};
use std::fmt::Display;
use std::io::{stdout, Write};
pub struct RawTerminal {}
impl RawTerminal {
pub fn new() -> Self {
Self {}
}
pub fn scroll_up(&self, n: u16) -> Result<(), IRustError> {
queue!(stdout(), ... | true |
14fe1c6882cd1e74e6d87e71c03bbda5a16dc7af | Rust | lilymonad/rust_riscv | /src/types.rs | UTF-8 | 4,307 | 3.171875 | 3 | [] | no_license | use std::ops::*;
pub trait MachineInteger
: Sized +
Copy +
Clone +
PartialEq +
Eq +
Shr<u32,Output=Self> + // MI >> u32
Shl<u32,Output=Self> + // MI << u32
BitAnd<Output=Self> + // MI & MI
BitOr<Output=Self> + // MI | MI
From<i32>
{
const XLEN : u32;
fn bit_slice(&self, i:usize, j:usize) -... | true |
e4ba30aedc3cd4567b77ecc79fe4eee3260a33cf | Rust | wolfiestyle/rtk | /core/src/widget/id.rs | UTF-8 | 1,250 | 3.21875 | 3 | [
"MIT"
] | permissive | use std::sync::atomic::{AtomicUsize, Ordering};
static WIDGET_ID: AtomicUsize = AtomicUsize::new(1);
/// Unique widget global id.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct WidgetId(usize);
impl WidgetId {
/// Null widget id.
///
/// This is the return value o... | true |
23a8dcc018fb007ab70325204344394ad8adb0cd | Rust | 0b01/solenoid | /src/ethabi/param_type/param_type.rs | UTF-8 | 1,739 | 3.046875 | 3 | [] | no_license | // Copyright 2015-2020 Parity Technologies
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except ... | true |
1777247beed7681a9f16e5258833b531bb78af7c | Rust | Tsdevendra1/custom_nn | /src/general_helpers/deconstruct_genome.rs | UTF-8 | 2,185 | 2.90625 | 3 | [] | no_license | use crate::structs::genome::Genome;
use crate::structs::gene::{ConnectionGene, NodeGene};
use std::collections::{HashSet, HashMap};
use crate::maths_helpers::graph_algorithm::Graph;
pub(crate) struct DeconstructGenome {}
impl DeconstructGenome {
fn unpack_genome(genome: Genome) {
/// Unpacks the genome a... | true |
e37c4fb960b035e69e12b5b9c79fe913d3565118 | Rust | chenziyi2018/py_sql | /src/node/proxy_node.rs | UTF-8 | 1,349 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | use crate::ast::RbatisAST;
use crate::error::Error;
use crate::node::node_type::NodeType;
use rexpr::runtime::RExprRuntime;
use serde_json::Value;
use std::fmt::Debug;
use std::ops::Deref;
use std::sync::Arc;
///CustomNode Generate,you can custom py lang parse
pub trait NodeFactory: Send + Sync + Debug {
///genera... | true |
46a7c2d5e549153330f31cce7ba0c4353f170a1b | Rust | isPoto/manga | /src/printer.rs | UTF-8 | 668 | 2.640625 | 3 | [
"MIT"
] | permissive | #[macro_export]
macro_rules! step_help {
( $msg:expr ) => {{
use colored::*;
let flag = "==>".bright_blue();
println!("{} {}", flag, $msg.to_string().bright_blue());
print!("{} ", flag);
std::io::stdout().flush()
}};
}
#[macro_export]
macro_rules! print_err {
( $e:ex... | true |
c042f0069604d66fe3b1205fb367d6192d681ed0 | Rust | utrescu/Rust-Peloton | /src/main.rs | UTF-8 | 3,958 | 3.25 | 3 | [] | no_license | use std::env;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::time::Duration;
use std::vec::Vec;
struct Corredor {
temps: String,
posicio: u16,
}
fn main() {
let args: Vec<String> = env::args().collect();
let mut filename = "in.txt";
if args.len() > 2 {
panic!("Please enter... | true |
b52b88cf72439475bb10d35e4031220ad5187945 | Rust | lolhub-dev/webclient | /src/utils.rs | UTF-8 | 628 | 2.71875 | 3 | [
"MIT"
] | permissive | use regex::Regex;
const STATIC_PATH: &str = "static";
const MOCK_PATH: &str = "static/mocks";
const IMAGES_PATH: &str = "static/images";
pub fn check_valid_email(email: &str) -> bool {
let email_regex = Regex::new(
r"^([a-z0-9_+]([a-z0-9_+.]*[a-z0-9_+])?)@([a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,6})",
... | true |
bf9a78fdde0f574bc49b71d579086e42cf1730f9 | Rust | yelite/refinery | /refinery_cli/src/migrate.rs | UTF-8 | 3,442 | 2.71875 | 3 | [
"MIT"
] | permissive | use clap::ArgMatches;
use failure::{format_err, Error, ResultExt};
use refinery_migrations::{
find_migrations_filenames, migrate_from_config, Config, ConfigDbType, Migration, MigrationType,
};
use std::fs;
use std::path::Path;
pub fn get_config(location: &str) -> Result<Config, Error> {
let file = std::fs::rea... | true |
43eaa5c2146e8d85336b2d57eb5d8c33abd460a6 | Rust | ebroto/cargo-minver | /tests/lang_files/relaxed_adts.rs | UTF-8 | 951 | 3.15625 | 3 | [] | no_license | #![allow(unused)]
struct TS(i32);
struct EmptyTS();
enum E {
TV(i32),
EmptyTV(),
}
struct S {
val: i32,
}
enum F {
SV { val: i32 },
}
fn main() {
// Tuple struct
let ts = TS(42);
let ts = TS { ..ts };
let ts = TS { 0: 42 };
match ts {
TS { 0: 42 } => {},
TS { ..... | true |
3aecb4c3943524e4960ecbe60c564074b819a3a0 | Rust | gong023/rust-tutorial | /trait.rs | UTF-8 | 533 | 3.5625 | 4 | [] | no_license | trait Monster {
fn attach(&self);
}
struct NormalMonster {
strength: int
}
struct StrongMonster {
strength: int
}
impl Monster for NormalMonster {
fn attach(&self) {
println!("{:d}", self.strength);
}
}
impl Monster for StrongMonster {
fn attach(&self) {
println!("{:d}", self... | true |
a2c850e4884424fa841164c185dbf59b09ab452d | Rust | ajm188/advent_of_code | /2015/day04/src/main.rs | UTF-8 | 645 | 2.859375 | 3 | [
"MIT"
] | permissive | extern crate openssl;
use openssl::crypto::hash::{hash, Type};
fn correct_hash(input: String) -> bool {
let md5 = hash(Type::MD5, input.as_bytes());
//five_leading_zeros(md5)
six_leading_zeros(md5)
}
fn six_leading_zeros(md5: Vec<u8>) -> bool {
md5.iter().take(3).all(|x| x + 0 == 0)
}
fn five_leadin... | true |
bef360a9b3167c38f4bcf984140df710aa92d992 | Rust | dapr/rust-sdk | /examples/invoke/grpc/server.rs | UTF-8 | 3,318 | 2.640625 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | permissive | use dapr::{
appcallback::*,
dapr::dapr::proto::runtime::v1::app_callback_server::{AppCallback, AppCallbackServer},
};
use prost::Message;
use tonic::{transport::Server, Request, Response, Status};
use hello_world::{HelloReply, HelloRequest};
pub mod hello_world {
tonic::include_proto!("helloworld"); // Th... | true |
e19c7507295fa5101dd6fb4be090a38950c02f94 | Rust | HerringtonDarkholme/leetcode | /src/1026_max_ancestor_diff.rs | UTF-8 | 1,116 | 3.234375 | 3 | [] | no_license | // Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
// #[inline]
// pub fn new(val: i32) -> Self {
// TreeNode {
// val,... | true |
0f9c07303aae67731a22e3f1d88753f8b2e75840 | Rust | bouzuya/rust-atcoder | /cargo-atcoder/contests/past201912-open/src/bin/g.rs | UTF-8 | 950 | 2.9375 | 3 | [] | no_license | use proconio::input;
use std::cmp::{max, min};
fn dfs(v: &Vec<Vec<i64>>, g: &mut Vec<usize>) -> i64 {
if g.len() == v.len() {
let mut sum = 0;
for (i, g_i) in g.iter().enumerate() {
for (j, g_j) in g.iter().enumerate() {
if i == j || g_i != g_j {
cont... | true |
8b6ae10a9da4aef876cac2d98386d11502df0f71 | Rust | bernep/Telescope | /src/templates/static_pages/mod.rs | UTF-8 | 1,105 | 2.875 | 3 | [
"MIT"
] | permissive | use crate::templates::page::Page;
use crate::web::{RequestContext, Template};
use actix_web::HttpResponse;
use serde::Serialize;
pub mod index;
pub mod sponsors;
pub mod projects;
pub mod developers;
/// A piece of static content that can be rendered in a Page object.
pub trait StaticPage: Serialize + Sized + Default... | true |
39be102a579795100c6ad1ecb75a0dc696df72e8 | Rust | irevoire/crustyline | /src/menu/food.rs | UTF-8 | 283 | 3.4375 | 3 | [
"WTFPL"
] | permissive | #[derive(Debug)]
pub struct Food {
pub name: String,
pub price: String, // because sometimes it's unparseable and I'm lazy
}
impl Food {
pub fn new(name: String, price: String) -> Food {
Food {
name: name,
price: price,
}
}
}
| true |
242e317ad751669e6c0008212f31af006ea4e56f | Rust | EstebanBorai/file-copycat | /src/lib.rs | UTF-8 | 1,598 | 2.5625 | 3 | [] | no_license | extern crate notify;
use notify::{DebouncedEvent, RecommendedWatcher, RecursiveMode, Watcher};
use std::fs::{read, write, File};
use std::path::Path;
use std::sync::mpsc::channel;
use std::time::Duration;
const OUTPUT_FILE_DEFAULT_NAME: &str = "./file_copycat_output";
pub type ReplacerFn = Box<dyn Fn(Vec<u8>) -> Vec... | true |
a71762c7f986214f706d59544fd86809acc7ea8a | Rust | dunnock/poloniex-api-rs | /src/actors/book.rs | UTF-8 | 3,159 | 2.9375 | 3 | [
"MIT"
] | permissive | use super::Processor;
use crate::data::messages::{BookRecord, BookUpdate, RecordUpdate};
use crate::data::trade::TradeBook;
use crate::error::PoloError;
use std::str::FromStr;
use std::sync::{Arc, Mutex};
#[derive(Clone)]
pub struct Accountant {
tb: Arc<Mutex<TradeBook>>,
}
impl Accountant {
pub fn new(tb: Ar... | true |
5480d81e96afff9dc52dde52d7d010e58f388695 | Rust | sivizius/procrastinator | /source/socket/old.rs | UTF-8 | 1,962 | 2.96875 | 3 | [] | no_license | use
{
async_std::
{
sync::
{
Arc,
},
},
futures::
{
future::
{
channel::
{
mpsc,
oneshot,
},
},
},
};
/// Request from `Client` to `Server`.
pub struct Requests
<
RequestData,
ResponseData,
>
{
port: on... | true |
6207594b30bd11bfa3955f6a5ef2b5c94defed75 | Rust | docopt/docopt.rs-old | /docopt.rs | UTF-8 | 5,589 | 3.03125 | 3 | [] | no_license | use cmp::Eq;
use str::str;
use std::map::Map;
use send_map::linear::LinearMap;
use std::json;
use std::json::ToJson;
//Toplevel public function for parsing. Args are taken from os::args()
pub fn docopt(doc: ~str) -> Result<LinearMap<~str, json::Json>, ~str> {
let argv = os::args();
docopt_ext(copy doc, cop... | true |
11781f75e2d7b7f33a320bfe6871a17076f76bfe | Rust | shurizzle/rust-libcaca | /src/file.rs | UTF-8 | 2,785 | 2.671875 | 3 | [] | no_license | use std::io::Read;
use std::io::Write;
use std::path::Path;
use libcaca_sys::caca_file_eof;
use libcaca_sys::caca_file_open;
use libcaca_sys::caca_file_read;
use libcaca_sys::{caca_file_close, caca_file_t, caca_file_tell, caca_file_write};
use crate::utils::lossy_cstring;
use crate::{error::Error, result::Result};
p... | true |
1acdcc47366ce16e56084c119077f1d4c1f16cdd | Rust | alexcameron89/sudoku | /src/validator.rs | UTF-8 | 6,127 | 3.609375 | 4 | [] | no_license | const VALID_SORTED_ROW: [i32; 9] = [1,2,3,4,5,6,7,8,9];
pub fn valid(puzzle: &[Vec<i32>]) -> bool {
let rows_are_valid = rows_are_valid(&puzzle);
let columns_are_valid = columns_are_valid(&puzzle);
let grids_are_valid = grids_are_valid(&puzzle);
rows_are_valid
&& columns_are_valid
&& g... | true |
774d14afbc743d6e8c4975e192cfa23d84c7869f | Rust | SergioBenitez/Pear | /examples/http/src/main.rs | UTF-8 | 7,656 | 3.03125 | 3 | [] | no_license | extern crate pear;
use pear::{parsers::*, combinators::*};
use pear::macros::{parser, switch, parse_error};
#[derive(Debug, PartialEq)]
enum Method {
Get, Head, Post, Put, Delete, Connect, Options, Trace, Patch
}
#[derive(Debug, PartialEq)]
struct RequestLine<'a> {
method: Method,
uri: &'a str,
versi... | true |
bd94d0ed8423a13c376f19950b248934f9cd09c9 | Rust | lloydmeta/gol-rs | /src/data/grid.rs | UTF-8 | 12,666 | 3.3125 | 3 | [
"MIT"
] | permissive | use data::cell::{Cell, Status};
use rand;
use rand::Rng;
use rayon::prelude::*;
use std::mem;
pub const PAR_THRESHOLD_AREA: usize = 250000;
/// Used for indexing into the grid
#[derive(Debug, PartialEq, Eq)]
pub struct GridIdx(pub usize);
#[derive(Debug)]
pub struct Grid {
/* Addressed by from-zero (i, j) notati... | true |
1a2ad94919a06a2d31e7f9dcd0b44a3aced40984 | Rust | LukeMiles49/Peer-Miner | /game-client/src/world_renderer.rs | UTF-8 | 3,630 | 2.578125 | 3 | [] | no_license | use std::{
cmp::*,
};
use game_interface::{
Canvas,
SmoothingQuality,
};
use game_state::World;
use lib::{Logger, Colour};
use sized_matrix::Vector;
use higher_order_functions::Map;
use num_traits::{Zero, PrimInt, AsPrimitive};
use noise_fn::{HashNoise, Seedable, NoiseDomain};
pub struct WorldRenderer<TCanvas: ... | true |
a213dec741204769375d0a6bef2d43ff2f146771 | Rust | KonishchevDmitry/investments | /src/broker_statement/open/moex/corporate_actions.rs | UTF-8 | 6,115 | 2.640625 | 3 | [] | no_license | use std::cmp::Ordering;
use std::collections::HashMap;
use lazy_static::lazy_static;
use num_traits::ToPrimitive;
use regex::Regex;
use serde::Deserialize;
use crate::broker_statement::corporate_actions::{CorporateAction, CorporateActionType, StockSplitRatio};
use crate::broker_statement::open::common::{deserialize_d... | true |
44afc5f952f468e13783e2b21aaee8c7d1cc5ea5 | Rust | dlameter/random_tables_web | /src/main.rs | UTF-8 | 5,150 | 2.609375 | 3 | [
"MIT"
] | permissive | use diesel::prelude::*;
use serde::Deserialize;
use serde_json;
use warp::{http::Response, Filter, Rejection};
use random_tables_web;
use random_tables_web::session;
#[tokio::main]
async fn main() {
let cors = warp::cors()
.allow_origin("http://localhost:3000")
.allow_methods(vec!["GET", "POST", "... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.