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
import-glob-circular.rs
// Copyright 2012 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 ...
() { info!("f1"); } pub fn common() -> uint { return 0u; } } mod circ2 { pub use circ1::f1; pub fn f2() { info!("f2"); } pub fn common() -> uint { return 1u; } } mod test { use circ1::*; fn test() { f1066(); } }
f1
identifier_name
main.rs
mod vector; mod objects; mod raytrace; use vector::*; use objects::*; use raytrace::*; fn main()
specular_exponent: 100.0 }; let scene = Scene { camera: Camera { position: Vec3::new(0.0, 0.0, 0.0), direction: Vec3::new(0.0, 0.0, -1.0), up: Vec3::new(0.0, 1.0, 0.0) }, lights: vec![ Light { position: Point::new(0...
{ let sphere = Object::Sphere { center: Vec3::new(0.0, 0.0, -2.0), radius: 0.5 }; let material = Material { ambient: Color::new(0.0, 0.2, 0.2), diffuse: Color::new(1.0, 1.0, 1.0), specular: Color::new(1.0, 1.0, 1.0), specular_exponent: 10.0 }; let sph...
identifier_body
main.rs
mod vector; mod objects; mod raytrace; use vector::*; use objects::*; use raytrace::*; fn main() { let sphere = Object::Sphere { center: Vec3::new(0.0, 0.0, -2.0), radius: 0.5 }; let material = Material { ambient: Color::new(0.0, 0.2, 0.2), diffuse: Color::new(1.0, 1.0, 1.0...
intensity: 0.2 }], objects: vec![(sphere, material), (sphere2, material2)] }; raytrace(&scene, 1920, 1080, std::f64::consts::PI / 3.5); }
random_line_split
main.rs
mod vector; mod objects; mod raytrace; use vector::*; use objects::*; use raytrace::*; fn
() { let sphere = Object::Sphere { center: Vec3::new(0.0, 0.0, -2.0), radius: 0.5 }; let material = Material { ambient: Color::new(0.0, 0.2, 0.2), diffuse: Color::new(1.0, 1.0, 1.0), specular: Color::new(1.0, 1.0, 1.0), specular_exponent: 10.0 }; let ...
main
identifier_name
homotopy.rs
/* This example demonstrates the usage of a discrete homotopy space. In homotopy theory, one constructs a continuous map between functions. There can be many different kinds of continuous maps, so spaces get very complex. It even gets worse by having continuous maps between continuous maps. Since there is a combinato...
println!("================================"); println!("Another way to construct a homotopy level 2 is to use `EqPair<Of<EqPair>>`:"); let s: EqPair<Of<EqPair>> = Construct::new(); let dim = 2; println!("{}", s.count(&dim)); println!("Similarly, at homotopy level 3 one can use `EqPair<Of<EqPai...
{ println!("A discrete homotopy space uses `EqPair` internally:"); let s: EqPair = Construct::new(); let dim = 4; let n = s.count(&dim); println!("{}", n); let mut pos = (0, 0); for x in 0..n { s.to_pos(&n, x, &mut pos); println!("{:?}", pos); } println!("============...
identifier_body
homotopy.rs
/* This example demonstrates the usage of a discrete homotopy space. In homotopy theory, one constructs a continuous map between functions. There can be many different kinds of continuous maps, so spaces get very complex. It even gets worse by having continuous maps between continuous maps. Since there is a combinato...
() { println!("A discrete homotopy space uses `EqPair` internally:"); let s: EqPair = Construct::new(); let dim = 4; let n = s.count(&dim); println!("{}", n); let mut pos = (0, 0); for x in 0..n { s.to_pos(&n, x, &mut pos); println!("{:?}", pos); } println!("=========...
main
identifier_name
homotopy.rs
/* This example demonstrates the usage of a discrete homotopy space. In homotopy theory, one constructs a continuous map between functions. There can be many different kinds of continuous maps, so spaces get very complex. It even gets worse by having continuous maps between continuous maps. Since there is a combinato...
1 0 1 3 6 10 2 0 1 6 21 55 3 0 1 21 231 1540 4 0 1 231 26796 1186570 5 0 1 26796 359026206 703974775735 */ extern crate discrete; use discrete::*; us...
random_line_split
update.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use diem_documentation_tool as diem_doc; use serde::Deserialize; use serde_reflection::{Samples, Tracer, TracerConfig}; #[allow(dead_code)] #[derive(Deserialize)] enum
{ Unit, Newtype(MyStruct), Tuple(u16, Option<bool>), Struct { a: u32 }, NewTupleArray((u16, u16, u16)), } #[derive(Deserialize)] struct MyStruct(u64); #[test] fn test_doctool() { let mut tracer = Tracer::new(TracerConfig::default()); let samples = Samples::new(); tracer.trace_type::<M...
MyEnum
identifier_name
update.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0
#[allow(dead_code)] #[derive(Deserialize)] enum MyEnum { Unit, Newtype(MyStruct), Tuple(u16, Option<bool>), Struct { a: u32 }, NewTupleArray((u16, u16, u16)), } #[derive(Deserialize)] struct MyStruct(u64); #[test] fn test_doctool() { let mut tracer = Tracer::new(TracerConfig::default()); ...
use diem_documentation_tool as diem_doc; use serde::Deserialize; use serde_reflection::{Samples, Tracer, TracerConfig};
random_line_split
step4.rs
println!("14. Issuer (Trust Anchor) is creating a Credential Offer for Prover"); let cred_offer_json = anoncreds::issuer_create_credential_offer(wallet_handle, &cred_def_id).wait().unwrap(); println!("15. Prover creates Credential Request"); let (cred_req_json, cred_req_metadata_json) = anoncreds::prover_create_creden...
println!("Stored Credential ID is {}", &out_cred_id); // Clean UP println!("17. Close and delete two wallets"); wallet::close_wallet(prover_wallet_handle).wait().unwrap(); wallet::delete_wallet(&prover_wallet_config, USEFUL_CREDENTIALS).wait().unwrap(); wallet::close_wallet(wallet_handle).wait().unwrap(); wallet::dele...
anoncreds::issuer_create_credential(wallet_handle, &cred_offer_json, &cred_req_json, &cred_values_json.to_string(), None, -1).wait().unwrap(); println!("17. Prover processes and stores Credential"); let out_cred_id = anoncreds::prover_store_credential(prover_wallet_handle, None, &cred_req_metadata_json, &cred_json...
random_line_split
keccak.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...
}
{ let mut keccak = Keccak::new_keccak256(); let mut result = [0u8; 32]; keccak.update(self); keccak.finalize(&mut result); result }
identifier_body
keccak.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...
fn keccak256(&self) -> T where T: Sized; } impl Keccak256<[u8; 32]> for [u8] { fn keccak256(&self) -> [u8; 32] { let mut keccak = Keccak::new_keccak256(); let mut result = [0u8; 32]; keccak.update(self); keccak.finalize(&mut result); result } }
use tiny_keccak::Keccak; pub trait Keccak256<T> {
random_line_split
keccak.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...
(&self) -> [u8; 32] { let mut keccak = Keccak::new_keccak256(); let mut result = [0u8; 32]; keccak.update(self); keccak.finalize(&mut result); result } }
keccak256
identifier_name
coord.rs
// Copyright 2014-2015 The GeoRust Developers // // 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 a...
Ok(()) } } impl<T> FromTokens<T> for Coord<T> where T: WktFloat + FromStr + Default, { fn from_tokens(tokens: &mut PeekableTokens<T>) -> Result<Self, &'static str> { let x = match tokens.next() { Some(Token::Number(n)) => n, _ => return Err("Expected a number for th...
{ write!(f, " {}", m)?; }
conditional_block
coord.rs
// Copyright 2014-2015 The GeoRust Developers // // 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 a...
impl<T> fmt::Display for Coord<T> where T: WktFloat + fmt::Display, { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "{} {}", self.x, self.y)?; if let Some(z) = self.z { write!(f, " {}", z)?; } if let Some(m) = self.m { write!...
random_line_split
coord.rs
// Copyright 2014-2015 The GeoRust Developers // // 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 a...
(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "{} {}", self.x, self.y)?; if let Some(z) = self.z { write!(f, " {}", z)?; } if let Some(m) = self.m { write!(f, " {}", m)?; } Ok(()) } } impl<T> FromTokens<T> for Coord<T> ...
fmt
identifier_name
coord.rs
// Copyright 2014-2015 The GeoRust Developers // // 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 a...
#[test] fn write_3d_coord() { let coord = Coord { x: 10.1, y: 20.2, z: Some(-30.3), m: None, }; assert_eq!("10.1 20.2 -30.3", format!("{}", coord)); } #[test] fn write_2d_coord_with_linear_referencing_system() { let ...
{ let coord = Coord { x: 10.1, y: 20.2, z: None, m: None, }; assert_eq!("10.1 20.2", format!("{}", coord)); }
identifier_body
rectangle.rs
use rand; use rand::Rng; use point::Point; #[derive(Debug, Hash, Eq, PartialEq)] pub struct Rectangle { pub top_left: Point<i16>, pub bottom_right: Point<i16>, } impl Rectangle { pub fn new(top_left: Point<i16>, (width, height): (u8, u8)) -> Rectangle { Rectangle { top_left: top_left,...
pub fn clamp_to(&mut self, (left, top): (i16, i16), (right, bottom): (i16, i16)) { if self.top_left.x < left { let diff = left - self.top_left.x; self.top_left.x += diff; self.bottom_right.x += diff; } if self.top_left.y < top { let diff = to...
{ self.top_left.x <= other.bottom_right.x && self.bottom_right.x >= other.top_left.x && self.top_left.y <= other.bottom_right.y && self.bottom_right.y >= other.top_left.y }
identifier_body
rectangle.rs
use rand::Rng; use point::Point; #[derive(Debug, Hash, Eq, PartialEq)] pub struct Rectangle { pub top_left: Point<i16>, pub bottom_right: Point<i16>, } impl Rectangle { pub fn new(top_left: Point<i16>, (width, height): (u8, u8)) -> Rectangle { Rectangle { top_left: top_left, ...
use rand;
random_line_split
rectangle.rs
use rand; use rand::Rng; use point::Point; #[derive(Debug, Hash, Eq, PartialEq)] pub struct Rectangle { pub top_left: Point<i16>, pub bottom_right: Point<i16>, } impl Rectangle { pub fn new(top_left: Point<i16>, (width, height): (u8, u8)) -> Rectangle { Rectangle { top_left: top_left,...
if self.top_left.y < top { let diff = top - self.top_left.y; self.top_left.y += diff; self.bottom_right.y += diff; } if self.bottom_right.x > right { let diff = right - self.bottom_right.x; self.top_left.x += diff; self.bo...
{ let diff = left - self.top_left.x; self.top_left.x += diff; self.bottom_right.x += diff; }
conditional_block
rectangle.rs
use rand; use rand::Rng; use point::Point; #[derive(Debug, Hash, Eq, PartialEq)] pub struct Rectangle { pub top_left: Point<i16>, pub bottom_right: Point<i16>, } impl Rectangle { pub fn new(top_left: Point<i16>, (width, height): (u8, u8)) -> Rectangle { Rectangle { top_left: top_left,...
(&mut self, (left, top): (i16, i16), (right, bottom): (i16, i16)) { if self.top_left.x < left { let diff = left - self.top_left.x; self.top_left.x += diff; self.bottom_right.x += diff; } if self.top_left.y < top { let diff = top - self.top_left.y; ...
clamp_to
identifier_name
templates.rs
/// Wrapper around the ``liquid`` crate to handle templating. use liquid::ParserBuilder; use std::{ fs::{create_dir_all, File}, io::Write, path::{Path, PathBuf}, }; use crate::error::{Result, ResultExt}; pub use liquid::value::{Object as Parameters, Value}; mod external { include!(concat!(env!("OUT_...
#[cfg(target_os = "macos")] { params.insert("graphics_backend".into(), Value::scalar("metal")); } #[cfg(not(target_os = "macos"))] { params.insert("graphics_backend".into(), Value::scalar("vulkan")); } } let params = &params; let temp...
{ let parser = ParserBuilder::with_liquid().build().unwrap(); let template_map = external::template_files(); let template_versions = template_map .keys() .map(|v| semver::Version::parse(v).unwrap()); let version: String = match version { Some(ref ver) => semver::Version::parse(ve...
identifier_body
templates.rs
/// Wrapper around the ``liquid`` crate to handle templating. use liquid::ParserBuilder; use std::{ fs::{create_dir_all, File}, io::Write, path::{Path, PathBuf}, }; use crate::error::{Result, ResultExt}; pub use liquid::value::{Object as Parameters, Value}; mod external { include!(concat!(env!("OUT_...
; #[cfg(target_os = "windows")] { use regex::Regex; out = Regex::new("(?P<last>[^\r])\n") .unwrap() .replace_all(&out, "$last\r\n") .to_string(); } #[cfg(not(target_os = "windows"))] { out = out.re...
{ content.to_owned() }
conditional_block
templates.rs
/// Wrapper around the ``liquid`` crate to handle templating. use liquid::ParserBuilder; use std::{ fs::{create_dir_all, File}, io::Write, path::{Path, PathBuf}, }; use crate::error::{Result, ResultExt}; pub use liquid::value::{Object as Parameters, Value}; mod external { include!(concat!(env!("OUT_...
( template: &str, version: &Option<String>, no_defaults: bool, output: &Path, params: &Parameters, ) -> Result<()> { let parser = ParserBuilder::with_liquid().build().unwrap(); let template_map = external::template_files(); let template_versions = template_map .keys() .map(...
deploy
identifier_name
templates.rs
/// Wrapper around the ``liquid`` crate to handle templating. use liquid::ParserBuilder; use std::{ fs::{create_dir_all, File}, io::Write, path::{Path, PathBuf}, }; use crate::error::{Result, ResultExt}; pub use liquid::value::{Object as Parameters, Value}; mod external { include!(concat!(env!("OUT_...
.ok_or_else(|| format!("No template for version {}", version))?; for &(path, content) in template_files.iter() { let mut path = path.to_owned(); let is_parsed = path.ends_with(LIQUID_TEMPLATE_EXTENSION); if is_parsed { let len = path.len(); path.truncate(len ...
random_line_split
channel.rs
use std::collections::HashSet; use ircnvim::user::User; const CHANNEL_STARTING_CHARACTERS: &'static str = "#&+!~"; pub trait IsChannelName { fn is_channel_name(&self) -> bool; } impl<'a> IsChannelName for &'a str { fn is_channel_name(&self) -> bool { return self.chars().nth(0).and_then(|c| CHANNEL_ST...
mod tests { use super::*; #[test] fn test_is_channel_name() { assert!("##c".to_string().is_channel_name()); assert!("&mychan".is_channel_name()); assert!("~otherchan".is_channel_name()); } }
} } #[cfg(test)]
random_line_split
channel.rs
use std::collections::HashSet; use ircnvim::user::User; const CHANNEL_STARTING_CHARACTERS: &'static str = "#&+!~"; pub trait IsChannelName { fn is_channel_name(&self) -> bool; } impl<'a> IsChannelName for &'a str { fn is_channel_name(&self) -> bool { return self.chars().nth(0).and_then(|c| CHANNEL_ST...
} pub struct Channel { pub name: String, pub topic: Option<String>, users: HashSet<User> } impl Channel { pub fn new(name: &str) -> Channel { return Channel { name: name.to_string(), topic: None, users: HashSet::new() }; } pub fn add_user(&...
{ return (&self[..]).is_channel_name(); }
identifier_body
channel.rs
use std::collections::HashSet; use ircnvim::user::User; const CHANNEL_STARTING_CHARACTERS: &'static str = "#&+!~"; pub trait IsChannelName { fn is_channel_name(&self) -> bool; } impl<'a> IsChannelName for &'a str { fn is_channel_name(&self) -> bool { return self.chars().nth(0).and_then(|c| CHANNEL_ST...
(&mut self, user: &User, new_nick: &str) { self.users.remove(user); self.users.insert(User::from_nick(new_nick.to_string())); } pub fn is_user_present(&self, user: &User) -> bool { return self.users.contains(user); } pub fn set_topic(&mut self, topic: String) { self.top...
rename
identifier_name
render.rs
// pub use primitive::{Sphere}; // pub type Ray = ray::Ray3<float>; // pub type Point = Point<float>; use super::Float; use nalgebra as na; use rayon::prelude::*; use std::cmp; use truescad_luascad::implicit3d::Object; const EPSILON: Float = 0.003; const APPROX_SLACK: Float = 0.1; const FOCAL_FACTOR: Float = 36. /*...
(&mut self, x: Float, y: Float) { let v = na::Vector3::new(-x as Float, y as Float, 0.); self.trans = self.trans.append_translation(&v); } fn cast_ray( &self, obj: &dyn Object<Float>, r: &Ray, light_dir: &na::Vector3<Float>, origin_value: Float, ) -> ...
translate_from_screen
identifier_name
render.rs
// pub use primitive::{Sphere}; // pub type Ray = ray::Ray3<float>; // pub type Point = Point<float>; use super::Float; use nalgebra as na; use rayon::prelude::*; use std::cmp; use truescad_luascad::implicit3d::Object; const EPSILON: Float = 0.003; const APPROX_SLACK: Float = 0.1; const FOCAL_FACTOR: Float = 36. /*...
if value < self.epsilon { break; } } let norm = obj.normal(&cr.origin); let dot = norm.dot(light_dir); if dot < 0. { return (iter, 0.); } (iter, dot) } pub fn draw_on_buf(&self, buf: &mut [u8], width: i32, hei...
{ return (iter, 0.); }
conditional_block
render.rs
// pub use primitive::{Sphere}; // pub type Ray = ray::Ray3<float>; // pub type Point = Point<float>; use super::Float; use nalgebra as na; use rayon::prelude::*; use std::cmp; use truescad_luascad::implicit3d::Object; const EPSILON: Float = 0.003; const APPROX_SLACK: Float = 0.1; const FOCAL_FACTOR: Float = 36. /*...
.max(my_obj.bbox().max.y.abs().max(my_obj.bbox().min.y.abs())) .max(my_obj.bbox().max.z.abs().max(my_obj.bbox().min.z.abs())) * 2.; } 0. } } impl Default for Renderer { fn default() -> Self { Self::new() } }
.max(my_obj.bbox().min.x.abs())
random_line_split
kailua-check-test.rs
#[macro_use] extern crate log; extern crate env_logger; extern crate clap; extern crate kailua_test; extern crate kailua_env; extern crate kailua_diag; extern crate kailua_syntax; extern crate kailua_types; extern crate kailua_check; use std::str; use std::usize; use std::cell::RefCell; use std::rc::Rc; use std::colle...
, Err(e) => { info!("check failed: {:?}", e); format!("error") }, } } } fn main() { env_logger::init().unwrap(); kailua_test::Tester::new("kailua-check-test", Testing::new()) .feature("no_implicit_func_sig", cfg!(feature = "no_implicit_...
{ if report.can_continue() { format!("ok") } else { info!("check failed due to prior errors"); format!("error") } }
conditional_block
kailua-check-test.rs
#[macro_use] extern crate log; extern crate env_logger; extern crate clap; extern crate kailua_test; extern crate kailua_env; extern crate kailua_diag; extern crate kailua_syntax; extern crate kailua_types; extern crate kailua_check; use std::str; use std::usize; use std::cell::RefCell; use std::rc::Rc; use std::colle...
} impl kailua_test::Testing for Testing { fn augment_args<'a, 'b: 'a>(&self, app: App<'a, 'b>) -> App<'a, 'b> { app.arg( Arg::with_name("note_spanned_infos") .short("s") .long("note-spanned-infos") .help("Displays a list of spanned informations.\n\ ...
{ Testing { note_spanned_infos: false } }
identifier_body
kailua-check-test.rs
#[macro_use] extern crate log; extern crate env_logger; extern crate clap; extern crate kailua_test; extern crate kailua_env; extern crate kailua_diag; extern crate kailua_syntax; extern crate kailua_types; extern crate kailua_check; use std::str; use std::usize; use std::cell::RefCell; use std::rc::Rc; use std::colle...
impl Testing { fn new() -> Testing { Testing { note_spanned_infos: false } } } impl kailua_test::Testing for Testing { fn augment_args<'a, 'b: 'a>(&self, app: App<'a, 'b>) -> App<'a, 'b> { app.arg( Arg::with_name("note_spanned_infos") .short("s") ....
use kailua_check::env::Context; struct Testing { note_spanned_infos: bool, }
random_line_split
kailua-check-test.rs
#[macro_use] extern crate log; extern crate env_logger; extern crate clap; extern crate kailua_test; extern crate kailua_env; extern crate kailua_diag; extern crate kailua_syntax; extern crate kailua_types; extern crate kailua_check; use std::str; use std::usize; use std::cell::RefCell; use std::rc::Rc; use std::colle...
(&self, source: Rc<RefCell<Source>>, span: Span, filespans: &HashMap<String, Span>, report: Rc<Report>) -> String { let chunk = match parse_chunk(&source.borrow(), span, &*report) { Ok(chunk) => chunk, Err(_) => return format!("parse error"), }; struct Opts { ...
run
identifier_name
day9.rs
use std::io::prelude::*; #[derive(Debug, Default, PartialEq)] struct Marker { length: u32, multiplier: u32, } fn main()
fn decoding_nested(line: &str) -> u64 { let (ret, _) = decoding_nested_rec(&mut line.chars(), std::u64::MAX); ret } fn decoding_nested_rec(it: &mut std::str::Chars, length: u64) -> (u64, u64) { let mut total_length: u64 = 0; let mut char_read: u64 = 0; while char_read < length { let lett...
{ let mut inputs = std::fs::File::open("day9_inputs.txt").expect("Cannot open input file"); let mut line = String::new(); inputs.read_to_string(&mut line).expect("Cannot read line"); line.pop(); // Last char is a new line. let length = decoding_light(line.clone()); println!("Length: {}", lengt...
identifier_body
day9.rs
use std::io::prelude::*; #[derive(Debug, Default, PartialEq)] struct Marker { length: u32, multiplier: u32, } fn main() { let mut inputs = std::fs::File::open("day9_inputs.txt").expect("Cannot open input file"); let mut line = String::new(); inputs.read_to_string(&mut line).expect("Cannot read lin...
assert_eq!(decoding_nested(input), 20); let input = "(27x12)(20x12)(13x14)(7x10)(1x12)A"; assert_eq!(decoding_nested(input), 241920); let input = "(25x3)(3x3)ABC(2x3)XY(5x2)PQRSTX(18x9)(3x2)TWO(5x7)SEVEN"; assert_eq!(decoding_nested(input), 445); } fn decoding_light(line: String) -> u32 { let...
let input = "(1x1)B"; assert_eq!(decoding_nested(input), 1); let input = "X(8x2)(3x3)ABCY";
random_line_split
day9.rs
use std::io::prelude::*; #[derive(Debug, Default, PartialEq)] struct Marker { length: u32, multiplier: u32, } fn main() { let mut inputs = std::fs::File::open("day9_inputs.txt").expect("Cannot open input file"); let mut line = String::new(); inputs.read_to_string(&mut line).expect("Cannot read lin...
() { assert_eq!(read_number(&mut "123".chars()), (123, 3)); assert_eq!(read_number(&mut "1".chars()), (1, 1)); assert_eq!(read_number(&mut "42)".chars()), (42, 2)); assert_eq!(read_number(&mut "2x".chars()), (2, 1)); }
read_number_test
identifier_name
regions-close-over-type-parameter-2.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 ...
}
repeater3(tmp1) };
random_line_split
regions-close-over-type-parameter-2.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 ...
() { // Error results because the type of is inferred to be // ~Repeat<&'blk int> where blk is the lifetime of the block below. let _ = { let tmp0 = 3i; let tmp1 = &tmp0; //~ ERROR `tmp0` does not live long enough repeater3(tmp1) }; }
main
identifier_name
regions-close-over-type-parameter-2.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 ...
} fn repeater3<'a,A:'a>(v: A) -> Box<Foo+'a> { box v as Box<Foo+'a> } fn main() { // Error results because the type of is inferred to be // ~Repeat<&'blk int> where blk is the lifetime of the block below. let _ = { let tmp0 = 3i; let tmp1 = &tmp0; //~ ERROR `tmp0` does not live long ...
{ }
identifier_body
gamepadlist.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/. */ use dom::bindings::cell::DomRefCell; use dom::bindings::codegen::Bindings::GamepadListBinding; use dom::bindings::...
} } } impl GamepadListMethods for GamepadList { // https://w3c.github.io/gamepad/#dom-navigator-getgamepads fn Length(&self) -> u32 { self.list.borrow().len() as u32 } // https://w3c.github.io/gamepad/#dom-navigator-getgamepads fn Item(&self, index: u32) -> Option<DomRoot<Game...
{ self.list.borrow_mut().push(Dom::from_ref(&*gamepad)); // Ensure that the gamepad has the correct index gamepad.update_index(self.list.borrow().len() as i32 - 1); }
conditional_block
gamepadlist.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/. */ use dom::bindings::cell::DomRefCell; use dom::bindings::codegen::Bindings::GamepadListBinding; use dom::bindings::...
pub fn new(global: &GlobalScope, list: &[&Gamepad]) -> DomRoot<GamepadList> { reflect_dom_object(box GamepadList::new_inherited(list), global, GamepadListBinding::Wrap) } pub fn add_if_not_exists(&self, gamepads: &[DomRoot<Gamepad>]) { ...
{ GamepadList { reflector_: Reflector::new(), list: DomRefCell::new(list.iter().map(|g| Dom::from_ref(&**g)).collect()) } }
identifier_body
gamepadlist.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/. */ use dom::bindings::cell::DomRefCell; use dom::bindings::codegen::Bindings::GamepadListBinding; use dom::bindings::...
(&self, gamepads: &[DomRoot<Gamepad>]) { for gamepad in gamepads { if!self.list.borrow().iter().any(|g| g.gamepad_id() == gamepad.gamepad_id()) { self.list.borrow_mut().push(Dom::from_ref(&*gamepad)); // Ensure that the gamepad has the correct index ga...
add_if_not_exists
identifier_name
gamepadlist.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/. */ use dom::bindings::cell::DomRefCell; use dom::bindings::codegen::Bindings::GamepadListBinding; use dom::bindings::...
} } } } impl GamepadListMethods for GamepadList { // https://w3c.github.io/gamepad/#dom-navigator-getgamepads fn Length(&self) -> u32 { self.list.borrow().len() as u32 } // https://w3c.github.io/gamepad/#dom-navigator-getgamepads fn Item(&self, index: u32) -> Option...
self.list.borrow_mut().push(Dom::from_ref(&*gamepad)); // Ensure that the gamepad has the correct index gamepad.update_index(self.list.borrow().len() as i32 - 1);
random_line_split
whoami.rs
#![crate_name = "whoami"] /* * This file is part of the uutils coreutils package. * * (c) Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* last synced with: whoami (GNU coreutils) 8.21 */ ex...
let mut opts = Options::new(); opts.optflag("h", "help", "display this help and exit"); opts.optflag("V", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => crash!(1, "{}", f), }; if matches.opt_present("help") ...
random_line_split
whoami.rs
#![crate_name = "whoami"] /* * This file is part of the uutils coreutils package. * * (c) Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* last synced with: whoami (GNU coreutils) 8.21 */ ex...
println!("{} {}", NAME, VERSION); return 0; } exec(); 0 } pub fn exec() { unsafe { let username = platform::getusername(); println!("{}", username); } }
{ let mut opts = Options::new(); opts.optflag("h", "help", "display this help and exit"); opts.optflag("V", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => crash!(1, "{}", f), }; if matches.opt_present("help"...
identifier_body
whoami.rs
#![crate_name = "whoami"] /* * This file is part of the uutils coreutils package. * * (c) Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* last synced with: whoami (GNU coreutils) 8.21 */ ex...
() { unsafe { let username = platform::getusername(); println!("{}", username); } }
exec
identifier_name
mipsel.rs
// Copyright 2012-2015 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...
(target_triple: String, target_os: abi::Os) -> target_strs::t { return target_strs::t { module_asm: "".to_string(), data_layout: match target_os { abi::OsMacos => { "e-p:32:32:32\ -i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\ -f32:32:32-f64:64:6...
get_target_strs
identifier_name
mipsel.rs
// Copyright 2012-2015 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...
abi::OsWindows => { "e-p:32:32:32\ -i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\ -f32:32:32-f64:64:64\ -v64:64:64-v128:64:128\ -a:0:64-n32".to_string() } abi::OsLinux => { "e-p:32:32:32\ ...
{ return target_strs::t { module_asm: "".to_string(), data_layout: match target_os { abi::OsMacos => { "e-p:32:32:32\ -i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\ -f32:32:32-f64:64:64\ -v64:64:64-v128:64:128\ -a:...
identifier_body
mipsel.rs
// Copyright 2012-2015 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...
-f32:32:32-f64:64:64\ -v64:64:64-v128:64:128\ -a:0:64-n32".to_string() } abi::OsFreebsd | abi::OsDragonfly | abi::OsBitrig | abi::OsOpenbsd => { "e-p:32:32:32\ -i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\ -...
} abi::OsAndroid => { "e-p:32:32:32\ -i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
random_line_split
htmlparamelement.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/. */ use dom::bindings::codegen::Bindings::HTMLParamElementBinding; use dom::bindings::js::Root; use dom::bindings::str...
(local_name: LocalName, prefix: Option<DOMString>, document: &Document) -> HTMLParamElement { HTMLParamElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document) } } #[allow(unrooted_must_root)] pub f...
new_inherited
identifier_name
htmlparamelement.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/. */ use dom::bindings::codegen::Bindings::HTMLParamElementBinding; use dom::bindings::js::Root; use dom::bindings::str...
} } #[allow(unrooted_must_root)] pub fn new(local_name: LocalName, prefix: Option<DOMString>, document: &Document) -> Root<HTMLParamElement> { Node::reflect_node(box HTMLParamElement::new_inherited(local_name, prefix, document), docum...
htmlelement: HTMLElement::new_inherited(local_name, prefix, document)
random_line_split
htmlparamelement.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/. */ use dom::bindings::codegen::Bindings::HTMLParamElementBinding; use dom::bindings::js::Root; use dom::bindings::str...
}
{ Node::reflect_node(box HTMLParamElement::new_inherited(local_name, prefix, document), document, HTMLParamElementBinding::Wrap) }
identifier_body
trait-impl-fn-incompatibility.rs
// Copyright 2016 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 ...
(x: i16) { } //~ ERROR incompatible type fn bar(&mut self, bar: &Bar) { } //~ ERROR incompatible type } fn main() { }
foo
identifier_name
trait-impl-fn-incompatibility.rs
// Copyright 2016 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // rustc-env:RUST_NEW_ERROR_FORMAT trait Foo { fn foo(x: u16); fn bar(&mut self, bar: &mut Bar); } struct Bar; impl Foo for Bar { fn foo(x:...
random_line_split
expect-infer-var-supply-ty-with-free-region.rs
// Copyright 2016 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 ...
where F: FnOnce(A, &u32) { } fn foo() { // This version works; we infer `A` to be `u32`, and take the type // of `y` to be `&u32`. with_closure(|x: u32, y| {}); } fn bar<'x>(x: &'x u32) { // Same. with_closure(|x: &'x u32, y| {}); } fn main() { }
fn with_closure<F, A>(_: F)
random_line_split
expect-infer-var-supply-ty-with-free-region.rs
// Copyright 2016 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 ...
<'x>(x: &'x u32) { // Same. with_closure(|x: &'x u32, y| {}); } fn main() { }
bar
identifier_name
expect-infer-var-supply-ty-with-free-region.rs
// Copyright 2016 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
post.rs
#[macro_use] extern crate rustful; use std::io::{self, Read}; use std::fs::File; use std::path::Path; use std::borrow::Cow; use std::error::Error; use rustful::{Server, Context, Response, Log, Handler}; use rustful::context::body::ExtQueryBody; use rustful::StatusCode::{InternalServerError, BadRequest}; fn say_hello...
} else { Cow::Borrowed(&files.form) }; //Insert the content into the page and write it to the response let complete_page = files.page.replace("{}", &content); response.send(complete_page); } //Dodge an ICE, related to functions as handlers. struct HandlerFn(fn(Context, Response)); impl Ha...
}; //Format the name or use the cached form let content = if let Some(name) = body.get("name") { Cow::Owned(format!("<p>Hello, {}!</p>", name))
random_line_split
post.rs
#[macro_use] extern crate rustful; use std::io::{self, Read}; use std::fs::File; use std::path::Path; use std::borrow::Cow; use std::error::Error; use rustful::{Server, Context, Response, Log, Handler}; use rustful::context::body::ExtQueryBody; use rustful::StatusCode::{InternalServerError, BadRequest}; fn say_hello...
}; let files: &Files = if let Some(files) = context.global.get() { files } else { //Oh no! Why is the global data not a File instance?! context.log.error("the global data should be of the type `Files`, but it's not"); response.set_status(InternalServerError); return...
{ //Oh no! Could not read the body response.set_status(BadRequest); return; }
conditional_block
post.rs
#[macro_use] extern crate rustful; use std::io::{self, Read}; use std::fs::File; use std::path::Path; use std::borrow::Cow; use std::error::Error; use rustful::{Server, Context, Response, Log, Handler}; use rustful::context::body::ExtQueryBody; use rustful::StatusCode::{InternalServerError, BadRequest}; fn say_hello...
Err(e) => println!("could not start server: {}", e.description()) } } fn read_string<P: AsRef<Path>>(path: P) -> io::Result<String> { //Read file into a string let mut string = String::new(); File::open(path).and_then(|mut f| f.read_to_string(&mut string)).map(|_| string) } //We want to store...
{ println!("Visit http://localhost:8080 to try this example."); //Preload the files let files = Files { page: read_string("examples/post/page.html").unwrap(), form: read_string("examples/post/form.html").unwrap() }; //Handlers implements the Router trait, so it can be passed to the...
identifier_body
post.rs
#[macro_use] extern crate rustful; use std::io::{self, Read}; use std::fs::File; use std::path::Path; use std::borrow::Cow; use std::error::Error; use rustful::{Server, Context, Response, Log, Handler}; use rustful::context::body::ExtQueryBody; use rustful::StatusCode::{InternalServerError, BadRequest}; fn
(mut context: Context, mut response: Response) { let body = match context.body.read_query_body() { Ok(body) => body, Err(_) => { //Oh no! Could not read the body response.set_status(BadRequest); return; } }; let files: &Files = if let Some(files) ...
say_hello
identifier_name
layer.rs
use crate::*; #[derive(Clone, Debug)] pub struct Layer { crate neurons: Vec<Neuron>, } impl Layer { pub fn new(neurons: Vec<Neuron>) -> Self { assert!(!neurons.is_empty()); assert!(neurons .iter() .all(|neuron| neuron.weights.len() == neurons[0].weights.len())); ...
() { let neurons = ( Neuron::new(0.0, vec![0.1, 0.2, 0.3]), Neuron::new(0.0, vec![0.4, 0.5, 0.6]), ); let layer = Layer::new(vec![neurons.0.clone(), neurons.1.clone()]); let inputs = &[-0.5, 0.0, 0.5]; let actual = layer.propa...
test
identifier_name
layer.rs
use crate::*; #[derive(Clone, Debug)] pub struct Layer { crate neurons: Vec<Neuron>, } impl Layer { pub fn new(neurons: Vec<Neuron>) -> Self { assert!(!neurons.is_empty()); assert!(neurons .iter() .all(|neuron| neuron.weights.len() == neurons[0].weights.len())); ...
#[test] fn test() { let neurons = ( Neuron::new(0.0, vec![0.1, 0.2, 0.3]), Neuron::new(0.0, vec![0.4, 0.5, 0.6]), ); let layer = Layer::new(vec![neurons.0.clone(), neurons.1.clone()]); let inputs = &[-0.5, 0.0, 0.5]; ...
} mod propagate { use super::*;
random_line_split
layer.rs
use crate::*; #[derive(Clone, Debug)] pub struct Layer { crate neurons: Vec<Neuron>, } impl Layer { pub fn new(neurons: Vec<Neuron>) -> Self { assert!(!neurons.is_empty()); assert!(neurons .iter() .all(|neuron| neuron.weights.len() == neurons[0].weights.len())); ...
} #[cfg(test)] mod tests { use super::*; mod random { use super::*; use rand::SeedableRng; use rand_chacha::ChaCha8Rng; #[test] fn test() { let mut rng = ChaCha8Rng::from_seed(Default::default()); let layer = Layer::random(&mut rng, 3, 2); ...
{ self.neurons .iter() .map(|neuron| neuron.propagate(&inputs)) .collect() }
identifier_body
main.rs
extern crate clap; extern crate intcode; // Time Start: Thu, 05 Dec 2019 19:25:20 -0500
// Time Finish 1: Thu, 05 Dec 2019 20:59:57 -0500 (1 hour, 34 minutes, 37 seconds) // Time Finish 2: Thu, 05 Dec 2019 21:11:50 -0500 (11 minutes, 53 seconds) // Time Total: 1 hour, 46 minutes, 30 seconds use clap::{Arg, App}; use intcode::Intcode; fn main() { let matches = App::new("Advent of Code 2019, Day 05")...
random_line_split
main.rs
extern crate clap; extern crate intcode; // Time Start: Thu, 05 Dec 2019 19:25:20 -0500 // Time Finish 1: Thu, 05 Dec 2019 20:59:57 -0500 (1 hour, 34 minutes, 37 seconds) // Time Finish 2: Thu, 05 Dec 2019 21:11:50 -0500 (11 minutes, 53 seconds) // Time Total: 1 hour, 46 minutes, 30 seconds use clap::{Arg, App}; us...
{ let matches = App::new("Advent of Code 2019, Day 05") .arg(Arg::with_name("FILE") .help("Input file to process") .index(1)) .get_matches(); let fname = String::from(matches.value_of("FILE").unwrap_or("05.in")); let mut ic = Intcode::load(&fname); ic.pipe(1); ...
identifier_body
main.rs
extern crate clap; extern crate intcode; // Time Start: Thu, 05 Dec 2019 19:25:20 -0500 // Time Finish 1: Thu, 05 Dec 2019 20:59:57 -0500 (1 hour, 34 minutes, 37 seconds) // Time Finish 2: Thu, 05 Dec 2019 21:11:50 -0500 (11 minutes, 53 seconds) // Time Total: 1 hour, 46 minutes, 30 seconds use clap::{Arg, App}; us...
() { let matches = App::new("Advent of Code 2019, Day 05") .arg(Arg::with_name("FILE") .help("Input file to process") .index(1)) .get_matches(); let fname = String::from(matches.value_of("FILE").unwrap_or("05.in")); let mut ic = Intcode::load(&fname); ic.pipe(1); ...
main
identifier_name
dissimilaroriginwindow.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/. */ use dom::bindings::codegen::Bindings::DissimilarOriginWindowBinding; use dom::bindings::codegen::Bindings::Dissimi...
(&self) -> &MutableOrigin { self.upcast::<GlobalScope>().origin() } } impl DissimilarOriginWindowMethods for DissimilarOriginWindow { // https://html.spec.whatwg.org/multipage/#dom-window fn Window(&self) -> Root<WindowProxy> { Root::from_ref(&*self.window_proxy) } // https://html....
origin
identifier_name
dissimilaroriginwindow.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/. */ use dom::bindings::codegen::Bindings::DissimilarOriginWindowBinding; use dom::bindings::codegen::Bindings::Dissimi...
// https://html.spec.whatwg.org/multipage/#dom-focus fn Focus(&self) { // TODO: Implement x-origin focus } // https://html.spec.whatwg.org/multipage/#dom-location fn Location(&self) -> Root<DissimilarOriginLocation> { self.location.or_init(|| DissimilarOriginLocation::new(self)) ...
{ // TODO: Implement x-origin blur }
identifier_body
dissimilaroriginwindow.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/. */ use dom::bindings::codegen::Bindings::DissimilarOriginWindowBinding; use dom::bindings::codegen::Bindings::Dissimi...
unsafe fn Opener(&self, _: *mut JSContext) -> JSVal { // TODO: Implement x-origin opener UndefinedValue() } #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-opener unsafe fn SetOpener(&self, _: *mut JSContext, _: HandleValue) { // TODO: Implement x-origin...
#[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-opener
random_line_split
solver.rs
use node::{OwnedNode, WeakNode}; use problem::{Problem, Constraint, Action}; use iter::{iter_col, ColumnIterator}; use cover::{try_cover_column, cover_column, uncover_column, try_cover_row, cover_row, uncover_row}; /// A `Solver` consumes a problem and computes solutions to the exact /// cover problem. pub struct Solv...
let con = constraint.unwrap(); if con.borrow().get_count().unwrap() == 0 { return false; } // pick an action for the constraint to satisfy (try_cover_column(&con), iter_col(&con)) }; // Try that action, and retu...
{ solution.extend_from_slice(&self.partial_solution); return true; }
conditional_block
solver.rs
use node::{OwnedNode, WeakNode}; use problem::{Problem, Constraint, Action}; use iter::{iter_col, ColumnIterator}; use cover::{try_cover_column, cover_column, uncover_column, try_cover_row, cover_row, uncover_row}; /// A `Solver` consumes a problem and computes solutions to the exact /// cover problem. pub struct Solv...
} // pick an action for the constraint to satisfy (try_cover_column(&con), iter_col(&con)) }; // Try that action, and return the solution to partial // problem, if possible. for action in action_nodes { let a = self.problem.get_action(&ac...
return false;
random_line_split
solver.rs
use node::{OwnedNode, WeakNode}; use problem::{Problem, Constraint, Action}; use iter::{iter_col, ColumnIterator}; use cover::{try_cover_column, cover_column, uncover_column, try_cover_row, cover_row, uncover_row}; /// A `Solver` consumes a problem and computes solutions to the exact /// cover problem. pub struct Solv...
(&mut self, action: A) -> Result<(), String> { match self.problem.require_row(action) { Ok(_) => { self.partial_solution.push(action); Ok(()) }, Err(s) => { Err(s) } } } /// Return a solution to the ...
require_action
identifier_name
solver.rs
use node::{OwnedNode, WeakNode}; use problem::{Problem, Constraint, Action}; use iter::{iter_col, ColumnIterator}; use cover::{try_cover_column, cover_column, uncover_column, try_cover_row, cover_row, uncover_row}; /// A `Solver` consumes a problem and computes solutions to the exact /// cover problem. pub struct Solv...
// println!("trying action {}", sa.borrow().get_row().unwrap()); // } // add the action the current solution self.current_solution.push(a); cover_row(&action_node); // Choose a new constraint let c = se...
{ if !self.running { self.init(); self.running = true; } let mut s = None; // At each step, take the next action in the iterator. Try to push a new state onto the column. while !self.iter_stack.is_empty() { let next_action = { ...
identifier_body
build.rs
//! This tiny build script ensures that rocket is not compiled with an //! incompatible version of rust. extern crate yansi; extern crate version_check; use yansi::Color::{Red, Yellow, Blue, White}; use version_check::{supports_features, is_min_version, is_min_date}; // Specifies the minimum nightly version needed t...
eprintln!("{}{}{}", Blue.paint("See the getting started guide ("), White.paint("https://rocket.rs/guide/getting-started/"), Blue.paint(") for more information.")); panic!("Aborting compilation due to incompatible compiler.") ...
{ let ok_channel = supports_features(); let ok_version = is_min_version(MIN_VERSION); let ok_date = is_min_date(MIN_DATE); let triple = (ok_channel, ok_version, ok_date); let print_version_err = |version: &str, date: &str| { eprintln!("{} {}. {} {}.", White.paint("Installe...
identifier_body
build.rs
//! This tiny build script ensures that rocket is not compiled with an //! incompatible version of rust. extern crate yansi; extern crate version_check; use yansi::Color::{Red, Yellow, Blue, White}; use version_check::{supports_features, is_min_version, is_min_date}; // Specifies the minimum nightly version needed t...
if!ok_version ||!ok_date { eprintln!("{} {}", Red.paint("Error:").bold(), White.paint("Rocket requires a more recent version of rustc.")); eprintln!("{}{}{}", Blue.paint("Use `"), White.paint("rustu...
{ eprintln!("{} {}", Red.paint("Error:").bold(), White.paint("Rocket requires a nightly or dev version of Rust.")); print_version_err(&*version, &*date); eprintln!("{}{}{}", Blue.paint("See the getting started guide ("...
conditional_block
build.rs
//! This tiny build script ensures that rocket is not compiled with an //! incompatible version of rust. extern crate yansi; extern crate version_check; use yansi::Color::{Red, Yellow, Blue, White}; use version_check::{supports_features, is_min_version, is_min_date};
fn main() { let ok_channel = supports_features(); let ok_version = is_min_version(MIN_VERSION); let ok_date = is_min_date(MIN_DATE); let triple = (ok_channel, ok_version, ok_date); let print_version_err = |version: &str, date: &str| { eprintln!("{} {}. {} {}.", White.paint...
// Specifies the minimum nightly version needed to compile Rocket. const MIN_DATE: &'static str = "2017-07-09"; const MIN_VERSION: &'static str = "1.20.0-nightly";
random_line_split
build.rs
//! This tiny build script ensures that rocket is not compiled with an //! incompatible version of rust. extern crate yansi; extern crate version_check; use yansi::Color::{Red, Yellow, Blue, White}; use version_check::{supports_features, is_min_version, is_min_date}; // Specifies the minimum nightly version needed t...
() { let ok_channel = supports_features(); let ok_version = is_min_version(MIN_VERSION); let ok_date = is_min_date(MIN_DATE); let triple = (ok_channel, ok_version, ok_date); let print_version_err = |version: &str, date: &str| { eprintln!("{} {}. {} {}.", White.paint("Insta...
main
identifier_name
net.rs
//! A trait to represent a stream use std::io; use std::io::{ErrorKind, Read, Write}; use std::net::{SocketAddr, TcpStream}; use std::fmt; use std::fmt::{Debug, Formatter}; use openssl::ssl::{SslContext, SslStream}; /// A trait for the concept of opening a stream pub trait Connector: Sized { /// Opens a connecti...
Ok(ssl_stream) => NetworkStream::Ssl(ssl_stream), Err(err) => return Err(io::Error::new(ErrorKind::Other, err)), }, NetworkStream::Ssl(stream) => NetworkStream::Ssl(stream), }; Ok(()) } } /// Represents the different types of underlying netwo...
fn upgrade_tls(&mut self, ssl_context: &SslContext) -> io::Result<()> { *self = match self.clone() { NetworkStream::Plain(stream) => match SslStream::connect_generic(ssl_context, stream) {
random_line_split
net.rs
//! A trait to represent a stream use std::io; use std::io::{ErrorKind, Read, Write}; use std::net::{SocketAddr, TcpStream}; use std::fmt; use std::fmt::{Debug, Formatter}; use openssl::ssl::{SslContext, SslStream}; /// A trait for the concept of opening a stream pub trait Connector: Sized { /// Opens a connecti...
} impl Read for NetworkStream { #[inline] fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { match *self { NetworkStream::Plain(ref mut stream) => stream.read(buf), NetworkStream::Ssl(ref mut stream) => stream.read(buf), } } } impl Write for NetworkStream { ...
{ f.write_str("NetworkStream(_)") }
identifier_body
net.rs
//! A trait to represent a stream use std::io; use std::io::{ErrorKind, Read, Write}; use std::net::{SocketAddr, TcpStream}; use std::fmt; use std::fmt::{Debug, Formatter}; use openssl::ssl::{SslContext, SslStream}; /// A trait for the concept of opening a stream pub trait Connector: Sized { /// Opens a connecti...
(addr: &SocketAddr, ssl_context: Option<&SslContext>) -> io::Result<NetworkStream> { let tcp_stream = try!(TcpStream::connect(addr)); match ssl_context { Some(context) => match SslStream::connect_generic(context, tcp_stream) { Ok(stream) => Ok(NetworkStream::Ssl(stream)), ...
connect
identifier_name
object-safety-sized-self-generic-method.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 c = CCounter { c: 0 }; tick1(&mut c); assert_eq!(c.tick(), 3); }
identifier_body
object-safety-sized-self-generic-method.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 ...
impl Counter for CCounter { fn tick(&mut self) -> u32 { self.c += 1; self.c } fn with<F:FnOnce(u32)>(&self, f: F) { f(self.c); } } fn tick1<C:Counter>(c: &mut C) { tick2(c); c.with(|i| ()); } fn tick2(c: &mut Counter) { tick3(c); } fn tick3<C:?Sized+Counter>(c: &mut C) { c.tick(); c.tick(...
struct CCounter { c: u32 }
random_line_split
object-safety-sized-self-generic-method.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 c = CCounter { c: 0 }; tick1(&mut c); assert_eq!(c.tick(), 3); }
main
identifier_name
remerge_source.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use crate::common::{ find_source_config, find_target_bookmark_and_value, find_target_sync_config, MegarepoOp, }; use anyhow::anyhow; us...
let move_commit = &moved_commits[0]; let move_commit = target_repo .changeset(move_commit.1.moved.get_changeset_id()) .await? .ok_or_else(|| { MegarepoError::internal(anyhow!("programming error - moved changeset not found!")) })?; ...
{ return Err( anyhow!("unexpected number of move commits {}", moved_commits.len()).into(), ); }
conditional_block
remerge_source.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */
}; use anyhow::anyhow; use context::CoreContext; use megarepo_config::{MononokeMegarepoConfigs, Target}; use megarepo_error::MegarepoError; use megarepo_mapping::SourceName; use mononoke_api::{Mononoke, RepoContext}; use mononoke_types::ChangesetId; use mutable_renames::MutableRenames; use std::sync::Arc; // remerge_s...
use crate::common::{ find_source_config, find_target_bookmark_and_value, find_target_sync_config, MegarepoOp,
random_line_split
remerge_source.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use crate::common::{ find_source_config, find_target_bookmark_and_value, find_target_sync_config, MegarepoOp, }; use anyhow::anyhow; us...
} impl<'a> RemergeSource<'a> { pub fn new( megarepo_configs: &'a Arc<dyn MononokeMegarepoConfigs>, mononoke: &'a Arc<Mononoke>, mutable_renames: &'a Arc<MutableRenames>, ) -> Self { Self { megarepo_configs, mononoke, mutable_renames, ...
{ &self.mononoke }
identifier_body
remerge_source.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use crate::common::{ find_source_config, find_target_bookmark_and_value, find_target_sync_config, MegarepoOp, }; use anyhow::anyhow; us...
( megarepo_configs: &'a Arc<dyn MononokeMegarepoConfigs>, mononoke: &'a Arc<Mononoke>, mutable_renames: &'a Arc<MutableRenames>, ) -> Self { Self { megarepo_configs, mononoke, mutable_renames, } } pub async fn run( self, ...
new
identifier_name
partial_eq.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 ...
macro_rules! md { ($name:expr, $f:ident) => { { let inline = cx.meta_word(span, Symbol::intern("inline")); let attrs = vec![cx.attribute(span, inline)]; MethodDef { name: $name, generics: LifetimeBounds::empty(), explicit_...
{ cs_op(cx, span, substr, BinOpKind::Ne, BinOpKind::Or, false) }
identifier_body
partial_eq.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 ...
(cx: &mut ExtCtxt, span: Span, substr: &Substructure, op: BinOpKind, combiner: BinOpKind, base: bool) -> P<Expr> { let op = |cx: &mut ExtCtxt, span: Span, self_f: P<Expr>, other_fs: &[P<Expr>]| { let other_f = match (o...
cs_op
identifier_name
partial_eq.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 ...
_ => cx.span_bug(span, "not exactly 2 arguments in `derive(PartialEq)`"), }; cx.expr_binary(span, op, self_f, other_f.clone()) }; cs_fold1(true, // use foldl |cx, span, subexpr, self_f, other_fs| { let eq = op(cx, span, self_f, other_...
random_line_split
mod.rs
extern crate discotech; #[macro_use] extern crate log; extern crate log4rs; use discotech::{Serverset, DiscoConfig, read_config}; use std::env; fn initialize_logging() { let root = log4rs::config::Root::builder(log::LogLevelFilter::Debug) .appender("stderr".to_string()); let console = Box::new(log4rs::appende...
#[test] fn integration() { let config_file_loc = match env::var("DISCO_CONF") { Err(_) => panic!("Please set the DISCO_CONF environment variable"), Ok(location) => location, }; match read_config(config_file_loc) { Err(reason) => panic!("Unable to read configuration; bailing: {}", reason), Ok(con...
{ initialize_logging(); let serverset = *Box::new(Serverset::new(config)); debug!("THINGS"); serverset.update_members(); for member in serverset.members.read().unwrap().iter() { debug!("Member: {:?}", member); } }
identifier_body
mod.rs
extern crate discotech; #[macro_use] extern crate log; extern crate log4rs; use discotech::{Serverset, DiscoConfig, read_config}; use std::env; fn
() { let root = log4rs::config::Root::builder(log::LogLevelFilter::Debug) .appender("stderr".to_string()); let console = Box::new(log4rs::appender::ConsoleAppender::builder().build()); let config = log4rs::config::Config::builder(root.build()) .appender(log4rs::config::Appender::builder("stderr".to_string()...
initialize_logging
identifier_name
mod.rs
extern crate discotech; #[macro_use] extern crate log; extern crate log4rs; use discotech::{Serverset, DiscoConfig, read_config};
fn initialize_logging() { let root = log4rs::config::Root::builder(log::LogLevelFilter::Debug) .appender("stderr".to_string()); let console = Box::new(log4rs::appender::ConsoleAppender::builder().build()); let config = log4rs::config::Config::builder(root.build()) .appender(log4rs::config::Appender::builde...
use std::env;
random_line_split
main.rs
use std::env; use std::process::exit; use std::sync::{Arc, RwLock}; use std::{thread, time}; use varlink::{Connection, VarlinkService}; use crate::org_example_more::*; // Dynamically build the varlink rust code. mod org_example_more; #[cfg(test)] mod test; pub type Result<T> = std::result::Result<T, Box<dyn std::e...
}); } // Client fn run_client(connection: Arc<RwLock<varlink::Connection>>) -> Result<()> { /* let new_addr = { let conn = connection.read().unwrap(); conn.address() }; */ let mut iface = org_example_more::VarlinkClient::new(connection); //let con2 = varlink::Connection::...
{ eprintln!("error: {:?}", err); 1 }
conditional_block
main.rs
use std::env; use std::process::exit; use std::sync::{Arc, RwLock}; use std::{thread, time}; use varlink::{Connection, VarlinkService}; use crate::org_example_more::*; // Dynamically build the varlink rust code. mod org_example_more; #[cfg(test)] mod test; pub type Result<T> = std::result::Result<T, Box<dyn std::e...
{ let myexamplemore = MyOrgExampleMore { sleep_duration }; let myinterface = org_example_more::new(Box::new(myexamplemore)); let service = VarlinkService::new( "org.varlink", "test service", "0.1", "http://varlink.org", vec![Box::new(myinterface)], ); varlink:...
identifier_body
main.rs
use std::env; use std::process::exit; use std::sync::{Arc, RwLock}; use std::{thread, time}; use varlink::{Connection, VarlinkService}; use crate::org_example_more::*; // Dynamically build the varlink rust code. mod org_example_more; #[cfg(test)] mod test; pub type Result<T> = std::result::Result<T, Box<dyn std::e...
(&self, call: &mut dyn Call_StopServing) -> varlink::Result<()> { call.reply()?; Err(varlink::ErrorKind::ConnectionClosed.into()) } fn test_more(&self, call: &mut dyn Call_TestMore, n: i64) -> varlink::Result<()> { if!call.wants_more() { return call.reply_test_more_error("cal...
stop_serving
identifier_name
main.rs
use std::env; use std::process::exit; use std::sync::{Arc, RwLock}; use std::{thread, time}; use varlink::{Connection, VarlinkService}; use crate::org_example_more::*; // Dynamically build the varlink rust code. mod org_example_more; #[cfg(test)] mod test; pub type Result<T> = std::result::Result<T, Box<dyn std::e...
fn stop_serving(&self, call: &mut dyn Call_StopServing) -> varlink::Result<()> { call.reply()?; Err(varlink::ErrorKind::ConnectionClosed.into()) } fn test_more(&self, call: &mut dyn Call_TestMore, n: i64) -> varlink::Result<()> { if!call.wants_more() { return call.reply_t...
random_line_split