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
ac.rs
//! Actor-critic algorithms. use crate::{ domains::Transition, fa::StateActionUpdate, policies::Policy, Function, Handler, }; pub trait Critic<'t, S: 't, A: 't> { fn target(&self, t: &'t Transition<S, A>) -> f64; } impl<'t, F, S: 't, A: 't> Critic<'t, S, A> for F where F: Fn(&'t Transition<S, ...
(q_func: Q, policy: P, alpha: f64) -> Self { ActorCritic { critic: QCritic(q_func), policy, alpha, } } } impl<V, P> ActorCritic<TDCritic<V>, P> { pub fn tdac(v_func: V, policy: P, alpha: f64, gamma: f64) -> Self { ActorCritic { critic: TDC...
qac
identifier_name
ac.rs
//! Actor-critic algorithms. use crate::{ domains::Transition, fa::StateActionUpdate, policies::Policy, Function, Handler, }; pub trait Critic<'t, S: 't, A: 't> { fn target(&self, t: &'t Transition<S, A>) -> f64; } impl<'t, F, S: 't, A: 't> Critic<'t, S, A> for F where F: Fn(&'t Transition<S, ...
else { let v = self.v_func.evaluate((t.from.state(),)); t.reward + self.gamma * nv - v } } } #[derive(Clone, Debug)] #[cfg_attr( feature = "serde", derive(Serialize, Deserialize), serde(crate = "serde_crate") )] pub struct ActorCritic<C, P> { pub critic: C, pub...
{ t.reward - nv }
conditional_block
ac.rs
//! Actor-critic algorithms. use crate::{ domains::Transition, fa::StateActionUpdate, policies::Policy, Function, Handler, }; pub trait Critic<'t, S: 't, A: 't> { fn target(&self, t: &'t Transition<S, A>) -> f64; } impl<'t, F, S: 't, A: 't> Critic<'t, S, A> for F where F: Fn(&'t Transition<S, ...
feature = "serde", derive(Serialize, Deserialize), serde(crate = "serde_crate") )] pub struct ActorCritic<C, P> { pub critic: C, pub policy: P, pub alpha: f64, } impl<C, P> ActorCritic<C, P> { pub fn new(critic: C, policy: P, alpha: f64) -> Self { ActorCritic { critic, ...
} #[derive(Clone, Debug)] #[cfg_attr(
random_line_split
compiler-calls.rs
// Copyright 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-MIT or ...
let args = vec!["compiler-calls".to_string(), "foo.rs".to_string()]; rustc_driver::run_compiler(args.as_slice(), &mut tc); assert!(tc.count == 30); }
let mut tc = TestCalls { count: 1 }; // we should never get use this filename, but lets make sure they are valid args.
random_line_split
compiler-calls.rs
// Copyright 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-MIT or ...
fn no_input(&mut self, _: &getopts::Matches, _: &config::Options, _: &Option<PathBuf>, _: &Option<PathBuf>, _: &diagnostics::registry::Registry) -> Option<(Input, Option<PathBuf>)> { panic!("This shouldn't happ...
{ self.count *= 5; (input, input_path) }
identifier_body
compiler-calls.rs
// Copyright 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-MIT or ...
(&mut self, _: &Session) -> driver::CompileController<'a> { panic!("This shouldn't be called"); } } fn main() { let mut tc = TestCalls { count: 1 }; // we should never get use this filename, but lets make sure they are valid args. let args = vec!["compiler-calls".to_string(), "foo.rs".to_strin...
build_controller
identifier_name
writer.rs
use std::fs::OpenOptions; use std::io::Result; use std::path::Path; use byteorder::{ BigEndian, LittleEndian, WriteBytesExt }; pub fn
(filename: &str, samples: Vec<i16>) -> Result<()> { let path = Path::new(filename); let mut f = try!(OpenOptions::new().write(true).truncate(true).create(true).open(&path)); for &sample in samples.iter() { try!(f.write_i16::<LittleEndian>(sample)); } Ok(()) } // See: https://ccrma.stanfor...
write_pcm
identifier_name
writer.rs
use std::fs::OpenOptions; use std::io::Result; use std::path::Path; use byteorder::{ BigEndian, LittleEndian, WriteBytesExt }; pub fn write_pcm(filename: &str, samples: Vec<i16>) -> Result<()> { let path = Path::new(filename); let mut f = try!(OpenOptions::new().write(true).truncate(true).create(true).open(&p...
let mut f = try!(OpenOptions::new().write(true).truncate(true).create(true).open(&path)); // Some WAV header fields let channels = 1; let bit_depth = 16; let subchunk_2_size = samples.len() * channels * bit_depth / 8; let chunk_size = 36 + subchunk_2_size as i32; let byte_rate = (sample_rat...
} // See: https://ccrma.stanford.edu/courses/422/projects/WaveFormat/ pub fn write_wav(filename: &str, sample_rate: usize, samples: Vec<i16>) -> Result<()> { let path = Path::new(filename);
random_line_split
writer.rs
use std::fs::OpenOptions; use std::io::Result; use std::path::Path; use byteorder::{ BigEndian, LittleEndian, WriteBytesExt }; pub fn write_pcm(filename: &str, samples: Vec<i16>) -> Result<()>
// See: https://ccrma.stanford.edu/courses/422/projects/WaveFormat/ pub fn write_wav(filename: &str, sample_rate: usize, samples: Vec<i16>) -> Result<()> { let path = Path::new(filename); let mut f = try!(OpenOptions::new().write(true).truncate(true).create(true).open(&path)); // Some WAV header fields ...
{ let path = Path::new(filename); let mut f = try!(OpenOptions::new().write(true).truncate(true).create(true).open(&path)); for &sample in samples.iter() { try!(f.write_i16::<LittleEndian>(sample)); } Ok(()) }
identifier_body
toggle.rs
use iup_sys; use std::ptr; use std::ffi::CString; use Element;
/// [1]: http://webserver2.tecgraf.puc-rio.br/iup/en/elem/iuptoggle.html pub struct Toggle(*mut iup_sys::Ihandle); impl Toggle { /// Creates a toggle with no text. pub fn new() -> Toggle { unsafe { Toggle::from_raw(iup_sys::IupToggle(ptr::null_mut(), ptr::null_mut())) } } /// Creates a toggle ...
/// See the [IUP Toggle Documentation][1].
random_line_split
toggle.rs
use iup_sys; use std::ptr; use std::ffi::CString; use Element; /// See the [IUP Toggle Documentation][1]. /// [1]: http://webserver2.tecgraf.puc-rio.br/iup/en/elem/iuptoggle.html pub struct Toggle(*mut iup_sys::Ihandle); impl Toggle { /// Creates a toggle with no text. pub fn new() -> Toggle
/// Creates a toggle with the specified text. pub fn with_title<S: Into<String>>(title: S) -> Toggle { let ctitle = CString::new(title.into()).unwrap(); unsafe { Toggle::from_raw(iup_sys::IupToggle(ctitle.as_ptr(), ptr::null_mut())) } } } impl_widget!(Toggle, "toggle"); impl ::callback::M...
{ unsafe { Toggle::from_raw(iup_sys::IupToggle(ptr::null_mut(), ptr::null_mut())) } }
identifier_body
toggle.rs
use iup_sys; use std::ptr; use std::ffi::CString; use Element; /// See the [IUP Toggle Documentation][1]. /// [1]: http://webserver2.tecgraf.puc-rio.br/iup/en/elem/iuptoggle.html pub struct Toggle(*mut iup_sys::Ihandle); impl Toggle { /// Creates a toggle with no text. pub fn
() -> Toggle { unsafe { Toggle::from_raw(iup_sys::IupToggle(ptr::null_mut(), ptr::null_mut())) } } /// Creates a toggle with the specified text. pub fn with_title<S: Into<String>>(title: S) -> Toggle { let ctitle = CString::new(title.into()).unwrap(); unsafe { Toggle::from_raw(iup_s...
new
identifier_name
main.rs
#![feature(globs)] extern crate graphics; extern crate piston; // extern crate sdl2_game_window; extern crate glfw_game_window;
// use Window = sdl2_game_window::GameWindowSDL2; use Window = glfw_game_window::GameWindowGLFW; use piston::{ Game, GameIteratorSettings, GameWindowSettings, UpdateArgs, RenderArgs, KeyPressArgs, KeyReleaseArgs, MousePressArgs, MouseReleaseArgs, MouseMoveArgs, MouseRelative...
random_line_split
main.rs
#![feature(globs)] extern crate graphics; extern crate piston; // extern crate sdl2_game_window; extern crate glfw_game_window; // use Window = sdl2_game_window::GameWindowSDL2; use Window = glfw_game_window::GameWindowGLFW; use piston::{ Game, GameIteratorSettings, GameWindowSettings, UpdateArgs, ...
fn key_release(&mut self, _args: &KeyReleaseArgs) {} fn mouse_press(&mut self, _args: &MousePressArgs) {} fn mouse_release(&mut self, _args: &MouseReleaseArgs) {} fn mouse_move(&mut self, _args: &MouseMoveArgs) {} /// Moved mouse relative, not bounded by cursor. fn mouse_relative_move(&mut sel...
{}
identifier_body
main.rs
#![feature(globs)] extern crate graphics; extern crate piston; // extern crate sdl2_game_window; extern crate glfw_game_window; // use Window = sdl2_game_window::GameWindowSDL2; use Window = glfw_game_window::GameWindowGLFW; use piston::{ Game, GameIteratorSettings, GameWindowSettings, UpdateArgs, ...
() { let mut window = Window::new( GameWindowSettings { title: "NanoMorph Demo".to_string(), size: [300, 300], fullscreen: false, exit_on_esc: true, } ); let mut app = App::new(); let game_iter_settings = GameIteratorSettings { ...
main
identifier_name
trait_def.rs
use crate::ich::{self, StableHashingContext}; use crate::traits::specialization_graph; use crate::ty::fast_reject; use crate::ty::fold::TypeFoldable; use crate::ty::{Ty, TyCtxt}; use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_hir::definitions::DefPathHash; use rustc_data_structures::fx::FxHashMap; use r...
if let Some(simplified_self_ty) = fast_reject::simplify_type(tcx, impl_self_ty, false) { impls.non_blanket_impls.entry(simplified_self_ty).or_default().push(impl_def_id); } else { impls.blanket_impls.push(impl_def_id); } } impls } impl<'a> HashStable<StableHas...
{ continue; }
conditional_block
trait_def.rs
use crate::ich::{self, StableHashingContext}; use crate::traits::specialization_graph; use crate::ty::fast_reject; use crate::ty::fold::TypeFoldable; use crate::ty::{Ty, TyCtxt}; use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_hir::definitions::DefPathHash; use rustc_data_structures::fx::FxHashMap; use r...
pub fn ancestors( &self, tcx: TyCtxt<'tcx>, of_impl: DefId, ) -> Result<specialization_graph::Ancestors<'tcx>, ErrorReported> { specialization_graph::ancestors(tcx, self.def_id, of_impl) } } impl<'tcx> TyCtxt<'tcx> { pub fn for_each_impl<F: FnMut(DefId)>(self, def_id: ...
{ TraitDef { def_id, unsafety, paren_sugar, has_auto_impl, is_marker, skip_array_during_method_dispatch, specialization_kind, def_path_hash, } }
identifier_body
trait_def.rs
use crate::ich::{self, StableHashingContext}; use crate::traits::specialization_graph; use crate::ty::fast_reject; use crate::ty::fold::TypeFoldable; use crate::ty::{Ty, TyCtxt}; use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_hir::definitions::DefPathHash; use rustc_data_structures::fx::FxHashMap; use r...
if let result @ Some(_) = f(impl_def_id) { return result; } } // simplify_type(.., false) basically replaces type parameters and // projections with infer-variables. This is, of course, done on // the impl trait-ref when it is instantiated, but no...
random_line_split
trait_def.rs
use crate::ich::{self, StableHashingContext}; use crate::traits::specialization_graph; use crate::ty::fast_reject; use crate::ty::fold::TypeFoldable; use crate::ty::{Ty, TyCtxt}; use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_hir::definitions::DefPathHash; use rustc_data_structures::fx::FxHashMap; use r...
( def_id: DefId, unsafety: hir::Unsafety, paren_sugar: bool, has_auto_impl: bool, is_marker: bool, skip_array_during_method_dispatch: bool, specialization_kind: TraitSpecializationKind, def_path_hash: DefPathHash, ) -> TraitDef { TraitDef { ...
new
identifier_name
fixture.rs
use std::rc::Rc; use std::cell::RefCell; use ::collision::{BroadPhase, Shape, PolygonShape, Aabb}; use ::common::Transform2d; use super::BodyHandleWeak; use cgmath::*; pub type FixtureHandle<'a> = Rc<RefCell<Fixture<'a>>>; pub struct FixtureConfig { pub friction: f32, pub restitution: f32, pub density: f3...
let aabb2 = self.shape.compute_aabb(transform2); let proxy_aabb = Aabb::combine(&aabb1, &aabb2); let displacement = transform2.position - transform1.position; broad_phase.move_proxy(proxy_id, &proxy_aabb, displacement); } } pub fn get_mass_data(&self) ...
if let Some(proxy_id) = self.proxy_id { // Compute an Aabb that covers the swept shape (may miss some rotation effect). let aabb1 = self.shape.compute_aabb(transform1);
random_line_split
fixture.rs
use std::rc::Rc; use std::cell::RefCell; use ::collision::{BroadPhase, Shape, PolygonShape, Aabb}; use ::common::Transform2d; use super::BodyHandleWeak; use cgmath::*; pub type FixtureHandle<'a> = Rc<RefCell<Fixture<'a>>>; pub struct FixtureConfig { pub friction: f32, pub restitution: f32, pub density: f3...
} pub fn get_mass_data(&self) -> (f32, Vector2<f32>, f32) { self.shape.compute_mass(self.density) } /*pub fn get_shape(&self) -> &PolygonShape { &self.shape }*/ }
{ // Compute an Aabb that covers the swept shape (may miss some rotation effect). let aabb1 = self.shape.compute_aabb(transform1); let aabb2 = self.shape.compute_aabb(transform2); let proxy_aabb = Aabb::combine(&aabb1, &aabb2); let displacement = transform2....
conditional_block
fixture.rs
use std::rc::Rc; use std::cell::RefCell; use ::collision::{BroadPhase, Shape, PolygonShape, Aabb}; use ::common::Transform2d; use super::BodyHandleWeak; use cgmath::*; pub type FixtureHandle<'a> = Rc<RefCell<Fixture<'a>>>; pub struct FixtureConfig { pub friction: f32, pub restitution: f32, pub density: f3...
() -> FixtureConfig { FixtureConfig { friction: 0.2, restitution: 0.0, density: 0.0, is_sensor: false, } } } pub struct Fixture<'a> { pub body: BodyHandleWeak<'a>, pub shape: Shape, pub friction: f32, pub restitution: f32, pub dens...
default
identifier_name
fixture.rs
use std::rc::Rc; use std::cell::RefCell; use ::collision::{BroadPhase, Shape, PolygonShape, Aabb}; use ::common::Transform2d; use super::BodyHandleWeak; use cgmath::*; pub type FixtureHandle<'a> = Rc<RefCell<Fixture<'a>>>; pub struct FixtureConfig { pub friction: f32, pub restitution: f32, pub density: f3...
/*pub fn get_shape(&self) -> &PolygonShape { &self.shape }*/ }
{ self.shape.compute_mass(self.density) }
identifier_body
parser.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/. */ //! The context within which CSS code is parsed. use cssparser::{Parser, SourcePosition}; use error_reporting::Pa...
; #[cfg(feature = "gecko")] pub struct ParserContextExtraData { pub base: Option<GeckoArcURI>, pub referrer: Option<GeckoArcURI>, pub principal: Option<GeckoArcPrincipal>, } impl ParserContextExtraData { #[cfg(not(feature = "gecko"))] pub fn default() -> ParserContextExtraData { ParserCont...
ParserContextExtraData
identifier_name
parser.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/. */ //! The context within which CSS code is parsed. use cssparser::{Parser, SourcePosition}; use error_reporting::Pa...
/// to log CSS parse errors to stderr. pub fn log_css_error(input: &mut Parser, position: SourcePosition, message: &str, parsercontext: &ParserContext) { parsercontext.error_reporter.report_error(input, position, message); }
/// Set a `RUST_LOG=style::errors` environment variable
random_line_split
parser.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/. */ //! The context within which CSS code is parsed. use cssparser::{Parser, SourcePosition}; use error_reporting::Pa...
pub fn new(stylesheet_origin: Origin, base_url: &'a Url, error_reporter: Box<ParseErrorReporter + Send>) -> ParserContext<'a> { let extra_data = ParserContextExtraData::default(); ParserContext::new_with_extra_data(stylesheet_origin, base_url, error_reporter, extra_data) } } i...
{ let mut selector_context = SelectorParserContext::new(); selector_context.in_user_agent_stylesheet = stylesheet_origin == Origin::UserAgent; ParserContext { stylesheet_origin: stylesheet_origin, base_url: base_url, selector_context: selector_context, ...
identifier_body
gcc.rs
// Copyright 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-MIT or ...
(eh_frame_begin: *const u8, object: *mut u8) { __deregister_frame_info(eh_frame_begin, object); } }
rust_eh_unregister_frames
identifier_name
gcc.rs
// Copyright 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-MIT or ...
pub unsafe fn cleanup(ptr: *mut u8) -> Box<dyn Any + Send> { let my_ep = ptr as *mut Exception; let cause = (*my_ep).cause.take(); uw::_Unwind_DeleteException(ptr as *mut _); cause.unwrap() } // Rust's exception class identifier. This is used by personality routines to // determine whether the excep...
{ ptr::null_mut() }
identifier_body
gcc.rs
// Copyright 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-MIT or ...
#[cfg(target_arch = "x86_64")] const UNWIND_DATA_REG: (i32, i32) = (0, 1); // RAX, RDX #[cfg(any(target_arch = "arm", target_arch = "aarch64"))] const UNWIND_DATA_REG: (i32, i32) = (0, 1); // R0, R1 / X0, X1 #[cfg(any(target_arch = "mips", target_arch = "mips64"))] const UNWIND_DATA_REG: (i32, i32) = (4, 5); // A0, ...
random_line_split
main.rs
#![feature(plugin)] #![plugin(regex_macros)] extern crate regex; use std::io; use std::io::prelude::*; use std::io::BufReader; use std::fs::File; use std::env; fn print_usage() { println!("Dogen - Documentation Generator for Lazy students"); println!("Copyright (c) 2016 Hannes Karppila Holder All Rights Reser...
(filename: &str, buffer: &String) -> Result<(), io::Error<>> { let mut file = try!(File::create(filename)); try!(file.write_all(&buffer.as_bytes())); Ok(()) } fn py_parse_args(range_str: &String) -> Vec<String> { let mut ret = Vec::new(); let mut buf = String::new(); let mut level = 0; for...
write_file
identifier_name
main.rs
#![feature(plugin)] #![plugin(regex_macros)] extern crate regex; use std::io; use std::io::prelude::*; use std::io::BufReader; use std::fs::File; use std::env; fn print_usage() { println!("Dogen - Documentation Generator for Lazy students"); println!("Copyright (c) 2016 Hannes Karppila Holder All Rights Reser...
buf.push(c); } } ret.push(buf.clone()); return ret; } fn py_range_to_string(range_str: &mut String) { let range_args = py_parse_args(&range_str); if!range_args.is_empty() { let mut start = "0".to_string(); let mut end = "".to_string(); let mut step = "1"...
if c == ' ' { continue } if level == 0 {
random_line_split
main.rs
#![feature(plugin)] #![plugin(regex_macros)] extern crate regex; use std::io; use std::io::prelude::*; use std::io::BufReader; use std::fs::File; use std::env; fn print_usage()
fn read_file(filename: &str, buffer: &mut String) -> Result<(), io::Error<>> { let file = try!(File::open(filename)); let reader = BufReader::new(file); for line in reader.lines() { let line = try!(line); buffer.push_str(&format!("{}\n", line)); } Ok(()) } fn write_file(filename:...
{ println!("Dogen - Documentation Generator for Lazy students"); println!("Copyright (c) 2016 Hannes Karppila Holder All Rights Reserved."); println!("\n\tUsage: dogen infile\n"); }
identifier_body
main.rs
#![feature(plugin)] #![plugin(regex_macros)] extern crate regex; use std::io; use std::io::prelude::*; use std::io::BufReader; use std::fs::File; use std::env; fn print_usage() { println!("Dogen - Documentation Generator for Lazy students"); println!("Copyright (c) 2016 Hannes Karppila Holder All Rights Reser...
let rr_decrease_one = get_group(&re_decrease_one, &inp); if!rr_decrease_one.is_empty() { result.push_str(&format!("# Decrease {} by one", rr_decrease_one)); return; } let rr_self_add = get_groups(&re_self_add, &inp); if!rr_self_add.is_empty() { result.push_str(&format!("# A...
{ result.push_str(&format!("# Increase {} by one", rr_increase_one)); return; }
conditional_block
mdout.rs
use std::path::{Path, PathBuf}; use std::fs::{ File, rename }; use std::io::Write; use std::io::{Result, Error, ErrorKind}; use std::cell::RefCell; // #[derive(Debug)] // XXX: not for File pub struct MarkdownOut { /// Directory into which we write outdir: PathBuf, /// Serial number prefix for output files...
fn mkout(outdir: &PathBuf, filenum: u32, leafname: &str, is_tmp: bool) -> PathBuf { let mut outpath = outdir.clone(); let sfx = if is_tmp { "+" // XXX: insecure tmpfile. tmpnam is unstable & libc; rand is elsewhere } else { "" }; outpath.push(format!("{:02}_{}.md{}", filenum, leafna...
random_line_split
mdout.rs
use std::path::{Path, PathBuf}; use std::fs::{ File, rename }; use std::io::Write; use std::io::{Result, Error, ErrorKind}; use std::cell::RefCell; // #[derive(Debug)] // XXX: not for File pub struct MarkdownOut { /// Directory into which we write outdir: PathBuf, /// Serial number prefix for output files...
(&self) -> Result<()> { let mut fhput = self.outfh.borrow_mut(); match *fhput { Some(_) => { *fhput = None; rename(self.tmppath.as_path(), self.outpath.as_path()) }, None => self.gone(), } } fn gone(&self) -> Result<()> ...
close
identifier_name
dht22_pt.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com> // // 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.o...
use std::rc::Rc; use syntax::ext::base::ExtCtxt; use builder::{Builder, TokenString, add_node_dependency}; use node; pub fn attach(builder: &mut Builder, _: &mut ExtCtxt, node: Rc<node::Node>) { node.materializer.set(Some(build_dht22 as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>))); node.mutator.set(Some(mutat...
random_line_split
dht22_pt.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com> // // 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.o...
if!node.expect_attributes(cx, &[("pin", node::RefAttribute), ("timer", node::RefAttribute)]) { return } let pin_node_name = node.get_ref_attr("pin").unwrap(); let timer_node_name = node.get_ref_attr("timer").unwrap(); let pin = TokenString(pin_node_name); let timer = TokenString(timer_node_nam...
{return}
conditional_block
dht22_pt.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com> // // 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.o...
(builder: &mut Builder, _: &mut ExtCtxt, node: Rc<node::Node>) { node.materializer.set(Some(build_dht22 as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>))); node.mutator.set(Some(mutate_pin as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>))); let pin_node_name = node.get_ref_attr("pin").unwrap(); let pin_node ...
attach
identifier_name
dht22_pt.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com> // // 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.o...
assert_that(pin_node.get_string_attr("direction").unwrap(), is(equal_to("out".to_string()))); }); } }
{ with_parsed(" timer@timer; pin@pin; dht@dht22 { pin = &pin; timer = &timer; }", |cx, failed, pt| { let mut builder = Builder::new(pt.clone(), cx); pt.get_by_name("timer").unwrap().set_type_name("T".to_string()); pt.get_by_name("pin").unwrap().set_type_name...
identifier_body
unix.rs
use syscall::arch::{syscall0, syscall1, syscall2, syscall3}; use error::Result; pub const SYS_BRK: usize = 45; pub const SYS_CHDIR: usize = 12; pub const SYS_CLONE: usize = 120; pub const CLONE_VM: usize = 0x100; pub const CLONE_FS: usize = 0x200; pub const CLONE_FILES: usize = 0x400; pub const CLONE_V...
syscall2(SYS_EXECVE, path as usize, args as usize) } pub fn sys_exit(status: usize) -> Result<usize> { unsafe { syscall1(SYS_EXIT, status) } } pub fn sys_fpath(fd: usize, buf: &mut [u8]) -> Result<usize> { unsafe { syscall3(SYS_FPATH, fd, buf.as_mut_ptr() as usize, buf.len()) } } pub fn sys_fstat(fd: usi...
pub unsafe fn sys_execve(path: *const u8, args: *const *const u8) -> Result<usize> {
random_line_split
unix.rs
use syscall::arch::{syscall0, syscall1, syscall2, syscall3}; use error::Result; pub const SYS_BRK: usize = 45; pub const SYS_CHDIR: usize = 12; pub const SYS_CLONE: usize = 120; pub const CLONE_VM: usize = 0x100; pub const CLONE_FS: usize = 0x200; pub const CLONE_FILES: usize = 0x400; pub const CLONE_V...
(path: *const u8) -> Result<usize> { syscall1(SYS_UNLINK, path as usize) } pub fn sys_waitpid(pid: usize, status: &mut usize, options: usize) -> Result<usize> { unsafe { syscall3(SYS_WAITPID, pid, status as *mut usize as usize, options) } } pub fn sys_write(fd: usize, buf: &[u8]) -> Result<usize> { unsafe...
sys_unlink
identifier_name
quaternion_relational.rs
use na::{RealField, U4}; use crate::aliases::{Qua, TVec}; /// Component-wise equality comparison between two quaternions.
pub fn quat_equal<N: RealField>(x: &Qua<N>, y: &Qua<N>) -> TVec<bool, U4> { crate::equal(&x.coords, &y.coords) } /// Component-wise approximate equality comparison between two quaternions. pub fn quat_equal_eps<N: RealField>(x: &Qua<N>, y: &Qua<N>, epsilon: N) -> TVec<bool, U4> { crate::equal_eps(&x.coords, &y...
random_line_split
quaternion_relational.rs
use na::{RealField, U4}; use crate::aliases::{Qua, TVec}; /// Component-wise equality comparison between two quaternions. pub fn quat_equal<N: RealField>(x: &Qua<N>, y: &Qua<N>) -> TVec<bool, U4> { crate::equal(&x.coords, &y.coords) } /// Component-wise approximate equality comparison between two quaternions. pu...
<N: RealField>(x: &Qua<N>, y: &Qua<N>) -> TVec<bool, U4> { crate::not_equal(&x.coords, &y.coords) } /// Component-wise approximate non-equality comparison between two quaternions. pub fn quat_not_equal_eps<N: RealField>(x: &Qua<N>, y: &Qua<N>, epsilon: N) -> TVec<bool, U4> { crate::not_equal_eps(&x.coords, &y....
quat_not_equal
identifier_name
quaternion_relational.rs
use na::{RealField, U4}; use crate::aliases::{Qua, TVec}; /// Component-wise equality comparison between two quaternions. pub fn quat_equal<N: RealField>(x: &Qua<N>, y: &Qua<N>) -> TVec<bool, U4>
/// Component-wise approximate equality comparison between two quaternions. pub fn quat_equal_eps<N: RealField>(x: &Qua<N>, y: &Qua<N>, epsilon: N) -> TVec<bool, U4> { crate::equal_eps(&x.coords, &y.coords, epsilon) } /// Component-wise non-equality comparison between two quaternions. pub fn quat_not_equal<N: Re...
{ crate::equal(&x.coords, &y.coords) }
identifier_body
hr-subtype.rs
// Targeted tests for the higher-ranked subtyping code. #![feature(rustc_attrs)] #![allow(dead_code)] // revisions: bound_a_vs_bound_a // revisions: bound_a_vs_bound_b // revisions: bound_inv_a_vs_bound_inv_b // revisions: bound_co_a_vs_bound_co_b // revisions: bound_a_vs_free_x // revisions: free_x_vs_free_x // revi...
//[bound_a_b_ret_a_vs_bound_a_ret_a]~^^^^ ERROR //[free_inv_x_vs_free_inv_y]~^^^^^ ERROR } }; } // If both have bound regions, they are equivalent, regardless of // variant. check! { bound_a_vs_bound_a: (for<'a> fn(&'a u32), for<'a> fn(&'a u32)) } check! { bound_a_vs_bound_b: (for<'...
//[free_x_vs_free_y]~^^ ERROR //[bound_inv_a_b_vs_bound_inv_a]~^^^ ERROR
random_line_split
hr-subtype.rs
// Targeted tests for the higher-ranked subtyping code. #![feature(rustc_attrs)] #![allow(dead_code)] // revisions: bound_a_vs_bound_a // revisions: bound_a_vs_bound_b // revisions: bound_inv_a_vs_bound_inv_b // revisions: bound_co_a_vs_bound_co_b // revisions: bound_a_vs_free_x // revisions: free_x_vs_free_x // revi...
<'a> { x: fn(&'a u32), } struct Contra<'a> { x: &'a u32, } macro_rules! check { ($rev:ident: ($t1:ty, $t2:ty)) => { #[cfg($rev)] fn subtype<'x, 'y: 'x, 'z: 'y>() { gimme::<$t2>(None::<$t1>); //[free_inv_x_vs_free_inv_y]~^ ERROR } #[cfg($rev)] ...
Co
identifier_name
token.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...
(&self) -> bool { match self.ident() { Some(id) => id.name == keywords::Super.name() || id.name == keywords::SelfValue.name() || id.name == keywords::SelfType.name(), None => false, } } /// Returns `true` if the token is ei...
is_path_segment_keyword
identifier_name
token.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...
Char(ast::Name), Integer(ast::Name), Float(ast::Name), Str_(ast::Name), StrRaw(ast::Name, usize), /* raw str delimited by n hash symbols */ ByteStr(ast::Name), ByteStrRaw(ast::Name, usize), /* raw byte str delimited by n hash symbols */ } impl Lit { pub fn short_name(&self) -> &'static ...
} #[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, Copy)] pub enum Lit { Byte(ast::Name),
random_line_split
date.rs
// Copyright 2016 LambdaStack All rights reserved. // // 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...
} fn update(&mut self, now: time::Timespec) { self.amt = 0; write!(LocalBuffer(self), "{}", time::at(now).rfc822()).unwrap(); self.next_update = now + Duration::seconds(1); self.next_update.nsec = 0; } } struct LocalBuffer<'a>(&'a mut LastRenderedNow); impl<'a> fmt::Write ...
impl LastRenderedNow { fn buffer(&self) -> &str { str::from_utf8(&self.bytes[..self.amt]).unwrap()
random_line_split
date.rs
// Copyright 2016 LambdaStack All rights reserved. // // 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...
fn update(&mut self, now: time::Timespec) { self.amt = 0; write!(LocalBuffer(self), "{}", time::at(now).rfc822()).unwrap(); self.next_update = now + Duration::seconds(1); self.next_update.nsec = 0; } } struct LocalBuffer<'a>(&'a mut LastRenderedNow); impl<'a> fmt::Write for L...
{ str::from_utf8(&self.bytes[..self.amt]).unwrap() }
identifier_body
date.rs
// Copyright 2016 LambdaStack All rights reserved. // // 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...
(&self) -> &str { str::from_utf8(&self.bytes[..self.amt]).unwrap() } fn update(&mut self, now: time::Timespec) { self.amt = 0; write!(LocalBuffer(self), "{}", time::at(now).rfc822()).unwrap(); self.next_update = now + Duration::seconds(1); self.next_update.nsec = 0; ...
buffer
identifier_name
date.rs
// Copyright 2016 LambdaStack All rights reserved. // // 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...
f.write_str(cache.buffer()) }) } } impl LastRenderedNow { fn buffer(&self) -> &str { str::from_utf8(&self.bytes[..self.amt]).unwrap() } fn update(&mut self, now: time::Timespec) { self.amt = 0; write!(LocalBuffer(self), "{}", time::at(now).rfc822()).unwrap(...
{ cache.update(now); }
conditional_block
ifletsource1.rs
fn
() { // Toutes les variables sont de type `Option<i32>`. let number = Some(7); let letter: Option<i32> = None; let emoticon: Option<i32> = None; // L'ensemble `if let` se déroule de cette manière: // `if let` déstructure `number` et assigne sa valeur à `i` et exécute // le bloc (`{}`). ...
main
identifier_name
ifletsource1.rs
fn main() { // Toutes les variables sont de type `Option<i32>`. let number = Some(7); let letter: Option<i32> = None; let emoticon: Option<i32> = None; // L'ensemble `if let` se déroule de cette manière: // `if let` déstructure `number` et assigne sa valeur à `i` et exécute
// Si vous devez spécifier un cas d'erreur, utilisez un `else`: if let Some(i) = letter { println!("{:?} a été trouvé!", i); } else { // Déstructuration ratée. On exécute le `else`. println!("Aucun nombre n'a été trouvé. Cherchons une lettre!"); }; // Fournit une c...
// le bloc (`{}`). if let Some(i) = number { println!("{:?} a été trouvé!", i); }
random_line_split
ifletsource1.rs
fn main()
}; // Fournit une condition alternative. let i_like_letters = false; if let Some(i) = emoticon { println!("{:?} a été trouvé!", i); // Déstructuration ratée. Passe à une condition `else if` pour tester si // la condition alternative est vraie. } else if i_like_letters { pr...
{ // Toutes les variables sont de type `Option<i32>`. let number = Some(7); let letter: Option<i32> = None; let emoticon: Option<i32> = None; // L'ensemble `if let` se déroule de cette manière: // `if let` déstructure `number` et assigne sa valeur à `i` et exécute // le bloc (`{}`). i...
identifier_body
ifletsource1.rs
fn main() { // Toutes les variables sont de type `Option<i32>`. let number = Some(7); let letter: Option<i32> = None; let emoticon: Option<i32> = None; // L'ensemble `if let` se déroule de cette manière: // `if let` déstructure `number` et assigne sa valeur à `i` et exécute // le bloc (`{...
// Déstructuration ratée. On exécute le `else`. println!("Aucun nombre n'a été trouvé. Cherchons une lettre!"); }; // Fournit une condition alternative. let i_like_letters = false; if let Some(i) = emoticon { println!("{:?} a été trouvé!", i); // Déstructuration ratée....
println!("{:?} a été trouvé!", i); } else {
conditional_block
lib.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/. */ #![cfg_attr(not(target_os = "windows"), feature(alloc_jemalloc))] #![feature(box_syntax)] #![feature(plugin)] #![f...
pub mod trace_dump;
random_line_split
lib.rs
use once_cell::sync::Lazy; pub const TLD: &str = "org"; pub const SLD: &str = "fengalin"; // Remove "-application" from `CARGO_PKG_NAME` pub static APP_NAME: Lazy<String> = Lazy::new(|| { env!("CARGO_PKG_NAME")
}); pub static APP_ID: Lazy<String> = Lazy::new(|| format!("{}.{}.{}", TLD, SLD, *APP_NAME)); pub static APP_PATH: Lazy<String> = Lazy::new(|| format!("/{}/{}/{}", TLD, SLD, *APP_NAME)); mod command_line; pub use self::command_line::{command_line, CommandLineArguments}; mod configuration; pub use self::configuration...
.rsplitn(2, '-') .last() .unwrap() .to_string()
random_line_split
write_a_ppm_file.rs
// http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file use std::path::Path; use std::io::Write; use std::fs::File; pub struct RGB { r: u8, g: u8, b: u8, }
} impl PPM { pub fn new(height: u32, width: u32) -> PPM { let size = 3 * height * width; let buffer = vec![0; size as usize]; PPM { height: height, width: width, data: buffer, } } fn buffer_size(&self) -> u32 { 3 * self.height * s...
pub struct PPM { height: u32, width: u32, data: Vec<u8>,
random_line_split
write_a_ppm_file.rs
// http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file use std::path::Path; use std::io::Write; use std::fs::File; pub struct RGB { r: u8, g: u8, b: u8, } pub struct PPM { height: u32, width: u32, data: Vec<u8>, } impl PPM { pub fn new(height: u32, width: u32) -> PPM { let size =...
(&self, filename: &str) -> std::io::Result<()> { let path = Path::new(filename); let mut file = try!(File::create(&path)); let header = format!("P6 {} {} 255\n", self.width, self.height); try!(file.write(header.as_bytes())); try!(file.write(&self.data)); Ok(()) } } f...
write_file
identifier_name
write_a_ppm_file.rs
// http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file use std::path::Path; use std::io::Write; use std::fs::File; pub struct RGB { r: u8, g: u8, b: u8, } pub struct PPM { height: u32, width: u32, data: Vec<u8>, } impl PPM { pub fn new(height: u32, width: u32) -> PPM { let size =...
None => None, } } pub fn set_pixel(&mut self, x: u32, y: u32, color: RGB) -> bool { match self.get_offset(x, y) { Some(offset) => { self.data[offset] = color.r; self.data[offset + 1] = color.g; self.data[offset + 2] = colo...
{ let r = self.data[offset]; let g = self.data[offset + 1]; let b = self.data[offset + 2]; Some(RGB { r: r, g: g, b: b }) }
conditional_block
write_a_ppm_file.rs
// http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file use std::path::Path; use std::io::Write; use std::fs::File; pub struct RGB { r: u8, g: u8, b: u8, } pub struct PPM { height: u32, width: u32, data: Vec<u8>, } impl PPM { pub fn new(height: u32, width: u32) -> PPM { let size =...
} fn main() { let ppm = PPM::new(400, 300); ppm.write_file("output.ppm").unwrap(); }
{ let path = Path::new(filename); let mut file = try!(File::create(&path)); let header = format!("P6 {} {} 255\n", self.width, self.height); try!(file.write(header.as_bytes())); try!(file.write(&self.data)); Ok(()) }
identifier_body
mod.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 ...
//! and are often seen in trait bounds. //! * `std::convert::`{ //! [`AsRef`](../convert/trait.AsRef.html), //! [`AsMut`](../convert/trait.AsMut.html), //! [`Into`](../convert/trait.Into.html), //! [`From`](../convert/trait.From.html) //! }. //! Generic conversions, used by savvy API authors to cr...
//! The comparision traits, which implement the comparison operators
random_line_split
orphan.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 ...
} _ => { span_err!(self.tcx.sess, item.span, E0118, "no base type found for inherent implementation; \ implement a trait or new type instead"); } } ...
{ let def_id = ast_util::local_def(item.id); match item.node { ast::ItemImpl(_, _, _, None, _, _) => { // For inherent impls, self type must be a nominal type // defined in this crate. debug!("coherence2::orphan check: inherent impl {}", item.r...
identifier_body
orphan.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 ...
(tcx: &ty::ctxt) { let mut orphan = OrphanChecker { tcx: tcx }; visit::walk_crate(&mut orphan, tcx.map.krate()); } struct OrphanChecker<'cx, 'tcx:'cx> { tcx: &'cx ty::ctxt<'tcx> } impl<'cx, 'tcx> OrphanChecker<'cx, 'tcx> { fn check_def_id(&self, span: Span, def_id: ast::DefId) { if def_id.krat...
check
identifier_name
orphan.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 ...
} visit::walk_item(self, item); } }
{ // Not an impl }
conditional_block
orphan.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 ...
} ast::ItemImpl(_, _, _, Some(_), _, _) => { // "Trait" impl debug!("coherence2::orphan check: trait impl {}", item.repr(self.tcx)); let trait_def_id = ty::impl_trait_ref(self.tcx, def_id).unwrap().def_id; match traits::orphan_check...
implement a trait or new type instead"); } }
random_line_split
errors.rs
// Copyright 2016 Mozilla // // 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 to in writing, software...
(error: SQLError) -> MentatError { MentatError::SQLError(error) } } #[cfg(feature = "syncable")] impl From<TolstoyError> for MentatError { fn from(error: TolstoyError) -> MentatError { MentatError::TolstoyError(error) } } #[cfg(feature = "syncable")] impl From<serde_json::Error> for Mentat...
from
identifier_name
errors.rs
// Copyright 2016 Mozilla // // 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 to in writing, software...
MentatError::EdnParseError(error) } } impl From<DbError> for MentatError { fn from(error: DbError) -> MentatError { MentatError::DbError(error) } } impl From<AlgebrizerError> for MentatError { fn from(error: AlgebrizerError) -> MentatError { MentatError::AlgebrizerError(error) ...
random_line_split
errors.rs
// Copyright 2016 Mozilla // // 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 to in writing, software...
} impl From<DbError> for MentatError { fn from(error: DbError) -> MentatError { MentatError::DbError(error) } } impl From<AlgebrizerError> for MentatError { fn from(error: AlgebrizerError) -> MentatError { MentatError::AlgebrizerError(error) } } impl From<ProjectorError> for MentatEr...
{ MentatError::EdnParseError(error) }
identifier_body
incoming.rs
use super::{ limits::{channels_per_key::MaxChannelsPerKey, requests_per_channel::MaxRequestsPerChannel}, Channel, }; use futures::prelude::*; use std::{fmt, hash::Hash}; #[cfg(feature = "tokio1")] use super::{tokio::TokioServerExecutor, Serve}; /// An extension trait for [streams](futures::prelude::Stream) of...
/// [Executes](Channel::execute) each incoming channel. Each channel will be handled /// concurrently by spawning on tokio's default executor, and each request will be also /// be spawned on tokio's default executor. #[cfg(feature = "tokio1")] #[cfg_attr(docsrs, doc(cfg(feature = "tokio1")))] ...
{ MaxRequestsPerChannel::new(self, n) }
identifier_body
incoming.rs
use super::{ limits::{channels_per_key::MaxChannelsPerKey, requests_per_channel::MaxRequestsPerChannel}, Channel, }; use futures::prelude::*; use std::{fmt, hash::Hash}; #[cfg(feature = "tokio1")] use super::{tokio::TokioServerExecutor, Serve}; /// An extension trait for [streams](futures::prelude::Stream) of...
where Self: Sized + Stream<Item = C>, C: Channel, { /// Enforces channel per-key limits. fn max_channels_per_key<K, KF>(self, n: u32, keymaker: KF) -> MaxChannelsPerKey<Self, K, KF> where K: fmt::Display + Eq + Hash + Clone + Unpin, KF: Fn(&C) -> K, { MaxChannelsPerKey::n...
random_line_split
incoming.rs
use super::{ limits::{channels_per_key::MaxChannelsPerKey, requests_per_channel::MaxRequestsPerChannel}, Channel, }; use futures::prelude::*; use std::{fmt, hash::Hash}; #[cfg(feature = "tokio1")] use super::{tokio::TokioServerExecutor, Serve}; /// An extension trait for [streams](futures::prelude::Stream) of...
<S>(self, serve: S) -> TokioServerExecutor<Self, S> where S: Serve<C::Req, Resp = C::Resp>, { TokioServerExecutor::new(self, serve) } } impl<S, C> Incoming<C> for S where S: Sized + Stream<Item = C>, C: Channel, { }
execute
identifier_name
triangle.rs
// Copyright 2015 Brendan Zabarauskas and the gl-rs 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 b...
} shader } fn link_program(vs: GLuint, fs: GLuint) -> GLuint { unsafe { let program = gl::CreateProgram(); gl::AttachShader(program, vs); gl::AttachShader(program, fs); gl::LinkProgram(program); // Get the link status let mut status = gl::FALSE as GLint; ...
{ let mut len = 0; gl::GetShaderiv(shader, gl::INFO_LOG_LENGTH, &mut len); let mut buf = Vec::with_capacity(len as usize); buf.set_len((len as usize) - 1); // subtract 1 to skip the trailing null character gl::GetShaderInfoLog( shader, ...
conditional_block
triangle.rs
// Copyright 2015 Brendan Zabarauskas and the gl-rs 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 b...
(vs: GLuint, fs: GLuint) -> GLuint { unsafe { let program = gl::CreateProgram(); gl::AttachShader(program, vs); gl::AttachShader(program, fs); gl::LinkProgram(program); // Get the link status let mut status = gl::FALSE as GLint; gl::GetProgramiv(program, gl::L...
link_program
identifier_name
triangle.rs
// Copyright 2015 Brendan Zabarauskas and the gl-rs 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 b...
gl::DeleteVertexArrays(1, &vao); } *control_flow = ControlFlow::Exit }, _ => (), }, Event::RedrawRequested(_) => { unsafe { // Clear the screen to black ...
gl::DeleteBuffers(1, &vbo);
random_line_split
triangle.rs
// Copyright 2015 Brendan Zabarauskas and the gl-rs 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 b...
unsafe { // Create Vertex Array Object gl::GenVertexArrays(1, &mut vao); gl::BindVertexArray(vao); // Create a Vertex Buffer Object and copy the vertex data to it gl::GenBuffers(1, &mut vbo); gl::BindBuffer(gl::ARRAY_BUFFER, vbo); gl::BufferData( ...
{ let event_loop = glutin::event_loop::EventLoop::new(); let window = glutin::window::WindowBuilder::new(); let gl_window = glutin::ContextBuilder::new() .build_windowed(window, &event_loop) .unwrap(); // It is essential to make the context current before calling `gl::load_with`. le...
identifier_body
zookeeper_example.rs
#![deny(unused_mut)] extern crate zookeeper; #[macro_use] extern crate log; extern crate env_logger; use std::io; use std::sync::Arc; use std::time::Duration; use std::thread; use std::env; use std::sync::mpsc; use zookeeper::{CreateMode, Watcher, WatchedEvent, ZooKeeper}; use zookeeper::acls; use zookeeper::recipes::...
() { env_logger::init().unwrap(); zk_example(); }
main
identifier_name
zookeeper_example.rs
#![deny(unused_mut)] extern crate zookeeper; #[macro_use] extern crate log; extern crate env_logger; use std::io; use std::sync::Arc; use std::time::Duration; use std::thread; use std::env; use std::sync::mpsc; use zookeeper::{CreateMode, Watcher, WatchedEvent, ZooKeeper}; use zookeeper::acls; use zookeeper::recipes::...
} } fn zk_example() { let zk_urls = zk_server_urls(); println!("connecting to {}", zk_urls); let zk = ZooKeeper::connect(&*zk_urls, Duration::from_secs(5), LoggingWatcher).unwrap(); let mut tmp = String::new(); let auth = zk.add_auth("digest", vec![1, 2, 3, 4]); println!("authenticated...
fn zk_server_urls() -> String { let key = "ZOOKEEPER_SERVERS"; match env::var(key) { Ok(val) => val, Err(_) => "localhost:2181".to_string(),
random_line_split
zookeeper_example.rs
#![deny(unused_mut)] extern crate zookeeper; #[macro_use] extern crate log; extern crate env_logger; use std::io; use std::sync::Arc; use std::time::Duration; use std::thread; use std::env; use std::sync::mpsc; use zookeeper::{CreateMode, Watcher, WatchedEvent, ZooKeeper}; use zookeeper::acls; use zookeeper::recipes::...
println!("exists -> {:?}", exists); let doesnt_exist = zk.exists("/blabla", true); println!("don't exists path -> {:?}", doesnt_exist); let get_acl = zk.get_acl("/test"); println!("get_acl -> {:?}", get_acl); let set_acl = zk.set_acl("/test", acls::OPEN_ACL_UNSAFE.clone(), -1); printl...
{ let zk_urls = zk_server_urls(); println!("connecting to {}", zk_urls); let zk = ZooKeeper::connect(&*zk_urls, Duration::from_secs(5), LoggingWatcher).unwrap(); let mut tmp = String::new(); let auth = zk.add_auth("digest", vec![1, 2, 3, 4]); println!("authenticated -> {:?}", auth); let...
identifier_body
macro_parser.rs
TypesWithoutColons, Parser}; use parse::token::{Token, EOF, Nonterminal}; use parse::token; use std::rc::Rc; use collections::HashMap; /* This is an Earley-like parser, without support for in-grammar nonterminals, only by calling out to the main rust parser for named nonterminals (which it commits to fully when it hi...
match ei.elts.get(idx).node.clone() { /* need to descend into sequence */ MatchSeq(ref matchers, ref sep, zero_ok, match_idx_lo, match_idx_hi) => { if zero_ok { let mut new_ei = ei.clone(); ...
of_eis.push(ei); } } else {
conditional_block
macro_parser.rs
/* Quick intro to how the parser works: A 'position' is a dot in the middle of a matcher, usually represented as a dot. For example `· a $( a )* a b` is a position, as is `a $( · a )* a b`. The parser walks through the input a character at a time, maintaining a list of items consistent with the current position in th...
"item" => match p.parse_item(Vec::new()) { Some(i) => token::NtItem(i), None => p.fatal("expected an item keyword") }, "block" => token::NtBlock(p.parse_block()), "stmt" => token::NtStmt(p.parse_stmt(Vec::new())), "pat" => token::NtPat(p.parse_pat()), "expr" => token::NtE...
identifier_body
macro_parser.rs
TypesWithoutColons, Parser}; use parse::token::{Token, EOF, Nonterminal}; use parse::token; use std::rc::Rc; use collections::HashMap; /* This is an Earley-like parser, without support for in-grammar nonterminals, only by calling out to the main rust parser for named nonterminals (which it commits to fully when it hi...
Ident, Rc<NamedMatch>>), Failure(codemap::Span, String), Error(codemap::Span, String) } pub fn parse_or_else(sess: &ParseSess, cfg: ast::CrateConfig, rdr: TtReader, ms: Vec<Matcher> ) -> HashMap<Ident, Rc<NamedMatch>> { mat...
ss(HashMap<
identifier_name
macro_parser.rs
AndTypesWithoutColons, Parser}; use parse::token::{Token, EOF, Nonterminal}; use parse::token; use std::rc::Rc; use collections::HashMap; /* This is an Earley-like parser, without support for in-grammar nonterminals, only by calling out to the main rust parser for named nonterminals (which it commits to fully when it...
-> HashMap<Ident, Rc<NamedMatch>> { match parse(sess, cfg, rdr, ms.as_slice()) { Success(m) => m, Failure(sp, str) => { sess.span_diagnostic.span_fatal(sp, str.as_slice()) } Error(sp, str) => { sess.span_diagnostic.span_fatal(sp, str.as_sl...
ms: Vec<Matcher> )
random_line_split
time.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 https://mozilla.org/MPL/2.0/. */ //! Computed time values. use crate::values::CSSFloat; use std::fmt::{self, Write}; use style_traits::{CssWriter...
(&self) -> CSSFloat { self.seconds } } impl ToCss for Time { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { self.seconds().to_css(dest)?; dest.write_str("s") } }
seconds
identifier_name
time.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 https://mozilla.org/MPL/2.0/. */ //! Computed time values.
use std::fmt::{self, Write}; use style_traits::{CssWriter, ToCss}; /// A computed `<time>` value. #[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, PartialOrd, ToResolvedValue)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] pub struct Time { seconds: CSSFloat, } impl Time { /// Creates a ...
use crate::values::CSSFloat;
random_line_split
time.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 https://mozilla.org/MPL/2.0/. */ //! Computed time values. use crate::values::CSSFloat; use std::fmt::{self, Write}; use style_traits::{CssWriter...
/// Returns the amount of seconds this time represents. #[inline] pub fn seconds(&self) -> CSSFloat { self.seconds } } impl ToCss for Time { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { self.seconds().to_css(dest)?; dest.wri...
{ Self::from_seconds(0.0) }
identifier_body
main.rs
#![feature(asm, const_fn, const_size_of, fn_traits)] extern crate glutin; extern crate cgmath; extern crate frame_timer; extern crate gl; extern crate image; #[macro_use] extern crate lazy_static; extern crate threadpool; extern crate rand; extern crate rusttype; #[macro_use] mod macros; pub mod game; pub mod graphi...
//буря-engine fn main() { //this is for assets that have been loaded by their threads //and then for the content manifest to keep track of them let (load_subthread_sender, content_manifest_asset_receiver): (Sender<EContentType>, Receiver<EContentType>) = mpsc::channel(); //this is for the ga...
use content::{ContentManifest, LoadContent}; use game::World; use graphics::renderer::{RenderFrame, Renderer};
random_line_split
main.rs
#![feature(asm, const_fn, const_size_of, fn_traits)] extern crate glutin; extern crate cgmath; extern crate frame_timer; extern crate gl; extern crate image; #[macro_use] extern crate lazy_static; extern crate threadpool; extern crate rand; extern crate rusttype; #[macro_use] mod macros; pub mod game; pub mod graphi...
//this is for assets that have been loaded by their threads //and then for the content manifest to keep track of them let (load_subthread_sender, content_manifest_asset_receiver): (Sender<EContentType>, Receiver<EContentType>) = mpsc::channel(); //this is for the game thread to ask for an as...
() {
identifier_name
main.rs
#![feature(asm, const_fn, const_size_of, fn_traits)] extern crate glutin; extern crate cgmath; extern crate frame_timer; extern crate gl; extern crate image; #[macro_use] extern crate lazy_static; extern crate threadpool; extern crate rand; extern crate rusttype; #[macro_use] mod macros; pub mod game; pub mod graphi...
//this is for the loading thread to send back the content id associated with the asset that the //game just asked for let (loading_thread_content_id, game_thread_content_id): (Sender<EContentRequestResult>, Receiver<EContentRequestResult>) = mpsc::channel(); //this is for the game thread to use...
//this is for assets that have been loaded by their threads //and then for the content manifest to keep track of them let (load_subthread_sender, content_manifest_asset_receiver): (Sender<EContentType>, Receiver<EContentType>) = mpsc::channel(); //this is for the game thread to ask for an asset...
identifier_body
pin.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Lionel Flandrin <lionel@svkt.org> // // 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/LICENS...
(pid: PortId, pin_index: u8, dir: GpioDirection, function: u8) -> Pin { // Retrieve GPIO port peripheral to enable it let (periph, regs) = match pid { PortId::PortA => (sysctl::periph::gpio::PORT_A, reg::PORT_A), PortId::PortB => (sysctl::periph::...
new
identifier_name
pin.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Lionel Flandrin <lionel@svkt.org> // // 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/LICENS...
//! Pin configuration //! Allows GPIO configuration //! Pin muxing not implemented yet. use hal::pin::{Gpio, GpioDirection, In, Out, GpioLevel, High, Low}; use hal::tiva_c::sysctl; use util::support::get_reg_ref; /// The pins are accessed through ports. Each port has 8 pins and are identified /// by a letter (PortA, ...
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License.
random_line_split
lib.rs
// Copyright 2014 Michael Yang. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. #![feature(concat_idents)] //! BLAS bindings and wrappers. //! //! Bindings are split by BLAS level and contained in a module named `ll` //! (stands for low level...
pub use vector::VectorOperations; pub use matrix::Matrix; pub use vector::ops::*; pub use matrix_vector::ops::*; pub use matrix::ops::*; #[macro_use] mod prefix; mod pointer; mod scalar; pub mod attribute; pub mod default; pub mod vector; pub mod matrix_vector; pub mod matrix; pub mod math;
pub use vector::Vector;
random_line_split
restyle_damage.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/. */ //! The restyle damage is a hint that tells layout which kind of operations may //! be needed in presence of incre...
, (REFLOW, "Reflow") , (RESOLVE_GENERATED_CONTENT, "ResolveGeneratedContent") , (RECONSTRUCT_FLOW, "ReconstructFlow") ]; for &(damage, damage_str) in &to_iter { if self.contains(damage) { if!first_elem { try!(write!(f, " | ")); } ...
, (STORE_OVERFLOW, "StoreOverflow") , (BUBBLE_ISIZES, "BubbleISizes") , (REFLOW_OUT_OF_FLOW, "ReflowOutOfFlow")
random_line_split
restyle_damage.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/. */ //! The restyle damage is a hint that tells layout which kind of operations may //! be needed in presence of incre...
} impl Default for ServoRestyleDamage { fn default() -> Self { Self::empty() } } impl fmt::Display for ServoRestyleDamage { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { let mut first_elem = true; let to_iter = [ (REPAINT, "Repaint") , (...
{ Self::empty() }
identifier_body
restyle_damage.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/. */ //! The restyle damage is a hint that tells layout which kind of operations may //! be needed in presence of incre...
Ok(()) } } // NB: We need the braces inside the RHS due to Rust #8012. This particular // version of this macro might be safe anyway, but we want to avoid silent // breakage on modifications. macro_rules! add_if_not_equal( ($old:ident, $new:ident, $damage:ident, [ $($effect:ident),* ], [ $($sty...
{ try!(write!(f, "NoDamage")); }
conditional_block
restyle_damage.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/. */ //! The restyle damage is a hint that tells layout which kind of operations may //! be needed in presence of incre...
(self, child_is_absolutely_positioned: bool) -> ServoRestyleDamage { if child_is_absolutely_positioned { self & (REPAINT | REPOSITION | STORE_OVERFLOW | REFLOW_OUT_OF_FLOW | RESOLVE_GENERATED_CONTENT) } else { self & (REPAINT | REPOSITION | STORE_OVERFLOW | RE...
damage_for_parent
identifier_name
css_provider.rs
// Copyright 2013-2015, The Gtk-rs 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> use std::fmt::{self, Display, Formatter}; use ffi::{self, GtkCssProvider}; use glib::translat...
(name: &str, variant: &str) -> Self { unsafe { CssProvider { pointer: ffi::gtk_css_provider_get_named(name.to_glib_none().0, variant.to_glib_none().0) } } } pub fn load_from_path(path: &str) -> Result<CssProvider, gl...
get_named
identifier_name
css_provider.rs
// Copyright 2013-2015, The Gtk-rs 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> use std::fmt::{self, Display, Formatter}; use ffi::{self, GtkCssProvider}; use glib::translat...
} impl_GObjectFunctions!(CssProvider, GtkCssProvider); impl_TraitObject!(CssProvider, GtkCssProvider);
{ let tmp: String = unsafe { from_glib_full(ffi::gtk_css_provider_to_string(self.pointer)) }; write!(f, "{}", tmp) }
identifier_body
css_provider.rs
// Copyright 2013-2015, The Gtk-rs 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> use std::fmt::{self, Display, Formatter}; use ffi::{self, GtkCssProvider}; use glib::translat...
pub fn get_named(name: &str, variant: &str) -> Self { unsafe { CssProvider { pointer: ffi::gtk_css_provider_get_named(name.to_glib_none().0, variant.to_glib_none().0) } } } pub fn load_from_path(path: &str) -> Re...
pub fn get_default() -> Self { unsafe { CssProvider { pointer: ffi::gtk_css_provider_get_default() } } }
random_line_split