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 |
|---|---|---|---|---|
lexical-scope-in-if.rs | // Copyright 2013-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-MI... | {()} | identifier_body | |
lexical-scope-in-if.rs | // Copyright 2013-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-MI... | else {
zzz();
sentinel();
let x = 1004;
let y = 1005;
zzz();
sentinel();
}
zzz();
sentinel();
}
fn zzz() {()}
fn sentinel() {()}
| {
unreachable!();
} | conditional_block |
lexical-scope-in-if.rs | // Copyright 2013-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-MI... | // check:$11 = 999
// debugger:print y
// check:$12 = -1
// debugger:continue
// BEGINNING of else branch
// debugger:finish
// debugger:print x
// check:$13 = 1004
// debugger:print y
// check:$14 = 1005
// debugger:continue
// BEGINNING of else branch
// debugger:finish
// debugger:print x
// check:$15 = 999
// deb... | // debugger:finish
// debugger:print x | random_line_split |
local_data_priv.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 ... | // way the TLS code knows exactly what the lifetime of the yielded pointer
// is, allowing callers to acquire references to owned data. This is also
// sound so long as measures are taken to ensure that while a TLS slot is
// loaned out to a caller, it's not modified recursively.
let map = get_local... | // For this reason, the reference is yielded to a specified closure. This | random_line_split |
local_data_priv.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 ... | }
match handle {
OldHandle(task) => oldsched_map(task),
NewHandle(local_storage) => newsched_map(local_storage)
}
}
fn key_to_key_value<T:'static>(key: local_data::Key<T>) -> *libc::c_void {
unsafe { cast::transmute(key) }
}
pub unsafe fn local_pop<T:'static>(handle: Handle,
... | {
// This is based on the same idea as the oldsched code above.
match &mut *local {
// If the at_exit function is already set, then we just need to take
// a loan out on the TLS map stored inside
&LocalStorage(ref mut map_ptr, Some(_)) => {
assert!(map... | identifier_body |
local_data_priv.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 ... |
Some(i) => {
let ret;
let mut return_loan = false;
match map[i] {
Some((_, ref data, ref mut loan)) => {
match (state, *loan) {
(_, NoLoan) => {
*loan = state;
... | { return f(None); } | conditional_block |
local_data_priv.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 ... | {
NoLoan, ImmLoan, MutLoan
}
impl LoanState {
fn describe(&self) -> &'static str {
match *self {
NoLoan => "no loan",
ImmLoan => "immutable",
MutLoan => "mutable"
}
}
}
trait LocalData {}
impl<T:'static> LocalData for T {}
// The task-local-map stores ... | LoanState | identifier_name |
client.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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 appl... |
fn with_spawner<P, T, S>(protocol: P, transport: T, spawner: S) -> Arc<Self::Api>
where
P: Protocol<Frame = T> +'static,
T: Transport + Sync,
P::Deserializer: Send,
S: Spawner;
}
pub trait Transport: Framing + Send + Sized +'static {
fn call(
&self,
service... | {
let spawner = crate::NoopSpawner;
Self::with_spawner(protocol, transport, spawner)
} | identifier_body |
client.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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 appl... | <P, T>(protocol: P, transport: T) -> Arc<Self::Api>
where
P: Protocol<Frame = T> +'static,
T: Transport + Sync,
P::Deserializer: Send,
{
let spawner = crate::NoopSpawner;
Self::with_spawner(protocol, transport, spawner)
}
fn with_spawner<P, T, S>(protocol: P, tra... | new | identifier_name |
client.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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 appl... |
fn create_interaction(&self, _method_name: &'static CStr) -> Result<Self, anyhow::Error> {
anyhow::bail!("Interactions are not supported by this transport");
}
} | ))
.boxed()
} | random_line_split |
msgsend-ring-mutex-arcs.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 ... | else {
args.clone().move_iter().collect()
};
let num_tasks = from_str::<uint>(args.get(1).as_slice()).unwrap();
let msg_per_task = from_str::<uint>(args.get(2).as_slice()).unwrap();
let (mut num_chan, num_port) = init();
let start = time::precise_time_s();
// create the ring
let... | {
vec!("".to_string(), "10".to_string(), "100".to_string())
} | conditional_block |
msgsend-ring-mutex-arcs.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 ... | for i in range(1u, num_tasks) {
//println!("spawning %?", i);
let (new_chan, num_port) = init();
let num_chan_2 = num_chan.clone();
let new_future = Future::spawn(proc() {
thread_ring(i, msg_per_task, num_chan_2, num_port)
});
futures.push(new_future);
... | {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
vec!("".to_string(), "100".to_string(), "10000".to_string())
} else if args.len() <= 1u {
vec!("".to_string(), "10".to_string(), "100".to_string())
} else {
args.clone().move_iter().collect()
};
... | identifier_body |
msgsend-ring-mutex-arcs.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 ... | () {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
vec!("".to_string(), "100".to_string(), "10000".to_string())
} else if args.len() <= 1u {
vec!("".to_string(), "10".to_string(), "100".to_string())
} else {
args.clone().move_iter().collect()
};
... | main | identifier_name |
msgsend-ring-mutex-arcs.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 ... | fn main() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
vec!("".to_string(), "100".to_string(), "10000".to_string())
} else if args.len() <= 1u {
vec!("".to_string(), "10".to_string(), "100".to_string())
} else {
args.clone().move_iter().collect()
... | random_line_split | |
lib.rs | //! A simple dsp node for multiplying the amplitude of its inputs by some given multiplier.
extern crate dsp;
extern crate time_calc as time;
/// A simple dsp node for multiplying the amplitude of its inputs by the held multiplier.
#[derive(Copy, Clone, Debug)]
pub struct Volume {
maybe_prev: Option<f32>,
pu... | volume += volume_increment;
let frame = &mut buffer[idx];
*frame = frame.scale_amp(volume.to_sample());
}
// Remaining frames.
for idx in interpolation_frames..buffer.len() {
let frame = &mut... | for idx in 0..interpolation_frames { | random_line_split |
lib.rs | //! A simple dsp node for multiplying the amplitude of its inputs by some given multiplier.
extern crate dsp;
extern crate time_calc as time;
/// A simple dsp node for multiplying the amplitude of its inputs by the held multiplier.
#[derive(Copy, Clone, Debug)]
pub struct Volume {
maybe_prev: Option<f32>,
pu... | for idx in interpolation_frames..buffer.len() {
let frame = &mut buffer[idx];
*frame = frame.scale_amp(volume.to_sample());
}
}
,
// Otherwise, simply multiply every sample by the current volume.
_ => for frame ... | {
// Calculate the interpolation duration in frames along with the volume increment
// to use for interpolation.
let interpolation_frames = std::cmp::min(
buffer.len(),
time::Ms(self.interpolation_ms).samples(sample_hz) as usize,
... | conditional_block |
lib.rs | //! A simple dsp node for multiplying the amplitude of its inputs by some given multiplier.
extern crate dsp;
extern crate time_calc as time;
/// A simple dsp node for multiplying the amplitude of its inputs by the held multiplier.
#[derive(Copy, Clone, Debug)]
pub struct Volume {
maybe_prev: Option<f32>,
pu... | () -> Volume {
Volume {
maybe_prev: None,
current: 1.0,
interpolation_ms: 10.0,
}
}
/// Builder for constructing a Volume with some given volume.
pub fn volume(mut self, volume: f32) -> Volume {
self.current = volume;
self
}
/// B... | new | identifier_name |
framebuffer.rs | use gl;
use gl::types::*;
use gl_context::GLContext;
use std::marker::PhantomData;
use texture::Texture2D;
pub struct Framebuffer<'a> {
pub gl_id: GLuint,
pub phantom: PhantomData<&'a ()>,
}
impl<'a> Framebuffer<'a> {
pub fn new<'b:'a>(_gl: &'a GLContext) -> Framebuffer<'b> |
pub fn bind(&mut self, _gl: &mut GLContext) {
unsafe {
gl::BindFramebuffer(gl::FRAMEBUFFER, self.gl_id);
}
}
pub fn attach_2d(&mut self, _gl: &GLContext, attachment: GLenum, tex: &Texture2D) {
unsafe {
gl::FramebufferTexture2D(gl::FRAMEBUFFER, attachment, gl::TEXTURE_2D, tex.handle.gl_i... | {
let mut gl_id = 0;
unsafe {
gl::GenFramebuffers(1, &mut gl_id);
}
Framebuffer {
gl_id: gl_id,
phantom: PhantomData,
}
} | identifier_body |
framebuffer.rs | use gl;
use gl::types::*;
use gl_context::GLContext;
use std::marker::PhantomData;
use texture::Texture2D;
pub struct Framebuffer<'a> {
pub gl_id: GLuint,
pub phantom: PhantomData<&'a ()>,
}
impl<'a> Framebuffer<'a> {
pub fn new<'b:'a>(_gl: &'a GLContext) -> Framebuffer<'b> {
let mut gl_id = 0;
unsafe ... | (&mut self, _gl: &GLContext, attachment: GLenum, tex: &Texture2D) {
unsafe {
gl::FramebufferTexture2D(gl::FRAMEBUFFER, attachment, gl::TEXTURE_2D, tex.handle.gl_id, 0);
}
}
}
impl<'a> Drop for Framebuffer<'a> {
fn drop(&mut self) {
unsafe {
gl::DeleteFramebuffers(1, &self.gl_id);
}
}
... | attach_2d | identifier_name |
framebuffer.rs | use gl;
use gl::types::*;
use gl_context::GLContext;
use std::marker::PhantomData;
use texture::Texture2D;
pub struct Framebuffer<'a> {
pub gl_id: GLuint, | pub fn new<'b:'a>(_gl: &'a GLContext) -> Framebuffer<'b> {
let mut gl_id = 0;
unsafe {
gl::GenFramebuffers(1, &mut gl_id);
}
Framebuffer {
gl_id: gl_id,
phantom: PhantomData,
}
}
pub fn bind(&mut self, _gl: &mut GLContext) {
unsafe {
gl::BindFramebuffer(gl::FRAMEB... | pub phantom: PhantomData<&'a ()>,
}
impl<'a> Framebuffer<'a> { | random_line_split |
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/. */
#![deny(unsafe_code)]
#![feature(box_syntax)]
#![feature(conservative_impl_trait)]
#![feature(mpsc_select)]
exter... | pub use pipeline::UnprivilegedPipelineContent;
#[cfg(not(target_os = "windows"))]
pub use sandboxing::content_process_sandbox_profile; | mod sandboxing;
mod timer_scheduler;
pub use constellation::{Constellation, FromCompositorLogger, FromScriptLogger, InitialConstellationState}; | random_line_split |
mod.rs | // Copyright 2017 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 ... |
PassWhere::BeforeLocation(_) => {
}
PassWhere::AfterTerminator(_) => {
}
PassWhere::BeforeBlock(_) | PassWhere::AfterLocation(_) | PassWhere::AfterCFG => {}
}
Ok(())
},
);
// Also dump the infere... | {
regioncx.dump_mir(out)?;
if let Some(closure_region_requirements) = closure_region_requirements {
writeln!(out, "|")?;
writeln!(out, "| Free Region Constraints")?;
for_each_region_constraint(closure_region... | conditional_block |
mod.rs | // Copyright 2017 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 ... | &universal_regions,
location_table,
borrow_set,
&mut all_facts,
flow_inits,
move_data,
elements,
);
if let Some(all_facts) = &mut all_facts {
all_facts
.universal_region
.extend(universal_regions.universal_regions());
}
... | {
let mut all_facts = if AllFacts::enabled(infcx.tcx) {
Some(AllFacts::default())
} else {
None
};
let universal_regions = Rc::new(universal_regions);
let elements = &Rc::new(RegionValueElements::new(mir));
// Run the MIR type-checker.
let MirTypeckResults {
constr... | identifier_body |
mod.rs | // Copyright 2017 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 ... | (
closure_region_requirements: &ClosureRegionRequirements,
with_msg: &mut dyn FnMut(&str) -> io::Result<()>,
) -> io::Result<()> {
for req in &closure_region_requirements.outlives_requirements {
let subject: &dyn Debug = match &req.subject {
ClosureOutlivesSubject::Region(subject) => sub... | for_each_region_constraint | identifier_name |
mod.rs | // Copyright 2017 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 ... | });
// Solve the region constraints.
let closure_region_requirements = regioncx.solve(infcx, &mir, def_id, errors_buffer);
// Dump MIR results into a file, if that is enabled. This let us
// write unit-tests, as well as helping with debugging.
dump_mir_results(
infcx,
MirSource... | } | random_line_split |
class-cast-to-trait.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 ... |
}
impl cat {
pub fn eat(&mut self) -> bool {
if self.how_hungry > 0 {
println!("OM NOM NOM");
self.how_hungry -= 2;
return true;
}
else {
println!("Not hungry!");
return false;
}
}
}
impl cat {
fn meow(&mut self) {
println!("Meow");
self.meo... | { self.meow(); } | identifier_body |
class-cast-to-trait.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 ... | (&mut self) { self.meow(); }
}
impl cat {
pub fn eat(&mut self) -> bool {
if self.how_hungry > 0 {
println!("OM NOM NOM");
self.how_hungry -= 2;
return true;
}
else {
println!("Not hungry!");
return false;
}
}
}
impl cat {
fn meow(&mut self) {
prin... | speak | identifier_name |
class-cast-to-trait.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 ... |
}
}
fn cat(in_x : uint, in_y : int, in_name: String) -> cat {
cat {
meows: in_x,
how_hungry: in_y,
name: in_name
}
}
pub fn main() {
let mut nyan = cat(0, 2, "nyan".to_string());
let mut nyan: &mut noisy = &mut nyan;
nyan.speak();
}
| {
self.how_hungry += 1;
} | conditional_block |
class-cast-to-trait.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 ... | trait noisy {
fn speak(&mut self);
}
struct cat {
meows: uint,
how_hungry: int,
name: String,
}
impl noisy for cat {
fn speak(&mut self) { self.meow(); }
}
impl cat {
pub fn eat(&mut self) -> bool {
if self.how_hungry > 0 {
println!("OM NOM NOM");
self.how_hungry -= 2;
return ... | random_line_split | |
term.rs | #![allow(clippy::should_implement_trait)]
use error::Error;
use parsers;
use serde::{Deserialize, Serialize};
use std::fmt;
use std::str::FromStr;
/// A Term can represent a Terminal or Nonterminal node
#[derive(Deserialize, Serialize, Clone, Debug, Eq, Hash, PartialEq)]
pub enum Term {
Terminal(String),
Nont... | () {
let some_space = String::from(" some space ");
assert_eq!(
Ok(Term::Nonterminal(some_space.clone())),
Term::from_str(&format!("<{}>", some_space))
);
}
#[test]
fn parse_whitespace_term() {
let some_space = String::from(" some space ");
as... | parse_whitespace_nonterm | identifier_name |
term.rs | #![allow(clippy::should_implement_trait)]
use error::Error;
use parsers;
use serde::{Deserialize, Serialize};
use std::fmt;
use std::str::FromStr;
/// A Term can represent a Terminal or Nonterminal node
#[derive(Deserialize, Serialize, Clone, Debug, Eq, Hash, PartialEq)]
pub enum Term {
Terminal(String),
Nont... | Error::ParseError(_) => (),
e => panic!("should should be Error::ParseError: {:?}", e),
},
Ok(s) => panic!("should should be Error::ParseError: {}", s),
}
}
#[test]
fn parse_error_display() {
let incomplete = Term::from_str("<dna");
... | let result = Term::from_str("");
assert!(result.is_err(), "{:?} should be err", result);
match result {
Err(e) => match e { | random_line_split |
term.rs | #![allow(clippy::should_implement_trait)]
use error::Error;
use parsers;
use serde::{Deserialize, Serialize};
use std::fmt;
use std::str::FromStr;
/// A Term can represent a Terminal or Nonterminal node
#[derive(Deserialize, Serialize, Clone, Debug, Eq, Hash, PartialEq)]
pub enum Term {
Terminal(String),
Nont... |
#[test]
fn parse_whitespace_term() {
let some_space = String::from(" some space ");
assert_eq!(
Ok(Term::Terminal(some_space.clone())),
Term::from_str(&format!("\"{}\"", some_space))
);
}
#[test]
fn parse_quote_term() {
let quote_term = Term... | {
let some_space = String::from(" some space ");
assert_eq!(
Ok(Term::Nonterminal(some_space.clone())),
Term::from_str(&format!("<{}>", some_space))
);
} | identifier_body |
glutin_handler.rs | use glium::glutin::Event;
use glium::Display;
use super::WindowHandler;
use glium::glutin::EventsLoop;
use glium::glutin::WindowEvent;
pub struct | {
focused_flag: bool,
requested_close: bool
}
impl GlutinInput {
pub fn new() -> GlutinInput {
GlutinInput {
focused_flag: true,
requested_close: false,
}
}
}
impl WindowHandler for GlutinInput {
fn receive_input(&mut self, events_loop: &mut EventsLoop) {
... | GlutinInput | identifier_name |
glutin_handler.rs | use glium::glutin::Event;
use glium::Display;
use super::WindowHandler;
use glium::glutin::EventsLoop;
use glium::glutin::WindowEvent;
pub struct GlutinInput {
focused_flag: bool,
requested_close: bool
}
impl GlutinInput {
pub fn new() -> GlutinInput {
GlutinInput {
focused_flag: true,... |
fn request_close(&self) -> bool { self.requested_close }
} | random_line_split | |
utils.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 rustc::front::map as ast_map;
use rustc::lint::{LateContext, LintContext};
use rustc::middle::def;
use rustc::... |
// Determines if a block is in an unsafe context so that an unhelpful
// lint can be aborted.
pub fn unsafe_context(map: &ast_map::Map, id: ast::NodeId) -> bool {
match map.find(map.get_parent(id)) {
Some(ast_map::NodeImplItem(itm)) => {
match itm.node {
hir::ImplItemKind::Meth... | {
cx.tcx.get_attrs(did).iter().any(|attr| {
match attr.node.value.node {
ast::MetaNameValue(ref name, ref val) if &**name == "servo_lang" => {
match val.node {
ast::LitStr(ref v, _) if &**v == value => {
mark_used(attr);
... | identifier_body |
utils.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 rustc::front::map as ast_map;
use rustc::lint::{LateContext, LintContext};
use rustc::middle::def;
use rustc::... | (map: &ast_map::Map, id: ast::NodeId) -> bool {
match map.find(map.get_parent(id)) {
Some(ast_map::NodeImplItem(itm)) => {
match itm.node {
hir::ImplItemKind::Method(ref sig, _) => sig.unsafety == hir::Unsafety::Unsafe,
_ => false
}
},
... | unsafe_context | identifier_name |
utils.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 rustc::front::map as ast_map;
use rustc::lint::{LateContext, LintContext};
use rustc::middle::def;
use rustc::... | ///
/// Try not to use this for types defined in crates you own, use match_lang_ty instead (for lint passes)
pub fn match_ty_unwrap<'a>(ty: &'a ast::Ty, segments: &[&str]) -> Option<&'a [P<ast::Ty>]> {
match ty.node {
ast::TyPath(_, ast::Path { segments: ref seg,.. }) => {
// So hir::Path isn't ... | use syntax::codemap::{ExpnFormat, Span};
use syntax::ptr::P;
/// Matches a type with a provided string, and returns its type parameters if successful | random_line_split |
utils.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 rustc::front::map as ast_map;
use rustc::lint::{LateContext, LintContext};
use rustc::middle::def;
use rustc::... | else {
None
}
},
_ => None
}
}
/// Checks if a type has a #[servo_lang = "str"] attribute
pub fn match_lang_ty(cx: &LateContext, ty: &hir::Ty, value: &str) -> bool {
match ty.node {
hir::TyPath(..) => {},
_ => return false,
}
let def = match... | {
match seg.last() {
Some(&ast::PathSegment { parameters: ast::PathParameters::AngleBracketed(ref a), .. }) => {
Some(&a.types)
}
_ => None
}
} | 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/. */
extern crate embedder_traits;
extern crate ipc_channel;
extern crate regex;
#[macro_use]
extern crate serde;
pub ... | {
Type(String),
Network,
NotFound,
NotSupported,
Security,
InvalidState,
}
#[derive(Deserialize, Serialize)]
pub enum GATTType {
PrimaryService,
Characteristic,
IncludedService,
Descriptor,
}
#[derive(Deserialize, Serialize)]
pub struct BluetoothDeviceMsg {
// Bluetooth De... | BluetoothError | identifier_name |
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/. */
extern crate embedder_traits;
extern crate ipc_channel;
extern crate regex;
#[macro_use]
extern crate serde;
pub ... | InvalidState,
}
#[derive(Deserialize, Serialize)]
pub enum GATTType {
PrimaryService,
Characteristic,
IncludedService,
Descriptor,
}
#[derive(Deserialize, Serialize)]
pub struct BluetoothDeviceMsg {
// Bluetooth Device properties
pub id: String,
pub name: Option<String>,
}
#[derive(De... | Type(String),
Network,
NotFound,
NotSupported,
Security, | random_line_split |
mod.rs | //! This module implements and describes common TTY methods & traits
use std::io::Write;
use ::Result;
use consts::KeyPress;
pub trait RawMode: Copy + Sized {
/// Disable RAW mode for the terminal.
fn disable_raw_mode(&self) -> Result<()>;
}
pub trait RawReader: Sized {
/// Blocking read of key pressed.
... | #[cfg(all(windows, not(test)))]
pub use self::windows::*;
// If on Unix platform import Unix TTY module
// and re-export into mod.rs scope
#[cfg(all(unix, not(test)))]
mod unix;
#[cfg(all(unix, not(test)))]
pub use self::unix::*;
#[cfg(test)]
mod test;
#[cfg(test)]
pub use self::test::*; | // and re-export into mod.rs scope
#[cfg(all(windows, not(test)))]
mod windows; | random_line_split |
jmp_instr.rs | // SPDX-License-Identifier: MIT
// Copyright wtfsckgh@gmail.com
// Copyright iced contributors
use super::super::super::iced_error::IcedError;
use super::super::*;
use super::*;
use core::cell::RefCell;
use core::{cmp, i32, i8, u32};
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
enum InstrKind {
Unch... | pub(super) fn new(block_encoder: &mut BlockEncoder, block: Rc<RefCell<Block>>, instruction: &Instruction) -> Self {
let mut instr_kind = InstrKind::Uninitialized;
let mut instr_copy: Instruction;
let size;
let short_instruction_size;
let near_instruction_size;
if!block_encoder.fix_branches() {
instr_kin... | random_line_split | |
jmp_instr.rs | // SPDX-License-Identifier: MIT
// Copyright wtfsckgh@gmail.com
// Copyright iced contributors
use super::super::super::iced_error::IcedError;
use super::super::*;
use super::*;
use core::cell::RefCell;
use core::{cmp, i32, i8, u32};
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
enum InstrKind {
Unch... | else {
instr_copy = *instruction;
instr_copy.set_code(instruction.code().as_short_branch());
instr_copy.set_near_branch64(0);
short_instruction_size = block_encoder.get_instruction_size(&instr_copy, 0);
instr_copy = *instruction;
instr_copy.set_code(instruction.code().as_near_branch());
instr_cop... | {
instr_kind = InstrKind::Unchanged;
instr_copy = *instruction;
instr_copy.set_near_branch64(0);
size = block_encoder.get_instruction_size(&instr_copy, 0);
short_instruction_size = 0;
near_instruction_size = 0;
} | conditional_block |
jmp_instr.rs | // SPDX-License-Identifier: MIT
// Copyright wtfsckgh@gmail.com
// Copyright iced contributors
use super::super::super::iced_error::IcedError;
use super::super::*;
use super::*;
use core::cell::RefCell;
use core::{cmp, i32, i8, u32};
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
enum InstrKind {
Unch... | target_address = self.target_instr.address(self);
next_rip = self.ip.wrapping_add(self.near_instruction_size as u64);
diff = target_address.wrapping_sub(next_rip) as i64;
use_near = i32::MIN as i64 <= diff && diff <= i32::MAX as i64;
}
if use_near {
if let Some(ref pointer_data) = self.pointer_data {... | {
if self.instr_kind == InstrKind::Unchanged || self.instr_kind == InstrKind::Short {
return false;
}
let mut target_address = self.target_instr.address(self);
let mut next_rip = self.ip.wrapping_add(self.short_instruction_size as u64);
let mut diff = target_address.wrapping_sub(next_rip) as i64;
if i8:... | identifier_body |
jmp_instr.rs | // SPDX-License-Identifier: MIT
// Copyright wtfsckgh@gmail.com
// Copyright iced contributors
use super::super::super::iced_error::IcedError;
use super::super::*;
use super::*;
use core::cell::RefCell;
use core::{cmp, i32, i8, u32};
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
enum InstrKind {
Unch... | (&self) -> u64 {
self.ip
}
fn set_ip(&mut self, new_ip: u64) {
self.ip = new_ip
}
fn orig_ip(&self) -> u64 {
self.orig_ip
}
fn initialize(&mut self, block_encoder: &BlockEncoder) {
self.target_instr = block_encoder.get_target(self, self.instruction.near_branch_target());
let _ = self.try_optimize();
... | ip | identifier_name |
issue-20831-debruijn.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 ... | () {}
| main | identifier_name |
issue-20831-debruijn.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 ... | // below. Note that changing to a named lifetime made the problem go
// away.
use std::cell::RefCell;
use std::marker::MarkerTrait;
use std::ops::{Shl, Shr};
pub trait Subscriber : MarkerTrait {
type Input;
}
pub trait Publisher<'a> {
type Output;
fn subscribe(&mut self, Box<Subscriber<Input=Self::Output... |
// Regression test for #20831: debruijn index account was thrown off
// by the (anonymous) lifetime in `<Self as Publisher>::Output` | random_line_split |
stylesheet.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 {Prefix, Namespace};
use context::QuirksMode;
use cssparser::{Parser, RuleListParser, ParserInput};
use error_... | !self.disabled()
}
}
impl Stylesheet {
/// Updates an empty stylesheet from a given string of text.
pub fn update_from_str(existing: &Stylesheet,
css: &str,
url_data: UrlExtraData,
stylesheet_loader: Option<&StylesheetL... | fn media<'a>(&'a self, guard: &'a SharedRwLockReadGuard) -> Option<&'a MediaList> {
Some(self.media.read_with(guard))
}
fn enabled(&self) -> bool { | random_line_split |
stylesheet.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 {Prefix, Namespace};
use context::QuirksMode;
use cssparser::{Parser, RuleListParser, ParserInput};
use error_... | (css: &str,
url_data: UrlExtraData,
origin: Origin,
media: Arc<Locked<MediaList>>,
shared_lock: SharedRwLock,
stylesheet_loader: Option<&StylesheetLoader>,
error_reporter: &ParseErrorReporter,
... | from_str | identifier_name |
stylesheet.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 {Prefix, Namespace};
use context::QuirksMode;
use cssparser::{Parser, RuleListParser, ParserInput};
use error_... |
/// Get the media associated with this stylesheet.
fn media<'a>(&'a self, guard: &'a SharedRwLockReadGuard) -> Option<&'a MediaList>;
/// Returns whether the style-sheet applies for the current device.
fn is_effective_for_device(
&self,
device: &Device,
guard: &SharedRwLockRea... | {
self.contents(guard).quirks_mode
} | identifier_body |
msr.rs | // Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
/// Model Specific Registers (MSRs) related functionality.
use std::result;
use arch_gen::x86::msr_index::*;
use kvm_bindings::{kvm_msr_entry, MsrList, Msrs};
use kvm_ioctls::{Kvm, VcpuFd};
#[derive(Debu... | };
ALLOWED_MSR_RANGES.iter().any(|range| range.contains(index))
}
// Creates and populates required MSR entries for booting Linux on X86_64.
fn create_boot_msr_entries() -> Vec<kvm_msr_entry> {
let msr_entry_default = |msr| kvm_msr_entry {
index: msr,
data: 0x0,
..Default::default()
... | if index == MSR_IA32_FEATURE_CONTROL || index == MSR_IA32_MCG_CTL {
return false; | random_line_split |
msr.rs | // Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
/// Model Specific Registers (MSRs) related functionality.
use std::result;
use arch_gen::x86::msr_index::*;
use kvm_bindings::{kvm_msr_entry, MsrList, Msrs};
use kvm_ioctls::{Kvm, VcpuFd};
#[derive(Debu... | ;
ALLOWED_MSR_RANGES.iter().any(|range| range.contains(index))
}
// Creates and populates required MSR entries for booting Linux on X86_64.
fn create_boot_msr_entries() -> Vec<kvm_msr_entry> {
let msr_entry_default = |msr| kvm_msr_entry {
index: msr,
data: 0x0,
..Default::default()
}... | {
return false;
} | conditional_block |
msr.rs | // Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
/// Model Specific Registers (MSRs) related functionality.
use std::result;
use arch_gen::x86::msr_index::*;
use kvm_bindings::{kvm_msr_entry, MsrList, Msrs};
use kvm_ioctls::{Kvm, VcpuFd};
#[derive(Debu... | (index: u32) -> bool {
// Denied MSRs not exported by Linux: IA32_FEATURE_CONTROL and IA32_MCG_CTL
if index == MSR_IA32_FEATURE_CONTROL || index == MSR_IA32_MCG_CTL {
return false;
};
ALLOWED_MSR_RANGES.iter().any(|range| range.contains(index))
}
// Creates and populates required MSR entries fo... | msr_should_serialize | identifier_name |
relu.rs | //! Applies the nonlinear Rectified Linear Unit.
//!
//! Non-linearity activation function: y = max(0, x)
//!
//! This is generally the preferred choice over Sigmod or TanH.
//! The max function used in ReLU is usually faster to compute than the exponentiation
//! needed in a Sigmoid layer.
use co::{IBackend, SharedTe... | input_gradients[0])
.unwrap()
}
None => backend.relu_pointwise_grad(input_data[0], input_gradients[0]).unwrap(),
}
}
}
impl<B: IBackend + Relu<f32> + ReluPointwise<f32>> ComputeParametersGradient<f32, B> for ReLU {} | input_data[0], | random_line_split |
relu.rs | //! Applies the nonlinear Rectified Linear Unit.
//!
//! Non-linearity activation function: y = max(0, x)
//!
//! This is generally the preferred choice over Sigmod or TanH.
//! The max function used in ReLU is usually faster to compute than the exponentiation
//! needed in a Sigmoid layer.
use co::{IBackend, SharedTe... | (&self,
backend: &B,
weights_data: &[&SharedTensor<f32>],
output_data: &[&SharedTensor<f32>],
output_gradients: &[&SharedTensor<f32>],
input_data: &[&SharedTensor<f32>],
... | compute_input_gradient | identifier_name |
relu.rs | //! Applies the nonlinear Rectified Linear Unit.
//!
//! Non-linearity activation function: y = max(0, x)
//!
//! This is generally the preferred choice over Sigmod or TanH.
//! The max function used in ReLU is usually faster to compute than the exponentiation
//! needed in a Sigmoid layer.
use co::{IBackend, SharedTe... |
}
impl<B: IBackend + Relu<f32> + ReluPointwise<f32>> ComputeInputGradient<f32, B> for ReLU {
fn compute_input_gradient(&self,
backend: &B,
weights_data: &[&SharedTensor<f32>],
output_data: &[&SharedTensor<f32>],
... | {
match input_data.get(0) {
Some(input) => backend.relu(input, output_data[0]).unwrap(),
None => backend.relu_pointwise(output_data[0]).unwrap(),
}
} | identifier_body |
relu.rs | //! Applies the nonlinear Rectified Linear Unit.
//!
//! Non-linearity activation function: y = max(0, x)
//!
//! This is generally the preferred choice over Sigmod or TanH.
//! The max function used in ReLU is usually faster to compute than the exponentiation
//! needed in a Sigmoid layer.
use co::{IBackend, SharedTe... |
}
}
impl<B: IBackend + Relu<f32> + ReluPointwise<f32>> ComputeOutput<f32, B> for ReLU {
fn compute_output(&self,
backend: &B,
_weights: &[&SharedTensor<f32>],
input_data: &[&SharedTensor<f32>],
output_data: &mut [&mut Shar... | {
let read_inp = inp.read().unwrap();
let input_desc = read_inp.desc();
input_gradient[0].write().unwrap().resize(input_desc).unwrap();
output_data[0].write().unwrap().resize(input_desc).unwrap();
output_gradient[0].write().unwrap().resize(input_desc).unwrap()... | conditional_block |
renderer.rs | use logic::game::*;
use opengl_graphics::{ GlGraphics };
use graphics::{ Context, DrawState};
use graphics::rectangle::*;
pub struct Renderer {
cellSize: f64,
rectangle: Rectangle,
// cellTexture : Texture,
// cellImage: Image,
}
impl Renderer {
pub fn new(cellSize: isize)->Renderer {
let b = Border{
color:... | (&mut self, coxt:&Context, gl: &mut GlGraphics, game:&Game) {
let board = &game.board;
for i in 0..board.size[0] {
for j in 0..board.size[1] {
if board.occuped([i, j]) > 0 {
let xpos: f64 = i as f64 * self.cellSize;
let ypos: f64 = j as f64 * self.cellSize;
self.rectangle.draw([xpos, ypos, s... | render | identifier_name |
renderer.rs | use logic::game::*;
use opengl_graphics::{ GlGraphics };
use graphics::{ Context, DrawState};
use graphics::rectangle::*;
pub struct Renderer {
cellSize: f64,
rectangle: Rectangle,
// cellTexture : Texture,
// cellImage: Image,
}
impl Renderer {
pub fn new(cellSize: isize)->Renderer {
let b = Border{
color:... | let rect = Rectangle::new([1.0, 1.0, 1.0, 1.0]).border(b);
Renderer {
cellSize: cellSize as f64,
rectangle: rect,
// cellTexture: Texture::from_path(Path::new("rust-2048.png")).unwrap(),
// cellImage: Image::new().rect(square(0.0, 0.0, 10.0)),
}
}
pub fn render(&mut self, coxt:&Context, gl: &mut GlG... | radius: 1.0
}; | random_line_split |
renderer.rs | use logic::game::*;
use opengl_graphics::{ GlGraphics };
use graphics::{ Context, DrawState};
use graphics::rectangle::*;
pub struct Renderer {
cellSize: f64,
rectangle: Rectangle,
// cellTexture : Texture,
// cellImage: Image,
}
impl Renderer {
pub fn new(cellSize: isize)->Renderer {
let b = Border{
color:... |
_ => { }
}
}
} | {
for i in 0..f.1.size[0] {
for j in 0..f.1.size[1] {
if f.1.occuped([i,j]) > 0 {
let xpos: f64 = (i as isize + f.0[0]) as f64 * self.cellSize;
let ypos: f64 = (j as isize + f.0[1]) as f64 * self.cellSize;
self.rectangle.draw([xpos, ypos, self.cellSize, self.cellSize], &DrawState::ne... | conditional_block |
gr_memb.rs | use super::{
errors::ParseErrF,
logsent::{ParseContext, SentID},
parser::{Number, Operator, UVal},
FreeMembershipToClass, GrTerminalKind, GroundedRef, Time,
};
use crate::agent::{
kb::bms::{BmsWrapper, HasBms, RecordHistory},
kb::repr::Representation,
};
use crate::FLOAT_EQ_ULPS;
use float_cmp::... | true
}
} else {
if let Some(val_lhs) = val_lhs {
let val_rhs = val_rhs.unwrap();
val_lhs.approx_eq_ulps(&val_rhs, FLOAT_EQ_ULPS) || val_lhs < val_rhs
} else {
... | val_lhs.approx_eq_ulps(&val_rhs, FLOAT_EQ_ULPS) || val_lhs > val_rhs
} else { | random_line_split |
gr_memb.rs | use super::{
errors::ParseErrF,
logsent::{ParseContext, SentID},
parser::{Number, Operator, UVal},
FreeMembershipToClass, GrTerminalKind, GroundedRef, Time,
};
use crate::agent::{
kb::bms::{BmsWrapper, HasBms, RecordHistory},
kb::repr::Representation,
};
use crate::FLOAT_EQ_ULPS;
use float_cmp::... |
}
#[cfg(feature = "persistence")]
impl storage::ToBinaryObject for GroundedMemb {
fn get_type() -> storage::BinType {
storage::BinType::GrMemb
}
}
| {
self.get_value()
} | identifier_body |
gr_memb.rs | use super::{
errors::ParseErrF,
logsent::{ParseContext, SentID},
parser::{Number, Operator, UVal},
FreeMembershipToClass, GrTerminalKind, GroundedRef, Time,
};
use crate::agent::{
kb::bms::{BmsWrapper, HasBms, RecordHistory},
kb::repr::Representation,
};
use crate::FLOAT_EQ_ULPS;
use float_cmp::... | (&self, other: &GroundedMemb) -> bool {
if &self.term!= other.get_name() {
return false;
}
if self.parent!= other.parent {
return false;
}
if self.operator.is_some() && other.operator.is_none() {
return false;
}
if other.operato... | comparable | identifier_name |
rotation.rs | // Copyright 2015 The CGMath Developers. For a full listing of the authors,
// refer to the Cargo.toml file at the top-level directory of this distribution.
//
// 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 ... | () {
let a: Basis2<_> = rotation::a2();
let a = a.concat(&a.invert());
let a: &Matrix2<_> = a.as_ref();
assert!(a.is_identity());
}
#[test]
fn test_invert_basis3() {
let a: Basis3<_> = rotation::a3();
let a = a.concat(&a.invert());
let a: &Matrix3<_> = a.as_ref();
assert!(a.is_identity(... | test_invert_basis2 | identifier_name |
rotation.rs | // Copyright 2015 The CGMath Developers. For a full listing of the authors,
// refer to the Cargo.toml file at the top-level directory of this distribution.
//
// 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 ... | Rotation3::from_axis_angle(&axis, deg(30.0).into())
}
}
#[test]
fn test_invert_basis2() {
let a: Basis2<_> = rotation::a2();
let a = a.concat(&a.invert());
let a: &Matrix2<_> = a.as_ref();
assert!(a.is_identity());
}
#[test]
fn test_invert_basis3() {
let a: Basis3<_> = rotation::a3();
... | Rotation2::from_angle(deg(30.0).into())
}
pub fn a3<R: Rotation3<f64>>() -> R {
let axis = Vector3::new(1.0, 1.0, 0.0).normalize(); | random_line_split |
rotation.rs | // Copyright 2015 The CGMath Developers. For a full listing of the authors,
// refer to the Cargo.toml file at the top-level directory of this distribution.
//
// 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 ... |
pub fn a3<R: Rotation3<f64>>() -> R {
let axis = Vector3::new(1.0, 1.0, 0.0).normalize();
Rotation3::from_axis_angle(&axis, deg(30.0).into())
}
}
#[test]
fn test_invert_basis2() {
let a: Basis2<_> = rotation::a2();
let a = a.concat(&a.invert());
let a: &Matrix2<_> = a.as_ref();
... | {
Rotation2::from_angle(deg(30.0).into())
} | identifier_body |
sync.rs | use std::io;
use std::net::SocketAddr;
use ldap::Ldap;
use search::{Scope, DerefAliases, SearchEntry};
use tokio_core::reactor::{Core, Handle};
pub struct LdapSync {
inner: Ldap,
core: Core,
}
impl LdapSync {
pub fn connect(addr: &SocketAddr) -> Result<LdapSync, io::Error> {
// TODO better error... | (&mut self,
base: String,
scope: Scope,
deref: DerefAliases,
typesonly: bool,
filter: String,
attrs: Vec<String>) -> io::Result<Vec<SearchEntry>> {
self.core.run(self.inner.search(base, scope, deref, type... | search | identifier_name |
sync.rs | use std::io;
use std::net::SocketAddr;
use ldap::Ldap;
use search::{Scope, DerefAliases, SearchEntry};
use tokio_core::reactor::{Core, Handle};
pub struct LdapSync {
inner: Ldap,
core: Core,
}
impl LdapSync {
pub fn connect(addr: &SocketAddr) -> Result<LdapSync, io::Error> {
// TODO better error... |
pub fn simple_bind(&mut self, dn: String, pw: String) -> io::Result<bool> {
self.core.run(self.inner.simple_bind(dn, pw))
}
pub fn search(&mut self,
base: String,
scope: Scope,
deref: DerefAliases,
typesonly: bool,
... | {
// TODO better error handling
let mut core = Core::new().unwrap();
let handle = core.handle();
let ldapfut = Ldap::connect_ssl(addr, &handle);
let ldap = try!(core.run(ldapfut));
Ok(LdapSync { inner: ldap, core: core })
} | identifier_body |
sync.rs | use std::io;
use std::net::SocketAddr;
use ldap::Ldap;
use search::{Scope, DerefAliases, SearchEntry};
use tokio_core::reactor::{Core, Handle};
pub struct LdapSync {
inner: Ldap,
core: Core,
}
impl LdapSync {
pub fn connect(addr: &SocketAddr) -> Result<LdapSync, io::Error> {
// TODO better error... |
pub fn connect_ssl(addr: &str) -> Result<LdapSync, io::Error> {
// TODO better error handling
let mut core = Core::new().unwrap();
let handle = core.handle();
let ldapfut = Ldap::connect_ssl(addr, &handle);
let ldap = try!(core.run(ldapfut));
Ok(LdapSync { inner: l... |
Ok(LdapSync { inner: ldap, core: core })
} | random_line_split |
alt-pattern-lit.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 ... | () { assert!((altlit(10) == 20)); assert!((altlit(11) == 22)); }
| main | identifier_name |
alt-pattern-lit.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 ... | { assert!((altlit(10) == 20)); assert!((altlit(11) == 22)); } | identifier_body | |
alt-pattern-lit.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 ... | 11 => { debug!("case 11"); return 22; }
_ => fail!(~"the impossible happened")
}
}
pub fn main() { assert!((altlit(10) == 20)); assert!((altlit(11) == 22)); } | 10 => { debug!("case 10"); return 20; } | random_line_split |
alt-pattern-lit.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 ... |
11 => { debug!("case 11"); return 22; }
_ => fail!(~"the impossible happened")
}
}
pub fn main() { assert!((altlit(10) == 20)); assert!((altlit(11) == 22)); }
| { debug!("case 10"); return 20; } | conditional_block |
main.rs | &[
(2, &format!("{:.1}", p.cpu_usage())),
(3, &format_number(memory)),
(
4,
&if disk_usage > 0 {
format_number(disk_usage)
... | (line: &str) -> Vec<String> {
match (line.find('\''), line.find('"')) {
(Some(x), Some(y)) => {
if x < y {
parse_quote(line, '\'')
} else {
parse_quote(line, '"')
}
}
(Some(_), None) => parse_quote(line, '\''),
(None... | parse_entry | identifier_name |
main.rs | (8, &disk_usage),
],
);
valid = list.iter_next(&iter);
seen.insert(pid);
} else {
valid = list.remove(&iter);
}
}
}
for (pid, pro) in entries.iter() {
if!seen.contains(pid) {
... | });
application.add_action(&about); | random_line_split | |
main.rs | (2, &format!("{:.1}", p.cpu_usage())),
(3, &format_number(memory)),
(
4,
&if disk_usage > 0 {
format_number(disk_usage)
} else {
... | {
let mut seen: HashSet<Pid> = HashSet::new();
if let Some(iter) = list.iter_first() {
let mut valid = true;
while valid {
let pid = match list.value(&iter, 0).get::<u32>() {
Ok(pid) => Pid::from_u32(pid),
_ => {
valid = list.iter_... | identifier_body | |
struct_with_struct.rs | /* automatically generated by rust-bindgen */
#![allow(non_snake_case)]
#[repr(C)]
#[derive(Debug, Copy)]
pub struct foo {
pub bar: foo__bindgen_ty_1,
}
#[repr(C)]
#[derive(Debug, Copy)]
pub struct foo__bindgen_ty_1 {
pub x: ::std::os::raw::c_uint,
pub y: ::std::os::raw::c_uint,
}
#[test]
fn bindgen_tes... | }
impl Clone for foo {
fn clone(&self) -> Self { *self }
} | random_line_split | |
struct_with_struct.rs | /* automatically generated by rust-bindgen */
#![allow(non_snake_case)]
#[repr(C)]
#[derive(Debug, Copy)]
pub struct foo {
pub bar: foo__bindgen_ty_1,
}
#[repr(C)]
#[derive(Debug, Copy)]
pub struct foo__bindgen_ty_1 {
pub x: ::std::os::raw::c_uint,
pub y: ::std::os::raw::c_uint,
}
#[test]
fn bindgen_tes... | () {
assert_eq!(::std::mem::size_of::<foo>(), 8usize);
assert_eq!(::std::mem::align_of::<foo>(), 4usize);
}
impl Clone for foo {
fn clone(&self) -> Self { *self }
}
| bindgen_test_layout_foo | identifier_name |
mod.rs | pub mod audio;
pub mod video;
pub mod container;
use std::ffi::OsString;
use std::error::Error as StdError;
use std::fmt;
#[derive(Debug)]
pub enum Error {
TooShort,
TooLong,
InvalidArg(String, &'static str)
}
impl StdError for Error {
fn description(&self) -> &str {
match *self {
... | (s: Option<String>) -> Result<container::Codec, Error> {
match s {
Some(s) => match try!(container::Codec::from_args(s.split(","))) {
(codec, mut rest) => {
match rest.next().is_some() {
false => {
Ok(codec)
}
... | get_container | identifier_name |
mod.rs | pub mod audio;
pub mod video;
pub mod container;
use std::ffi::OsString;
use std::error::Error as StdError;
use std::fmt;
#[derive(Debug)]
pub enum Error {
TooShort,
TooLong,
InvalidArg(String, &'static str)
}
impl StdError for Error {
fn description(&self) -> &str {
match *self {
... | }
true => {
Err(Error::TooLong)
}
}
}
},
None => Ok(container::Codec::default())
}
} | false => {
Ok(codec) | random_line_split |
frontend.rs | use std::path::{Path, PathBuf};
//use std::collections::HashMap;
use serde::Serialize;
use rocket_contrib::Template;
use rocket::response::NamedFile;
use rocket::Route;
use rocket::response::{Redirect, Failure};
use rocket::http::Status;
use rocket::request::Form;
use rocket::response::Flash;
use context_builder::Con... | <'a, T: Serialize>(current_url: Option<&'a str>, context_builder: &mut ContextBuilder<'a, T>) {
let menu_builder = context_builder.menu_builder("main");
if let Some(url) = current_url {
menu_builder.set_active(url);
}
}
#[get("/")]
fn index(db: DbConn, mut context_builder: ContextBuilder<Vec<Post>... | prepare_context_builder | identifier_name |
frontend.rs | use std::path::{Path, PathBuf};
//use std::collections::HashMap;
use serde::Serialize;
use rocket_contrib::Template;
use rocket::response::NamedFile;
use rocket::Route;
use rocket::response::{Redirect, Failure};
use rocket::http::Status;
use rocket::request::Form;
use rocket::response::Flash;
use context_builder::Con... |
#[get("/post")]
fn new_post_form(mut context_builder: ContextBuilder<NewPostForm>) -> Template {
prepare_context_builder(Some("/post/new"), &mut context_builder);
let context = context_builder.finalize_with_default();
Template::render("frontend/create", &context)
}
#[post("/post", data = "<post>")]
fn ne... | {
prepare_context_builder(Some("/"), &mut context_builder);
let posts = posts::posts(&db).into_iter().map(|mut post| {
post.body = parse_markdown(&post.body);
post
}).collect();
let context = context_builder.finalize_with_data(posts);
Template::render("frontend/index", &context)
} | identifier_body |
frontend.rs | use std::path::{Path, PathBuf};
//use std::collections::HashMap;
use serde::Serialize;
use rocket_contrib::Template;
use rocket::response::NamedFile;
use rocket::Route;
use rocket::response::{Redirect, Failure};
use rocket::http::Status;
use rocket::request::Form;
use rocket::response::Flash;
use context_builder::Con... | }
/// Parses markdown to html using pulldown_cmark.
fn parse_markdown(md: &str) -> String {
use pulldown_cmark::{Parser, html, Options, OPTION_ENABLE_TABLES, OPTION_ENABLE_FOOTNOTES};
let mut options = Options::empty();
options.insert(OPTION_ENABLE_TABLES);
options.insert(OPTION_ENABLE_FOOTNOTES);
... | /// This is automatically protected from requesting files outside of the `static/` directory.
#[get("/<path..>", rank = 1000)]
fn static_files(path: PathBuf) -> Option<NamedFile> {
NamedFile::open(Path::new("static/").join(path)).ok() | random_line_split |
lib.rs | // Copyright 2014 The syscall.rs Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>... | pub mod platform; | random_line_split | |
mod.rs | // Copyright 2020 Google LLC
//
// Use of this source code is governed by an MIT-style license that can be found
// in the LICENSE file or at https://opensource.org/licenses/MIT.
#[cfg(any(target_os = "windows", test))]
mod wtf8;
use std::path::PathBuf;
/// Interprets given bytes as an operating system path.
///
///... | /// A type enumerating all possible error kinds of path parsing errors.
#[derive(Debug, PartialEq, Eq)]
#[non_exhaustive]
enum ParseErrorKind {
/// Parsing failed because of issues with decoding a WTF-8 string.
#[cfg(target_family = "windows")]
Wtf8(wtf8::ParseError),
} | }
}
| random_line_split |
mod.rs | // Copyright 2020 Google LLC
//
// Use of this source code is governed by an MIT-style license that can be found
// in the LICENSE file or at https://opensource.org/licenses/MIT.
#[cfg(any(target_os = "windows", test))]
mod wtf8;
use std::path::PathBuf;
/// Interprets given bytes as an operating system path.
///
///... | {
/// Parsing failed because of issues with decoding a WTF-8 string.
#[cfg(target_family = "windows")]
Wtf8(wtf8::ParseError),
}
| ParseErrorKind | identifier_name |
mod.rs | // Copyright 2020 Google LLC
//
// Use of this source code is governed by an MIT-style license that can be found
// in the LICENSE file or at https://opensource.org/licenses/MIT.
#[cfg(any(target_os = "windows", test))]
mod wtf8;
use std::path::PathBuf;
/// Interprets given bytes as an operating system path.
///
///... |
#[cfg(target_family = "windows")]
fn from_bytes_impl(bytes: Vec<u8>) -> Result<PathBuf, ParseError> {
let bytes_u16 = wtf8::into_ill_formed_utf16(bytes)?;
use std::os::windows::ffi::OsStringExt as _;
Ok(std::ffi::OsString::from_wide(&bytes_u16).into())
}
#[cfg(target_family = "unix")]
fn into_bytes_impl... | {
use std::os::unix::ffi::OsStringExt as _;
Ok(std::ffi::OsString::from_vec(bytes).into())
} | identifier_body |
generate_lockfile.rs | use std::env;
use cargo::ops;
use cargo::util::{CliResult, Config};
use cargo::util::important_paths::find_root_manifest_for_wd;
#[derive(RustcDecodable)]
struct Options {
flag_manifest_path: Option<String>,
flag_verbose: bool,
flag_quiet: bool,
flag_color: Option<String>,
}
pub const USAGE: &'static... | try!(config.shell().set_verbosity(options.flag_verbose, options.flag_quiet));
try!(config.shell().set_color_config(options.flag_color.as_ref().map(|s| &s[..])));
let root = try!(find_root_manifest_for_wd(options.flag_manifest_path, config.cwd()));
try!(ops::generate_lockfile(&root, config));
Ok(Non... | --color WHEN Coloring: auto, always, never
";
pub fn execute(options: Options, config: &Config) -> CliResult<Option<()>> {
debug!("executing; cmd=cargo-generate-lockfile; args={:?}", env::args().collect::<Vec<_>>()); | random_line_split |
generate_lockfile.rs | use std::env;
use cargo::ops;
use cargo::util::{CliResult, Config};
use cargo::util::important_paths::find_root_manifest_for_wd;
#[derive(RustcDecodable)]
struct | {
flag_manifest_path: Option<String>,
flag_verbose: bool,
flag_quiet: bool,
flag_color: Option<String>,
}
pub const USAGE: &'static str = "
Generate the lockfile for a project
Usage:
cargo generate-lockfile [options]
Options:
-h, --help Print this message
--manifest-path PA... | Options | identifier_name |
capsule.rs | reset if the capsule can't start */
for (vid, params) in c.iter_init()
{
if let Err(_e) = add_vcore(cid, *vid, params.entry, params.dtb, params.prio)
{
hvalert!("Failed to restart capsule {} vcore {}: {:?}", cid, vid, _e);
}
... | (&mut self, to_add: Mapping)
{
self.memory.push(to_add);
}
/* get a copy of the capsule's memory mappings */
pub fn get_memory_mappings(&self) -> Vec<Mapping> { self.memory.clone() }
/* returns true if property is present for this capsule, or false if not */
pub fn has_property(&self, ... | set_memory_mapping | identifier_name |
capsule.rs |
/* empty the waiting list of capsules to restart and recreate their vcores */
pub fn restart_awaiting()
{
for cid in TO_RESTART.lock().drain()
{
if let Some(c) = CAPSULES.lock().get_mut(&cid)
{
/* capsule is ready to roll again, call this before injecting
virtual cores i... | () => ($crate::capsule::restart_awaiting());
} | random_line_split | |
capsule.rs | hard reset if the capsule can't start */
for (vid, params) in c.iter_init()
{
if let Err(_e) = add_vcore(cid, *vid, params.entry, params.dtb, params.prio)
{
hvalert!("Failed to restart capsule {} vcore {}: {:?}", cid, vid, _e);
... | else
{
/* either add to the capsule's output buffer, or create a new buffer */
let mut stdout = STDOUT.lock();
match stdout.get_mut(&cid)
{
Some(entry) => entry.push(character),
None =>
... | {
let cid = match pcore::PhysicalCore::get_capsule_id()
{
Some(c) => c,
None => return Err(Cause::CapsuleBadID)
};
/* find the capsule we're going to write into */
match CAPSULES.lock().get_mut(&cid)
{
Some(capsule) =>
{
/* if this capsule can write s... | identifier_body |
capsule.rs | reset if the capsule can't start */
for (vid, params) in c.iter_init()
{
if let Err(_e) = add_vcore(cid, *vid, params.entry, params.dtb, params.prio)
{
hvalert!("Failed to restart capsule {} vcore {}: {:?}", cid, vid, _e);
}
... | trigger the final teardown via drop */
lock.remove(&cid);
hvdebug!("Completed termination of capsule {}", cid);
}
return Ok(());
},
false => return Err(Cause::CapsuleCantDie)
}
}
else
... | {
match victim.set_state_dying()
{
true =>
{
/* remove this current vcore ID from the capsule's
hash table. also mark the vcore as doomed, meaning
it will be dropped when it's context switched out */
victim.remove_vc... | conditional_block |
vga_buffer.rs | use core::fmt;
use core::ptr::Unique;
use volatile::Volatile;
use spin::Mutex;
#[allow(dead_code)] // Don't complain about unused variables.
#[derive(Debug, Clone, Copy)]
#[repr(u8)] // Store each value as byte.
pub enum Color {
Black = 0,
Blue = 1,
Green = 2,
Cyan = 3,
... | (&mut self, byte: u8) {
match byte {
b'\n' => self.new_line(),
byte => {
if self.column_position >= BUFFER_WIDTH {
self.new_line();
}
let row = BUFFER_HEIGHT - 1;
let col = self.column_po... | write_byte | identifier_name |
vga_buffer.rs | use core::fmt;
use core::ptr::Unique;
use volatile::Volatile;
use spin::Mutex;
#[allow(dead_code)] // Don't complain about unused variables.
#[derive(Debug, Clone, Copy)]
#[repr(u8)] // Store each value as byte.
pub enum Color {
Black = 0,
Blue = 1,
Green = 2,
Cyan = 3,
... |
fn buffer(&mut self) -> &mut Buffer {
unsafe {
self.buffer.as_mut()
}
}
fn new_line(&mut self) {
// Omit 0th row because that's shifted off screen.
for row in 1..BUFFER_HEIGHT {
for col in 0..BUFFER_WIDTH {
let buffer = self.buffer()... | {
match byte {
b'\n' => self.new_line(),
byte => {
if self.column_position >= BUFFER_WIDTH {
self.new_line();
}
let row = BUFFER_HEIGHT - 1;
let col = self.column_position;
... | identifier_body |
vga_buffer.rs | use core::fmt;
use core::ptr::Unique;
use volatile::Volatile;
use spin::Mutex;
#[allow(dead_code)] // Don't complain about unused variables.
#[derive(Debug, Clone, Copy)]
#[repr(u8)] // Store each value as byte.
pub enum Color {
Black = 0,
Blue = 1,
Green = 2,
Cyan = 3,
... | fn buffer(&mut self) -> &mut Buffer {
unsafe {
self.buffer.as_mut()
}
}
fn new_line(&mut self) {
// Omit 0th row because that's shifted off screen.
for row in 1..BUFFER_HEIGHT {
for col in 0..BUFFER_WIDTH {
let buffer = self.buffer();
... | }
}
}
| random_line_split |
locals_opt_default.rs | // RUN: %Slang %s
// RUN: %rs-filecheck-wrapper %s
// CHECK-NOT: define internal i32 @main(
// CHECK-NOT: %f = alloca float,
// CHECK-NOT: %pf = alloca float*,
// CHECK-NOT: %ppn = alloca i32**,
// This test case should behave identically to locals_opt_3.rs.
struct | {
float f;
float f2[2];
} compound_float;
static
int main(int argc, char* argv[])
{
float f = 0.f;
float *pf = &f;
double d[2][2] = {{0, 1}, {2, 3.0}};
struct float_struct s;
unsigned short us = -1;
const unsigned long l = (unsigned long) -1.0e8f;
{
int** ppn = 0;
if (ppn) {
return... | float_struct | identifier_name |
locals_opt_default.rs | // RUN: %Slang %s
// RUN: %rs-filecheck-wrapper %s
// CHECK-NOT: define internal i32 @main(
// CHECK-NOT: %f = alloca float,
// CHECK-NOT: %pf = alloca float*,
// CHECK-NOT: %ppn = alloca i32**,
// This test case should behave identically to locals_opt_3.rs.
struct float_struct {
float f;
float f2[2];
} compound_... | }
}
s.f = 10e-4f;
s.f2[0] = 1e4f;
s.f2[1] = 100.5f;
double result = pf[0] * d[1][1] * s.f * us * l;
return (result == 0? 0 : -1);
}
void the_main() {
main(0, 0);
}
#pragma version(1)
#pragma rs java_package_name(foo) | random_line_split | |
locals_opt_default.rs | // RUN: %Slang %s
// RUN: %rs-filecheck-wrapper %s
// CHECK-NOT: define internal i32 @main(
// CHECK-NOT: %f = alloca float,
// CHECK-NOT: %pf = alloca float*,
// CHECK-NOT: %ppn = alloca i32**,
// This test case should behave identically to locals_opt_3.rs.
struct float_struct {
float f;
float f2[2];
} compound_... |
}
s.f = 10e-4f;
s.f2[0] = 1e4f;
s.f2[1] = 100.5f;
double result = pf[0] * d[1][1] * s.f * us * l;
return (result == 0? 0 : -1);
}
void the_main() {
main(0, 0);
}
#pragma version(1)
#pragma rs java_package_name(foo)
| {
return -1;
} | conditional_block |
test_cargo_run.rs | use std::path;
use support::{project, execs};
use support::{COMPILING, RUNNING};
use hamcrest::{assert_that, existing_file};
fn setup() {
}
test!(simple {
let p = project("foo")
.file("Cargo.toml", r#"
[project]
name = "foo"
version = "0.0.1"
authors = []
... | .file("Cargo.toml", r#"
[project]
name = "foo"
version = "0.0.1"
authors = []
"#)
.file("src/main.rs", r#"
fn main() {
assert_eq!(std::os::args().get(1).as_slice(), "hello");
assert_eq!(std::os::args().get(... | let p = project("foo") | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.