text stringlengths 232 16.3k | domain stringclasses 1
value | difficulty stringclasses 3
values | meta dict |
|---|---|---|---|
<|fim_prefix|>// repo: samwho/advent-of-code-2020 path: /src/1.rs
use std::{error::Error, fs::File, io::BufRead, io::BufReader};
fn main() -> Result<(), Box<dyn Error>> {
let file = File::open("data/1")?;
let reader = BufReader::new(file);
<|fim_suffix|> for result in reader.lines() {
let line = r... | code_fim | medium | {
"lang": "rust",
"repo": "samwho/advent-of-code-2020",
"path": "/src/1.rs",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> use std::fmt::Write;
let s = "escape 'me' & \"you\"";
let mut es = String::new();
write!(es, "{}", super::Escaped(&s)).unwrap();
assert_eq!(es, "escape 'me' & "you"");
}
}<|fim_prefix|>// repo: Nemo157/hamlet path: /src/escape.rs
use std::... | code_fim | medium | {
"lang": "rust",
"repo": "Nemo157/hamlet",
"path": "/src/escape.rs",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: Nemo157/hamlet path: /src/escape.rs
use std::fmt;
fn escape_char<'a>(c: char) -> Option<&'a str> {
match c {
'<' => Some("<"),
'>' => Some(">"),
'"' => Some("""),
'\'' => Some("'"),
'&' => Some("&"),
_ => None,
}
}
pub ... | code_fim | hard | {
"lang": "rust",
"repo": "Nemo157/hamlet",
"path": "/src/escape.rs",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: dvdsk/yarte path: /yarte_html/src/interface.rs
// Copyright 2014-2017 The html5ever Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0... | code_fim | hard | {
"lang": "rust",
"repo": "dvdsk/yarte",
"path": "/yarte_html/src/interface.rs",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> /// Append a `DOCTYPE` element to the `Document` node.
fn append_doctype_to_document(
&mut self,
name: StrTendril,
public_id: StrTendril,
system_id: StrTendril,
);
/// Mark a HTML `<script>` as "already started".
fn mark_script_already_started(&mut self... | code_fim | hard | {
"lang": "rust",
"repo": "dvdsk/yarte",
"path": "/yarte_html/src/interface.rs",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> fn close(&self, window: Self::Window);
}
#[derive(Debug, Clone, Copy)]
pub struct WindowDims {
pub x: i32,
pub y: i32,
pub width: u32,
pub height: u32,
}
#[derive(Debug, Clone, PartialEq)]
pub enum WindowEvent {
CloseRequested,
CloseHappened,
ResizeHappened { dims: (f64, f64) },
MouseMove(Mouse... | code_fim | hard | {
"lang": "rust",
"repo": "IntrepidPig/raw-brass",
"path": "/src/window.rs",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|>
fn create_window(&self, title: &str, dims: WindowDims) -> Result<Self::Window, Self::Error>;
fn get_window_events(&self, window: &mut Self::Window, event_buf: &mut VecDeque<WindowEvent>);
fn set_window_size(&self, window: &Self::Window, dims: (u32, u32));
fn set_window_position(&self, window: &Sel... | code_fim | medium | {
"lang": "rust",
"repo": "IntrepidPig/raw-brass",
"path": "/src/window.rs",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: IntrepidPig/raw-brass path: /src/window.rs
use crate::event::KeyboardEvent;
use crate::event::MouseClickEvent;
use crate::event::MouseMoveEvent;
use std::collections::VecDeque;
use std::fmt::Debug;
pub mod winit;
pub mod xcb;
pub trait WindowBackend: Sized {
type Window;
type Error: Debug;
... | code_fim | medium | {
"lang": "rust",
"repo": "IntrepidPig/raw-brass",
"path": "/src/window.rs",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: rust-lang/rust path: /src/tools/clippy/tests/ui/type_id_on_box.rs
#![warn(clippy::type_id_on_box)]
use std::any::{Any, TypeId};
use std::ops::Deref;
type SomeBox = Box<dyn Any>;
struct BadBox(Box<dyn Any>);
impl Deref for BadBox {
type Target = Box<dyn Any>;
fn deref(&self) -> &Self... | code_fim | medium | {
"lang": "rust",
"repo": "rust-lang/rust",
"path": "/src/tools/clippy/tests/ui/type_id_on_box.rs",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> let b = existential();
let _ = b.type_id(); // Don't lint.
let b: SomeBox = Box::new(0usize);
let _ = b.type_id();
let b = BadBox(Box::new(0usize));
let _ = b.type_id(); // Don't lint. This is a call to `<BadBox as Any>::type_id`. Not `std::boxed::Box`!
}<|fim_prefix|>// repo: ru... | code_fim | hard | {
"lang": "rust",
"repo": "rust-lang/rust",
"path": "/src/tools/clippy/tests/ui/type_id_on_box.rs",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>pub static numnames: &[&str] =
&["cols", "it", "lines", "lm", "xmc", "pb", "vt", "wsl", "nlab", "lh", "lw", "ma", "wnum",
"colors", "pairs", "ncv", "bufsz", "spinv", "spinh", "maddr", "mjump", "mcs", "mls",
"npins", "orc", "orl", "orhi", "orvi", "cps", "widcs", "btns", "bitwin", "bitype", ... | code_fim | hard | {
"lang": "rust",
"repo": "Stebalien/term",
"path": "/src/terminfo/parser/names.rs",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: Stebalien/term path: /src/terminfo/parser/names.rs
_down_cursor",
"parm_ich",
"parm_index",
"parm_insert_line",
"parm_left_cursor",
... | code_fim | hard | {
"lang": "rust",
"repo": "Stebalien/term",
"path": "/src/terminfo/parser/names.rs",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> "enter_doublewide_mode",
"enter_draft_quality",
"enter_italics_mode",
"enter_leftward_mode",
"enter_micro_mode",
... | code_fim | hard | {
"lang": "rust",
"repo": "Stebalien/term",
"path": "/src/terminfo/parser/names.rs",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: zshipko/ocaml-rs path: /src/pointer.rs
#![allow(unknown_lints)]
#![allow(clippy::derive_partial_eq_without_eq)]
use core::marker::PhantomData;
use crate::{Custom, FromValue, Raw, Runtime, ToValue, Value};
/// A handle to a Rust value/reference owned by the OCaml heap.
///
/// This should only... | code_fim | hard | {
"lang": "rust",
"repo": "zshipko/ocaml-rs",
"path": "/src/pointer.rs",
"mode": "psm",
"license": "ISC",
"source": "the-stack-v2"
} |
<|fim_suffix|>impl<T: Custom> Pointer<T> {
/// Allocate a `Custom` value
pub fn alloc_custom(x: T) -> Pointer<T>
where
T: Custom,
{
unsafe {
let mut ptr = Pointer(Value::alloc_custom::<T>(), PhantomData);
ptr.set(x);
ptr
}
}
}
impl<T> Poin... | code_fim | hard | {
"lang": "rust",
"repo": "zshipko/ocaml-rs",
"path": "/src/pointer.rs",
"mode": "spm",
"license": "ISC",
"source": "the-stack-v2"
} |
<|fim_suffix|> let mut sum: i32 = 0;
for i in 0..nums.len() - 2 {
for j in (i + 1)..nums.len() - 1 {
let mut k: usize = j + 1;
while k < nums.len() && nums[i] + nums[j] > nums[k] {
k += 1;
}
sum += (k - j) as i32 - 1;
}
}
sum
}
}
fn main() {
prin... | code_fim | medium | {
"lang": "rust",
"repo": "redsnapper2006/leetcode-cn",
"path": "/V/611-valid-triangle-number/main.rs",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: redsnapper2006/leetcode-cn path: /V/611-valid-triangle-number/main.rs
struct Solution {}
impl Solution {
pub fn triangle_number2(mut nums: Vec<i32>) -> i32 {
if nums.len() < 3 {
return 0;
}
nums.sort();
let mut sum: i32 = 0;
for i in 0..nums.len() - 2 {
for j i... | code_fim | medium | {
"lang": "rust",
"repo": "redsnapper2006/leetcode-cn",
"path": "/V/611-valid-triangle-number/main.rs",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> // Validate everything parsed to the right type as a sanity check
match strat {
VerificationStrategy::MultipleAttestationGreedy(roles) => {
assert!(
roles.contains(&SignatureRole::Creator),
"Roles should contain creator"
... | code_fim | hard | {
"lang": "rust",
"repo": "michelleN/bindle",
"path": "/src/invoice/verification.rs",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: michelleN/bindle path: /src/invoice/verification.rs
erified");
if !target_role && !all_verified {
debug!("Not a target role, not checking for verification");
continue;
} else if all_roles {
... | code_fim | hard | {
"lang": "rust",
"repo": "michelleN/bindle",
"path": "/src/invoice/verification.rs",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> // Verify the signature
// TODO: This would allow a trivial DOS attack in which an attacker
// would only need to attach a known-bad signature, and that would
// prevent the module from ever being usable. This is marginally
... | code_fim | hard | {
"lang": "rust",
"repo": "michelleN/bindle",
"path": "/src/invoice/verification.rs",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: axelf4/lis path: /src/lib.rs
/*!
An implementation of the
[Longest increasing subsequence algorithm](https://en.wikipedia.org/wiki/Longest_increasing_subsequence).
# Examples
The main trait exposed by this crate is [`LisExt`], which is implemented for,
inter alia, arrays:
```
use lis::LisExt;... | code_fim | hard | {
"lang": "rust",
"repo": "axelf4/lis",
"path": "/src/lib.rs",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> struct Cb<T> {
v: Vec<T>,
idx: usize,
last_add_one: usize,
}
impl<T: Copy + Eq> DiffCallback<(usize, &T), (usize, &T)> for Cb<T> {
fn inserted(&mut self, (_j, new): (usize, &T)) {
self.v.insert(self.idx, *new);
... | code_fim | hard | {
"lang": "rust",
"repo": "axelf4/lis",
"path": "/src/lib.rs",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: ftsujikawa/rust-sample path: /ch17/code17-6/src/main.rs
fn main() {
println!("use zip");
let a = [1,2,3,4,5<|fim_suffix|>let c: Vec<_> = a.iter().zip(b.iter()).collect();
for (n,w) in c {
println!("c is {} and {}", n, w);
}
}<|fim_middle|>];
let b = ["one", "two", "th... | code_fim | medium | {
"lang": "rust",
"repo": "ftsujikawa/rust-sample",
"path": "/ch17/code17-6/src/main.rs",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|>,w) in c {
println!("c is {} and {}", n, w);
}
}<|fim_prefix|>// repo: ftsujikawa/rust-sample path: /ch17/code17-6/src/main.rs
fn main() {
println!("use zip");
let a = [1,2,3,4,5];
let b = ["one", "two", "three", "four", "five"];
<|fim_middle|>let c: Vec<_> = a.iter().zip(b.it... | code_fim | medium | {
"lang": "rust",
"repo": "ftsujikawa/rust-sample",
"path": "/ch17/code17-6/src/main.rs",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: the10thWiz/cryptopals path: /src/data/mod.rs
one, Default)]
pub struct Bytes {
bytes: Vec<u8>,
}
impl Bytes {
pub fn new() -> Bytes {
Self { bytes: Vec::new() }
}
pub fn with_capacity(size: usize) -> Bytes {
Self {
bytes: Vec::with_capacity(size),
... | code_fim | hard | {
"lang": "rust",
"repo": "the10thWiz/cryptopals",
"path": "/src/data/mod.rs",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> /**
* Reads data as hex values from `s`
*
* Allows both upper and lower case
*/
pub fn read_hex(s: &str) -> Bytes {
let mut ret = Vec::with_capacity(s.len() / 2);
let mut cur = 0u8;
let mut top = true;
for c in s.chars() {
let tmp = m... | code_fim | hard | {
"lang": "rust",
"repo": "the10thWiz/cryptopals",
"path": "/src/data/mod.rs",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> let mut ret = String::with_capacity(2);
ret += match b / 0x10 {
0x00 => "0",
0x01 => "1",
0x02 => "2",
0x03 => "3",
0x04 => "4",
0x05 => "5",
0x06 => "6",
0x07 => "7",
0x08 => "8",
... | code_fim | hard | {
"lang": "rust",
"repo": "the10thWiz/cryptopals",
"path": "/src/data/mod.rs",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: drozdowsky/sample-rs path: /src/main.rs
use std::io;
use std::cmp::{min, max};
use termion;
use termion::raw::IntoRawMode;
use termion::input::TermRead;
use termion::screen::AlternateScreen;
use tui::Terminal;
use tui::backend::TermionBackend;
use tui::widgets::{Widget, Block, Borders, Gauge};
u... | code_fim | hard | {
"lang": "rust",
"repo": "drozdowsky/sample-rs",
"path": "/src/main.rs",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> let input = stdin.next();
if let Some(Ok(key)) = input {
match key {
termion::event::Key::Char('q') => break,
termion::event::Key::Char('p') => {
if percent < 100 {
percent+=1;
}
... | code_fim | hard | {
"lang": "rust",
"repo": "drozdowsky/sample-rs",
"path": "/src/main.rs",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|>/// Creates a Stream that yields an item after every period has elapsed.
#[inline(always)]
pub fn interval(period: Duration) -> impl Stream<Item = ()> {
imp::interval(period)
}<|fim_prefix|>// repo: kulicuu/yew path: /packages/yew/src/platform/time.rs
//! Utilities for bridging time and tasks.
use s... | code_fim | medium | {
"lang": "rust",
"repo": "kulicuu/yew",
"path": "/packages/yew/src/platform/time.rs",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: kulicuu/yew path: /packages/yew/src/platform/time.rs
//! Utilities for bridging time and tasks.
use std::future::Future;
use std::time::Duration;
use futures::stream::Stream;
<|fim_suffix|>/// Creates a Stream that yields an item after every period has elapsed.
#[inline(always)]
pub fn interv... | code_fim | medium | {
"lang": "rust",
"repo": "kulicuu/yew",
"path": "/packages/yew/src/platform/time.rs",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>/// Take a pre-state + instruction and mutate it to produce a post-state。
pub trait TransferFunctions {
type State: AbstractDomain + Clone;
type AnalysisError: Clone;
fn execute_block(
&mut self,
block_id: BlockId,
pre_state: Self::State,
instrs: &[Bytecode],
... | code_fim | hard | {
"lang": "rust",
"repo": "jolestar/libra",
"path": "/language/move-prover/stackless-bytecode-generator/src/dataflow_analysis.rs",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: jolestar/libra path: /language/move-prover/stackless-bytecode-generator/src/dataflow_analysis.rs
// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! Adapted from AbstractInterpreter for Bytecode, this module defines the data-flow analysis
//! framework for st... | code_fim | hard | {
"lang": "rust",
"repo": "jolestar/libra",
"path": "/language/move-prover/stackless-bytecode-generator/src/dataflow_analysis.rs",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: cmhteixeira/advent-of-code-2020 path: /day-1/src/part1.rs
use std::iter::Iterator;
fn find_values(input: &[i32]) -> Option<(i32, i32)> {
let mut res: Option<(i32, i32)> = None;
for (pos, i) in input.iter().enumerate() {
for j in input.split_at(pos).1 {
if i + j == 2... | code_fim | medium | {
"lang": "rust",
"repo": "cmhteixeira/advent-of-code-2020",
"path": "/day-1/src/part1.rs",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> let input = vec![3, 4, 5, 7, 3, 90, 1021, 999, 34, 234, 909, 341];
assert_eq!(part1(input.as_slice()), 1019979)
}
#[test]
fn entries_not_in_sequence(){
let input = vec![1721, 979, 366, 299, 675, 1456];
assert_eq!(part1(input.as_slice()), 514579)
}
}<|fim_pr... | code_fim | hard | {
"lang": "rust",
"repo": "cmhteixeira/advent-of-code-2020",
"path": "/day-1/src/part1.rs",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: agrif/sprunk path: /src/server.rs
use crate::Sink;
use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex, RwLock, Weak};
use std::time::{Duration, Instant};
use hyper::body::Bytes;
use tokio_stream::StreamExt;
const RADIO_TIMEOUT: Duration = Duration::from_secs(60 * 5);
const ... | code_fim | hard | {
"lang": "rust",
"repo": "agrif/sprunk",
"path": "/src/server.rs",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
pub async fn server_run<P>(
addr: &std::net::SocketAddr,
index: crate::RadioIndex,
staticfiles: P,
) -> anyhow::Result<()>
where
P: AsRef<std::path::Path>,
{
let state = Arc::new(Serve... | code_fim | hard | {
"lang": "rust",
"repo": "agrif/sprunk",
"path": "/src/server.rs",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> rpc get_user(payload: Token) -> (UserId, Role) | AuthError;
rpc set_user_role(payload: SetUserRolePayload) -> () | AuthError;
}<|fim_prefix|>// repo: Bitspleaseee/security-gate path: /src/comms/auth.rs
use datatypes::auth::requests::*;
use datatypes::auth::responses::*;
use datatypes::content::reque... | code_fim | medium | {
"lang": "rust",
"repo": "Bitspleaseee/security-gate",
"path": "/src/comms/auth.rs",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: Bitspleaseee/security-gate path: /src/comms/auth.rs
use datatypes::auth::requests::*;
use datatypes::auth::responses::*;
use datatypes::content::requests::*;
use datatypes::valid::ids::UserId;
use datatypes::valid::token::Token;
service! {
rpc authenticate(payload: AuthPayload) -> Token | A... | code_fim | medium | {
"lang": "rust",
"repo": "Bitspleaseee/security-gate",
"path": "/src/comms/auth.rs",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|>e))
// });
// }
// Regardless for the sake of showing off what I know, lets use a more tide idiomatic approach:
#[async_std::test]
async fn test_health_check_works() -> tide::Result<()> {
Ok(assert_eq!(
build_app(ApplicationState::default())
.get("/health_check")
.... | code_fim | hard | {
"lang": "rust",
"repo": "zexa/technical-exercise",
"path": "/tests/health_check.rs",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: zexa/technical-exercise path: /tests/health_check.rs
use technical_exercise::{build_app, ApplicationState};
use tide::StatusCode;
use tide_testing::TideTestingExt;
// I suppose you could do something like in the zero2prod example such as bellow and then use sync
// tests everywhere. You could d... | code_fim | hard | {
"lang": "rust",
"repo": "zexa/technical-exercise",
"path": "/tests/health_check.rs",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: ktp-forked-repos/iban_validate path: /src/lib.rs
//! This crate provides an easy way to validate an IBAN (International Bank Account Number). To do
//! so, you can use the function [`parse()`]. If you want to check whether the address has a valid
//! BBAN (Basic Bank Account Number), you can use... | code_fim | hard | {
"lang": "rust",
"repo": "ktp-forked-repos/iban_validate",
"path": "/src/lib.rs",
"mode": "psm",
"license": "LicenseRef-scancode-unknown-license-reference",
"source": "the-stack-v2"
} |
<|fim_suffix|> /// This function computes the checksum of an address. The function assumes the string only
/// contains 0-9 and A-Z.
///
/// # Panics
/// If the address contains any characters other than 0-9 or A-Z, this function will panic.
fn compute_checksum(address: &str) -> u8 {
addr... | code_fim | hard | {
"lang": "rust",
"repo": "ktp-forked-repos/iban_validate",
"path": "/src/lib.rs",
"mode": "spm",
"license": "LicenseRef-scancode-unknown-license-reference",
"source": "the-stack-v2"
} |
<|fim_suffix|> if address_match.is_some() {
BbanResult::Valid
} else {
BbanResult::Invalid
}
} else {
BbanResult::CountryUnknown
}
}
/// Returns the electronic format of an IBAN. This a simple string representation w... | code_fim | hard | {
"lang": "rust",
"repo": "ktp-forked-repos/iban_validate",
"path": "/src/lib.rs",
"mode": "spm",
"license": "LicenseRef-scancode-unknown-license-reference",
"source": "the-stack-v2"
} |
<|fim_suffix|>impl UnboundScript {
/// Binds the script to the currently entered context.
pub fn bind_to_current_context<'s>(
&self,
scope: &mut HandleScope<'s>,
) -> Local<'s, Script> {
unsafe {
scope.cast_local(|_| v8__UnboundScript__BindToCurrentContext(self))
}
.unwrap()
}
}<|fim_p... | code_fim | medium | {
"lang": "rust",
"repo": "LukeChannings/rusty_v8",
"path": "/src/unbound_script.rs",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: LukeChannings/rusty_v8 path: /src/unbound_script.rs
use crate::HandleScope;
use crate::Local;
use crate::Script;
use crate::UnboundScript;
<|fim_suffix|>impl UnboundScript {
/// Binds the script to the currently entered context.
pub fn bind_to_current_context<'s>(
&self,
scope: &mut... | code_fim | medium | {
"lang": "rust",
"repo": "LukeChannings/rusty_v8",
"path": "/src/unbound_script.rs",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: YoloDev/yolodev-jsonnet path: /crates/lex/src/str_block.rs
use super::*;
use core::ops::Range;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum StringBlockToken {
Valid,
UnexpectedEndOfString,
MissingTextBlockNewLine,
MissingTextBlockTermination,
MissingTextBlockIndent,
}
... | code_fim | hard | {
"lang": "rust",
"repo": "YoloDev/yolodev-jsonnet",
"path": "/crates/lex/src/str_block.rs",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> loop {
debug_assert_ne!(num_whitespace, 0, "Unexpected value for num_whitespace");
ctx.skip(num_whitespace);
loop {
match ctx.next() {
None => {
guess_token_end_and_bump(lex, &ctx);
return UnexpectedEndOfString;
}
Some('\n') => break,
... | code_fim | hard | {
"lang": "rust",
"repo": "YoloDev/yolodev-jsonnet",
"path": "/crates/lex/src/str_block.rs",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: oknozor/musicbrainz_rs path: /src/deserialization/date_format.rs
use chrono::NaiveDate;
use serde::{self, Deserialize, Deserializer};
const FORMAT: &str = "%Y-%m-%d";
/// Some times, music brainz dates doesn't have a month or day
/// This artificially add january 1st before deserializing the A... | code_fim | hard | {
"lang": "rust",
"repo": "oknozor/musicbrainz_rs",
"path": "/src/deserialization/date_format.rs",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> let life_span: LifeSpan = serde_json::from_str(input).unwrap();
assert_eq!(
life_span,
LifeSpan {
ended: Some(true),
begin: Some(NaiveDate::from_ymd_opt(1988, 1, 1).unwrap()),
end: None,
}
)
}
... | code_fim | hard | {
"lang": "rust",
"repo": "oknozor/musicbrainz_rs",
"path": "/src/deserialization/date_format.rs",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: Justin-Schmitz/git-mit path: /git-mit-config/src/cmd/lint_enable.rs
use std::convert::TryInto;
use std::env::current_dir;
use clap::ArgMatches;
use mit_commit_message_lints::external;
use mit_commit_message_lints::lints::Lints;
<|fim_suffix|> let lints: Lints = subcommand
.values_o... | code_fim | hard | {
"lang": "rust",
"repo": "Justin-Schmitz/git-mit",
"path": "/git-mit-config/src/cmd/lint_enable.rs",
"mode": "psm",
"license": "LicenseRef-scancode-unknown-license-reference",
"source": "the-stack-v2"
} |
<|fim_suffix|> let lints: Lints = subcommand
.values_of("lint")
.ok_or(LintNameNotGiven)?
.collect::<Vec<_>>()
.try_into()?;
mit_commit_message_lints::lints::set_status(lints, &mut vcs, true)?;
Ok(())
}<|fim_prefix|>// repo: Justin-Schmitz/git-mit path: /git-mit-config/src/... | code_fim | hard | {
"lang": "rust",
"repo": "Justin-Schmitz/git-mit",
"path": "/git-mit-config/src/cmd/lint_enable.rs",
"mode": "spm",
"license": "LicenseRef-scancode-unknown-license-reference",
"source": "the-stack-v2"
} |
<|fim_suffix|>wait;
},
Some(Err(e)) => {
log::warn!("Timer misfired: {}", e);
continue;
}
}
}
}
// Do we have sufficient commands, and are we the next leader?
/... | code_fim | hard | {
"lang": "rust",
"repo": "libdist-rs/libchatter-rs",
"path": "/consensus/optsync/src/node/reactor.rs",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: libdist-rs/libchatter-rs path: /consensus/optsync/src/node/reactor.rs
/// The core consensus module used for Opt Sync
///
/// The reactor reacts to all the messages from the network, and talks to the
/// clients accordingly.
use tokio::sync::mpsc::{
UnboundedSender,
UnboundedReceiver
... | code_fim | hard | {
"lang": "rust",
"repo": "libdist-rs/libchatter-rs",
"path": "/consensus/optsync/src/node/reactor.rs",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|>pub fn verse(n: u32) -> String {
format!("{}\n{}\n", first_line(n), second_line(n))
}
pub fn sing(start: u32, end: u32) -> String {
(end..=start)
.rev()
.map(verse)
.collect::<Vec<_>>()
.join("\n")
}<|fim_prefix|>// repo: attilahorvath/exercism-rust path: /beer-so... | code_fim | hard | {
"lang": "rust",
"repo": "attilahorvath/exercism-rust",
"path": "/beer-song/src/lib.rs",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: attilahorvath/exercism-rust path: /beer-song/src/lib.rs
use std::fmt::Display;
trait StringExtensions
where
Self: Display,
{
fn capitalize(&self) -> String {
let string = self.to_string();
let mut chars = string.chars();
if let Some(first) = chars.next() {
... | code_fim | hard | {
"lang": "rust",
"repo": "attilahorvath/exercism-rust",
"path": "/beer-song/src/lib.rs",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: ellipticoin/moonshined path: /ellipticoind/src/api/types.rs
use juniper::{ParseScalarResult, ParseScalarValue, Value};
use std::convert::TryInto;
#[derive(Clone, Debug)]
pub struct BlockchainState {
pub usd_exchange_rate: BigUint,
pub bridge_address: Address,
pub signers: Vec<Bytes>... | code_fim | hard | {
"lang": "rust",
"repo": "ellipticoin/moonshined",
"path": "/ellipticoind/src/api/types.rs",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> self.id.clone()
}
fn network_id(&self) -> U64 {
self.network_id.clone()
}
fn block_number(&self) -> U32 {
self.block_number.clone()
}
fn position(&self) -> U32 {
self.position.clone()
}
fn contract(&self) -> String {
self.contract... | code_fim | hard | {
"lang": "rust",
"repo": "ellipticoin/moonshined",
"path": "/ellipticoind/src/api/types.rs",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: streichgeorg/suffix_tree path: /benches/lcs_codon_sequences.rs
#[macro_use] extern crate criterion;
extern crate suffix_tree;
use criterion::Criterion;
use std::fs::File;
use std::io::{BufRead, BufReader};
use suffix_tree::longest_common_subsequence;
use suffix_tree::alphabet::Alphabet;
fn se... | code_fim | hard | {
"lang": "rust",
"repo": "streichgeorg/suffix_tree",
"path": "/benches/lcs_codon_sequences.rs",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> c.bench_function("lcs codon sequence", move |b| {
b.iter_with_large_setup(|| setup(), |strings| compute(strings));
});
}
criterion_group!{
name = benches;
config = Criterion::default().sample_size(20);
targets = benchmark
}
criterion_main!(benches);<|fim_prefix|>// repo: stre... | code_fim | hard | {
"lang": "rust",
"repo": "streichgeorg/suffix_tree",
"path": "/benches/lcs_codon_sequences.rs",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: Arnaz87/arna-organ path: /src/effects/room.rs
use sample::*;
use effects::buffer::*;
use helpers::*;
// Pulse Stuff
#[derive(Clone, Copy)]
enum Side {L, R, NL, NR}
#[derive(Clone, Copy)]
struct Pulse {
side: Side,
gain: f32,
delay: f32,
}
macro_rules! pulse {
($sid... | code_fim | hard | {
"lang": "rust",
"repo": "Arnaz87/arna-organ",
"path": "/src/effects/room.rs",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> fn pulse (&self, pulse: Pulse) -> Sample {
//let pulse_gain = 1.0-( pulse.delay / (self.size*23798.0/44100.0) );
//let vol = self.delay + pulse_gain*(1.0-self.delay);
let s = self.pulse_buf.get(pulse.delay * self.size);
match pulse.side {
Side::L => Sample::new(s, 0.0),
Si... | code_fim | hard | {
"lang": "rust",
"repo": "Arnaz87/arna-organ",
"path": "/src/effects/room.rs",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: ChunMinChang/https-server-tokio-rustls path: /src/main.rs
use argh::FromArgs;
use std::fs::File;
use std::io::{self, BufReader};
use std::net::ToSocketAddrs;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio::io::AsyncWriteExt;
use tokio::net::{TcpListener, TcpStream};
use tokio_rust... | code_fim | hard | {
"lang": "rust",
"repo": "ChunMinChang/https-server-tokio-rustls",
"path": "/src/main.rs",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> tls_stream
.write_all(
&b"HTTP/1.0 200 ok\r\n\
Connection: close\r\n\
Content-length: 12\r\n\
\r\n\
Hello world!"[..],
)
.await?;
tls_stream.shutdown().await?;
Ok(())
}
fn load_config(options: &Options) -> io::Result<Server... | code_fim | hard | {
"lang": "rust",
"repo": "ChunMinChang/https-server-tokio-rustls",
"path": "/src/main.rs",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> loop {
let (stream, peer_addr) = tcp_listener.accept().await?;
println!("Connection from: {}", peer_addr);
let acceptor = tls_acceptor.clone();
tokio::spawn(async move {
if let Err(err) = handle_connection(acceptor, stream).await {
eprintln!(... | code_fim | hard | {
"lang": "rust",
"repo": "ChunMinChang/https-server-tokio-rustls",
"path": "/src/main.rs",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: EliaGeretto/fork_bench path: /src/main.rs
use core::slice;
use std::{
ffi::c_void,
io::Cursor,
mem::size_of,
path::PathBuf,
process, ptr,
str::FromStr,
time::{Duration, Instant},
};
use anyhow::{anyhow, bail, Context};
use byteorder::{LittleEndian, ReadBytesExt, Writ... | code_fim | hard | {
"lang": "rust",
"repo": "EliaGeretto/fork_bench",
"path": "/src/main.rs",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> Ok(wait_time)
}
ForkResult::Child => {
// Touching the maps would mean corrupting the measurement
process::exit(0);
}
}
}
fn benchmark_func<F>(mut measure_func: F) -> anyhow::Result<Stats>
where
F: FnMut() -> anyhow::Result<Duration>,
{
... | code_fim | hard | {
"lang": "rust",
"repo": "EliaGeretto/fork_bench",
"path": "/src/main.rs",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> print!("Enter Number of Tiles: ");
io::stdout().flush().ok().expect("Could not flush stdout");
match io::stdin().read_line(&mut input) {
Ok(_) => {
match input.trim().parse::<usize>() {
Ok(num_tiles) => Board::new(num_tiles, num_tiles / 2, num_tiles / 2).dis... | code_fim | medium | {
"lang": "rust",
"repo": "hone/maximum_apocalypse_map_generator",
"path": "/src/bin.rs",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: hone/maximum_apocalypse_map_generator path: /src/bin.rs
extern crate ma_mapper;
use std::io;
use std::io::prelude::*;
use ma_mapper::board::Board;
<|fim_suffix|> let mut input = String::new();
print!("Enter Number of Tiles: ");... | code_fim | medium | {
"lang": "rust",
"repo": "hone/maximum_apocalypse_map_generator",
"path": "/src/bin.rs",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: spcan/micro path: /src/peripherals/core/guard.rs
//! Guarding struct
//! Guards the core peripherals so no two instances of a peripheral
//! can live at the same time. This excludes system calls, which
//! have a higher priority level and can force create an instance.
#[derive(Debug)]
pub struc... | code_fim | hard | {
"lang": "rust",
"repo": "spcan/micro",
"path": "/src/peripherals/core/guard.rs",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> /// Force access to the SCB
///
/// Remember that this instance must be manually killed with `kill` method
pub fn force_scb(&mut self) -> &mut Scb {
self.forced[SCB_POS] += 1;
scb::Scb::from_addr( scb::ADDRESS )
}
}<|fim_prefix|>// repo: spcan/micro path: /src/peripherals/core/guard.rs
//! Guar... | code_fim | hard | {
"lang": "rust",
"repo": "spcan/micro",
"path": "/src/peripherals/core/guard.rs",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: hobofan/margo path: /margo-fetch/src/source_resolver.rs
#[cfg(feature = "source_resolver_remote_registry")]
mod remote_registry;
#[cfg(feature = "source_resolver_remote_registry")]
pub use self::remote_registry::RemoteRegistrySourceResolver;
<|fim_suffix|>pub trait SourceResolver<T> {
type ... | code_fim | medium | {
"lang": "rust",
"repo": "hobofan/margo",
"path": "/margo-fetch/src/source_resolver.rs",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>pub trait SourceResolver<T> {
type F: StdFuture<Item = T, Error = ()> + Send;
fn resolve_crate(&self, _crate: &Crate) -> Self::F;
}<|fim_prefix|>// repo: hobofan/margo path: /margo-fetch/src/source_resolver.rs
#[cfg(feature = "source_resolver_remote_registry")]
mod remote_registry;
#[cfg(feature... | code_fim | medium | {
"lang": "rust",
"repo": "hobofan/margo",
"path": "/margo-fetch/src/source_resolver.rs",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: gnoliyil/fuchsia path: /src/devices/ctap/src/ctap_hid/message.rs
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
anyhow::{format_err, Error},
bytes::Bytes,
fidl_... | code_fim | hard | {
"lang": "rust",
"repo": "gnoliyil/fuchsia",
"path": "/src/devices/ctap/src/ctap_hid/message.rs",
"mode": "psm",
"license": "BSD-2-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> const TEST_CHANNEL: u32 = 0x89abcdef;
const TEST_COMMAND: CtapHidCommand = CtapHidCommand::Wink;
#[test]
fn message_getters() -> Result<(), Error> {
let message = Message::new(TEST_CHANNEL, TEST_COMMAND, &vec![0xff, 0xee])?;
assert_eq!(message.channel(), TEST_CHANNEL);
... | code_fim | hard | {
"lang": "rust",
"repo": "gnoliyil/fuchsia",
"path": "/src/devices/ctap/src/ctap_hid/message.rs",
"mode": "spm",
"license": "BSD-2-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> let mut required_motion = MotionParameters::new(0.0, 0.0);
let calibration_rot_speed = 0.2;
let calibration_rot_range = 3.14 / 8.0;
match self.robot_stats.state() {
RobotStateMachine::Initialization => {
self.robot_stats.s... | code_fim | hard | {
"lang": "rust",
"repo": "adamek727/rust_bpc_prp",
"path": "/src/controller.rs",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|>
let wheel_speeds = motion_model.get_wheel_speeds( required_motion );
let wheel_speeds_in_microsteps = motion_model.wheel_speed_to_microsteps_with_saturation(wheel_speeds);
left_wheel_ramp_gen.set_required_microsteps_per_sec(&wheel_speeds_in_microsteps);
ri... | code_fim | hard | {
"lang": "rust",
"repo": "adamek727/rust_bpc_prp",
"path": "/src/controller.rs",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: adamek727/rust_bpc_prp path: /src/controller.rs
use std::time::{Duration, SystemTime};
use std::net::UdpSocket;
use std::thread;
use std::thread::sleep;
use std::sync::mpsc::{channel, Sender, Receiver};
use timer;
use chrono;
use crate::nmea;
use crate::message_factory;
use crate::robot;
use cr... | code_fim | hard | {
"lang": "rust",
"repo": "adamek727/rust_bpc_prp",
"path": "/src/controller.rs",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> pub fn raster_line(&self, y: i32) -> &[u8] {
assert!(y >= 0);
assert!(y < self.height());
assert!(self.line_size_bytes() >= self.pixel_size_bytes() * self.width());
unsafe { from_raw_parts(*((&*self.ptr).image).offset(y as _) as *mut u8, self.line_size_bytes() as usize) }
}
pub fn r... | code_fim | hard | {
"lang": "rust",
"repo": "peterhj/pillowimage",
"path": "/src/lib.rs",
"mode": "spm",
"license": "LicenseRef-scancode-secret-labs-2011",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: peterhj/pillowimage path: /src/lib.rs
#[macro_use]
extern crate lazy_static;
use ffi::*;
use std::ffi::{CString};
use std::os::raw::{c_char};
use std::slice::{from_raw_parts, from_raw_parts_mut};
pub mod ffi;
lazy_static! {
static ref MODE_1: CString = CString::new("1").unwrap();
... | code_fim | hard | {
"lang": "rust",
"repo": "peterhj/pillowimage",
"path": "/src/lib.rs",
"mode": "psm",
"license": "LicenseRef-scancode-secret-labs-2011",
"source": "the-stack-v2"
} |
<|fim_suffix|>pub fn one_of<I: Stream<Item=char>>(chars: &str) -> impl Parser<Input=I, Output=char> {
let choices: Vec<_> = chars.chars().map(char).collect();
choice(choices)
}
pub fn identifier<I: Stream<Item=char>>() -> impl Parser<Input=I, Output=String> {
let first = letter().or(one_of("_-"));
let ... | code_fim | medium | {
"lang": "rust",
"repo": "jonathanmcelroy/rust_progress_server",
"path": "/src/parser/util.rs",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: jonathanmcelroy/rust_progress_server path: /src/parser/util.rs
use std::ascii::AsciiExt;
use combine::{many, many1, satisfy, choice};
use combine::char::{char, letter, alpha_num, crlf, newline, string, string_cmp};
use combine::primitives::{Parser, Stream};
// type Parser<O> = combine::Parser<... | code_fim | hard | {
"lang": "rust",
"repo": "jonathanmcelroy/rust_progress_server",
"path": "/src/parser/util.rs",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> #[test]
fn failure_attribute_without_open_quote() {
use super::Error::*;
let r = full_parse("<hi oops=value' />");
assert_eq!(r, Err((9, vec![ExpectedOpeningQuote("\'"), ExpectedOpeningQuote("\"")])));
}
#[test]
fn failure_attribute_without_close_quote() {
... | code_fim | hard | {
"lang": "rust",
"repo": "flying-sheep/sxd-document",
"path": "/src/parser.rs",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> fn consume_comment(&self) -> XmlProgress<'a, &'a str> {
self.consume_to(self.s.end_of_comment()).map_err(|_| Error::ExpectedCommentBody)
}
fn consume_pi_value(&self) -> XmlProgress<'a, &'a str> {
self.consume_to(self.s.end_of_pi_value()).map_err(|_| Error::ExpectedProcessingIn... | code_fim | hard | {
"lang": "rust",
"repo": "flying-sheep/sxd-document",
"path": "/src/parser.rs",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: flying-sheep/sxd-document path: /src/parser.rs
success(DecimalCharReference(dec), xml)
}
fn parse_hex_char_ref<'a>(&self, xml: StringPoint<'a>) -> XmlProgress<'a, Reference<'a>> {
let (xml, _) = try_parse!(xml.consume_literal("&#x").map_err(|_| Error::ExpectedHexRefere... | code_fim | hard | {
"lang": "rust",
"repo": "flying-sheep/sxd-document",
"path": "/src/parser.rs",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: mozilla/source-map path: /wasm-mappings/tests/tests.rs
extern crate source_map_mappings;
use source_map_mappings::{parse_mappings, Bias, Mapping, Mappings, OriginalLocation};
#[test]
fn parse_empty_mappings() {
let mut mappings = parse_mappings::<()>(&[]).expect("should parse OK");
ass... | code_fim | hard | {
"lang": "rust",
"repo": "mozilla/source-map",
"path": "/wasm-mappings/tests/tests.rs",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> let mut mappings = parse_mappings::<()>(TEST_MAPPINGS_4).unwrap();
let mappings_on_source_0_line_0_column_1: Vec<_> = mappings
.all_generated_locations_for(0, 0, Some(1))
.cloned()
.collect();
assert_eq!(
mappings_on_source_0_line_0_column_1,
vec![
... | code_fim | hard | {
"lang": "rust",
"repo": "mozilla/source-map",
"path": "/wasm-mappings/tests/tests.rs",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: Swoorup/mysh-rs path: /src/main.rs
#![feature(nll)]
#![feature(box_syntax, box_patterns)]
#![feature(associated_type_defaults)]
#![feature(iter_advance_by)]
#![warn(rust_2018_idioms)]
use std::env;
use std::io;
use std::io::Write;
mod builtin;
mod interpret;
mod lexer;
mod parser;
use crate::... | code_fim | hard | {
"lang": "rust",
"repo": "Swoorup/mysh-rs",
"path": "/src/main.rs",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
// end of stream
if input.is_empty() {
return;
}
let debug_print = env::var("DEBUG_PRINT").is_ok();
// put it to lexer
match input.as_str().tokenize() {... | code_fim | hard | {
"lang": "rust",
"repo": "Swoorup/mysh-rs",
"path": "/src/main.rs",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: d8aninja/persCode path: /rust/efficient_iters/src/main.rs
// main idea here is to learn the difference and when to use .iter(), iter_mut(), and into_iter()
fn main() {
increment_str_bytes("Howdy!");
increment_str_bytes("Every day I'm iteratin'");
let scores = vec!( ("Jeff".to_strin... | code_fim | medium | {
"lang": "rust",
"repo": "d8aninja/persCode",
"path": "/rust/efficient_iters/src/main.rs",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> let bytes_into = bytes
.into_iter()
.map(| a | a + 1);
for i in bytes_into { print!("\nNew: {}", i) }
}
fn pluck_first_name(v: Vec<(String, usize)>) -> Vec<String> {
v.into_iter()
.map(|(name, _score)| name)
.collect()
}<|fim_prefix|>// repo: d8aninja/persCode... | code_fim | hard | {
"lang": "rust",
"repo": "d8aninja/persCode",
"path": "/rust/efficient_iters/src/main.rs",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> let result = split_vec_equal(&orig_vec, 2);
let expected = vec![vec!["a", "b"], vec!["c", "d"]];
assert_eq!(expected, result);
}
#[test]
fn split_vec_equal_count_not_matching() {
let orig_vec = vec!["a", "b", "c"];
let result = split_vec_equal(&orig_ve... | code_fim | hard | {
"lang": "rust",
"repo": "Julian-Alberts/csv-types",
"path": "/csv_types_sys/src/vec.rs",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: Julian-Alberts/csv-types path: /csv_types_sys/src/vec.rs
use super::CsvInput;
pub fn csv_to_vec(csv_input: CsvInput) -> Vec<Vec<String>> {
let mut csv_reader = match csv_input {
CsvInput::Csv(csv) => csv::ReaderBuilder::new()
.has_headers(false)
.from_reader(c... | code_fim | hard | {
"lang": "rust",
"repo": "Julian-Alberts/csv-types",
"path": "/csv_types_sys/src/vec.rs",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: dainslef/RustPractice path: /src/leetcode/q50_pow_x_n.rs
/**
* Implement pow(x, n), which calculates x raised to the power n (xn).
*
* Example 1:
*
* Input: 2.00000, 10
* Output: 1024.00000
* Example 2:
*
* Input: 2.10000, 3
* Output: 9.26100
* Example 3:
*
* Input: 2.00000, -2
* O... | code_fim | hard | {
"lang": "rust",
"repo": "dainslef/RustPractice",
"path": "/src/leetcode/q50_pow_x_n.rs",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>#[test]
fn q50_test() {
assert_eq!(my_pow(0.0, 0), 1.0);
assert_eq!(my_pow(0.0, 2147483647), 0.0);
assert_eq!(my_pow(0.00001, 2147483647), 0.0);
assert_eq!(my_pow(1111.0, 0), 1.0);
assert_eq!(my_pow(2.0, 10), 1024.0);
assert_eq!(my_pow(2.0, -2), 0.25);
}<|fim_prefix|>// repo: dainslef/RustPrac... | code_fim | hard | {
"lang": "rust",
"repo": "dainslef/RustPractice",
"path": "/src/leetcode/q50_pow_x_n.rs",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>pub fn reader(dataset: &str) -> Vec<Vec<(String, Value)>> {
let mut articles: Vec<Vec<(String, Value)>> = Vec::new();
let f = File::open(dataset).unwrap();
let file = BufReader::new(&f);
let re = Regex::new(r"[\t]+").unwrap();
let mut count = 1;
for line in file.lines() {
l... | code_fim | medium | {
"lang": "rust",
"repo": "arso-project/tantivy-ir-evaluation",
"path": "/src/moviedb_importer.rs",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: arso-project/tantivy-ir-evaluation path: /src/moviedb_importer.rs
use tantivy::schema::*;
use tantivy::Result;
use regex::Regex;
use std::collections::HashMap;
use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
pub fn benchmarkreader(dataset: &str) -> Result<HashMap<String, Vec<i... | code_fim | medium | {
"lang": "rust",
"repo": "arso-project/tantivy-ir-evaluation",
"path": "/src/moviedb_importer.rs",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: ashishtyagi10/rust path: /mongo/src/main.rs
use chrono::TimeZone;
use chrono::Utc;
use mongodb::bson::{self, doc, Bson};
use std::env;
use std::error::Error;
use tokio;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
// Load the MongoDB connection string from an environment va... | code_fim | medium | {
"lang": "rust",
"repo": "ashishtyagi10/rust",
"path": "/mongo/src/main.rs",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_suffix|> println!("{}",new_doc);
let movies = client.database("address_book").collection("movies");
let insert_result = movies.insert_one(new_doc.clone(), None).await?;
println!("New document ID: {}", insert_result.inserted_id);
Ok(())
}<|fim_prefix|>// repo: ashishtyagi10/rust path: /mongo/sr... | code_fim | hard | {
"lang": "rust",
"repo": "ashishtyagi10/rust",
"path": "/mongo/src/main.rs",
"mode": "spm",
"license": "unknown",
"source": "the-stack-v2"
} |
<|fim_prefix|>// repo: tychedelia/franz path: /src/bin/test.rs
use franz::client::connect;
<|fim_suffix|> let _client = connect("127.0.0.1:9092".parse().unwrap()).await.unwrap();
println!("Stopping.");
}<|fim_middle|>#[tokio::main]
async fn main() {
env_logger::init();
| code_fim | easy | {
"lang": "rust",
"repo": "tychedelia/franz",
"path": "/src/bin/test.rs",
"mode": "psm",
"license": "unknown",
"source": "the-stack-v2"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.