file_name large_stringlengths 4 69 | prefix large_stringlengths 0 26.7k | suffix large_stringlengths 0 24.8k | middle large_stringlengths 0 2.12k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
mod.rs | use std::env;
use std::fs::{self, File};
use std::io::Read;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use super::actor::Actor;
use super::{Result, expand, collapse};
lazy_static! {
static ref CURRENT_DIR: PathBuf = {
let path = fs::canonicalize(Path::new(file!()).parent().unwrap()).unwrap();
... | compare(format!("script_{}.m", part),
format!("script{}.m", part.replace('_', "")),
true);
}
});
test!(collapsing {
with_backup("script.m", "script_backup.m", || {
try(expand(Actor::new(), "script.m", false));
try(collapse(Actor::new(), "script.m"));
... | for part in &["_0", "a_1", "b_2", "if_true_3", "gen"] { | random_line_split |
build.rs | // Copyright (c) 2016 Adam Perry <adam.n.perry@gmail.com>
//
// This software may be modified and distributed under the terms of the MIT license. See the
// LICENSE file for details.
use std::env;
use std::fs::copy;
use std::path::Path;
use std::process::Command;
fn main() {
let out_dir = env::var("OUT_DIR").unw... | // clean up the temporary build files
Command::new("make")
.current_dir(&c_src_path)
.arg("clean")
.output()
.expect("Failed to clean up build files.");
// clean up the configuration files
Command::new("make")
.arg("distclean")
.current_dir(&c_src_path)
... | copy("parasail_c/.libs/libparasail.a", target_file)
.expect("Problem copying library to target directoy.");
| random_line_split |
build.rs | // Copyright (c) 2016 Adam Perry <adam.n.perry@gmail.com>
//
// This software may be modified and distributed under the terms of the MIT license. See the
// LICENSE file for details.
use std::env;
use std::fs::copy;
use std::path::Path;
use std::process::Command;
fn | () {
let out_dir = env::var("OUT_DIR").unwrap();
let num_jobs = env::var("NUM_JOBS").unwrap();
let c_src_path = Path::new("parasail_c");
// configure the build
Command::new("./configure")
.arg("--enable-shared")
.arg("--with-pic")
.current_dir(&c_src_path)
.output()
... | main | identifier_name |
build.rs | // Copyright (c) 2016 Adam Perry <adam.n.perry@gmail.com>
//
// This software may be modified and distributed under the terms of the MIT license. See the
// LICENSE file for details.
use std::env;
use std::fs::copy;
use std::path::Path;
use std::process::Command;
fn main() | // put the static library in the right directory so we can clean up
let target_file = format!("{}/libparasail.a", out_dir);
copy("parasail_c/.libs/libparasail.a", target_file)
.expect("Problem copying library to target directoy.");
// clean up the temporary build files
Command::new("make")
... | {
let out_dir = env::var("OUT_DIR").unwrap();
let num_jobs = env::var("NUM_JOBS").unwrap();
let c_src_path = Path::new("parasail_c");
// configure the build
Command::new("./configure")
.arg("--enable-shared")
.arg("--with-pic")
.current_dir(&c_src_path)
.output()
... | identifier_body |
source.rs | // Copyright 2013-2015, The Rust-GNOME Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! Manages available sources of events for the main loop
use std::cell::RefCell;
use st... | pub fn timeout_add_seconds<F>(interval: u32, func: F) -> u32
where F: FnMut() -> Continue +'static {
let f: Box<RefCell<Box<FnMut() -> Continue +'static>>> = Box::new(RefCell::new(Box::new(func)));
unsafe {
g_timeout_add_seconds_full(PRIORITY_DEFAULT, interval, transmute(trampoline),
int... | /// timeout_add_seconds(10, || {
/// println!("This prints once every 10 seconds");
/// Continue(true)
/// });
/// ``` | random_line_split |
source.rs | // Copyright 2013-2015, The Rust-GNOME Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! Manages available sources of events for the main loop
use std::cell::RefCell;
use st... | (ptr: gpointer) {
unsafe {
// Box::from_raw API stability workaround
let ptr = ptr as *mut RefCell<Box<FnMut() -> Continue +'static>>;
let _: Box<RefCell<Box<FnMut() -> Continue +'static>>> = transmute(ptr);
}
}
const PRIORITY_DEFAULT: i32 = 0;
const PRIORITY_DEFAULT_IDLE: i32 = 200;
... | destroy_closure | identifier_name |
source.rs | // Copyright 2013-2015, The Rust-GNOME Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! Manages available sources of events for the main loop
use std::cell::RefCell;
use st... |
/// Sets a function to be called at regular intervals with the default priority, `PRIORITY_DEFAULT`.
///
/// The function is called repeatedly until it returns `Continue(false)`, at which point the timeout
/// is automatically destroyed and the function will not be called again.
///
/// Note that the first call of th... | {
let f: Box<RefCell<Box<FnMut() -> Continue + 'static>>> = Box::new(RefCell::new(Box::new(func)));
unsafe {
g_timeout_add_full(PRIORITY_DEFAULT, interval, transmute(trampoline),
into_raw(f) as gpointer, destroy_closure)
}
} | identifier_body |
access.rs | use std::io;
use std::net::{IpAddr, SocketAddr, ToSocketAddrs};
use std::str::FromStr;
use std::time::Duration;
use access::err::AccessError;
use access::keys::{ClientKeyData, KeyDataReader};
use access::packet;
use access::req::{ReqData, SessReq, REQ_PORT};
use access::resp::SessResp;
use access::state::{ClientState,... | (remote_addr: &SocketAddr) -> Result<SocketAddr, AccessError> {
let bind_addr_str = if remote_addr.is_ipv4() {
"0.0.0.0:0"
} else if remote_addr.is_ipv6() {
"[::]:0"
} else {
return Err(AccessError::NoIpv4Addr);
};
Ok(bind_addr_str.to_socket_addrs().unwrap().nth(0).unwrap())... | get_bind_addr_for_remote | identifier_name |
access.rs | use std::io;
use std::net::{IpAddr, SocketAddr, ToSocketAddrs};
use std::str::FromStr;
use std::time::Duration;
use access::err::AccessError;
use access::keys::{ClientKeyData, KeyDataReader};
use access::packet;
use access::req::{ReqData, SessReq, REQ_PORT};
use access::resp::SessResp;
use access::state::{ClientState,... | match SessResp::from_msg(&resp_packet) {
Ok(recv_resp) => println!("{}: {}", addr, recv_resp),
Err(e) => println!("couldn't interpret response: {}", e),
};
}
Err(e) => println!("decrypt failed: {}", e),
}
Ok(... | match packet::open(buf, &self.key_data.secret, &self.key_data.peer_public) {
Ok(resp_packet) => { | random_line_split |
access.rs | use std::io;
use std::net::{IpAddr, SocketAddr, ToSocketAddrs};
use std::str::FromStr;
use std::time::Duration;
use access::err::AccessError;
use access::keys::{ClientKeyData, KeyDataReader};
use access::packet;
use access::req::{ReqData, SessReq, REQ_PORT};
use access::resp::SessResp;
use access::state::{ClientState,... | .arg(
Arg::with_name("state-file")
.empty_values(false)
.short("s")
.long("state-file")
.default_value(&default_state_filename)
.help("Path to state file"),
)
.arg(
Arg::with_name("key-data-file")
... | {
let default_state_filename =
format!("{}/.access/state.yaml", dirs::home_dir().unwrap().display());
let default_key_data_filename = format!(
"{}/.access/keydata.yaml",
dirs::home_dir().unwrap().display()
);
let matches = App::new("access")
.version(crate_version!())
... | identifier_body |
decodable.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (cx: &mut ExtCtxt, trait_span: Span,
substr: &Substructure,
krate: &str) -> P<Expr> {
let decoder = substr.nonself_args[0].clone();
let recurse = vec!(cx.ident_of(krate),
cx.ident_of("Decodable"),
cx.ident_of("decode"));... | decodable_substructure | identifier_name |
decodable.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | else {
let fields = fields.iter().enumerate().map(|(i, &span)| {
getarg(cx, span,
token::intern_and_get_ident(&format!("_field{}", i)[]),
i)
}).collect();
cx.expr_call(trait_span, path_expr, field... | {
path_expr
} | conditional_block |
decodable.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | vec!(krate, "Decoder"), None,
vec!(), true))))
},
explicit_self: None,
args: vec!(Ptr(box Literal(Path::new_local("__D")),
Borrowed(None, MutMutable))),
ret... | name: "decode",
generics: LifetimeBounds {
lifetimes: Vec::new(),
bounds: vec!(("__D", vec!(Path::new_( | random_line_split |
decodable.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
pub fn expand_deriving_decodable<F>(cx: &mut ExtCtxt,
span: Span,
mitem: &MetaItem,
item: &Item,
push: F) where
F: FnOnce(P<Item>),
{
expand_deriving_decodable_imp(cx... | {
expand_deriving_decodable_imp(cx, span, mitem, item, push, "rustc_serialize")
} | identifier_body |
main.rs | // rscheme -- a scheme interpreter written in Rust
// Copyright (C) {2015) Elizabeth Henry <liz.henry@ouvaton.org>
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either ... | () {
init::init();
repl();
}
| main | identifier_name |
main.rs | // rscheme -- a scheme interpreter written in Rust
// Copyright (C) {2015) Elizabeth Henry <liz.henry@ouvaton.org>
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either ... |
}
}
let mut line = String::new();
stdin.lock().read_line(&mut line).unwrap();
let cs = line.chars().collect();
{
let mut l = Lexer::new(&cs,&mut tokens);
l.with_n_par(n_par);
n_par = l.tokenize();
}
if n_p... | {
error!("Error flushing stdout. abort");
break;
} | conditional_block |
main.rs | // rscheme -- a scheme interpreter written in Rust
// Copyright (C) {2015) Elizabeth Henry <liz.henry@ouvaton.org>
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either vers... |
}
if n_par == 0 {
let es = read::read(&tokens);
tokens = vec!();
for e in es {
c = c.eval_expr(e.clone());
if c.error {
c.error = false;
break;
} else {
printl... | random_line_split | |
main.rs | // rscheme -- a scheme interpreter written in Rust
// Copyright (C) {2015) Elizabeth Henry <liz.henry@ouvaton.org>
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either ... | {
init::init();
repl();
} | identifier_body | |
model.rs | // Copyright 2019-2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed t... | (&mut self, updates: Vec<StoreUpdate>) -> StoreResult<()> {
// Fail if the transaction is invalid.
if self.format.transaction_valid(&updates).is_none() {
return Err(StoreError::InvalidArgument);
}
// Fail if there is not enough capacity.
let capacity = self.format.tra... | transaction | identifier_name |
model.rs | // Copyright 2019-2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed t... |
/// Returns the modeled content.
pub fn content(&self) -> &HashMap<usize, Box<[u8]>> {
&self.content
}
/// Returns the storage configuration.
pub fn format(&self) -> &Format {
&self.format
}
/// Simulates a store operation.
pub fn apply(&mut self, operation: StoreOper... | {
let content = HashMap::new();
StoreModel { content, format }
} | identifier_body |
model.rs | // Copyright 2019-2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed t... | for update in updates {
match update {
StoreUpdate::Insert { key, value } => {
self.content.insert(key, value.into_boxed_slice());
}
StoreUpdate::Remove { key } => {
self.content.remove(&key);
}
... | if self.capacity().remaining() < capacity {
return Err(StoreError::NoCapacity);
}
// Apply the updates. | random_line_split |
lib.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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 ... | #![feature(unsafe_destructor)]
#![feature(core)]
#![feature(test)]
#![feature(rand)]
#![feature(unicode)]
#![feature(std_misc)]
#![feature(libc)]
#![feature(hash)]
#![feature(io)]
#![feature(collections)]
#![allow(deprecated)] // rand
extern crate core;
extern crate test;
extern crate libc;
extern crate unicode;
mod ... | #![feature(unboxed_closures)] | random_line_split |
retourpremsource0.rs | // On utilise `String` comme type d'erreur.
type Result<T> = std::result::Result<T, String>;
fn double_first(vec: Vec<&str>) -> Result<i32> {
// On convertit l'`Option` en un `Result` s'il y a une valeur.
// Autrement, on fournit une instance `Err` contenant la `String`.
let first = match vec.first() {
... | let empty = vec![];
let strings = vec!["tofu", "93", "18"];
print(double_first(empty));
print(double_first(strings));
}
| identifier_body | |
retourpremsource0.rs | // On utilise `String` comme type d'erreur.
type Result<T> = std::result::Result<T, String>;
fn double_first(vec: Vec<&str>) -> Result<i32> {
// On convertit l'`Option` en un `Result` s'il y a une valeur.
// Autrement, on fournit une instance `Err` contenant la `String`.
let first = match vec.first() {
... | {
let empty = vec![];
let strings = vec!["tofu", "93", "18"];
print(double_first(empty));
print(double_first(strings));
}
| n() | identifier_name |
retourpremsource0.rs | // On utilise `String` comme type d'erreur.
type Result<T> = std::result::Result<T, String>;
fn double_first(vec: Vec<&str>) -> Result<i32> {
// On convertit l'`Option` en un `Result` s'il y a une valeur.
// Autrement, on fournit une instance `Err` contenant la `String`.
let first = match vec.first() {
... | }
fn print(result: Result<i32>) {
match result {
Ok(n) => println!("The first doubled is {}", n),
Err(e) => println!("Error: {}", e),
}
}
fn main() {
let empty = vec![];
let strings = vec!["tofu", "93", "18"];
print(double_first(empty));
print(double_first(strings));
} | Ok(i) => Ok(2 * i),
Err(e) => Err(e.to_string()),
} | random_line_split |
005.rs | /*
* Smallest multiple
* =================
* 2520 is the smallest number that can be divided by each of the numbers from 1
* to 10 without any remainder.
*
* What is the smallest positive number that is evenly divisible by all of the
* numbers from 1 to 20?
*/
fn gcd(n: u64, m: u64) -> u64 |
fn lcm(n: u64, m: u64) -> u64 {
n * m / gcd(n, m)
}
fn main() {
// Lowest common multiple can be calculated piecewise. Uses Euclid's Algorithm
// to calculate greatest common divisors and form lowest common multiples.
let answer = (1..21).fold(1, |acc, n| lcm(acc, n));
println!("{}", answer);
}
| {
// Euclid's insanely beautiful greatest common divisor algorithm.
let mut a = n;
let mut b = m;
while b > 0 {
let t = b;
b = a % t;
a = t;
}
a
} | identifier_body |
005.rs | /*
* Smallest multiple
* =================
* 2520 is the smallest number that can be divided by each of the numbers from 1
* to 10 without any remainder.
*
* What is the smallest positive number that is evenly divisible by all of the
* numbers from 1 to 20?
*/
fn gcd(n: u64, m: u64) -> u64 {
// Euclid's ins... | (n: u64, m: u64) -> u64 {
n * m / gcd(n, m)
}
fn main() {
// Lowest common multiple can be calculated piecewise. Uses Euclid's Algorithm
// to calculate greatest common divisors and form lowest common multiples.
let answer = (1..21).fold(1, |acc, n| lcm(acc, n));
println!("{}", answer);
}
| lcm | identifier_name |
005.rs | /*
* Smallest multiple
* =================
* 2520 is the smallest number that can be divided by each of the numbers from 1
* to 10 without any remainder.
*
* What is the smallest positive number that is evenly divisible by all of the
* numbers from 1 to 20?
*/
fn gcd(n: u64, m: u64) -> u64 {
// Euclid's ins... | fn lcm(n: u64, m: u64) -> u64 {
n * m / gcd(n, m)
}
fn main() {
// Lowest common multiple can be calculated piecewise. Uses Euclid's Algorithm
// to calculate greatest common divisors and form lowest common multiples.
let answer = (1..21).fold(1, |acc, n| lcm(acc, n));
println!("{}", answer);
} | a
}
| random_line_split |
json.rs | /*
* Copyright 2015-2016 Torrie Fischer <tdfischer@hackerbots.net>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless requi... |
pub fn array<'a>(json: &'a Json, path: &str) -> &'a Array {
match self::path(json, path).as_array() {
Some(p) => p,
None => panic!("{} in {} is not an array", path, json.pretty())
}
}
pub fn string<'a>(json: &'a Json, path: &str) -> &'a str{
match self::path(json, path).as_string() {
... | {
// why not just use json.find_path ooi? -matthew
let parts = path.split(".");
let mut cur = json;
for p in parts {
cur = match cur.as_object().unwrap().get(p) {
Some(c) => c,
None => panic!("Could not find {} in {} (lost at {})", path, json.pretty(), p)
}
}
... | identifier_body |
json.rs | /*
* Copyright 2015-2016 Torrie Fischer <tdfischer@hackerbots.net>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless requi... | pub fn string<'a>(json: &'a Json, path: &str) -> &'a str{
match self::path(json, path).as_string() {
Some(p) => p,
None => panic!("{} in {} is not a string", path, json.pretty())
}
} | }
| random_line_split |
json.rs | /*
* Copyright 2015-2016 Torrie Fischer <tdfischer@hackerbots.net>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless requi... | <'a>(json: &'a Json, path: &str) -> &'a Array {
match self::path(json, path).as_array() {
Some(p) => p,
None => panic!("{} in {} is not an array", path, json.pretty())
}
}
pub fn string<'a>(json: &'a Json, path: &str) -> &'a str{
match self::path(json, path).as_string() {
Some(p) =>... | array | identifier_name |
Insertion_Sort.rs | use std::io;
use std::str::FromStr;
fn main() {
println!("Enter the numbers to be sorted (separated by space) : ");
let mut i = read_values :: <i32>().unwrap();
insertion_sort(&mut i);
println!("Sorted array: {:?}", i)
}
fn insertion_sort(arr: &mut Vec<i32>) {
for i in 1..arr.len() {
let ... | <T: FromStr>() -> Result<Vec<T>, T::Err> {
let mut s = String::new();
io::stdin()
.read_line(&mut s)
.expect("could not read from stdin");
s.trim()
.split_whitespace()
.map(|word| word.parse())
.collect()
}
/*
Sample Input :
Enter the numbers to be sorted (separated ... | read_values | identifier_name |
Insertion_Sort.rs | use std::io;
use std::str::FromStr;
fn main() {
println!("Enter the numbers to be sorted (separated by space) : ");
let mut i = read_values :: <i32>().unwrap();
insertion_sort(&mut i);
println!("Sorted array: {:?}", i)
}
fn insertion_sort(arr: &mut Vec<i32>) {
for i in 1..arr.len() {
let ... | .map(|word| word.parse())
.collect()
}
/*
Sample Input :
Enter the numbers to be sorted (separated by space) :
45 34 112 50 91 ... | io::stdin()
.read_line(&mut s)
.expect("could not read from stdin");
s.trim()
.split_whitespace() | random_line_split |
Insertion_Sort.rs | use std::io;
use std::str::FromStr;
fn main() {
println!("Enter the numbers to be sorted (separated by space) : ");
let mut i = read_values :: <i32>().unwrap();
insertion_sort(&mut i);
println!("Sorted array: {:?}", i)
}
fn insertion_sort(arr: &mut Vec<i32>) {
for i in 1..arr.len() {
let ... |
/*
Sample Input :
Enter the numbers to be sorted (separated by space) :
45 34 112 50 91
Sample Output :
Sorted array: [3... | {
let mut s = String::new();
io::stdin()
.read_line(&mut s)
.expect("could not read from stdin");
s.trim()
.split_whitespace()
.map(|word| word.parse())
.collect()
} | identifier_body |
part_b.rs | use regex::Regex;
use std::str::FromStr;
lazy_static! {
static ref REGEX: Regex = Regex::new(r"\((?P<length>[0-9]+)x(?P<times>[0-9]+)\)").unwrap();
}
pub fn solve(data: &str) {
println!("{}", "------------- [ PART B ] -------------");
println!("NOOT NOOT! its da sound of da pingu 🐧");
println!("{}", ... | use part_b::Node;
#[test]
fn test_solve_without_subnodes() {
let subject = Node { content_length: 10, multiplier: 3, nodes: Vec::new() };
assert_eq!(subject.len(), 30);
}
#[test]
fn test_solve_with_one_level_subnodes() {
// example: (22x11)(3x5)ICQ(9x5)IYUPTHPKX
... | mod node_tests { | random_line_split |
part_b.rs | use regex::Regex;
use std::str::FromStr;
lazy_static! {
static ref REGEX: Regex = Regex::new(r"\((?P<length>[0-9]+)x(?P<times>[0-9]+)\)").unwrap();
}
pub fn solve(data: &str) {
println!("{}", "------------- [ PART B ] -------------");
println!("NOOT NOOT! its da sound of da pingu 🐧");
println!("{}", ... | {
let node : Node = "(5x11)ABCDE".parse().unwrap();
assert_eq!(node.content_length, 5);
assert_eq!(node.multiplier, 11);
assert_eq!(node.nodes.len(), 0);
}
#[test]
fn test_from_str_with_subnodes() {
let node : Node = "(10x4)(4x10)FGHI".parse().unwrap(); // total len... | t_from_str_simple() | identifier_name |
part_b.rs | use regex::Regex;
use std::str::FromStr;
lazy_static! {
static ref REGEX: Regex = Regex::new(r"\((?P<length>[0-9]+)x(?P<times>[0-9]+)\)").unwrap();
}
pub fn solve(data: &str) {
println!("{}", "------------- [ PART B ] -------------");
println!("NOOT NOOT! its da sound of da pingu 🐧");
println!("{}", ... |
impl FromStr for Node {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
let cap = REGEX.captures_iter(s).nth(0).unwrap();
// grab end of capture and grab new sequence from end of capture until end of s
// parse new sequence into node and add onto nodes.
let r... | self.multiplier * (self.content_length + self.nodes.iter().fold(0, {|v, n| v + n.len() }))
}
}
| identifier_body |
pythagorean-triplet.rs | use pythagorean_triplet::find;
use std::collections::HashSet;
fn process_tripletswithsum_case(sum: u32, expected: &[[u32; 3]]) {
let triplets = find(sum);
if!expected.is_empty() {
let expected: HashSet<_> = expected.iter().cloned().collect();
assert_eq!(expected, triplets);
} else {
... | () {
process_tripletswithsum_case(
30_000,
&[
[1200, 14_375, 14_425],
[1875, 14_000, 14_125],
[5000, 12_000, 13_000],
[6000, 11_250, 12_750],
[7500, 10_000, 12_500],
],
);
}
| test_triplets_for_large_number | identifier_name |
pythagorean-triplet.rs | use pythagorean_triplet::find;
use std::collections::HashSet;
fn process_tripletswithsum_case(sum: u32, expected: &[[u32; 3]]) {
let triplets = find(sum);
if!expected.is_empty() {
let expected: HashSet<_> = expected.iter().cloned().collect();
assert_eq!(expected, triplets);
} else {
... |
#[test]
#[ignore]
fn test_triplets_for_large_number() {
process_tripletswithsum_case(
30_000,
&[
[1200, 14_375, 14_425],
[1875, 14_000, 14_125],
[5000, 12_000, 13_000],
[6000, 11_250, 12_750],
[7500, 10_000, 12_500],
],
);
}
| {
process_tripletswithsum_case(
840,
&[
[40, 399, 401],
[56, 390, 394],
[105, 360, 375],
[120, 350, 370],
[140, 336, 364],
[168, 315, 357],
[210, 280, 350],
[240, 252, 348],
],
);
} | identifier_body |
pythagorean-triplet.rs | use pythagorean_triplet::find; |
if!expected.is_empty() {
let expected: HashSet<_> = expected.iter().cloned().collect();
assert_eq!(expected, triplets);
} else {
assert!(triplets.is_empty());
}
}
#[test]
fn test_triplets_whose_sum_is_12() {
process_tripletswithsum_case(12, &[[3, 4, 5]]);
}
#[test]
#[ignore]
... | use std::collections::HashSet;
fn process_tripletswithsum_case(sum: u32, expected: &[[u32; 3]]) {
let triplets = find(sum); | random_line_split |
pythagorean-triplet.rs | use pythagorean_triplet::find;
use std::collections::HashSet;
fn process_tripletswithsum_case(sum: u32, expected: &[[u32; 3]]) {
let triplets = find(sum);
if!expected.is_empty() | else {
assert!(triplets.is_empty());
}
}
#[test]
fn test_triplets_whose_sum_is_12() {
process_tripletswithsum_case(12, &[[3, 4, 5]]);
}
#[test]
#[ignore]
fn test_triplets_whose_sum_is_108() {
process_tripletswithsum_case(108, &[[27, 36, 45]]);
}
#[test]
#[ignore]
fn test_triplets_whose_sum_is_10... | {
let expected: HashSet<_> = expected.iter().cloned().collect();
assert_eq!(expected, triplets);
} | conditional_block |
terminal.rs | use std::io::{self, Stdout};
use std::thread::{sleep, spawn};
use std::time::Duration;
use futures::sync::mpsc::{unbounded, UnboundedReceiver, UnboundedSender};
use futures::{Async, Poll, Sink, Stream};
use failure::{Error, ResultExt};
use termion::event::Event;
use termion::input::MouseTerminal;
use termion::input:... |
fn start_size_listening(tx: UnboundedSender<(u16, u16)>) {
let mut tx = tx;
spawn(move || {
let mut current_size = (0, 0);
info!("waiting for resize events");
loop {
match terminal_size() {
Ok(new_size) => if new_size!= curren... | {
let mut tx = tx;
spawn(move || {
info!("waiting for input events");
for event_res in io::stdin().events() {
match event_res {
// TODO: at least log the errors
Ok(event) => {
let _ = tx.start_send(ev... | identifier_body |
terminal.rs | use std::io::{self, Stdout};
use std::thread::{sleep, spawn};
use std::time::Duration;
use futures::sync::mpsc::{unbounded, UnboundedReceiver, UnboundedSender};
use futures::{Async, Poll, Sink, Stream};
use failure::{Error, ResultExt};
use termion::event::Event;
use termion::input::MouseTerminal;
use termion::input:... | }
Ok(Async::Ready(None)) => {
warn!("terminal input sender closed the channel");
return Ok(Async::Ready(None));
}
Ok(Async::NotReady) => {}
Err(()) => return Err(()),
}
Ok(Async::NotReady)
}
} | }
match self.stdin.poll() {
Ok(Async::Ready(Some(event))) => {
return Ok(Async::Ready(Some(TerminalEvent::Input(event)))) | random_line_split |
terminal.rs | use std::io::{self, Stdout};
use std::thread::{sleep, spawn};
use std::time::Duration;
use futures::sync::mpsc::{unbounded, UnboundedReceiver, UnboundedSender};
use futures::{Async, Poll, Sink, Stream};
use failure::{Error, ResultExt};
use termion::event::Event;
use termion::input::MouseTerminal;
use termion::input:... |
Err(()) => return Err(()),
}
Ok(Async::NotReady)
}
}
| {} | conditional_block |
terminal.rs | use std::io::{self, Stdout};
use std::thread::{sleep, spawn};
use std::time::Duration;
use futures::sync::mpsc::{unbounded, UnboundedReceiver, UnboundedSender};
use futures::{Async, Poll, Sink, Stream};
use failure::{Error, ResultExt};
use termion::event::Event;
use termion::input::MouseTerminal;
use termion::input:... | {
Resize((u16, u16)),
Input(Event),
}
impl Stream for Terminal {
type Item = TerminalEvent;
type Error = ();
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
match self.size.poll() {
Ok(Async::Ready(Some(size))) => {
return Ok(Async::Ready(Some(Ter... | TerminalEvent | identifier_name |
test_cat.rs | use common::util::*;
|
#[test]
fn test_output_multi_files_print_all_chars() {
let (_, mut ucmd) = testing(UTIL_NAME);
ucmd.arg("alpha.txt")
.arg("256.txt")
.arg("-A")
.arg("-n");
assert_eq!(ucmd.run().stdout,
" 1\tabcde$\n 2\tfghij$\n 3\tklmno$\n 4\tpqrst$\n \
... | static UTIL_NAME: &'static str = "cat"; | random_line_split |
test_cat.rs | use common::util::*;
static UTIL_NAME: &'static str = "cat";
#[test]
fn test_output_multi_files_print_all_chars() {
let (_, mut ucmd) = testing(UTIL_NAME);
ucmd.arg("alpha.txt")
.arg("256.txt")
.arg("-A")
.arg("-n");
assert_eq!(ucmd.run().stdout,
" 1\tabcde$\n ... | () {
let (_, mut ucmd) = testing(UTIL_NAME);
let out = ucmd.arg("-b")
.arg("-")
.run_piped_stdin("\na\nb\n\n\nc".as_bytes())
.stdout;
assert_eq!(out, "\n 1\ta\n 2\tb\n\n\n 3\tc");
}
| test_stdin_number_non_blank | identifier_name |
test_cat.rs | use common::util::*;
static UTIL_NAME: &'static str = "cat";
#[test]
fn test_output_multi_files_print_all_chars() {
let (_, mut ucmd) = testing(UTIL_NAME);
ucmd.arg("alpha.txt")
.arg("256.txt")
.arg("-A")
.arg("-n");
assert_eq!(ucmd.run().stdout,
" 1\tabcde$\n ... | {
let (_, mut ucmd) = testing(UTIL_NAME);
let out = ucmd.arg("-b")
.arg("-")
.run_piped_stdin("\na\nb\n\n\nc".as_bytes())
.stdout;
assert_eq!(out, "\n 1\ta\n 2\tb\n\n\n 3\tc");
} | identifier_body | |
unboxed-closures-cross-crate.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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 ... | <T: Add<T,T> + Copy>(x: T, y: T) -> T {
let mut f = move |&mut:| x;
let g = |:| y;
f() + g()
}
| has_generic_closures | identifier_name |
unboxed-closures-cross-crate.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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 ... | let mut f = move |&mut:| x;
let y = 1u;
let g = |:| y;
f() + g()
}
pub fn has_generic_closures<T: Add<T,T> + Copy>(x: T, y: T) -> T {
let mut f = move |&mut:| x;
let g = |:| y;
f() + g()
} | #[inline]
pub fn has_closures() -> uint {
let x = 1u; | random_line_split |
unboxed-closures-cross-crate.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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 ... |
pub fn has_generic_closures<T: Add<T,T> + Copy>(x: T, y: T) -> T {
let mut f = move |&mut:| x;
let g = |:| y;
f() + g()
}
| {
let x = 1u;
let mut f = move |&mut:| x;
let y = 1u;
let g = |:| y;
f() + g()
} | identifier_body |
oneshot.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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 ... |
pub enum UpgradeResult {
UpSuccess,
UpDisconnected,
UpWoke(SignalToken),
}
pub enum SelectionResult<T> {
SelCanceled,
SelUpgraded(SignalToken, Receiver<T>),
SelSuccess,
}
enum MyUpgrade<T> {
NothingSent,
SendUsed,
GoUp(Receiver<T>),
}
impl<T: Send> Packet<T> {
pub fn new() ->... | Disconnected,
Upgraded(Receiver<T>),
} | random_line_split |
oneshot.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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 ... | (&mut self) -> Result<T, Failure<T>> {
// Attempt to not block the task (it's a little expensive). If it looks
// like we're not empty, then immediately go through to `try_recv`.
if self.state.load(Ordering::SeqCst) == EMPTY {
let (wait_token, signal_token) = blocking::tokens();
... | recv | identifier_name |
oneshot.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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 ... | // this we first need to check if there's data available and *then*
// we go through and process the upgrade.
DISCONNECTED => {
match self.data.take() {
Some(data) => Ok(data),
None => {
match mem::replac... | {
match self.state.load(Ordering::SeqCst) {
EMPTY => Err(Empty),
// We saw some data on the channel, but the channel can be used
// again to send us an upgrade. As a result, we need to re-insert
// into the channel that there's no data available (otherwise we'll
... | identifier_body |
builtin-superkinds-simple.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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 ... | trait Bar : Freeze { }
impl <'self> Bar for &'self mut () { } //~ ERROR cannot implement this trait
fn main() { } | trait Foo : Send { }
impl <'self> Foo for &'self mut () { } //~ ERROR cannot implement this trait
| random_line_split |
builtin-superkinds-simple.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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 ... | { } | identifier_body | |
builtin-superkinds-simple.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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 ... | () { }
| main | identifier_name |
svd.rs | ///! Truncated singular value decomposition
///!
///! This module computes the k largest/smallest singular values/vectors for a dense matrix.
use super::lobpcg::{lobpcg, LobpcgResult, Order};
use crate::error::Result;
use crate::generate;
use cauchy::Scalar;
use lax::Lapack;
use ndarray::prelude::*;
use ndarray::Scalar... |
/// Returns singular values, left-singular vectors and right-singular vectors
pub fn values_vectors(&self) -> (Array2<A>, Array1<A>, Array2<A>) {
let (values, indices) = self.singular_values_with_indices();
// branch n > m (for A is [n x m])
let (u, v) = if self.ngm {
let ... | {
let (values, _) = self.singular_values_with_indices();
values
} | identifier_body |
svd.rs | ///! Truncated singular value decomposition
///!
///! This module computes the k largest/smallest singular values/vectors for a dense matrix.
use super::lobpcg::{lobpcg, LobpcgResult, Order};
use crate::error::Result;
use crate::generate;
use cauchy::Scalar;
use lax::Lapack;
use ndarray::prelude::*;
use ndarray::Scalar... | }
#[cfg(test)]
mod tests {
use super::Order;
use super::TruncatedSvd;
use crate::{close_l2, generate};
use ndarray::{arr1, arr2, Array2};
#[test]
fn test_truncated_svd() {
let a = arr2(&[[3., 2., 2.], [2., 3., -2.]]);
let res = TruncatedSvd::new(a, Order::Largest)
... | 1.0e6
} | random_line_split |
svd.rs | ///! Truncated singular value decomposition
///!
///! This module computes the k largest/smallest singular values/vectors for a dense matrix.
use super::lobpcg::{lobpcg, LobpcgResult, Order};
use crate::error::Result;
use crate::generate;
use cauchy::Scalar;
use lax::Lapack;
use ndarray::prelude::*;
use ndarray::Scalar... | <A: Scalar> {
order: Order,
problem: Array2<A>,
precision: f32,
maxiter: usize,
}
impl<A: Float + Scalar + ScalarOperand + Lapack + PartialOrd + Default> TruncatedSvd<A> {
pub fn new(problem: Array2<A>, order: Order) -> TruncatedSvd<A> {
TruncatedSvd {
precision: 1e-5,
... | TruncatedSvd | identifier_name |
main.rs | use std::fs::File;
use std::io::{BufReader};
use bstr::io::BufReadExt;
fn main() | }
| {
let filename = "chry_multiplied.fa";
let mut cc: [u32; 256] = [0; 256];
// Open the file in read-only mode (ignoring errors).
let file = File::open(filename).unwrap();
let reader = BufReader::new(file);
// Read the file line by line using the lines() iterator from std::io::BufRead.
r... | identifier_body |
main.rs | use std::fs::File;
use std::io::{BufReader};
use bstr::io::BufReadExt;
fn | () {
let filename = "chry_multiplied.fa";
let mut cc: [u32; 256] = [0; 256];
// Open the file in read-only mode (ignoring errors).
let file = File::open(filename).unwrap();
let reader = BufReader::new(file);
// Read the file line by line using the lines() iterator from std::io::BufRead.
... | main | identifier_name |
main.rs | use std::fs::File;
use std::io::{BufReader};
use bstr::io::BufReadExt;
fn main() {
let filename = "chry_multiplied.fa";
let mut cc: [u32; 256] = [0; 256];
// Open the file in read-only mode (ignoring errors).
let file = File::open(filename).unwrap();
let reader = BufReader::new(file);
// ... | let at = cc[b'A' as usize] + cc[b'T' as usize];
let gc_ratio: f64 = gc as f64 / (gc as f64 + at as f64);
println!("GC ratio (gc/(gc+at)): {}", gc_ratio);
} | random_line_split | |
main.rs | use std::fs::File;
use std::io::{BufReader};
use bstr::io::BufReadExt;
fn main() {
let filename = "chry_multiplied.fa";
let mut cc: [u32; 256] = [0; 256];
// Open the file in read-only mode (ignoring errors).
let file = File::open(filename).unwrap();
let reader = BufReader::new(file);
// ... |
for c in line { cc[*c as usize] += 1; }
Ok(true)
}).unwrap();
let gc = cc[b'G' as usize] + cc[b'C' as usize];
let at = cc[b'A' as usize] + cc[b'T' as usize];
let gc_ratio: f64 = gc as f64 / (gc as f64 + at as f64);
println!("GC ratio (gc/(gc+at)): {}", gc_ratio);
}
| {
return Ok(true)
} | conditional_block |
rpc_settings.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! ... | // Parity is distributed in the hope that it will be useful, | random_line_split |
rpc_settings.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | {
/// Whether RPC is enabled.
pub enabled: bool,
/// The interface being listened on.
pub interface: String,
/// The port being listened on.
pub port: u64,
}
| RpcSettings | identifier_name |
instr_vextractf64x4.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn vextractf64x4_1() {
run_test(&Instruction { mnemonic: Mnemonic::VEXTRACTF64x4, operand1: ... | () {
run_test(&Instruction { mnemonic: Mnemonic::VEXTRACTF64x4, operand1: Some(IndirectDisplaced(RAX, 1609800228, Some(OperandSize::Ymmword), None)), operand2: Some(Direct(ZMM10)), operand3: Some(Literal8(118)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: N... | vextractf64x4_4 | identifier_name |
instr_vextractf64x4.rs | use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn vextractf64x4_1() {
run_test(&Instruction { mnemonic: Mnemonic::VEXTRACTF64x4, operand1: Some(Direct(YMM2)), operand2: Some(Direct(ZMM7)), operand3: Some(Literal8(77)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Ze... | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*; | random_line_split | |
instr_vextractf64x4.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn vextractf64x4_1() {
run_test(&Instruction { mnemonic: Mnemonic::VEXTRACTF64x4, operand1: ... |
#[test]
fn vextractf64x4_3() {
run_test(&Instruction { mnemonic: Mnemonic::VEXTRACTF64x4, operand1: Some(Direct(YMM23)), operand2: Some(Direct(ZMM11)), operand3: Some(Literal8(52)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K6), broadcast:... | {
run_test(&Instruction { mnemonic: Mnemonic::VEXTRACTF64x4, operand1: Some(Indirect(EBX, Some(OperandSize::Ymmword), None)), operand2: Some(Direct(ZMM1)), operand3: Some(Literal8(80)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[98, 243, 253, 72,... | identifier_body |
macro-inner-attributes.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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 ... | {
a::bar();
//~^ ERROR failed to resolve. Use of undeclared type or module `a`
//~^^ ERROR unresolved name `a::bar`
b::bar();
} | identifier_body | |
macro-inner-attributes.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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 ... | #[cfg(not(qux))],
pub fn bar() { });
#[qux]
fn main() {
a::bar();
//~^ ERROR failed to resolve. Use of undeclared type or module `a`
//~^^ ERROR unresolved name `a::bar`
b::bar();
} | pub fn bar() { });
test!(b, | random_line_split |
macro-inner-attributes.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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 ... | () {
a::bar();
//~^ ERROR failed to resolve. Use of undeclared type or module `a`
//~^^ ERROR unresolved name `a::bar`
b::bar();
}
| main | identifier_name |
domain.rs | use std::collections::HashSet;
use crate::validation::common::ValidationError;
use crate::structure::domain::DomainDocument;
#[derive(Debug)]
pub struct Validation {}
impl Validation {
pub fn validate(doc: &DomainDocument) -> Vec<ValidationError> {
let mut errors = Vec::<ValidationError>::new();
... | }
} |
errors | random_line_split |
domain.rs | use std::collections::HashSet;
use crate::validation::common::ValidationError;
use crate::structure::domain::DomainDocument;
#[derive(Debug)]
pub struct Validation {}
impl Validation {
pub fn validate(doc: &DomainDocument) -> Vec<ValidationError> {
let mut errors = Vec::<ValidationError>::new();
... | }
}
errors
}
}
| {
let mut errors = Vec::<ValidationError>::new();
let mut entities = HashSet::<&String>::new();
for entity in &doc.body.entities {
entities.insert(&entity.name);
}
for entity in &doc.body.entities {
for reference in &entity.references {
... | identifier_body |
domain.rs | use std::collections::HashSet;
use crate::validation::common::ValidationError;
use crate::structure::domain::DomainDocument;
#[derive(Debug)]
pub struct | {}
impl Validation {
pub fn validate(doc: &DomainDocument) -> Vec<ValidationError> {
let mut errors = Vec::<ValidationError>::new();
errors.extend(Validation::all_references_point_to_existing_entities(&doc));
errors
}
pub fn all_references_point_to_existing_entities(doc: &Domain... | Validation | identifier_name |
domain.rs | use std::collections::HashSet;
use crate::validation::common::ValidationError;
use crate::structure::domain::DomainDocument;
#[derive(Debug)]
pub struct Validation {}
impl Validation {
pub fn validate(doc: &DomainDocument) -> Vec<ValidationError> {
let mut errors = Vec::<ValidationError>::new();
... |
}
}
errors
}
}
| {
errors.push(ValidationError {
code: 1,
message: format!("Domain : Entity '{entity}' contains a reference to non-existent entity '{reference}'", entity=entity.name, reference=&reference.name),
paths: vec![
... | conditional_block |
benchmarks.rs | // Copyright 2020 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... |
#[bench]
fn bench_aes_siv_encrypt(b: &mut Bencher) {
let (d, _ct) = setup(tink_daead::aes_siv_key_template());
b.iter(|| d.encrypt_deterministically(MSG, AAD).unwrap());
}
#[bench]
fn bench_aes_siv_decrypt(b: &mut Bencher) {
let (d, ct) = setup(tink_daead::aes_siv_key_template());
b.iter(|| d.decrypt... | {
let (a, ct) = setup(kt);
(
a,
ct.iter()
.enumerate()
.map(|(i, b)| if i < PREFIX_SIZE { *b } else { b ^ 0b10101010 })
.collect(),
)
} | identifier_body |
benchmarks.rs | // Copyright 2020 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | (b: &mut Bencher) {
let (d, ct) = setup(tink_daead::aes_siv_key_template());
b.iter(|| d.decrypt_deterministically(&ct, AAD).unwrap());
}
#[bench]
fn bench_aes_siv_decrypt_fail(b: &mut Bencher) {
let (d, ct) = setup_failure(tink_daead::aes_siv_key_template());
b.iter(|| d.decrypt_deterministically(&ct,... | bench_aes_siv_decrypt | identifier_name |
benchmarks.rs | // Copyright 2020 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | else { b ^ 0b10101010 })
.collect(),
)
}
#[bench]
fn bench_aes_siv_encrypt(b: &mut Bencher) {
let (d, _ct) = setup(tink_daead::aes_siv_key_template());
b.iter(|| d.encrypt_deterministically(MSG, AAD).unwrap());
}
#[bench]
fn bench_aes_siv_decrypt(b: &mut Bencher) {
let (d, ct) = setup(tink... | { *b } | conditional_block |
benchmarks.rs | // Copyright 2020 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | fn setup_failure(kt: tink_proto::KeyTemplate) -> (Box<dyn tink_core::DeterministicAead>, Vec<u8>) {
let (a, ct) = setup(kt);
(
a,
ct.iter()
.enumerate()
.map(|(i, b)| if i < PREFIX_SIZE { *b } else { b ^ 0b10101010 })
.collect(),
)
}
#[bench]
fn bench_aes_si... | random_line_split | |
lib.rs | use std::time::{SystemTime, UNIX_EPOCH};
pub mod columns {
extern crate termion;
extern crate extra;
use std::cmp::max;
use std::cmp::min;
use std::io::{stdout, stderr, Write, BufWriter};
use self::extra::option::OptionalExt;
/// Prints a vector of strings in a table-like way to the termin... | (min: usize, max: usize, words: &Vec<usize>, terminal_width: usize) -> usize {
let diff = min as isize - max as isize;
let fits = try_rows(words, min + (max - min) / 2, terminal_width);
if diff == -1 || diff == 0 || diff == 1{
return min;
} else if fits {
return ... | bin_search | identifier_name |
lib.rs | use std::time::{SystemTime, UNIX_EPOCH};
pub mod columns {
extern crate termion;
extern crate extra;
use std::cmp::max;
use std::cmp::min;
use std::io::{stdout, stderr, Write, BufWriter};
use self::extra::option::OptionalExt;
/// Prints a vector of strings in a table-like way to the termin... | else if fits {
return bin_search(min + (max - min) / 2, max, words, terminal_width);
} else {
return bin_search(min, min + (max - min) / 2, words, terminal_width);
}
}
/// Find the length of the longest word in a list
fn longest_word(words: &Vec<usize>) -> usize {
... | {
return min;
} | conditional_block |
lib.rs | use std::time::{SystemTime, UNIX_EPOCH};
pub mod columns {
extern crate termion;
extern crate extra;
use std::cmp::max;
use std::cmp::min;
use std::io::{stdout, stderr, Write, BufWriter};
use self::extra::option::OptionalExt;
/// Prints a vector of strings in a table-like way to the termin... |
/// splits a vector of cloneables into a vector of vectors of cloneables where lines_amt
/// is the length of the outer vector and columns the max len of the inner vector
fn split_into_columns<T: Clone>(words: &Vec<T>, columns: usize, lines_amt: usize) -> Vec<Vec<T>> {
assert!(words.len() <= colum... | {
words.iter().fold(0, |x, y| {max(x, *y)})
} | identifier_body |
lib.rs | use std::time::{SystemTime, UNIX_EPOCH};
pub mod columns {
extern crate termion;
extern crate extra;
use std::cmp::max;
use std::cmp::min;
use std::io::{stdout, stderr, Write, BufWriter};
use self::extra::option::OptionalExt;
/// Prints a vector of strings in a table-like way to the termin... | }
(c, e, f, h, m, s)
}
pub fn format_time(ts: i64, tz_offset: i64) -> String {
let (c, e, f, h, m, s) = get_time_tuple(ts, tz_offset);
format!("{:>04}-{:>02}-{:>02} {:>02}:{:>02}:{:>02}", c, e, f, h, m, s)
}
pub fn to_human_readable_string(size: u64) -> String {
if size < 1024 {
return for... | c -= 4716;
e -= 1;
} else {
c -= 4715;
e -= 13; | random_line_split |
issue-58344.rs | // check-pass
use std::ops::Add;
trait Trait<T> {
fn get(self) -> T;
}
struct Holder<T>(T);
impl<T> Trait<T> for Holder<T> {
fn get(self) -> T {
self.0
}
}
enum Either<L, R> {
Left(L),
Right(R),
}
impl<L, R> Either<L, R> {
fn converge<T>(self) -> T
where | Either::Right(val) => val.get(),
}
}
}
fn add_generic<A: Add<B>, B>(
lhs: A,
rhs: B,
) -> Either<impl Trait<<A as Add<B>>::Output>, impl Trait<<A as Add<B>>::Output>> {
if true { Either::Left(Holder(lhs + rhs)) } else { Either::Right(Holder(lhs + rhs)) }
}
fn add_one(
value: u3... | L: Trait<T>,
R: Trait<T>,
{
match self {
Either::Left(val) => val.get(), | random_line_split |
issue-58344.rs | // check-pass
use std::ops::Add;
trait Trait<T> {
fn get(self) -> T;
}
struct Holder<T>(T);
impl<T> Trait<T> for Holder<T> {
fn get(self) -> T {
self.0
}
}
enum Either<L, R> {
Left(L),
Right(R),
}
impl<L, R> Either<L, R> {
fn converge<T>(self) -> T
where
L: Trait<T>,
... |
}
fn add_generic<A: Add<B>, B>(
lhs: A,
rhs: B,
) -> Either<impl Trait<<A as Add<B>>::Output>, impl Trait<<A as Add<B>>::Output>> {
if true { Either::Left(Holder(lhs + rhs)) } else { Either::Right(Holder(lhs + rhs)) }
}
fn add_one(
value: u32,
) -> Either<impl Trait<<u32 as Add<u32>>::Output>, impl T... | {
match self {
Either::Left(val) => val.get(),
Either::Right(val) => val.get(),
}
} | identifier_body |
issue-58344.rs | // check-pass
use std::ops::Add;
trait Trait<T> {
fn get(self) -> T;
}
struct Holder<T>(T);
impl<T> Trait<T> for Holder<T> {
fn get(self) -> T {
self.0
}
}
enum Either<L, R> {
Left(L),
Right(R),
}
impl<L, R> Either<L, R> {
fn converge<T>(self) -> T
where
L: Trait<T>,
... | else { Either::Right(Holder(lhs + rhs)) }
}
fn add_one(
value: u32,
) -> Either<impl Trait<<u32 as Add<u32>>::Output>, impl Trait<<u32 as Add<u32>>::Output>> {
add_generic(value, 1u32)
}
pub fn main() {
add_one(3).converge();
}
| { Either::Left(Holder(lhs + rhs)) } | conditional_block |
issue-58344.rs | // check-pass
use std::ops::Add;
trait Trait<T> {
fn get(self) -> T;
}
struct Holder<T>(T);
impl<T> Trait<T> for Holder<T> {
fn get(self) -> T {
self.0
}
}
enum Either<L, R> {
Left(L),
Right(R),
}
impl<L, R> Either<L, R> {
fn | <T>(self) -> T
where
L: Trait<T>,
R: Trait<T>,
{
match self {
Either::Left(val) => val.get(),
Either::Right(val) => val.get(),
}
}
}
fn add_generic<A: Add<B>, B>(
lhs: A,
rhs: B,
) -> Either<impl Trait<<A as Add<B>>::Output>, impl Trait<<A as ... | converge | identifier_name |
dom_html_div_element.rs | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files.git)
// DO NOT EDIT
use crate::DOMElement;
use crate::DOMEventTarget;
use crate::DOMHTMLElement;
use crate::DOMNode;
use crate::DOMObject;
use glib::object::Cast;
use glib::object::IsA;
use glib::si... | b"notify::align\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_align_trampoline::<Self, F> as *const (),
)),
Box_::into_raw(f),
)
}
}
}
impl fmt::Display for DOMHTMLDivElement {
... | }
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _, | random_line_split |
dom_html_div_element.rs | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files.git)
// DO NOT EDIT
use crate::DOMElement;
use crate::DOMEventTarget;
use crate::DOMHTMLElement;
use crate::DOMNode;
use crate::DOMObject;
use glib::object::Cast;
use glib::object::IsA;
use glib::si... | )
}
}
}
impl fmt::Display for DOMHTMLDivElement {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("DOMHTMLDivElement")
}
}
| {
unsafe extern "C" fn notify_align_trampoline<P, F: Fn(&P) + 'static>(
this: *mut ffi::WebKitDOMHTMLDivElement,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) where
P: IsA<DOMHTMLDivElement>,
{
let f: &F = &*(f as *const F... | identifier_body |
dom_html_div_element.rs | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files.git)
// DO NOT EDIT
use crate::DOMElement;
use crate::DOMEventTarget;
use crate::DOMHTMLElement;
use crate::DOMNode;
use crate::DOMObject;
use glib::object::Cast;
use glib::object::IsA;
use glib::si... | <P, F: Fn(&P) +'static>(
this: *mut ffi::WebKitDOMHTMLDivElement,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) where
P: IsA<DOMHTMLDivElement>,
{
let f: &F = &*(f as *const F);
f(&DOMHTMLDivElement::from_glib_borrow(t... | notify_align_trampoline | identifier_name |
encoding_support.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Parsing stylesheets from bytes (not `&str`).
extern crate encoding;
use context::QuirksMode;
use cssparser::... | matches!(encoding.name(), "utf-16be" | "utf-16le")
}
fn from_label(ascii_label: &[u8]) -> Option<Self::Encoding> {
str::from_utf8(ascii_label).ok().and_then(encoding::label::encoding_from_whatwg_label)
}
}
fn decode_stylesheet_bytes(css: &[u8], protocol_encoding_label: Option<&str>,
... |
fn is_utf16_be_or_le(encoding: &Self::Encoding) -> bool { | random_line_split |
encoding_support.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Parsing stylesheets from bytes (not `&str`).
extern crate encoding;
use context::QuirksMode;
use cssparser::... | () -> Self::Encoding {
encoding::all::UTF_8
}
fn is_utf16_be_or_le(encoding: &Self::Encoding) -> bool {
matches!(encoding.name(), "utf-16be" | "utf-16le")
}
fn from_label(ascii_label: &[u8]) -> Option<Self::Encoding> {
str::from_utf8(ascii_label).ok().and_then(encoding::label::... | utf8 | identifier_name |
encoding_support.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Parsing stylesheets from bytes (not `&str`).
extern crate encoding;
use context::QuirksMode;
use cssparser::... |
fn is_utf16_be_or_le(encoding: &Self::Encoding) -> bool {
matches!(encoding.name(), "utf-16be" | "utf-16le")
}
fn from_label(ascii_label: &[u8]) -> Option<Self::Encoding> {
str::from_utf8(ascii_label).ok().and_then(encoding::label::encoding_from_whatwg_label)
}
}
fn decode_stylesheet... | {
encoding::all::UTF_8
} | identifier_body |
chain.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | () {
let mut net = TestNet::new(3);
net.peer_mut(1).chain.add_blocks(100, EachBlockWith::Uncle);
net.peer_mut(2).chain.add_blocks(100, EachBlockWith::Uncle);
let total_steps = net.sync();
assert!(total_steps < 7);
}
#[test]
fn empty_blocks() {
::env_logger::init().ok();
let mut net = TestNet::new(3);
for n in ... | takes_few_steps | identifier_name |
chain.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... |
if net.peer(0).queue[i].packet_id == 0x7 {
blocks += 1;
}
}
assert!(blocks + hashes == 5);
}
#[test]
fn propagate_blocks() {
let mut net = TestNet::new(2);
net.peer_mut(1).chain.add_blocks(10, EachBlockWith::Uncle);
net.sync();
net.peer_mut(0).chain.add_blocks(10, EachBlockWith::Uncle);
net.trigger_cha... | {
hashes += 1;
} | conditional_block |
chain.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... |
#[test]
fn status_empty() {
let net = TestNet::new(2);
assert_eq!(net.peer(0).sync.status().state, SyncState::NotSynced);
}
#[test]
fn status_packet() {
let mut net = TestNet::new(2);
net.peer_mut(0).chain.add_blocks(100, EachBlockWith::Uncle);
net.peer_mut(1).chain.add_blocks(1, EachBlockWith::Uncle);
net.sta... | assert_eq!(status.state, SyncState::NotSynced);
} | random_line_split |
chain.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... |
#[test]
fn empty_blocks() {
::env_logger::init().ok();
let mut net = TestNet::new(3);
for n in 0..200 {
let with = if n % 2 == 0 { EachBlockWith::Nothing } else { EachBlockWith::Uncle };
net.peer_mut(1).chain.add_blocks(5, with.clone());
net.peer_mut(2).chain.add_blocks(5, with);
}
net.sync();
assert!(net... | {
let mut net = TestNet::new(3);
net.peer_mut(1).chain.add_blocks(100, EachBlockWith::Uncle);
net.peer_mut(2).chain.add_blocks(100, EachBlockWith::Uncle);
let total_steps = net.sync();
assert!(total_steps < 7);
} | identifier_body |
angle.rs | /*
Copyright (c) 2015, 2016 Saurav Sachidanand
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, di... | ;
(deg as f64) + (M as f64)/60.0 + S/3600.0
}
/**
Computes an angle expressed in degrees, arcminutes and
arcseconds, from an angle in degrees with decimals
# Returns
`(deg, min, sec)`
* `deg`: Degrees
* `min`: Arcminutes
* `sec`: Arcseconds
# Arguments
* `deg`: Angle in degrees with decimals
**/
#[inline]
pu... | { (min, sec) } | conditional_block |
angle.rs | /*
Copyright (c) 2015, 2016 Saurav Sachidanand
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, di... |
/**
Computes the equivalent angle in [0, 2π] radian range
# Arguments
* `angl`: Angle *| in radians*
**/
#[inline]
pub fn limit_to_two_PI(angl: f64) -> f64
{
let n = (angl / TWO_PI) as i64;
let limited_angl = angl - (TWO_PI * (n as f64));
if limited_angl < 0.0 { limited_angl + TWO_PI }
else ... | {
let n = (angl / 360.0) as i64;
let limited_angl = angl - (360.0 * (n as f64));
if limited_angl < 0.0 { limited_angl + 360.0 }
else { limited_angl }
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.