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
d851e1cf8c099d692ac18ed202921bb8c6d39142
Rust
acidburn0zzz/ruffle
/core/src/xml/namespace.rs
UTF-8
2,919
3.359375
3
[ "Apache-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
//! XML namespacing support use crate::xml::Error; use gc_arena::Collect; use std::borrow::Cow; use std::fmt; /// Represents a scoped name within XML. /// /// All names in XML are optionally namespaced. Each namespace is represented /// as a string; the document contains a mapping of namespaces to URIs. /// /// The s...
true
e881f5496e0707913666c30527f4dd640792d538
Rust
ritobanrc/aoc2019
/src/day1.rs
UTF-8
1,374
3.453125
3
[]
no_license
#[aoc(day1, part1)] pub fn day_1_p1(input: &str) -> u64 { input .lines() .map(|n| n.parse::<u64>().unwrap()) .map(|n| n / 3 - 2) .sum() } #[aoc(day1, part2)] pub fn day_1_p2(input: &str) -> u64 { fn calc_fuel(mass: u64) -> u64 { let mut additional_fuel = mass / 3 - 2; ...
true
08c684d22fafbe318d44e41a65334d795fdbd6c8
Rust
creativcoder/bastion
/src/bastion/src/child_ref.rs
UTF-8
10,487
3.28125
3
[ "MIT", "Apache-2.0" ]
permissive
//! //! Allows users to communicate with Child through the mailboxes. use crate::broadcast::Sender; use crate::context::BastionId; use crate::envelope::{Envelope, RefAddr}; use crate::message::{Answer, BastionMessage, Message}; use crate::path::BastionPath; use std::cmp::{Eq, PartialEq}; use std::fmt::Debug; use std::h...
true
0fa1ab02d415a9da7e47672ad2abb43a8373c8c7
Rust
bluss/odds
/src/vec.rs
UTF-8
2,786
3.890625
4
[ "MIT", "Apache-2.0" ]
permissive
//! Extensions to `Vec` //! //! Requires `feature="std-vec"` #![cfg(feature="std-vec")] use slice::SliceFind; /// Create a new vec from the iterable pub fn vec<I>(iterable: I) -> Vec<I::Item> where I: IntoIterator { iterable.into_iter().collect() } /// Extra methods for `Vec<T>` /// /// Requires `feature="...
true
e4a9368f4865cbc5d9467c36a84c232bbe8683b8
Rust
lidavidm/gfx-space-rs
/src/sprite.rs
UTF-8
5,490
2.5625
3
[]
no_license
use std::rc::Rc; use cgmath::{self, Rotation}; use gfx; use gfx::traits::FactoryExt; // gfx_defines! creates a submodule, so we need `pub use` to make sure // the import here is visible. pub use types::*; gfx_defines! { vertex Vertex { pos: [f32; 2] = "a_Pos", color: [f32; 3] = "a_Color", ...
true
a06d2ac36bbb6ad433812b730e9f07a96263c1ca
Rust
Animeshz/git-mit
/mit-commit-message-lints/src/mit/cmd/get_authors.rs
UTF-8
2,256
2.78125
3
[ "LicenseRef-scancode-unknown-license-reference", "CC0-1.0" ]
permissive
use std::{ convert::TryFrom, fs, path::PathBuf, process::{Command, Stdio}, }; use miette::{IntoDiagnostic, Result}; use crate::mit::Authors; pub trait AuthorArgs { fn author_command(&self) -> Option<&str>; fn author_file(&self) -> Option<&str>; } /// Get authors from config /// /// # Errors ...
true
dc4c75c8a84fe6970e3778de98212ca955ee4667
Rust
4e6/bioinformatics
/src/dna/dna_impl.rs
UTF-8
5,882
3.796875
4
[ "MIT" ]
permissive
//! DNA implementation based on u8 vector. use std::ascii::AsciiExt; use std::fmt; use std::iter::IntoIterator; use std::ops; use std::slice; use std::str; use std::vec; pub const A: u8 = b'A'; pub const T: u8 = b'T'; pub const G: u8 = b'G'; pub const C: u8 = b'C'; /// DNA abstraction over a byte vector. /// /// # E...
true
0290155567272935f3255d605272093dba47e88a
Rust
Amdrel/notch
/src/cpu.rs
UTF-8
24,404
2.984375
3
[ "BSD-2-Clause" ]
permissive
use std::thread::sleep; use std::time::Duration; use super::rand::random; use super::time; use super::memory::END_RESERVED; use super::interconnect::Interconnect; // Instructions are 2 bytes long and stored as BigEndian. const INSTRUCTION_SIZE: u16 = 2; // Round about 60Hz delay for timers. const TIMER_DELAY: u64 =...
true
3c1c69ffdbac7879bade41d328f050d81fd00a4a
Rust
kecors/AoC-2017
/day-17/src/main.rs
UTF-8
1,684
3.859375
4
[ "MIT" ]
permissive
#[derive(Debug)] struct Spinlock { buffer: Vec<u64>, position: usize, steps: usize, } impl Spinlock { fn new(steps: usize) -> Spinlock { let mut buffer = Vec::new(); buffer.push(0); let position = 0; Spinlock { buffer, position, step...
true
cbfdb7b28969685aab17bb290a3f64241b7c57b3
Rust
sno2/vex
/vex/examples/simple.rs
UTF-8
706
2.65625
3
[ "MIT" ]
permissive
use std::time::Duration; use minifier::Minifier; use vex::vex; const SAMPLE_1: &str = "./vex/examples/samples/simple.css"; fn benchmark<T: FnOnce()>(cl: T) -> Duration { let start = std::time::Instant::now(); cl(); let end = std::time::Instant::now(); return end - start; } fn main() -> Result<(), Box<dyn std::e...
true
64b2369009edae19d17bd7ea460b9ce2489c9510
Rust
ilya-epifanov/riscv-minimal-rt
/src/lib.rs
UTF-8
8,465
2.90625
3
[ "ISC" ]
permissive
//! Minimal startup / runtime for RISC-V CPU's //! //! # Minimum Supported Rust Version (MSRV) //! //! This crate is guaranteed to compile on stable Rust 1.31 and up. It *might* //! compile with older versions but that may change in any new patch release. //! Note that `riscv64imac-unknown-none-elf` and `riscv64gc-unkn...
true
ae6da861c73c06fa6077903137bf4a89898ab34c
Rust
tock/tock
/kernel/src/platform/watchdog.rs
UTF-8
1,562
2.78125
3
[ "Apache-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// Licensed under the Apache License, Version 2.0 or the MIT License. // SPDX-License-Identifier: Apache-2.0 OR MIT // Copyright Tock Contributors 2022. //! Interface for configuring a watchdog /// A trait for implementing a watchdog in the kernel. /// This trait is called from the `kernel_loop()` code to setup /// a...
true
9010fc49a17b27600121fe830e056053f91f4ad5
Rust
yannleretaille/cpp_to_rust
/src/tests/utils.rs
UTF-8
2,949
3.34375
3
[ "MIT" ]
permissive
#[test] fn join() { use string_utils::JoinWithString; let a1 = vec!["a", "b", "c"]; assert_eq!(a1.join(""), "abc"); assert_eq!(a1.join("_"), "a_b_c"); let a2: Vec<String> = vec![]; assert_eq!(a2.join(""), ""); assert_eq!(a2.join("_"), ""); let a3 = ["Q", "W", "E"]; assert_eq!(a3.join("x"), "QxWxE");...
true
cea145fbf801c6d808ef13c7348fe09c25bbe2f0
Rust
pratikIT95/hand_cricket_rust
/src/main.rs
UTF-8
2,731
3.546875
4
[]
no_license
use std::io; use rand::Rng; use std::cmp::Ordering; fn receive_validate_input() ->u32{ println!("Enter your number:"); let mut player_intended_input = String::new(); io::stdin().read_line(&mut player_intended_input) .expect("Failed to read line"); let player_intended_input:u32 = match player_intend...
true
024d55ef4e246059fd919a72afa274be4d6fe724
Rust
ThomasdenH/adventofcode2019
/src/day_11.rs
UTF-8
7,047
3.109375
3
[]
no_license
use crate::intcode::{Computer, ComputerError, Memory, Value}; use futures::channel::mpsc::{channel, Receiver, Sender}; use futures::future::try_select; use futures::future::Either; use futures::pin_mut; use futures::prelude::*; use std::collections::HashMap; use std::convert::TryFrom; use std::fmt; use thiserror::*; #...
true
58c860e08f37edaaffbc5df832e61da0d83157d3
Rust
jtdowney/advent-2018
/day13/src/main.rs
UTF-8
8,970
3.28125
3
[]
no_license
use std::collections::HashMap; use std::env; use std::fs; #[derive(Copy, Clone)] enum Track { Straight, CurveLeft, CurveRight, Intersection, } #[derive(Copy, Clone)] enum Direction { Up, Down, Left, Right, } impl Direction { fn turn(self, turn: Turn) -> Direction { match (...
true
d5dcaef7a8b1379570904ad2686a9aeccccbce33
Rust
lucafanselau/city-builder
/crates/ecs/src/event.rs
UTF-8
2,675
3.5625
4
[]
no_license
//! This event system aims the be easily usable with the ecs system in place use std::cell::RefMut; pub trait Event = 'static; pub struct EventBuffer<T: Event> { buffer: Vec<T>, } enum EventState { Alpha, Beta, } pub struct Events<T: Event> { state: EventState, alpha: EventBuffer<T>, beta: ...
true
b1b76a6ed140f4fc0ab46e0d0994d1b35ca2aabc
Rust
Corallus-Caninus/windows-rs
/crates/tests/winrt/signatures/tests/test_u8.rs
UTF-8
2,216
2.734375
3
[]
no_license
#![allow(non_snake_case)] use core::convert::TryInto; use test_winrt_signatures::*; use windows::core::*; use Component::Signatures::*; #[implement(Component::Signatures::ITestUInt8)] struct RustTest(); impl RustTest { fn SignatureUInt8(&self, a: u8, b: &mut u8) -> Result<u8> { *b = a; Ok(a) ...
true
0b5c7703b9771878d2cbd0b17edcb81e474aaf28
Rust
stm32-rs/stm32f4xx-hal
/examples/rtic-i2s-audio-in-out.rs
UTF-8
12,441
2.90625
3
[ "BSD-3-Clause", "0BSD" ]
permissive
//! # I2S example with rtic //! //! This application show how to use I2sDriver with interruption. Be careful to you ear, wrong //! operation can trigger loud noise on the DAC output. //! //! # Hardware required //! //! * a STM32F411 based board //! * I2S ADC and DAC, eg PCM1808 and PCM5102 from TI //! * Audio signal at...
true
ee69a477f78ead4419396fd438c2edab05830453
Rust
Dineshs91/x-ray
/src/cli/mod.rs
UTF-8
4,115
2.859375
3
[]
no_license
use std::env; use clap::{Arg, App, SubCommand}; const ABOUT: &'static str = " x-ray generates python code from a configuration file and vice versa. "; pub enum ConfType { Toml, Yaml } pub struct CliConf { pub skip_validations: bool, pub conf_file: Option<String>, pub conf_type: ConfType, pub...
true
f7ef3bfc1c500be37672b68e62668375de4c8a8f
Rust
atsamd-rs/atsamd
/hal/src/sercom/i2c.rs
UTF-8
13,560
3.359375
3
[ "Apache-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
//! Use the SERCOM peripheral for I2C communications //! //! Configuring an I2C peripheral occurs in three steps. First, you must create //! a set of [`Pads`] for use by the peripheral. Next, you assemble pieces into //! a [`Config`] struct. After configuring the peripheral, you then [`enable`] //! it, yielding a funct...
true
16acd704226cbb6ec031e2450fe7087309956d31
Rust
jwbuurlage/advent-of-code-2018
/src/bin/day20.rs
UTF-8
5,420
3.0625
3
[ "MIT" ]
permissive
use std::io::{self, Read}; fn main() { let mut input = String::new(); let _result = io::stdin().read_to_string(&mut input); let mut stack: Vec<char> = input.chars().collect(); stack.reverse(); let counts: Vec<_> = ['N', 'W', 'S', 'E'] .iter() .map(|&x| input.chars().filter(|&c| c =...
true
c66b14be9c8c11c9a02ec4763bd2077afe62eeb1
Rust
aquarial/webassembly-amazons-ai
/rust/src/solver/compact_board.rs
UTF-8
6,273
3.109375
3
[ "MIT" ]
permissive
use crate::board::*; use bv::BitVec; use std::collections::VecDeque; /// Player and what they do. #[derive(Clone, Debug)] pub struct CompactMove { pub player_ix: usize, pub old_pos: Pos, pub new_pos: Pos, pub new_shot: Pos, } impl From<CompactMove> for Move { fn from(cm: CompactMove) -> Move { Move { ...
true
79b2020a6dfe927b4ad9e632dec7a7cd83c74f98
Rust
qolop/ip-locator
/src/main.rs
UTF-8
1,720
3.171875
3
[]
no_license
extern crate hyper; use std::env; use std::net::IpAddr; use hyper::Client; use hyper::header::Connection; use std::io::Read; struct IPAddrInfo { region: String, country: String, city: String, region_code: String, country_code: String, zip_code: String, organization: String, latitude: St...
true
728da02ae2ea1889f6727941e2e65bd20812044c
Rust
GeorgeKT/menhir-lang
/src/ast/bindings.rs
UTF-8
2,748
3.03125
3
[ "MIT" ]
permissive
use crate::ast::{prefix, Expression, StructPattern, TreePrinter, Type}; use crate::span::Span; use itertools::free::join; #[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)] pub enum BindingType { Name(String), Struct(StructPattern), } #[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)] ...
true
a23dfcd55f73ecb1853cad8e50866faabfc98ff4
Rust
logansquirel/advent_of_code
/aoc_2015/day_10/src/lib.rs
UTF-8
1,106
3.890625
4
[ "MIT" ]
permissive
pub fn part_one(input: &str) -> usize { let mut buffer = input.trim().to_string(); for _ in 0..40 { buffer = look_and_say(&buffer); } buffer.len() } pub fn part_two(input: &str) -> usize { let mut buffer = input.trim().to_string(); for _ in 0..50 { buffer = look_and_say(&buffer)...
true
1a5074fb83b3909779dddac81e047a114ca9b756
Rust
msuesskraut/bf-interp
/src/buffer_tests.rs
UTF-8
923
3.3125
3
[ "MIT" ]
permissive
//! Tests for `IBuffer`. use buffer::IBuffer; use std::io::Read; #[test] fn read_from_string() { let mut in_buf = IBuffer::from_str("Hello world"); let mut buf = [0u8; 6]; let res = in_buf.read(&mut buf); assert_eq!(6, res.expect("read must be ok")); assert_eq!([b'H', b'e', b'l', b'l', b'o', b' ...
true
6701e04f3101e3077992d7dda22b218b84029765
Rust
smccauliff/advent-of-code-2020
/src/dec3-1/dec3-1.rs
UTF-8
1,488
2.984375
3
[ "Unlicense" ]
permissive
use std::env; use std::vec::Vec; use a2020::process_lines; #[derive(Clone)] struct Position { row : usize, column : usize, } fn process_terrain_line(line : &String, slopes : &Vec<Position>, positions : &mut Vec<Position>, counters : &mut Vec<i64>) { let bytes = line.as_bytes(); let tree = '#' as u8; ...
true
f79209c770809517246753eb41618d445e8e01a3
Rust
digama0/mm0
/mm0-rs/components/mmcc/src/symbol.rs
UTF-8
3,787
3.453125
3
[ "CC0-1.0" ]
permissive
//! A simple string interner. use std::{collections::HashMap, fmt::Display, sync::Mutex}; use mm0_util::MutexExt; use once_cell::sync::Lazy; use crate::types::IdxVec; mk_id! { /// A `Symbol` is an interned string, used to avoid copying strings around everywhere /// in the compiler. These can refer to keywords or ...
true
944c6ddabfcbc42258d87b7cfb0e3b2b1539fc70
Rust
andysalerno/reversi_rs
/lib_agents/src/util.rs
UTF-8
654
2.84375
3
[ "MIT" ]
permissive
use rand::rngs::SmallRng; use rand::seq::SliceRandom; use rand::Rng; pub fn random_pick<'a, T, R>(choices: &'a [T], rng: &mut R) -> Option<&'a T> where R: Rng, { choices.choose(rng) } pub fn random_choice<T, R>(choices: &[T], rng: &mut R) -> T where T: Copy, R: Rng, { *random_pick(choices, rng).ex...
true
f4d81ecb141ff355e756e0f334c56bfeab5e6302
Rust
sonicXconst1/kuna_sdk
/src/client.rs
UTF-8
7,501
2.53125
3
[]
no_license
use crate::base; use crate::extractor; use crate::coin; use crate::models; pub struct KunaClient<TConnector> { client: std::sync::Arc<hyper::Client<TConnector>>, auth_context: std::sync::Arc<crate::context::AuthContext>, } impl<TConnector> KunaClient<TConnector> where TConnector: hyper::client::connect::C...
true
059679ea67ebf3b006c3b230a8559e3d5eb2026f
Rust
WaDelma/kolli-desu
/src/gjk.rs
UTF-8
1,912
2.796875
3
[ "MIT" ]
permissive
use crate::na::zero; use crate::shapes::support; use crate::shapes::Shape; use crate::simplex::Simplex; use crate::{Point, Vector}; /// a x (b x c) pub fn triple_product(a: Vector<f32>, b: Vector<f32>, c: Vector<f32>) -> Vector<f32> { b * c.dot(&a) - a * c.dot(&b) } pub fn collides<S1, S2>(a: (&S1, Point<f32>), ...
true
928576e81f61cfbc61714c8048b04bd726e71946
Rust
project-ela/rota
/src/common/error.rs
UTF-8
2,486
2.8125
3
[ "MIT" ]
permissive
use std::{error, fmt}; use x86asm::instruction::{ mnemonic::Mnemonic, operand::{register::Register, Operand}, }; use crate::{common::pos::Pos, frontend::lexer::token::TokenKind}; #[derive(Debug)] pub enum ErrorKind { UnexpectedChar { actual: char, }, UnexpectedToken { expected: Op...
true
06c00a587da9ca8fd1e5b558ac0883a199971952
Rust
ciaran2/feo3boy
/feo3boy-microcode-generator/src/validation.rs
UTF-8
2,086
2.78125
3
[ "MIT" ]
permissive
use syn::{Error, Result, Type}; use crate::defs::{ArgSource, Defs, MicrocodeOp}; /// Provides basic validation of the extracted definitions before code generation. pub fn validate_defs(defs: &Defs) -> Result<()> { for op in &defs.microcode_type.ops { validate_op(op, defs)?; } Ok(()) } /// Valida...
true
87666508e075ec2f554df009605f5e6e4a911bab
Rust
N3xed/freertos-rust
/src/semaphore.rs
UTF-8
2,870
3.09375
3
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
use crate::InterruptContext; use crate::base::*; use crate::glue; use crate::units::*; /// A counting or binary semaphore #[repr(transparent)] pub struct Semaphore { semaphore: QueueHandle, } unsafe impl Send for Semaphore {} unsafe impl Sync for Semaphore {} impl Semaphore { /// Create a new binary semaphor...
true
2608fb5e580863b82d404cc3e50b11eae44df9ba
Rust
heyrutvik/cyclone-physics-rs
/src/cyclone/demo/timing.rs
UTF-8
1,569
3.03125
3
[]
no_license
use std::time::{SystemTime, UNIX_EPOCH}; use crate::precision::Real; #[derive(Debug)] pub struct Timing { frame_number: u64, last_frame_timestamp: u64, last_frame_duration: u64, is_paused: bool, average_frame_duration: f64, fps: f64, } impl Timing { pub fn update(&mut self) { if !...
true
8909569963f763a7d9f8ec6731c2706d1b87bc80
Rust
media-io/amq-protocol
/types/src/generation.rs
UTF-8
15,083
2.65625
3
[ "BSD-2-Clause" ]
permissive
/// Serialization types and traits pub use cookie_factory::{GenChain, GenError, GenResult}; use crate::{ flags::*, types::*, value::*, }; use cookie_factory::{be_f32, be_f64, be_i8, be_i16, be_i32, be_i64, be_u8, be_u16, be_u32, be_u64, many_ref, slice}; use std::io::Write; /// Trait used to skip part o...
true
5db18fa90e8c03bccee1ce7ab377f49dc1c1e2ef
Rust
wunderdogsw/wundernut-vol10
/winning_solution/rust_henri_pirinen/src/state.rs
UTF-8
514
3.3125
3
[ "MIT" ]
permissive
use std::collections::HashMap; pub type Int = i64; pub struct State { variables: HashMap<String, Int>, } impl State { pub fn new() -> State { State { variables: HashMap::new(), } } pub fn get(&self, name: &String) -> Int { *self .variables ...
true
fbfd393263cc14d631ac083362a1aefebe159801
Rust
shawnanastasio/rudo
/src/auth/mod.rs
UTF-8
2,389
2.953125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
use std::error::Error; use std::io::prelude::*; use std::io; use std::cmp; use session::create_session; use session::check_session; use settings::Settings; use osutils::OSUtils; #[cfg(feature = "pam")] pub mod pam; #[cfg(feature = "pam")] use self::pam::*; #[cfg(feature = "touchid")] pub mod touchid; #[cfg(feature ...
true
6c444c0c1d94f820ecf230d6c23694e8e15ad1d4
Rust
mason0510/rust-stratum-v2
/stratumv2/src/noise/signature_noise_message.rs
UTF-8
2,510
2.859375
3
[]
no_license
use crate::{ codec::{ByteParser, Deserializable, Serializable}, error::Result, noise::{ signed_certificate::{authority_sign_cert, SignedCertificate}, types::AuthorityKeyPair, types::Signature, }, }; use std::io; /// SignatureNoiseMessage is sent by the Server after the NX Noise ...
true
7393badd3e3e2f0f3f9b6538fa6d9dd911701383
Rust
iCodeIN/ybc
/src/components/pagination.rs
UTF-8
6,904
3.28125
3
[ "MIT", "Apache-2.0" ]
permissive
use derive_more::Display; use yew::events::MouseEvent; use yew::prelude::*; use yewtil::NeqAssign; use crate::{Alignment, Size}; #[derive(Clone, Debug, Properties, PartialEq)] pub struct PaginationProps { /// The child `li`, `pagination-link` & `pagination-ellipsis` elements for pagination. #[prop_or_default]...
true
9f839d66f35f2e8994bf05e1ac2a7e970c06a0d9
Rust
liuchong/sf
/src/ctx.rs
UTF-8
2,354
3.328125
3
[ "MIT", "Apache-2.0" ]
permissive
use super::consts::MAX_SEQ; use super::utils::ms_since_epoch; use super::Id; use std::sync::{Arc, Mutex}; struct State { seq: u16, // sequence in milliseconds ts: u64, // timestamp in milliseconds } #[derive(Clone)] pub struct Context { epoch: u128, // time offset from start of unix time in millisecon...
true
b56fd7e2f6f4a229ca2e5b6cd0413a39322897f4
Rust
starship/starship
/src/logger.rs
UTF-8
12,351
2.796875
3
[ "ISC" ]
permissive
use crate::utils; use log::{Level, LevelFilter, Metadata, Record}; use nu_ansi_term::Color; use once_cell::sync::OnceCell; use std::{ cmp, collections::HashSet, env, fs::{self, File, OpenOptions}, io::Write, path::{Path, PathBuf}, sync::{Mutex, RwLock}, }; pub struct StarshipLogger { lo...
true
9ef81ea92efed76b0c02c724fb1dd684bd66822c
Rust
bastiendavid/speedrun-kata
/rust/src/org/training/speedrun/stage4.rs
UTF-8
1,849
3.265625
3
[]
no_license
use std::vec::Vec; use std::ops::Add; /** * Make this code clean. */ fn compute_price(cart: &Vec<f64>, vip_client: bool, black_friday: bool) -> f64 { let total = cart.iter().fold(0f64, Add::add); let discount = (compute_discount(cart.len(), black_friday, vip_client) as f64)*total / 100f64; total - discount } ...
true
6282b18950401eb71a5f6afae643a15cb4bbd0cb
Rust
zaeleus/noodles
/noodles-util/src/variant/reader/builder.rs
UTF-8
7,201
2.859375
3
[ "MIT" ]
permissive
use std::{ fs::File, io::{self, BufRead, BufReader, Read}, path::Path, }; use noodles_bcf as bcf; use noodles_bgzf as bgzf; use noodles_vcf::{self as vcf, VariantReader}; use crate::variant::{Compression, Format}; use super::Reader; /// A variant reader builder. #[derive(Default)] pub struct Builder { ...
true
e0f90d18f46917f09af285a0298cc708675cb1a8
Rust
llogiq/overflower
/overflower-plugin/src/lib.rs
UTF-8
11,816
2.703125
3
[ "Apache-2.0" ]
permissive
extern crate proc_macro; extern crate syn; extern crate quote; use self::proc_macro::TokenStream; use quote::quote; use syn::fold::{self, Fold}; use syn::parse::{Parse, ParseStream, Result}; use syn::*; // This is a helper to allow us to parse attributes struct OverflowerAttr(Vec<Attribute>); impl Parse for Overflow...
true
3380935668963289807cafaef2207a712e6d1e53
Rust
Anaisdg/flux
/libflux/flux-core/src/parser/tests/strings.rs
UTF-8
27,677
2.53125
3
[ "MIT" ]
permissive
use pretty_assertions::assert_eq; use super::*; use crate::ast::{ tests::Locator, Expression::{Array, Member}, StringExprPart::{Interpolated, Text}, }; #[test] fn parse_string_literal() { let errors: Vec<String> = vec![]; let mut p = Parser::new(r#""Hello world""#); let result = p.parse_strin...
true
c3d6912b36aac37aa17ebd9d3215b7f8e46412ba
Rust
adjivas/pasteur
/src/middlewares/style.rs
UTF-8
4,377
2.640625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
// @adjivas - github.com/adjivas. See the LICENSE // file at the top-level directory of this distribution and at // https://github.com/adjivas/pasteur // // This file may not be copied, modified, or distributed // except according to those terms. extern crate std; use std::io::Read; use sass_rs; use iron; /// The `...
true
ca484453616158fca5fbe1baae2116dd7a4a210d
Rust
blakesmith/arrow2
/src/scalar/boolean.rs
UTF-8
1,145
3.40625
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
use crate::datatypes::DataType; use super::Scalar; /// The [`Scalar`] implementation of a boolean. #[derive(Debug, Clone)] pub struct BooleanScalar { value: bool, is_valid: bool, } impl PartialEq for BooleanScalar { fn eq(&self, other: &Self) -> bool { self.is_valid == other.is_valid && ((!self.i...
true
83037bc5c92ccd97ce0a045feadc4f9d7db2443d
Rust
prisma/opentls
/src/async_io/handshake.rs
UTF-8
3,023
2.578125
3
[ "MIT", "Apache-2.0" ]
permissive
use crate::{ async_io::{ runtime::{AsyncRead, AsyncWrite}, std_adapter::StdAdapter, TlsStream, }, sync_io, Error, HandshakeError, }; use openssl::ssl::MidHandshakeSslStream; use std::{ future::Future, io::{Read, Write}, marker::Unpin, pin::Pin, ptr::null_mut, ...
true
8c22ac0f8dcf21fd5956ae31fcca8ffbf7a87f2b
Rust
astral-sh/ruff
/crates/ruff/src/rules/flake8_bandit/rules/try_except_continue.rs
UTF-8
1,904
2.953125
3
[ "BSD-3-Clause", "0BSD", "LicenseRef-scancode-free-unknown", "GPL-1.0-or-later", "MIT", "Apache-2.0" ]
permissive
use ruff_python_ast::{ExceptHandler, Expr, Ranged, Stmt}; use ruff_diagnostics::{Diagnostic, Violation}; use ruff_macros::{derive_message_formats, violation}; use crate::checkers::ast::Checker; use crate::rules::flake8_bandit::helpers::is_untyped_exception; /// ## What it does /// Checks for uses of the `try`-`excep...
true
b7ec128372fad1a6e33dc520b25dd522dc145cf3
Rust
schaefer-dev/whoami
/src/linux.rs
UTF-8
2,537
2.578125
3
[ "MIT", "BSL-1.0" ]
permissive
// "whoami" crate - Licensed under the MIT LICENSE // * Copyright (c) 2017-2018 Jeron A. Lau <jeron.lau@plopgrizzly.com> use super::libc; use super::DesktopEnv; use std::ptr::{ null_mut }; use std::io::BufReader; use std::io::Read; use std::mem; use std::process::Command; use std::process::Stdio; fn getpwuid(buffe...
true
e910d2fa9e0f6b32aa77eea97ccd5e3a5fd8af1c
Rust
kinghajj/deque
/tests/lib.rs
UTF-8
7,154
2.9375
3
[ "Apache-2.0", "MIT", "LicenseRef-scancode-other-permissive" ]
permissive
extern crate deque; extern crate rand; use std::boxed::Box; use std::mem; use std::thread::{self, JoinHandle}; use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, AtomicUsize, ATOMIC_USIZE_INIT}; use std::sync::atomic::Ordering::SeqCst; use deque::{Data, Abort, Empty, Worker, Stealer}; use rand::Rng; #[test] fn sm...
true
53e91c1d4714b5eaa8b81ccd067fe3bda2afb05e
Rust
isgasho/stronghold.rs
/client/src/client.rs
UTF-8
13,269
2.546875
3
[ "Apache-2.0" ]
permissive
// Copyright 2020 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 use crate::{ actors::{InternalResults, SHRequest, SHResults}, line_error, utils::LoadFromPath, ClientId, Location, VaultId, }; use engine::vault::RecordId; use riker::actors::*; use std::collections::BTreeMap; use serde::{Deseri...
true
97e39cc49765c90220994e36002c1a98f9373cdb
Rust
cithiLoe/exercism
/rust/nth-prime/src/lib.rs
UTF-8
527
3.65625
4
[]
no_license
pub fn nth(n: u32) -> Result<u32, ()> { if n == 0 { Err(()) } else if n == 1 { Ok(2) } else { let mut i = 1; let mut candidate = 1; while i < n { candidate += 2; if is_prime(candidate) { i += 1; } } O...
true
1563e7b87fd8a216e683c9a8c9daf678da52bf8a
Rust
arsing/mqtt-async
/src/acceptor.rs
UTF-8
1,251
2.6875
3
[]
no_license
pub struct Acceptor { inner: std::net::TcpListener, session: std::rc::Rc<crate::Session>, } impl Acceptor { pub fn bind( addr: impl std::net::ToSocketAddrs, session: std::rc::Rc<crate::Session>, ) -> std::io::Result<Self> { let inner = std::net::TcpListener::bind(addr)?; ...
true
30079cbf0d5f6df637a14e10e9e80868c5355547
Rust
losfair/FlatMk-v0
/user/early/flatrt-thread/src/lib.rs
UTF-8
8,173
2.65625
3
[ "MIT" ]
permissive
//! This crate builds a thread abstraction on top of FlatMk's Task capability. #![no_std] #![feature(naked_functions, llvm_asm, new_uninit)] extern crate flatrt_allocator; extern crate alloc; use alloc::boxed::Box; use alloc::vec::Vec; use alloc::collections::btree_map::BTreeMap; use alloc::sync::Arc; use core::mem:...
true
862cdfdda32e6c18fd1bf1c6f5db2f2e2a37f156
Rust
ruoshui-git/stuygfx-rs-src-1
/src/color.rs
UTF-8
1,442
4.03125
4
[]
no_license
//! Module to work with colors. /// Represent an rgb triple. /// /// The fields are of type `u8`, since that's the standard RGB space. But the actual upper bound of color defined by PPM file spec is /// 2^16. Just change all instance of u8 here if you want that instead. You would also need to change the fns that writ...
true
0c72c812e7b7e0ffd34b615239ce15efa356d5bc
Rust
whentze/klinke
/src/alloc.rs
UTF-8
2,648
3
3
[]
no_license
use std::{ alloc::{GlobalAlloc, Layout, System}, cell::Cell, ptr, sync::atomic::{Ordering, AtomicUsize}, thread, }; use crossbeam_channel::{Sender, bounded}; // Each thread may hold a channel to send garbage on. thread_local! { static DISPOSAL: Cell<Option<Sender<Garbage>>> = Cell::new...
true
92066f51e0697ae28a412f308816a42d08a5a3c5
Rust
Manishearth/humpty_dumpty
/tests/match-return.rs
UTF-8
1,287
2.65625
3
[]
no_license
#![feature(plugin)] #![feature(custom_attribute)] #![plugin(humpty_dumpty)] #![allow(unused_attributes)] #![allow(unused_variables)] #![allow(dead_code)] #[drop_protect] struct Foo; impl Foo { #[allow_drop="Foo"] fn close(self) { } } #[test] fn match_return() { let f = Foo; match true { true...
true
14e394405c453ba311ae5fe6ed95378094a9d637
Rust
jungbin-kwon/tokenizer
/src/processors/eraser.rs
UTF-8
705
3.171875
3
[ "MIT" ]
permissive
use cow_utils::CowUtils; use super::{PreProcessor, ProcessedText}; pub struct Eraser(char, String); impl Eraser { /// replaces the occurences of `c`, if any, with the equivalent amount of spaces in bytes. /// e.g: "l’espagne" becomes "l espagne" because '’' is 3 bytes long. This allows the string /// t...
true
3448ec02be97c35813eb7925adc409bae5f31335
Rust
igxactly/hnsw
/tests/simple.rs
UTF-8
2,454
3.0625
3
[ "MIT" ]
permissive
//! Useful tests for debugging since they are hand-written and easy to see the debugging output. use hnsw::{Hnsw, Searcher}; use rand_pcg::Pcg64; use space::{Metric, Neighbor}; struct Euclidean; impl Metric<&[f64]> for Euclidean { type Unit = u64; fn distance(&self, a: &&[f64], b: &&[f64]) -> u64 { a...
true
f35fa39ab870b7eced0d87e2bb5f9b7871e64b95
Rust
zhaog6/Rust
/examples/enum.rs
UTF-8
771
3.171875
3
[ "MIT" ]
permissive
/*********************************************************************** > File Name: enum.rs > Author: Zhao Gang > Mail: zhaog6@lsec.cc.ac.cn > Created Time: 2020/12/03 星期四 13时48分25秒 ***********************************************************************/ #[derive(Debug)] enum Book { Papery {index: u32}, Elec...
true
5f8f299b0833d918c2e131d30fd02d3d9f7183cc
Rust
vadixidav/mli
/mli/src/zip.rs
UTF-8
1,791
2.78125
3
[ "MIT" ]
permissive
use crate::{Backward, ChainData, Forward, Train}; #[derive(Clone, Debug)] pub struct Zip<T, U>(pub T, pub U); impl<T, U> Forward for Zip<T, U> where T: Forward, U: Forward, { type Input = (T::Input, U::Input); type Internal = (T::Internal, U::Internal); type Output = (T::Output, U::Output); f...
true
8e7628ffabe1665f611dea3ad9bb518aaa233772
Rust
little-dude/netlink
/netlink-packet-route/src/rtnl/link/nlas/link_state.rs
UTF-8
1,520
3.0625
3
[ "MIT", "MITNFA" ]
permissive
// SPDX-License-Identifier: MIT use crate::constants::*; #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum State { /// Status can't be determined Unknown, /// Some component is missing NotPresent, /// Down Down, /// Down due to state of lower layer LowerLayerDown, /// In some t...
true
07372041a7d76fc0d5e6a5805e8d419d5e56b72c
Rust
echelon/kinect.rs
/src/capture.rs
UTF-8
2,349
2.875
3
[]
no_license
#![allow(unused)] use crate::Image; use k4a_sys_temp as k4a_sys; use std::ptr::null_mut; /// Represents a single capture. #[derive(Debug)] pub struct Capture(pub k4a_sys::k4a_capture_t); // These are ref-counted handles and are safe to Send. unsafe impl Send for Capture{} // Remove a libk4a capture refcount on ever...
true
de3695adce8bf929d2d922821c732688eb4b60ab
Rust
zhangjunfang/rust_read_code
/mysql_simple/src/main.rs
UTF-8
4,914
2.625
3
[ "Apache-2.0" ]
permissive
#[macro_use] extern crate mysql; use mysql as my; #[derive(Debug, PartialEq, Eq)] struct Payment { customer_id: i32, amount: i32, account_name: Option<String>, } #[derive(Debug, PartialEq, Eq)] struct Myuser { user_id: i32, name: Option<String>, sex: i8, } //middle vlue #[derive(Debug, Parti...
true
747b0d8c44224222d0531e71809be06c966d9167
Rust
enso-org/enso
/lib/rust/ensogl/core/src/animation/frp/easing.rs
UTF-8
1,730
2.828125
3
[ "AGPL-3.0-only", "Apache-2.0", "AGPL-3.0-or-later" ]
permissive
//! FRP bindings to the animation engine. use crate::prelude::*; use crate::animation::easing; use enso_frp as frp; // ============== // === Easing === // ============== crate::define_endpoints! { Input { set_duration (f32), target (f32), stop_and_rewind (f32), ski...
true
75d33d2d5a753906b0296b1ee514af942f440c70
Rust
jamcleod/LibAFL
/libafl/src/stats/multi.rs
UTF-8
3,265
2.96875
3
[ "Apache-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
//! Stats to disply both cumulative and per-client stats use alloc::{string::String, vec::Vec}; use core::{time, time::Duration}; #[cfg(feature = "introspection")] use alloc::string::ToString; use crate::{ bolts::current_time, stats::{ClientStats, Stats}, }; /// Tracking stats during fuzzing and display bot...
true
ca7e4901eb86f808f201c4fc445525883b3f2ab6
Rust
kezenator/adventofcode
/2019/examples/8.rs
UTF-8
1,808
3.3125
3
[ "MIT" ]
permissive
const INPUT: &str = include_str!("input_8.txt"); fn layers(input: &str, width: usize, height: usize) -> Vec<String> { let per_layer = width * height; let num_layers = input.len() / per_layer; (0..num_layers).map(|i| input.chars().skip(i * per_layer).take(per_layer).collect::<String>()).collect() } fn get...
true
e26e0d5ddf5232b66915c08812fa993365431917
Rust
draftedus/tangram
/app/common/production_stats/prediction_stats.rs
UTF-8
5,499
2.71875
3
[ "MIT" ]
permissive
use super::number_stats::{NumberStats, NumberStatsOutput}; use crate::monitor_event::PredictOutput; use std::collections::BTreeMap; use tangram_metrics::StreamingMetric; #[derive(serde::Serialize, serde::Deserialize, Clone, Debug)] pub enum ProductionPredictionStats { Regression(RegressionProductionPredictionStats), ...
true
3a425a5c16d0f1ef04af77dd6e09ca032b1b7de2
Rust
peterhj/kevlar
/src/test.rs
UTF-8
365
2.90625
3
[ "MIT" ]
permissive
extern crate kevlar; use kevlar::db::{KevlarDb}; fn main() { println!("Hello, world!"); let mut db = KevlarDb::new(); db.put_str(~"foo", ~"bar"); db.put_str(~"hello", ~"world"); db.put_str(~"asdf", ~"qwerty"); db.delete(~"asdf"); println!("{}", db.get_str(~"foo")); println!("{}", db.get_str(~"hello"))...
true
f455c0d66a49b8d2952315a32ad56c377adf25b0
Rust
mkanenobu/til
/rust/the_book/associated_types/src/main.rs
UTF-8
1,674
3.734375
4
[ "WTFPL" ]
permissive
fn main() { associated_types(); } /** 関連型(associated type)はトレイトのメソッド定義がシグネチャでプレースホルダの型を使用できるように、 トレイトと型のプレースホルダを結びつける **/ struct Counter { count: i32, max: i32, } impl Iterator for Counter { // Iterator トレイトには Item のプレースホルダ型が定義されており、他のメソッドのシグネチャに使用されている // そのため Iterator トレイトを実装する型は Item 型の取る具体的な型...
true
8bd5c2848c3904771380cfb6d548c8998480cd70
Rust
Cassin01/PracticeForCompetitiveProgramming
/at_coder/C/abc_114/src/main.rs
UTF-8
3,368
2.90625
3
[]
no_license
#![allow(unused_mut)] #![allow(non_snake_case)] #![allow(unused_imports)] use std::collections::HashSet; use std::collections::HashMap; use std::collections::BTreeSet; use std::collections::VecDeque; use std::cmp::{max, min}; // https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 #[allow(unused_macros)] macro_rules! in...
true
e39b2722c038f24c1b0516faba084d159efd9fb9
Rust
rustkas/rust_javatpoint
/javatpoint_rust_src/generics/src/trait06.rs
UTF-8
575
2.65625
3
[ "MIT" ]
permissive
/* cargo run -p generics --bin trait06 cargo fmt --verbose --package generics */ use std::fmt::{Debug, Display}; fn compare_prints<T: Debug + Display>(t: &T) { println!("Debug: '{:?}'", t); println!("Display: '{}'", t); assert_ne!(format!("{}", t), format!("{:?}", t)) } #[allow(dead_code)] fn fun1<T: Disp...
true
1ad7e41cc40489309734b8ba6fd10bffb5cf6719
Rust
dralley/RustPython
/compiler/src/ir.rs
UTF-8
7,641
2.75
3
[ "MIT", "CC-BY-4.0" ]
permissive
use crate::IndexSet; use rustpython_bytecode::{CodeFlags, CodeObject, ConstantData, Instruction, Label, Location}; pub type BlockIdx = Label; #[derive(Debug)] pub struct InstructionInfo { /// If the instruction has a Label argument, it's actually a BlockIdx, not a code offset pub instr: Instruction, pub l...
true
ba5232ef48f65634aabdd14bbf438bd30a71ad26
Rust
Justin-D-Lin/Programming-Languages-Project
/real-app/real-app/src/main.rs
UTF-8
1,060
3.8125
4
[]
no_license
//This rust file is a simple calculator that computes an operation between two variables. //The selected operation and two float variables are taken from user input. #[macro_use] extern crate text_io; fn main() { use std::io::{stdin}; let mut operation = String::new(); println!("What operation would you like ...
true
e9c785ac7aafccf7ad19f653dadbef3c48d65ec4
Rust
isgasho/rust-dns
/src/name.rs
UTF-8
6,054
3.140625
3
[ "BSD-2-Clause" ]
permissive
use std::io; use std::fmt; /// An RFC1035 `<domain-name>` (sequence of labels) /// #[deriving(PartialEq,Eq,Hash,Clone)] pub struct Name { labels: Vec<String>, } impl Name { pub fn new() -> Name { Name { labels: Vec::new() } } /// Parse a byte slice containing an already-decompressed name. ...
true
65636c9b1d86262c3cfcbed6a622e2cba67268a8
Rust
edwardgeorge/avocado-build-state
/src/main.rs
UTF-8
3,750
2.65625
3
[]
no_license
use clap::{App, AppSettings, Arg, SubCommand}; use dkregistry::v2::Client; use std::fs::File; use std::path::{Path, PathBuf}; use thiserror::Error; use tokio::runtime::Runtime; mod args; mod images; use crate::args::process_args; use crate::images::Item; const REGISTRY_CRED_USR: &str = "REGISTRY_CRED_USR"; const REGI...
true
763554026b8e581bd1ddb37c1bc9f4b025de2591
Rust
MinusGix/fiskar
/src/styled.rs
UTF-8
27,108
3.34375
3
[]
no_license
use std::ops::Range; use cursive::{ theme::Style, utils::markup::{ StyledIndexedSpan as CursiveStyledIndexedSpan, StyledString as CursiveStyledString, }, }; #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum InsertMode { /// Break apart anything it was inserted in the middle of, so the inse...
true
79afe85d16a08a3cb10fcd1843ffb59072729b15
Rust
Weibye/kepler
/crates/kepler/src/lib.rs
UTF-8
4,259
2.875
3
[]
no_license
mod base_units; mod orbits; mod body; mod shapes; mod plane; mod bundles; mod utils; pub use base_units::*; pub use orbits::*; pub use body::*; pub use shapes::*; pub use plane::*; pub use bundles::*; pub use utils::*; use std::f32::consts::PI as PI32; use std::f64::consts::PI as PI64; use physical_constants::NEWTONI...
true
399ff2b5745a3ae055e1428dea6c2a104264db5f
Rust
seanwallawalla-forks/nushell
/crates/nu-command/src/commands/core_commands/history.rs
UTF-8
2,043
2.90625
3
[ "MIT" ]
permissive
use crate::prelude::*; use nu_engine::WholeStreamCommand; use nu_errors::ShellError; use nu_protocol::{ReturnSuccess, Signature, UntaggedValue}; use std::fs::File; use std::io::{BufRead, BufReader}; pub struct History; impl WholeStreamCommand for History { fn name(&self) -> &str { "history" } fn ...
true
1908a61d6eb0c140e6f5b6e98fa9ab8b4438db33
Rust
nuhtan/lifestyle
/src/core/api/mod.rs
UTF-8
1,885
2.859375
3
[]
no_license
use super::{response, state_data::state::State}; pub mod calories; pub mod progress; pub mod rendered; pub fn apply_request<'a>( path: &'a str, body: String, shared_data: State, ) -> Result<response::Response<'a>, response::Response<'a>> { match path { "/api/calories/add/day" => calories::add_...
true
9c70127a35e96536f5ac020b95a3e3668d038264
Rust
hasokon/chcookie
/src/decrypter.rs
UTF-8
1,330
2.515625
3
[]
no_license
use aes::Aes128; use block_modes::{Cbc, BlockMode}; use block_modes::block_padding::Pkcs7; type AesCbc = Cbc<Aes128, Pkcs7>; use crate::models::{CookieDataRaw, DecryptedCookie, Result, GetChromeCookieError}; use crate::key::get_chrome_key; const IV: [u8; 16] = [0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0...
true
e1ea35785e5b05ec900cd32e790a19b6019c3a28
Rust
Gabriel-Paulucci/Do-Ferro-A-Ferrugem
/1-introdução/src/main.rs
UTF-8
217
3.4375
3
[ "MIT" ]
permissive
fn main() { let result: u128 = fibonacci(20); println!("{}", result); } fn fibonacci(n: u128) -> u128 { match n { 1 => 1, 2 => 1, _ => fibonacci(n - 1) + fibonacci(n - 2), } }
true
3c79404e1e7cbff8736797a5ff332e5d944e01e6
Rust
flasco/automic-checkin
/src/main.rs
UTF-8
850
2.671875
3
[]
no_license
use std::env; use std::error::Error; use std::time::Duration; mod api; use api::*; #[tokio::main] async fn main() -> Result<(), Box<dyn Error>> { let mut args = env::args(); args.next(); let cookie = args.next().unwrap_or("".to_string()); if cookie.len() < 1 { eprintln!("need cookie"); ...
true
d717a0c8a6010ad9c3341ccc7ac53311ac233d5f
Rust
sru-systems/rust-kpdb
/src/crypto/aes256.rs
UTF-8
3,355
2.6875
3
[ "Apache-2.0", "MIT", "LicenseRef-scancode-unknown" ]
permissive
// Copyright (c) 2016-2017 Martijn Rijkeboer <mrr@sru-systems.com> // // 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, o...
true
5e593a9ec93425107d2fa42931c077b76466eeb8
Rust
st3fan/exercism
/rust/protein-translation/src/lib.rs
UTF-8
1,198
3.28125
3
[]
no_license
use std::collections::HashMap; pub struct CodonsInfo<'a> { codons: HashMap<&'a str, &'a str>, } impl<'a> CodonsInfo<'a> { pub fn name_for(&self, codon: &str) -> Option<&'a str> { if let Some(protein) = self.codons.get(codon) { return Some(*protein); } None } pub fn...
true
2bbfda7415fbd19d94d72782807bc859d3b215dc
Rust
BrianMcKeever/My-exercism-solutions
/rust/nth-prime/src/lib.rs
UTF-8
665
3.515625
4
[ "MIT" ]
permissive
fn is_prime(n: u32) -> bool { if n % 2 == 0 { return false; } let max: f64 = n.into(); let max = max.sqrt().floor() as u32 + 1; for i in (3..max).step_by(2) { if n % i == 0 { return false; } } return true; } pub fn nth(n: u32) -> u32 { if n == 0 { ...
true
7cc0355736b18d2b1b0686fd1c3ee82f9a9cf70b
Rust
lunjon/dotfiles
/src/path.rs
UTF-8
2,161
3.046875
3
[]
no_license
use std::path::PathBuf; use directories::BaseDirs; use lazy_static::lazy_static; /// Converts a Path/PathBuf into String type. /// Uses unwrap(), which may panic for a path with /// invalid utf-8 for certain OSes. #[macro_export] macro_rules! path_str { ($p:expr) => { $p.to_str().expect("valid utf-8 strin...
true
637ecab2268b124c2d2aa1993107276c23933513
Rust
fluid-lang/fluid
/packages/fluid_parser/src/ast.rs
UTF-8
2,772
4.0625
4
[ "Apache-2.0" ]
permissive
//! This file contains all of the AST interfaces. /// An expression. #[derive(Debug)] pub enum Expression { /// A variable reference. VarRef(String), /// A variable assign. VarAssign(String, Box<Expression>), /// A function call. FunctionCall(String, Vec<Expression>), /// A binary operator....
true
2d342f2e7966916e7760c5cd0236b172bac33a80
Rust
seanmonstar/reqwest
/src/blocking/wait.rs
UTF-8
2,096
3.03125
3
[ "Apache-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
use std::future::Future; use std::sync::Arc; use std::task::{Context, Poll}; use std::thread::{self, Thread}; use std::time::Duration; use tokio::time::Instant; pub(crate) fn timeout<F, I, E>(fut: F, timeout: Option<Duration>) -> Result<I, Waited<E>> where F: Future<Output = Result<I, E>>, { enter(); let...
true
3e08edb1b1bab7d2102ba05d75b86c900bb5c44d
Rust
appaquet/exocore
/apps/sdk/src/time.rs
UTF-8
5,738
3.09375
3
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
use std::{collections::BinaryHeap, sync::Mutex, time::Duration}; use chrono::{DateTime, TimeZone, Utc}; use futures::{channel::oneshot, Future, FutureExt}; use crate::binding::__exocore_host_now; /// Unix timestamp in nanoseconds. #[derive(PartialEq, Eq, PartialOrd, Ord, Copy, Clone, Debug)] pub struct Timestamp(pub...
true
774c393344bca5d5080db01779d4e834616a1ef6
Rust
zonderclue/anchor
/client/src/lib.rs
UTF-8
6,471
2.5625
3
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
//! `anchor_client` provides an RPC client to send transactions and fetch //! deserialized accounts from Solana programs written in `anchor_lang`. use anchor_lang::solana_program::instruction::{AccountMeta, Instruction}; use anchor_lang::solana_program::program_error::ProgramError; use anchor_lang::solana_program::pub...
true
ff6544a0d3329c9146628c187d6bd608c2cab8a7
Rust
hamersaw/stitch
/impl/yogi/src/lib.rs
UTF-8
1,134
2.765625
3
[ "MIT" ]
permissive
use protobuf::{Filter, Image, ImageListRequest, ImageManagementClient}; use tonic::Request; use std::cmp::Ordering; use std::error::Error; #[tokio::main] pub async fn get_images(album: &str, filter: Filter, rpc_address: &str) -> Result<Vec<Image>, Box<dyn Error>> { // initialize ImageManagement grpc clien...
true
31f9bfc5bb0032ae3905f96b0a62d3e4c3584e65
Rust
proehlen/honeycomb
/tests/language.rs
UTF-8
4,249
3.40625
3
[ "Apache-2.0" ]
permissive
extern crate honeycomb; use honeycomb::{ language::{array, identifier, number, punctuation, string, token}, Error, }; #[test] fn token_test() { assert_eq!( (token() * (..)).parse( r#" fn main() { println!("Hello world!"); } "# ), Ok(vec![ String::from("...
true
899af6e86024237f14edef2b9bbfca5452425adb
Rust
snwallet/rust-np
/rust01/src/main.rs
UTF-8
1,268
3.734375
4
[ "Apache-2.0" ]
permissive
const MAX_POINT:u32 = 10000; fn main(){ //1、变量定义 //定义变量用let 如果变量没有用mut,那么是不可变的 //let name : type let a = 1; let mut b:u32 = 2; println!("{},{}",a,b); b=3; println!("{}",b); //隐藏 let b:f32 = 1.9; println!("{}",b); //常量 println!("MAX_POINTS={}",MAX_POINT); printl...
true
c9f953c3ded7e9aa4f9350d68b17354d47c6fee6
Rust
afidegnum/usersman_stable
/src/auth/auth.rs
UTF-8
671
2.625
3
[]
no_license
use crate::auth::user::User; use crate::errors::ServiceError; use actix_web::web; use deadpool_postgres::{Client, Pool}; use serde::Deserialize; #[derive(Debug, Deserialize)] pub struct AuthRequest { pub email: String, pub password: String, } impl AuthRequest { pub async fn authenticate(&self, pool: &Clie...
true
f38dfdafc3323712f00a2967786b8f41dfaf95c2
Rust
etaoins/arret
/compiler/reporting.rs
UTF-8
3,995
2.90625
3
[ "Apache-2.0" ]
permissive
use codespan_reporting::diagnostic::{Diagnostic, Label}; use arret_syntax::span::{FileId, Span}; use crate::source::SourceLoader; /// Traces the location of report through macro expansions #[derive(Debug, PartialEq, Clone)] pub struct LocTrace { origin: Span, macro_invocation: Option<Span>, } impl LocTrace ...
true
e6f22bc92c48150ca79a074ce77559c399009d6d
Rust
MikailBag/kube-utils
/src/webhook/apis.rs
UTF-8
2,657
2.78125
3
[]
no_license
//! Low-level types #[derive(serde::Serialize, Debug, Clone)] pub struct Status { #[serde(skip_serializing_if = "Option::is_none")] pub code: Option<u16>, #[serde(skip_serializing_if = "Option::is_none")] pub message: Option<String>, } impl Status { pub fn is_empty(&self) -> bool { self.co...
true