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 |
|---|---|---|---|---|
range.rs | use std::borrow::Borrow;
use std::collections::HashSet;
use enums::Direction;
use structs::Point;
use traits::travel::Travel;
use traits::range::Base;
/// Trait wrapping range implementation
pub trait Range: Borrow<Point> {
/// Find the points within the provided manhattan distance
fn range(&self, range: i32) -> ... | () {
let point: Point = Point(1, 2, 5);
let set: HashSet<Point> = point.range(1);
assert!(set.contains(&Point(1, 2, 5)));
assert!(set.contains(&Point(2, 2, 5)));
assert!(set.contains(&Point(1, 3, 5)));
assert!(set.contains(&Point(0, 3, 5)));
assert!(set.contains(&Point(0, 2, 5)));
asser... | range | identifier_name |
range.rs | use std::borrow::Borrow;
use std::collections::HashSet;
use enums::Direction;
use structs::Point;
use traits::travel::Travel;
use traits::range::Base;
/// Trait wrapping range implementation
pub trait Range: Borrow<Point> {
/// Find the points within the provided manhattan distance
fn range(&self, range: i32) -> ... |
}
| {
let point: Point = Point(1, 2, 5);
let set: HashSet<Point> = point.range(1);
assert!(set.contains(&Point(1, 2, 5)));
assert!(set.contains(&Point(2, 2, 5)));
assert!(set.contains(&Point(1, 3, 5)));
assert!(set.contains(&Point(0, 3, 5)));
assert!(set.contains(&Point(0, 2, 5)));
assert!(... | identifier_body |
range.rs | use std::borrow::Borrow;
use std::collections::HashSet;
use enums::Direction;
use structs::Point;
use traits::travel::Travel;
use traits::range::Base;
/// Trait wrapping range implementation
pub trait Range: Borrow<Point> {
/// Find the points within the provided manhattan distance
fn range(&self, range: i32) -> ... | }
set
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn range() {
let point: Point = Point(1, 2, 5);
let set: HashSet<Point> = point.range(1);
assert!(set.contains(&Point(1, 2, 5)));
assert!(set.contains(&Point(2, 2, 5)));
assert!(set.contains(&Point(1, 3, 5)));
assert!(s... |
set.extend(point.travel(&Direction::Up, index).base_range(diff));
set.extend(point.travel(&Direction::Down, index).base_range(diff)); | random_line_split |
script.rs | #[cfg(any(target_arch = "x86", target_arch = "arm"))]
pub type Word = u32;
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
pub type Word = u64;
#[cfg_attr(any(target_arch = "x86_64", target_arch = "aarch64"), repr(C, u64))]
#[cfg_attr(any(target_arch = "x86", target_arch = "arm"), repr(C, u32))]
#[allow(d... | {
/// Close last opened file and open a new file.
OpenNext(LoadStatementOpen),
/// Open a file, and save the file descriptor.
Open(LoadStatementOpen),
/// Map a part of the last opened file into memory.
MmapFile(LoadStatementMmap),
/// Mapping a segment of anonymous private space into memor... | LoadStatement | identifier_name |
script.rs | #[cfg(any(target_arch = "x86", target_arch = "arm"))]
pub type Word = u32;
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
pub type Word = u64;
#[cfg_attr(any(target_arch = "x86_64", target_arch = "aarch64"), repr(C, u64))]
#[cfg_attr(any(target_arch = "x86", target_arch = "arm"), repr(C, u32))]
#[allow(d... | StartTraced(LoadStatementStart),
///
Start(LoadStatementStart),
}
#[repr(C)]
#[derive(Debug)]
pub struct LoadStatementOpen {
pub string_address: Word,
}
#[repr(C)]
#[derive(Debug)]
pub struct LoadStatementMmap {
/// The starting address for the new mapping.
pub addr: Word,
/// The length o... | MmapAnonymous(LoadStatementMmap),
/// Set the stack space to be executable
MakeStackExec(LoadStatementStackExec),
/// (The purpose of the project is not yet clear) | random_line_split |
mod.rs | use num::{ToPrimitive, FromPrimitive};
use std::ptr;
use EventPump;
use rect::Rect;
use video::Window;
use sys::keyboard as ll;
mod keycode;
mod scancode;
pub use self::keycode::Keycode;
pub use self::scancode::Scancode;
bitflags! {
flags Mod: u32 {
const NOMOD = 0x0000,
const LSHIFTMOD = 0x0001... | (&mut self) -> Option<Scancode> {
while let Some((scancode, pressed)) = self.iter.next() {
if pressed { return Some(scancode) }
}
None
}
}
impl ::Sdl {
#[inline]
pub fn keyboard(&self) -> KeyboardUtil {
KeyboardUtil {
_sdldrop: self.sdldrop()
... | next | identifier_name |
mod.rs | use num::{ToPrimitive, FromPrimitive};
use std::ptr;
use EventPump;
use rect::Rect;
use video::Window;
use sys::keyboard as ll;
mod keycode;
mod scancode;
pub use self::keycode::Keycode;
pub use self::scancode::Scancode;
bitflags! {
flags Mod: u32 {
const NOMOD = 0x0000,
const LSHIFTMOD = 0x0001... | /// Returns an iterator all scancodes with a boolean indicating if the scancode is pressed.
pub fn scancodes(&self) -> ScancodeIterator {
ScancodeIterator {
index: 0,
keyboard_state: self.keyboard_state
}
}
/// Returns an iterator of pressed scancodes.
///
... | random_line_split | |
mod.rs | use num::{ToPrimitive, FromPrimitive};
use std::ptr;
use EventPump;
use rect::Rect;
use video::Window;
use sys::keyboard as ll;
mod keycode;
mod scancode;
pub use self::keycode::Keycode;
pub use self::scancode::Scancode;
bitflags! {
flags Mod: u32 {
const NOMOD = 0x0000,
const LSHIFTMOD = 0x0001... |
}
pub fn mod_state(&self) -> Mod {
unsafe { Mod::from_bits(ll::SDL_GetModState()).unwrap() }
}
pub fn set_mod_state(&self, flags: Mod) {
unsafe { ll::SDL_SetModState(flags.bits()); }
}
}
/// Text input utility functions. Access with `VideoSubsystem::text_input()`.
///
/// These f... | {
let id = unsafe { ::sys::video::SDL_GetWindowID(raw) };
Some(id)
} | conditional_block |
main.rs | //
// gash.rs
//
// Starting code for PS2
// Running on Rust 0.9
//
// University of Virginia - cs4414 Spring 2014
// Weilin Xu, David Evans
// Version 0.4
//
extern crate getopts;
use getopts::{optopt, getopts};
use std::io::BufferedReader;
use std::io::Command;
use std::io::stdin;
use std::{io, os};
use std::str;
... |
}
fn get_cmdline_from_args() -> Option<String> {
/* Begin processing program arguments and initiate the parameters. */
let args = os::args();
let opts = &[
getopts::optopt("c", "", "", "")
];
getopts::getopts(args.tail(), opts).unwrap().opt_str("c")
}
fn main() {
let opt_cmd_line = ... | {
Command::new("which").arg(cmd_path).status().unwrap().success()
} | identifier_body |
main.rs | //
// gash.rs
//
// Starting code for PS2
// Running on Rust 0.9
//
// University of Virginia - cs4414 Spring 2014
// Weilin Xu, David Evans
// Version 0.4
//
extern crate getopts;
use getopts::{optopt, getopts};
use std::io::BufferedReader;
use std::io::Command;
use std::io::stdin;
use std::{io, os};
use std::str;
... |
}
}
}
fn run_cmdline(&self, cmd_line: &str) {
let argv: Vec<&str> = cmd_line.split(' ').filter_map(|x| {
if x == "" {
None
} else {
Some(x)
}
}).collect();
match argv.first() {
Some(&pr... | { self.run_cmdline(cmd_line); } | conditional_block |
main.rs | //
// gash.rs
//
// Starting code for PS2
// Running on Rust 0.9
//
// University of Virginia - cs4414 Spring 2014
// Weilin Xu, David Evans
// Version 0.4
//
extern crate getopts;
use getopts::{optopt, getopts};
use std::io::BufferedReader;
use std::io::Command;
use std::io::stdin;
use std::{io, os};
use std::str;
... | }
fn get_cmdline_from_args() -> Option<String> {
/* Begin processing program arguments and initiate the parameters. */
let args = os::args();
let opts = &[
getopts::optopt("c", "", "", "")
];
getopts::getopts(args.tail(), opts).unwrap().opt_str("c")
}
fn main() {
let opt_cmd_line = g... | fn cmd_exists(&self, cmd_path: &str) -> bool {
Command::new("which").arg(cmd_path).status().unwrap().success()
} | random_line_split |
main.rs | //
// gash.rs
//
// Starting code for PS2
// Running on Rust 0.9
//
// University of Virginia - cs4414 Spring 2014
// Weilin Xu, David Evans
// Version 0.4
//
extern crate getopts;
use getopts::{optopt, getopts};
use std::io::BufferedReader;
use std::io::Command;
use std::io::stdin;
use std::{io, os};
use std::str;
... | (&self, cmd_line: &str) {
let argv: Vec<&str> = cmd_line.split(' ').filter_map(|x| {
if x == "" {
None
} else {
Some(x)
}
}).collect();
match argv.first() {
Some(&program) => self.run_cmd(program, argv.tail()),
... | run_cmdline | identifier_name |
query.rs | use common::{ApiError, Body, Credentials, Query, QueryParams, discovery_api};
use hyper::method::Method::Get;
use serde_json::Value;
pub fn query(creds: &Credentials,
env_id: &str,
collection_id: &str,
query: QueryParams)
-> Result<Value, ApiError> {
let path = "... | (creds: &Credentials,
env_id: &str,
collection_id: &str,
query: QueryParams)
-> Result<Value, ApiError> {
let path = "/v1/environments/".to_string() + env_id + "/collections/" +
collection_id + "/notices";
Ok(discovery_api(creds, Get, &p... | notices | identifier_name |
query.rs | use common::{ApiError, Body, Credentials, Query, QueryParams, discovery_api};
use hyper::method::Method::Get;
use serde_json::Value;
pub fn query(creds: &Credentials,
env_id: &str,
collection_id: &str,
query: QueryParams)
-> Result<Value, ApiError> |
pub fn notices(creds: &Credentials,
env_id: &str,
collection_id: &str,
query: QueryParams)
-> Result<Value, ApiError> {
let path = "/v1/environments/".to_string() + env_id + "/collections/" +
collection_id + "/notices";
Ok(discovery_ap... | {
let path = "/v1/environments/".to_string() + env_id + "/collections/" +
collection_id + "/query";
Ok(discovery_api(creds, Get, &path, Query::Query(query), &Body::None)?)
} | identifier_body |
query.rs | use common::{ApiError, Body, Credentials, Query, QueryParams, discovery_api};
use hyper::method::Method::Get;
use serde_json::Value;
pub fn query(creds: &Credentials,
env_id: &str,
collection_id: &str,
query: QueryParams)
-> Result<Value, ApiError> {
let path = "... | -> Result<Value, ApiError> {
let path = "/v1/environments/".to_string() + env_id + "/collections/" +
collection_id + "/notices";
Ok(discovery_api(creds, Get, &path, Query::Query(query), &Body::None)?)
} | random_line_split | |
xy_pad.rs |
use {
Backend,
Color,
Colorable,
Frameable,
FramedRectangle,
FontSize,
IndexSlot,
Labelable,
Line,
Mouse,
Positionable,
Scalar,
Sizeable,
Text,
Widget,
};
use num::Float;
use widget;
use utils::{map_range, val_to_string};
/// Used for displaying and control... | (&self) -> Self::State {
State {
interaction: Interaction::Normal,
x: self.x, min_x: self.min_x, max_x: self.max_x,
y: self.y, min_y: self.min_y, max_y: self.max_y,
rectangle_idx: IndexSlot::new(),
label_idx: IndexSlot::new(),
h_line_idx: I... | init_state | identifier_name |
xy_pad.rs |
use {
Backend,
Color,
Colorable,
Frameable,
FramedRectangle,
FontSize,
IndexSlot,
Labelable,
Line,
Mouse,
Positionable,
Scalar,
Sizeable,
Text,
Widget,
};
use num::Float;
use widget;
use utils::{map_range, val_to_string};
/// Used for displaying and control... |
fn unique_kind(&self) -> &'static str {
KIND
}
fn init_state(&self) -> Self::State {
State {
interaction: Interaction::Normal,
x: self.x, min_x: self.min_x, max_x: self.max_x,
y: self.y, min_y: self.min_y, max_y: self.max_y,
rectangle_idx: I... | {
&mut self.common
} | identifier_body |
xy_pad.rs | use {
Backend,
Color,
Colorable,
Frameable,
FramedRectangle,
FontSize,
IndexSlot,
Labelable,
Line,
Mouse,
Positionable,
Scalar,
Sizeable,
Text,
Widget,
};
use num::Float;
use widget;
use utils::{map_range, val_to_string};
/// Used for displaying and controll... | #[derive(Debug, PartialEq, Clone, Copy)]
pub enum Interaction {
Normal,
Highlighted,
Clicked,
}
impl Interaction {
/// The color associated with the current state.
fn color(&self, color: Color) -> Color {
match *self {
Interaction::Normal => color,
Interaction::Highl... | v_line_idx: IndexSlot,
value_label_idx: IndexSlot,
}
/// The interaction state of the XYPad. | random_line_split |
TestRemainder.rs | /*
* Copyright (C) 2016 The Android Open Source Project
*
* 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 app... | * limitations under the License.
*/
// Don't edit this file! It is auto-generated by frameworks/rs/api/generate.sh.
#pragma version(1)
#pragma rs java_package_name(android.renderscript.cts)
rs_allocation gAllocInDenominator;
float __attribute__((kernel)) testRemainderFloatFloatFloat(float inNumerator, unsigned i... | * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and | random_line_split |
test.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let magic: u64 = 0xDEADBEEF;
// Let's test calling it cross crate
let back = unsafe {
testcrate::give_back(mem::transmute(magic))
};
assert_eq!(magic, back);
// And just within this crate
let back = unsafe {
give_back(mem::transmute(magic))
};
assert_eq!(magic,... | main | identifier_name |
test.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern crate tes... | random_line_split | |
test.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let magic: u64 = 0xDEADBEEF;
// Let's test calling it cross crate
let back = unsafe {
testcrate::give_back(mem::transmute(magic))
};
assert_eq!(magic, back);
// And just within this crate
let back = unsafe {
give_back(mem::transmute(magic))
};
assert_eq!(magic, ba... | identifier_body | |
configuration.rs | use clingo::*;
use std::env;
fn print_prefix(depth: u8) {
println!();
for _ in 0..depth {
print!(" ");
}
}
// recursively print the configuartion object
fn print_configuration(conf: &Configuration, key: Id, depth: u8) | // print array offset (with prefix for readability)
let subkey = conf
.array_at(key, i)
.expect("Failed to retrieve statistics array.");
print_prefix(depth);
print!("{}:", i);
// recursively print sube... | {
// get the type of an entry and switch over its various values
let configuration_type = conf.configuration_type(key).unwrap();
match configuration_type {
// print values
ConfigurationType::VALUE => {
let value = conf
.value_get(key)
.expect("Fail... | identifier_body |
configuration.rs | use clingo::*;
use std::env;
fn print_prefix(depth: u8) {
println!();
for _ in 0..depth {
print!(" ");
}
}
// recursively print the configuartion object
fn print_configuration(conf: &Configuration, key: Id, depth: u8) {
// get the type of an entry and switch over its various values
let co... | .expect("Failed to ground a logic program.");
// solve
solve(&mut ctl);
} |
// ground the base part
let part = Part::new("base", &[]).unwrap();
let parts = vec![part];
ctl.ground(&parts) | random_line_split |
configuration.rs | use clingo::*;
use std::env;
fn print_prefix(depth: u8) {
println!();
for _ in 0..depth {
print!(" ");
}
}
// recursively print the configuartion object
fn print_configuration(conf: &Configuration, key: Id, depth: u8) {
// get the type of an entry and switch over its various values
let co... | (ctl: &mut Control) {
// get a solve handle
let mut handle = ctl
.solve(SolveMode::YIELD, &[])
.expect("Failed retrieving solve handle.");
// loop over all models
loop {
handle.resume().expect("Failed resume on solve handle.");
match handle.model() {
// print t... | solve | identifier_name |
text.rs | impl specs::Component for FixedCamera {
type Storage = specs::NullStorage<Self>;
}
pub struct FixedCameraText {
pub string: String,
}
impl specs::Component for FixedCameraText {
type Storage = specs::VecStorage<Self>;
}
impl FixedCameraText {
pub fn new(s: String) -> Self {
FixedCameraText {
... | use specs;
#[derive(Clone,Default)]
pub struct FixedCamera; | random_line_split | |
text.rs | use specs;
#[derive(Clone,Default)]
pub struct FixedCamera;
impl specs::Component for FixedCamera {
type Storage = specs::NullStorage<Self>;
}
pub struct FixedCameraText {
pub string: String,
}
impl specs::Component for FixedCameraText {
type Storage = specs::VecStorage<Self>;
}
impl FixedCameraText {
... | (s: String) -> Self {
FixedCameraText {
string: s,
}
}
}
pub struct Text {
pub string: String,
pub x: f32,
pub y: f32,
pub scale: f32,
}
impl specs::Component for Text {
type Storage = specs::VecStorage<Self>;
}
impl Text {
pub fn new(x: f32, y: f32, scale: f32,... | new | identifier_name |
trade.rs | use types::deserialize::*;
use std::fmt;
use std::cmp::{Ord, Ordering};
#[derive(Debug, PartialEq, Serialize, Clone, Copy)]
pub enum TradeApi {
BTC,
LTC,
ETH,
ETC,
}
impl fmt::Display for TradeApi {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&TradeApi... | fn cmp(&self, other: &Trade) -> Ordering {
self.tid.cmp(&other.tid)
}
}
impl PartialOrd for Trade {
fn partial_cmp(&self, other: &Trade) -> Option<Ordering> {
Some(self.tid.cmp(&other.tid))
}
}
impl Eq for Trade {}
#[derive(Deserialize, Debug, Serialize)]
pub struct TradeResponse {
... | random_line_split | |
trade.rs |
use types::deserialize::*;
use std::fmt;
use std::cmp::{Ord, Ordering};
#[derive(Debug, PartialEq, Serialize, Clone, Copy)]
pub enum TradeApi {
BTC,
LTC,
ETH,
ETC,
}
impl fmt::Display for TradeApi {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&TradeAp... | (&self, other: &Trade) -> Ordering {
self.tid.cmp(&other.tid)
}
}
impl PartialOrd for Trade {
fn partial_cmp(&self, other: &Trade) -> Option<Ordering> {
Some(self.tid.cmp(&other.tid))
}
}
impl Eq for Trade {}
#[derive(Deserialize, Debug, Serialize)]
pub struct TradeResponse {
order_id:... | cmp | identifier_name |
var-captured-in-nested-closure.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn main() {
let mut variable = 1;
let constant = 2;
let a_struct = Struct {
a: -3,
b: 4.5,
c: 5
};
let struct_ref = &a_struct;
let owned = ~6;
let managed = @7;
let closure = || {
let closure_local = 8;
let nested_closure = || {
zz... | } | random_line_split |
var-captured-in-nested-closure.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let mut variable = 1;
let constant = 2;
let a_struct = Struct {
a: -3,
b: 4.5,
c: 5
};
let struct_ref = &a_struct;
let owned = ~6;
let managed = @7;
let closure = || {
let closure_local = 8;
let nested_closure = || {
zzz();
... | main | identifier_name |
mod.rs | use std::path::Path;
use std::process::{Command, Stdio};
use url::Url;
use ::consts::*;
pub mod errors;
pub mod ipv4;
pub mod md5sum;
pub mod notify;
pub mod url;
use self::errors::*;
use self::ipv4::IPv4;
macro_rules! xE {
( $x:expr ) => { xE!($x,) };
( $x:expr, $($k:ident => $v:expr),* ) => {
xml::Elem... | (path: Option<&Path>, ip: &IPv4, hostname: &str) -> Result<()> {
let hosts_path: &str = match path {
Some(v) => v.to_str().unwrap(),
None => "/etc/hosts",
};
// create autogenerated part if not exists.
{
let pat = format!("/# autogenerated by {}/{{:a;$!{{N;ba}};q;}};$ a\\\\n# \
... | update_etc_hosts | identifier_name |
mod.rs | use std::path::Path;
use std::process::{Command, Stdio};
use url::Url;
use ::consts::*;
pub mod errors;
pub mod ipv4;
pub mod md5sum;
pub mod notify;
pub mod url;
use self::errors::*;
use self::ipv4::IPv4;
macro_rules! xE {
( $x:expr ) => { xE!($x,) };
( $x:expr, $($k:ident => $v:expr),* ) => {
xml::Elem... | f.write(orig1.as_bytes()).expect("write into temp hosts file failed");
// pattern 1.
{
let ip1 = IPv4::from_cidr_notation("11.11.11.11/24").unwrap();
let entry1 = (&ip1, &"test11".to_string());
// "3" is just an arbitrary num. to show idempotence
... | {
let temp_file = env::temp_dir().join(".test_update_etc_hosts");
let mut f = File::create(&temp_file).expect("failed to create file");
let orig1 = "\
# The following lines are desirable for IPv4 capable hosts\n\
127.0.0.1 localhost.localdomain localhost\n\
12... | identifier_body |
mod.rs | use std::path::Path;
use std::process::{Command, Stdio};
use url::Url;
use ::consts::*;
pub mod errors;
pub mod ipv4;
pub mod md5sum;
pub mod notify;
pub mod url;
use self::errors::*;
use self::ipv4::IPv4;
macro_rules! xE {
( $x:expr ) => { xE!($x,) };
( $x:expr, $($k:ident => $v:expr),* ) => {
xml::Elem... | ;
match Command::new("wget")
.args(&[remote_url.as_str(), option, local_path.to_str().unwrap()])
.stderr(Stdio::null())
.status() {
Ok(status) if status.success() => Ok(()),
Ok(status) => {
Err(format!("`wget {} {} {}` failed [error: {}]",
rem... | { "-O" } | conditional_block |
mod.rs | use std::path::Path;
use std::process::{Command, Stdio};
use url::Url;
use ::consts::*;
pub mod errors;
pub mod ipv4;
pub mod md5sum;
pub mod notify;
pub mod url;
use self::errors::*;
use self::ipv4::IPv4;
macro_rules! xE {
( $x:expr ) => { xE!($x,) };
( $x:expr, $($k:ident => $v:expr),* ) => {
xml::Elem... | }
macro_rules! cmd {
( $x:expr ) => {{
let vec = $x.split(" ").collect::<Vec<&str>>();
let (ref head, ref tail) = vec.split_first().unwrap();
Command::new(head).args(tail)
}}
}
// Update /etc/hosts file on host side (where the entire programme
// is running) to enable ssh login guest node just spe... | }} | random_line_split |
sync-rwlock-read-mode-shouldnt-escape.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 |
// error-pattern: cannot infer an appropriate lifetime
extern mod extra;
use extra::sync;
fn main() {
let x = ~sync::RWlock();
let mut y = None;
do x.write_downgrade |write_mode| {
y = Some(x.downgrade(write_mode));
}
// Adding this line causes a method unification failure instead
// do... | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms. | random_line_split |
sync-rwlock-read-mode-shouldnt-escape.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 x = ~sync::RWlock();
let mut y = None;
do x.write_downgrade |write_mode| {
y = Some(x.downgrade(write_mode));
}
// Adding this line causes a method unification failure instead
// do (&option::unwrap(y)).read { }
}
| main | identifier_name |
sync-rwlock-read-mode-shouldnt-escape.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 x = ~sync::RWlock();
let mut y = None;
do x.write_downgrade |write_mode| {
y = Some(x.downgrade(write_mode));
}
// Adding this line causes a method unification failure instead
// do (&option::unwrap(y)).read { }
} | identifier_body | |
console.rs | // Copyright © 2018 Cormac O'Brien | // Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
// BUT NOT L... | //
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell... | random_line_split |
console.rs | // Copyright © 2018 Cormac O'Brien
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use, copy, modify, merge, publish,
// ... | },
_ => (),
},
_ => (),
}
Ok(())
}
}
|
match event {
Event::WindowEvent { event, .. } => match event {
WindowEvent::ReceivedCharacter(c) => self.console.borrow_mut().send_char(c),
WindowEvent::KeyboardInput {
input:
KeyboardInput {
v... | identifier_body |
console.rs | // Copyright © 2018 Cormac O'Brien
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use, copy, modify, merge, publish,
// ... | {
console: Rc<RefCell<Console>>,
}
impl ConsoleInput {
pub fn new(console: Rc<RefCell<Console>>) -> ConsoleInput {
ConsoleInput { console }
}
pub fn handle_event<T>(&self, event: Event<T>) -> Result<(), Error> {
match event {
Event::WindowEvent { event,.. } => match event {... | onsoleInput | identifier_name |
main.rs | #[macro_use]
extern crate gfx;
extern crate gfx_support;
extern crate image;
use std::io::Cursor;
use std::time::Instant;
use gfx::format::Rgba8;
use gfx_support::{BackbufferView, ColorFormat};
use gfx::{Bundle, GraphicsPoolExt};
gfx_defines!{
vertex Vertex {
pos: [f32; 2] = "a_Pos",
uv: [f32; 2] ... | Vertex::new([ 1.0, -1.0], [1.0, 0.0]),
Vertex::new([ 1.0, 1.0], [1.0, 1.0]),
Vertex::new([-1.0, -1.0], [0.0, 0.0]),
Vertex::new([ 1.0, 1.0], [1.0, 1.0]),
Vertex::new([-1.0, 1.0], [0.0, 1.0]),
];
let (vbuf, slice) = device.create_vertex_buf... | {
use gfx::traits::DeviceExt;
let vs = gfx_support::shade::Source {
glsl_120: include_bytes!("shader/flowmap_120.glslv"),
glsl_150: include_bytes!("shader/flowmap_150.glslv"),
hlsl_40: include_bytes!("data/vertex.fx"),
msl_11: include_bytes!("shader/fl... | identifier_body |
main.rs | #[macro_use]
extern crate gfx;
extern crate gfx_support;
extern crate image;
use std::io::Cursor;
use std::time::Instant;
use gfx::format::Rgba8;
use gfx_support::{BackbufferView, ColorFormat};
use gfx::{Bundle, GraphicsPoolExt};
gfx_defines!{
vertex Vertex {
pos: [f32; 2] = "a_Pos",
uv: [f32; 2] ... |
self.cycles[1] += 0.25 * delta;
if self.cycles[1] > 1.0 {
self.cycles[1] -= 1.0;
}
let (cur_color, _) = self.views[frame.id()].clone();
self.bundle.data.out = cur_color;
let mut encoder = pool.acquire_graphics_encoder();
self.bundle.data.offset0 = s... | {
self.cycles[0] -= 1.0;
} | conditional_block |
main.rs | #[macro_use]
extern crate gfx;
extern crate gfx_support;
extern crate image;
use std::io::Cursor;
use std::time::Instant;
use gfx::format::Rgba8;
use gfx_support::{BackbufferView, ColorFormat};
use gfx::{Bundle, GraphicsPoolExt};
gfx_defines!{
vertex Vertex {
pos: [f32; 2] = "a_Pos",
uv: [f32; 2] ... |
impl<B: gfx::Backend> gfx_support::Application<B> for App<B> {
fn new(device: &mut B::Device,
_: &mut gfx::queue::GraphicsQueue<B>,
backend: gfx_support::shade::Backend,
window_targets: gfx_support::WindowTargets<B::Resources>) -> Self
{
use gfx::traits::DeviceExt;
... | } | random_line_split |
main.rs | #[macro_use]
extern crate gfx;
extern crate gfx_support;
extern crate image;
use std::io::Cursor;
use std::time::Instant;
use gfx::format::Rgba8;
use gfx_support::{BackbufferView, ColorFormat};
use gfx::{Bundle, GraphicsPoolExt};
gfx_defines!{
vertex Vertex {
pos: [f32; 2] = "a_Pos",
uv: [f32; 2] ... | (p: [f32; 2], u: [f32; 2]) -> Vertex {
Vertex {
pos: p,
uv: u,
}
}
}
fn load_texture<R, D>(device: &mut D, data: &[u8])
-> Result<gfx::handle::ShaderResourceView<R, [f32; 4]>, String>
where R: gfx::Resources, D: gfx::Device<R> {
use gfx::texture a... | new | identifier_name |
test_default_bytes.rs | // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | }
}
macro_rules! regex_set {
($res:expr) => {
regex_set_new!($res).unwrap()
}
}
// Must come before other module definitions.
include!("macros_bytes.rs");
include!("macros.rs");
mod api;
mod bytes;
mod crazy;
mod flags;
mod fowler;
mod multiline;
mod noparse;
mod regression;
mod replace;
mod set;... | }
macro_rules! regex {
($re:expr) => {
regex_new!($re).unwrap() | random_line_split |
regions-mock-trans-impls.rs | // xfail-fast
// 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
// <... | () {
let ccx = Ccx { x: 0 };
f(&ccx);
}
| main | identifier_name |
regions-mock-trans-impls.rs | // xfail-fast
// 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
// <... | arena: &'self Arena,
ccx: &'self Ccx
}
struct Ccx {
x: int
}
fn h<'r>(bcx : &'r Bcx<'r>) -> &'r Bcx<'r> {
return bcx.fcx.arena.alloc(|| Bcx { fcx: bcx.fcx });
}
fn g(fcx : &Fcx) {
let bcx = Bcx { fcx: fcx };
h(&bcx);
}
fn f(ccx : &Ccx) {
let a = Arena();
let fcx = &Fcx { arena: &a, c... | fcx: &'self Fcx<'self>
}
struct Fcx<'self> { | random_line_split |
unboxed-closures-manual-impl.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
impl FnOnce<(i32,)> for S {
type Output = i32;
extern "rust-call" fn call_once(mut self, args: (i32,)) -> i32 { self.call_mut(args) }
}
fn call_it<F:FnMut(i32)->i32>(mut f: F, x: i32) -> i32 {
f(x) + 3
}
fn call_box(f: &mut FnMut(i32) -> i32, x: i32) -> i32 {
f(x) + 3
}
fn main() {
let x = call... | impl FnMut<(i32,)> for S {
extern "rust-call" fn call_mut(&mut self, (x,): (i32,)) -> i32 {
x * x
}
} | random_line_split |
unboxed-closures-manual-impl.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (mut self, args: (i32,)) -> i32 { self.call_mut(args) }
}
fn call_it<F:FnMut(i32)->i32>(mut f: F, x: i32) -> i32 {
f(x) + 3
}
fn call_box(f: &mut FnMut(i32) -> i32, x: i32) -> i32 {
f(x) + 3
}
fn main() {
let x = call_it(S, 1);
let y = call_box(&mut S, 1);
assert_eq!(x, 4);
assert_eq!(y, 4);
... | call_once | identifier_name |
unboxed-closures-manual-impl.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
impl FnOnce<(i32,)> for S {
type Output = i32;
extern "rust-call" fn call_once(mut self, args: (i32,)) -> i32 { self.call_mut(args) }
}
fn call_it<F:FnMut(i32)->i32>(mut f: F, x: i32) -> i32 {
f(x) + 3
}
fn call_box(f: &mut FnMut(i32) -> i32, x: i32) -> i32 {
f(x) + 3
}
fn main() {
let x = c... | {
x * x
} | identifier_body |
text_buffer.rs | // Copyright 2013-2016, 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 libc::{c_char, c_int};
use std::boxed::Box as Box_;
use std::mem::transmute;
use std::{sl... | <F: Fn(&TextBuffer, &mut TextIter, &str) +'static>(&self, f: F) -> SignalHandlerId {
unsafe {
let f: Box_<Box_<Fn(&TextBuffer, &mut TextIter, &str) +'static>> = Box_::new(Box_::new(f));
connect(self.to_glib_none().0, "insert-text",
transmute(insert_text_trampoline as usiz... | connect_insert_text | identifier_name |
text_buffer.rs | // Copyright 2013-2016, 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 libc::{c_char, c_int};
use std::boxed::Box as Box_;
use std::mem::transmute;
use std::{sl... | &mut from_glib_borrow(location),
str::from_utf8(slice::from_raw_parts(text as *const u8, len as usize)).unwrap())
} | random_line_split | |
text_buffer.rs | // Copyright 2013-2016, 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 libc::{c_char, c_int};
use std::boxed::Box as Box_;
use std::mem::transmute;
use std::{sl... |
}
unsafe extern "C" fn insert_text_trampoline(this: *mut ffi::GtkTextBuffer,
location: *mut ffi::GtkTextIter,
text: *mut c_char,
len: c_int,
f... | {
unsafe {
let f: Box_<Box_<Fn(&TextBuffer, &mut TextIter, &str) + 'static>> = Box_::new(Box_::new(f));
connect(self.to_glib_none().0, "insert-text",
transmute(insert_text_trampoline as usize), Box_::into_raw(f) as *mut _)
}
} | identifier_body |
ssl.rs | // #![feature(plugin)]
// #![plugin(clippy)]
extern crate cassandra_sys;
use std::mem;
use std::io::Result as IoResult;
use std::io::Read;
use std::fs::File;
use cassandra_sys::*;
use std::ffi::CString;
fn load_trusted_cert_file(file: &str, ssl: &mut CassSsl) -> IoResult<()> {
unsafe {
let mut file = try... |
rc => {
println!("Failed to load certificate disabling peer verification: {:?}",
rc);
cass_ssl_set_verify_flags(ssl, CASS_SSL_VERIFY_NONE as i32);
}
}
cass_cluster_set_ssl(cluster, ssl);
let connect_future = cass... | {} | conditional_block |
ssl.rs | // #![feature(plugin)]
// #![plugin(clippy)]
extern crate cassandra_sys;
use std::mem;
use std::io::Result as IoResult;
use std::io::Read;
use std::fs::File;
use cassandra_sys::*;
use std::ffi::CString;
fn load_trusted_cert_file(file: &str, ssl: &mut CassSsl) -> IoResult<()> {
unsafe {
let mut file = try... | unsafe {
// Setup and connect to cluster
let cluster = cass_cluster_new();
let session = cass_session_new();
let ssl = cass_ssl_new();
cass_cluster_set_contact_points(cluster, CString::new("127.0.0.1").unwrap().as_ptr());
// Only verify the certification and not the... |
fn main() { | random_line_split |
ssl.rs | // #![feature(plugin)]
// #![plugin(clippy)]
extern crate cassandra_sys;
use std::mem;
use std::io::Result as IoResult;
use std::io::Read;
use std::fs::File;
use cassandra_sys::*;
use std::ffi::CString;
fn load_trusted_cert_file(file: &str, ssl: &mut CassSsl) -> IoResult<()> | }
}
}
fn main() {
unsafe {
// Setup and connect to cluster
let cluster = cass_cluster_new();
let session = cass_session_new();
let ssl = cass_ssl_new();
cass_cluster_set_contact_points(cluster, CString::new("127.0.0.1").unwrap().as_ptr());
// Only veri... | {
unsafe {
let mut file = try!(File::open(file));
let cert_size = try!(file.metadata()).len() as usize;
let mut cert: Vec<u8> = Vec::with_capacity(cert_size);
let byte_len = try!(file.read_to_end(&mut cert));
match byte_len == cert_size {
true => {
... | identifier_body |
ssl.rs | // #![feature(plugin)]
// #![plugin(clippy)]
extern crate cassandra_sys;
use std::mem;
use std::io::Result as IoResult;
use std::io::Read;
use std::fs::File;
use cassandra_sys::*;
use std::ffi::CString;
fn load_trusted_cert_file(file: &str, ssl: &mut CassSsl) -> IoResult<()> {
unsafe {
let mut file = try... | () {
unsafe {
// Setup and connect to cluster
let cluster = cass_cluster_new();
let session = cass_session_new();
let ssl = cass_ssl_new();
cass_cluster_set_contact_points(cluster, CString::new("127.0.0.1").unwrap().as_ptr());
// Only verify the certification and no... | main | identifier_name |
mod.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/. */
//! Animated values.
//!
//! Some values, notably colors, cannot be interpolated directly with their
//! computed ... | ///
/// This trait is derivable with `#[derive(ToAnimatedValue)]`.
pub trait ToAnimatedValue {
/// The type of the animated value.
type AnimatedValue;
/// Converts this value to an animated value.
fn to_animated_value(self) -> Self::AnimatedValue;
/// Converts back an animated value into a compute... | }
/// Conversion between computed values and intermediate values for animations.
///
/// Notably, colors are represented as four floats during animations. | random_line_split |
mod.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/. */
//! Animated values.
//!
//! Some values, notably colors, cannot be interpolated directly with their
//! computed ... |
let a = a.as_shorthand().unwrap();
let b = b.as_shorthand().unwrap();
// Within shorthands, sort by the number of subproperties, then by IDL
// name.
let subprop_count_a = a.longhands().count();
let subprop_count_b = b.longhands().count();
subprop_count_a
.cmp(&subprop_count_b)
... |
return cmp::Ordering::Equal;
}
| conditional_block |
mod.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/. */
//! Animated values.
//!
//! Some values, notably colors, cannot be interpolated directly with their
//! computed ... |
#[inline]
fn from_animated_value(animated: Self::AnimatedValue) -> Self {
ComputedBorderCornerRadius::new(
(animated.0).0.width.clamp_to_non_negative(),
(animated.0).0.height.clamp_to_non_negative(),
)
}
}
impl ToAnimatedZero for Au {
#[inline]
fn to_animate... |
self
}
| identifier_body |
mod.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/. */
//! Animated values.
//!
//! Some values, notably colors, cannot be interpolated directly with their
//! computed ... | &self) -> Result<Self, ()> {
Ok(0)
}
}
impl<T> ToAnimatedZero for Option<T>
where
T: ToAnimatedZero,
{
#[inline]
fn to_animated_zero(&self) -> Result<Self, ()> {
match *self {
Some(ref value) => Ok(Some(value.to_animated_zero()?)),
None => Ok(None),
}
... | o_animated_zero( | identifier_name |
main.rs | #![deny(
missing_debug_implementations,
missing_copy_implementations,
warnings,
trivial_numeric_casts,
unstable_features,
unused,
future_incompatible
)]
use actix_web::server;
use anyhow::Result;
use log::info;
use potboiler_common::pg;
use std::env;
fn main() -> Result<()> | {
log4rs::init_file("log.yaml", Default::default()).expect("log config ok");
let db_url: &str = &env::var("DATABASE_URL").expect("Needed DATABASE_URL");
let pool = pg::get_pool(db_url).unwrap();
let app_state = pigtail::AppState::new(pool)?;
let port: u16 = env::var("PORT")
.unwrap_or_else(|... | identifier_body | |
main.rs | #![deny(
missing_debug_implementations,
missing_copy_implementations,
warnings,
trivial_numeric_casts,
unstable_features,
unused,
future_incompatible
)]
use actix_web::server;
use anyhow::Result;
use log::info;
use potboiler_common::pg;
use std::env;
fn | () -> Result<()> {
log4rs::init_file("log.yaml", Default::default()).expect("log config ok");
let db_url: &str = &env::var("DATABASE_URL").expect("Needed DATABASE_URL");
let pool = pg::get_pool(db_url).unwrap();
let app_state = pigtail::AppState::new(pool)?;
let port: u16 = env::var("PORT")
.... | main | identifier_name |
main.rs | #![deny(
missing_debug_implementations,
missing_copy_implementations,
warnings,
trivial_numeric_casts,
unstable_features,
unused,
future_incompatible
)]
use actix_web::server;
use anyhow::Result;
use log::info;
use potboiler_common::pg;
use std::env;
fn main() -> Result<()> {
log4rs::i... | .unwrap()
.run();
pigtail::register();
info!("Pigtail booted");
Ok(())
} | .bind(("0.0.0.0", port)) | random_line_split |
aggregate_kernels.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... |
}
builder.finish()
}
fn create_string_array(size: usize, with_nulls: bool) -> StringArray {
// use random numbers to avoid spurious compiler optimizations wrt to branching
let mut rng = seedable_rng();
let mut builder = StringBuilder::new(size);
for _ in 0..size {
if with_nulls && rng... | {
builder.append_value(rng.gen()).unwrap();
} | conditional_block |
aggregate_kernels.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | (arr_a: &Float32Array) {
criterion::black_box(sum(&arr_a).unwrap());
}
fn bench_min(arr_a: &Float32Array) {
criterion::black_box(min(&arr_a).unwrap());
}
fn bench_min_string(arr_a: &StringArray) {
criterion::black_box(min_string(&arr_a).unwrap());
}
fn add_benchmark(c: &mut Criterion) {
let arr_a = c... | bench_sum | identifier_name |
aggregate_kernels.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | let arr_b = create_string_array(512, false);
c.bench_function("min string 512", |b| b.iter(|| bench_min_string(&arr_b)));
let arr_b = create_string_array(512, true);
c.bench_function("min nulls string 512", |b| {
b.iter(|| bench_min_string(&arr_b))
});
}
criterion_group!(benches, add_bench... | random_line_split | |
aggregate_kernels.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... |
fn add_benchmark(c: &mut Criterion) {
let arr_a = create_array(512, false);
c.bench_function("sum 512", |b| b.iter(|| bench_sum(&arr_a)));
c.bench_function("min 512", |b| b.iter(|| bench_min(&arr_a)));
let arr_a = create_array(512, true);
c.bench_function("sum nulls 512", |b| b.iter(|| bench_su... | {
criterion::black_box(min_string(&arr_a).unwrap());
} | identifier_body |
map.rs | //! Extension methods for `Stream` based on record-by-record transformation.
use Data;
use dataflow::{Stream, Scope};
use dataflow::channels::pact::Pipeline;
use dataflow::operators::unary::Unary;
/// Extension trait for `Stream`.
pub trait Map<S: Scope, D: Data> {
/// Consumes each element of the stream and yiel... | /// ```
fn map_in_place<L: Fn(&mut D)+'static>(&self, logic: L) -> Stream<S, D>;
/// Consumes each element of the stream and yields some number of new elements.
///
/// #Examples
/// ```
/// use timely::dataflow::operators::{ToStream, Map, Inspect};
///
/// timely::example(|scope| {
... | random_line_split | |
map.rs | //! Extension methods for `Stream` based on record-by-record transformation.
use Data;
use dataflow::{Stream, Scope};
use dataflow::channels::pact::Pipeline;
use dataflow::operators::unary::Unary;
/// Extension trait for `Stream`.
pub trait Map<S: Scope, D: Data> {
/// Consumes each element of the stream and yiel... | <I: Iterator, L: Fn(D)->I+'static>(&self, logic: L) -> Stream<S, I::Item> where I::Item: Data {
self.unary_stream(Pipeline, "FlatMap", move |input, output| {
input.for_each(|time, data| {
output.session(&time).give_iterator(data.drain(..).flat_map(|x| logic(x)));
});
... | flat_map | identifier_name |
map.rs | //! Extension methods for `Stream` based on record-by-record transformation.
use Data;
use dataflow::{Stream, Scope};
use dataflow::channels::pact::Pipeline;
use dataflow::operators::unary::Unary;
/// Extension trait for `Stream`.
pub trait Map<S: Scope, D: Data> {
/// Consumes each element of the stream and yiel... |
// fn filter_map<D2: Data, L: Fn(D)->Option<D2>+'static>(&self, logic: L) -> Stream<S, D2> {
// self.unary_stream(Pipeline, "FilterMap", move |input, output| {
// while let Some((time, data)) = input.next() {
// output.session(time).give_iterator(data.drain(..).filter_map(|x| lo... | {
self.unary_stream(Pipeline, "FlatMap", move |input, output| {
input.for_each(|time, data| {
output.session(&time).give_iterator(data.drain(..).flat_map(|x| logic(x)));
});
})
} | identifier_body |
sync.rs | /*
(C) Joshua Yanovski (@pythonesque)
https://gist.github.com/pythonesque/5bdf071d3617b61b3fed
*/
#![allow(dead_code)]
use std::cell::UnsafeCell;
use std::mem;
use std::sync::{self, MutexGuard, Mutex};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::marker::PhantomData;
// This may seem useless but pro... | let _g3 = LOCK.try_lock();
let _g4 = LOCK.lock();
}
} | random_line_split | |
sync.rs | /*
(C) Joshua Yanovski (@pythonesque)
https://gist.github.com/pythonesque/5bdf071d3617b61b3fed
*/
#![allow(dead_code)]
use std::cell::UnsafeCell;
use std::mem;
use std::sync::{self, MutexGuard, Mutex};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::marker::PhantomData;
// This may seem useless but pro... | (&self) -> bool {
self.get_thread_id() == self.owner.load(Ordering::Relaxed)
}
fn store_thread_id(&self, guard: MutexGuard<()>) {
unsafe {
let tid = self.get_thread_id();
self.owner.store(tid, Ordering::Relaxed);
*self.guard.get() = mem::transmute(Box::new(gu... | is_same_thread | identifier_name |
sync.rs | /*
(C) Joshua Yanovski (@pythonesque)
https://gist.github.com/pythonesque/5bdf071d3617b61b3fed
*/
#![allow(dead_code)]
use std::cell::UnsafeCell;
use std::mem;
use std::sync::{self, MutexGuard, Mutex};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::marker::PhantomData;
// This may seem useless but pro... |
fn is_same_thread(&self) -> bool {
self.get_thread_id() == self.owner.load(Ordering::Relaxed)
}
fn store_thread_id(&self, guard: MutexGuard<()>) {
unsafe {
let tid = self.get_thread_id();
self.owner.store(tid, Ordering::Relaxed);
*self.guard.get() = mem... | {
THREAD_ID.with(|x| x as *const _ as usize)
} | identifier_body |
pde.rs | use ndarray::*;
use ndarray_linalg::*;
use std::f64::consts::PI;
use std::iter::FromIterator;
use eom::pde::*;
#[test]
fn pair_r2c2r() {
let n = 128;
let a: Array1<f64> = random(n);
let mut p = Pair::new(n);
p.r.copy_from_slice(&a.as_slice().unwrap());
p.r2c();
p.c2r();
let b: Array1<f64> ... | let n = 128;
let k0 = 2.0 * PI / n as f64;
let a = Array::from_shape_fn(n, |i| 2.0 * (i as f64 * k0).cos());
let mut p = Pair::new(n);
p.c[1] = c64::new(1.0, 0.0);
p.c2r();
let b = Array::from_iter(p.r.iter().cloned());
assert_close_l2!(&a, &b, 1e-7);
} | fn pair_c2r() { | random_line_split |
pde.rs | use ndarray::*;
use ndarray_linalg::*;
use std::f64::consts::PI;
use std::iter::FromIterator;
use eom::pde::*;
#[test]
fn | () {
let n = 128;
let a: Array1<f64> = random(n);
let mut p = Pair::new(n);
p.r.copy_from_slice(&a.as_slice().unwrap());
p.r2c();
p.c2r();
let b: Array1<f64> = Array::from_iter(p.r.iter().cloned());
assert_close_l2!(&a, &b, 1e-7);
}
#[test]
fn pair_c2r() {
let n = 128;
let k0 = ... | pair_r2c2r | identifier_name |
pde.rs | use ndarray::*;
use ndarray_linalg::*;
use std::f64::consts::PI;
use std::iter::FromIterator;
use eom::pde::*;
#[test]
fn pair_r2c2r() {
let n = 128;
let a: Array1<f64> = random(n);
let mut p = Pair::new(n);
p.r.copy_from_slice(&a.as_slice().unwrap());
p.r2c();
p.c2r();
let b: Array1<f64> ... | {
let n = 128;
let k0 = 2.0 * PI / n as f64;
let a = Array::from_shape_fn(n, |i| 2.0 * (i as f64 * k0).cos());
let mut p = Pair::new(n);
p.c[1] = c64::new(1.0, 0.0);
p.c2r();
let b = Array::from_iter(p.r.iter().cloned());
assert_close_l2!(&a, &b, 1e-7);
} | identifier_body | |
convert_string_literal.rs | use rstest::*;
use std::net::SocketAddr;
| #[case(true, r#"4.3.2.1:24"#)]
#[case(false, "[2001:db8:85a3:8d3:1319:8a2e:370:7348]:443")]
#[case(false, r#"[2aa1:db8:85a3:8af:1319:8a2e:375:4873]:344"#)]
#[case(false, "this.is.not.a.socket.address")]
#[case(false, r#"this.is.not.a.socket.address"#)]
fn cases(#[case] expected: bool, #[case] addr: SocketAddr) {
as... | #[rstest]
#[case(true, "1.2.3.4:42")] | random_line_split |
convert_string_literal.rs | use rstest::*;
use std::net::SocketAddr;
#[rstest]
#[case(true, "1.2.3.4:42")]
#[case(true, r#"4.3.2.1:24"#)]
#[case(false, "[2001:db8:85a3:8d3:1319:8a2e:370:7348]:443")]
#[case(false, r#"[2aa1:db8:85a3:8af:1319:8a2e:375:4873]:344"#)]
#[case(false, "this.is.not.a.socket.address")]
#[case(false, r#"this.is.not.a.socket... | (#[case] cases: &[u8], #[values(b"abc")] values: &[u8]) {
assert_eq!(5, cases.len());
assert_eq!(3, values.len());
}
trait MyTrait {
fn my_trait(&self) -> u32 {
42
}
}
impl MyTrait for &str {}
#[rstest]
#[case("impl", "nothing")]
fn not_convert_impl(#[case] that_impl: impl MyTrait, #[case] s:... | not_convert_byte_array | identifier_name |
color.rs | use std::ops::{Add, Mul};
use std::iter::Sum;
#[derive(Copy, Clone, Serialize, Deserialize)]
pub struct Color(pub f64, pub f64, pub f64);
pub const RED: Color = Color(1.0, 0.0, 0.0);
pub const GREEN: Color = Color(0.0, 1.0, 0.0);
pub const BLUE: Color = Color(0.0, 0.0, 1.0);
pub const WHITE: Color = Color(1.0, 1.0, 1... | if self.1 > 1.0 {
self.1 = 1.0;
}
if self.2 > 1.0 {
self.2 = 1.0;
}
(
(255.0 * self.0) as u8,
(255.0 * self.1) as u8,
(255.0 * self.2) as u8,
)
}
}
impl Sum for Color {
fn sum<I>(iter: I) -> Self
wh... | if self.0 > 1.0 {
self.0 = 1.0;
} | random_line_split |
color.rs | use std::ops::{Add, Mul};
use std::iter::Sum;
#[derive(Copy, Clone, Serialize, Deserialize)]
pub struct Color(pub f64, pub f64, pub f64);
pub const RED: Color = Color(1.0, 0.0, 0.0);
pub const GREEN: Color = Color(0.0, 1.0, 0.0);
pub const BLUE: Color = Color(0.0, 0.0, 1.0);
pub const WHITE: Color = Color(1.0, 1.0, 1... | <I>(iter: I) -> Self
where
I: Iterator<Item = Self>,
{
iter.fold(Color(0.0, 0.0, 0.0), |s, c| s + c)
}
}
| sum | identifier_name |
color.rs | use std::ops::{Add, Mul};
use std::iter::Sum;
#[derive(Copy, Clone, Serialize, Deserialize)]
pub struct Color(pub f64, pub f64, pub f64);
pub const RED: Color = Color(1.0, 0.0, 0.0);
pub const GREEN: Color = Color(0.0, 1.0, 0.0);
pub const BLUE: Color = Color(0.0, 0.0, 1.0);
pub const WHITE: Color = Color(1.0, 1.0, 1... |
}
impl Into<(u8, u8, u8)> for Color {
fn into(mut self) -> (u8, u8, u8) {
if self.0 > 1.0 {
self.0 = 1.0;
}
if self.1 > 1.0 {
self.1 = 1.0;
}
if self.2 > 1.0 {
self.2 = 1.0;
}
(
(255.0 * self.0) as u8,
... | {
Color(self.0 * other, self.1 * other, self.2 * other)
} | identifier_body |
color.rs | use std::ops::{Add, Mul};
use std::iter::Sum;
#[derive(Copy, Clone, Serialize, Deserialize)]
pub struct Color(pub f64, pub f64, pub f64);
pub const RED: Color = Color(1.0, 0.0, 0.0);
pub const GREEN: Color = Color(0.0, 1.0, 0.0);
pub const BLUE: Color = Color(0.0, 0.0, 1.0);
pub const WHITE: Color = Color(1.0, 1.0, 1... |
if self.1 > 1.0 {
self.1 = 1.0;
}
if self.2 > 1.0 {
self.2 = 1.0;
}
(
(255.0 * self.0) as u8,
(255.0 * self.1) as u8,
(255.0 * self.2) as u8,
)
}
}
impl Sum for Color {
fn sum<I>(iter: I) -> Self
w... | {
self.0 = 1.0;
} | conditional_block |
config.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | {
/// Indicates if tracing should be enabled or not.
/// If it's None, it will be automatically configured.
pub enabled: bool,
/// Traces blooms configuration.
pub blooms: BloomConfig,
/// Preferef cache-size.
pub pref_cache_size: usize,
/// Max cache-size.
pub max_cache_size: usize,
}
impl Default for Confi... | Config | identifier_name |
config.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | use bloomchain::Config as BloomConfig;
/// Traces config.
#[derive(Debug, PartialEq, Clone)]
pub struct Config {
/// Indicates if tracing should be enabled or not.
/// If it's None, it will be automatically configured.
pub enabled: bool,
/// Traces blooms configuration.
pub blooms: BloomConfig,
/// Preferef cach... | // along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Traces config. | random_line_split |
hook_macro.rs | //! A macro that handles hooking an exported function that may have already
//! been hooked in a way that GetProcAddress doesn't return the expected dll.
use std::io;
use libc::c_void;
use crate::windows;
// It would be preferrable to refactor this macro away to some sort of an api like
// ```
// let mut hook = ... |
// Short jump
0xeb => {
let offset = *address.add(1) as i8 as isize as usize;
address = address.wrapping_add(2).wrapping_add(offset);
}
_ => return Ok(address as usize),
}
}
}
| {
let offset = (address.add(1) as *const i32).read_unaligned() as isize as usize;
address = address.wrapping_add(5).wrapping_add(offset);
} | conditional_block |
hook_macro.rs | //! A macro that handles hooking an exported function that may have already
//! been hooked in a way that GetProcAddress doesn't return the expected dll.
use std::io;
use libc::c_void;
use crate::windows;
// It would be preferrable to refactor this macro away to some sort of an api like
// ```
// let mut hook = ... | (lib: &windows::Library, proc: &str) -> Result<usize, io::Error> {
let mut address = lib.proc_address(proc)? as *const u8;
loop {
match *address {
// Long jump
0xe9 => {
let offset = (address.add(1) as *const i32).read_unaligned() as isize as usize;
... | hook_proc_address | identifier_name |
hook_macro.rs | //! A macro that handles hooking an exported function that may have already
//! been hooked in a way that GetProcAddress doesn't return the expected dll.
use std::io;
use libc::c_void;
use crate::windows;
// It would be preferrable to refactor this macro away to some sort of an api like
// ```
// let mut hook = ... | // Short jump
0xeb => {
let offset = *address.add(1) as i8 as isize as usize;
address = address.wrapping_add(2).wrapping_add(offset);
}
_ => return Ok(address as usize),
}
}
} | random_line_split | |
hook_macro.rs | //! A macro that handles hooking an exported function that may have already
//! been hooked in a way that GetProcAddress doesn't return the expected dll.
use std::io;
use libc::c_void;
use crate::windows;
// It would be preferrable to refactor this macro away to some sort of an api like
// ```
// let mut hook = ... |
/// Determines address for hooking the function.
///
/// In addition to just GetProcAddress this follows any unconditional jumps at the
/// address returned by GetProcAddress, in order to avoid placing a second hook
/// at a address which was already hooked by some system DLL (Nvidia driver).
/// This should end up b... | {
// Windows has always 4k pages
let start = proc_address & !0xfff;
let end = ((proc_address + 0x10) | 0xfff) + 1;
let len = end - start;
// If the unprotection for some reason fails, just keep going and hope the memory
// can be written.
let start = start as *mut c_void;
debug!("Unprote... | identifier_body |
global.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/. */
//! Abstractions for global scopes.
//!
//! This module contains smart pointers to global scopes, to simplify writ... | }
}
}
impl GlobalField {
/// Create a new `GlobalField` from a rooted reference.
pub fn from_rooted(global: &GlobalRef) -> GlobalField {
match *global {
GlobalRef::Window(window) => GlobalField::Window(JS::from_ref(window)),
GlobalRef::Worker(worker) => GlobalField::... | pub fn r<'c>(&'c self) -> GlobalRef<'c> {
match *self {
GlobalRoot::Window(ref window) => GlobalRef::Window(window.r()),
GlobalRoot::Worker(ref worker) => GlobalRef::Worker(worker.r()), | random_line_split |
global.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/. */
//! Abstractions for global scopes.
//!
//! This module contains smart pointers to global scopes, to simplify writ... |
/// Get the URL for this global scope.
pub fn get_url(&self) -> Url {
match *self {
GlobalRef::Window(ref window) => window.get_url(),
GlobalRef::Worker(ref worker) => worker.get_url().clone(),
}
}
/// `ScriptChan` used to send messages to the event loop of thi... | {
match *self {
GlobalRef::Window(ref window) => window.get_next_worker_id(),
GlobalRef::Worker(ref worker) => worker.get_next_worker_id()
}
} | identifier_body |
global.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/. */
//! Abstractions for global scopes.
//!
//! This module contains smart pointers to global scopes, to simplify writ... | (&self) -> *mut JSContext {
match *self {
GlobalRef::Window(ref window) => window.get_cx(),
GlobalRef::Worker(ref worker) => worker.get_cx(),
}
}
/// Extract a `Window`, causing task failure if the global object is not
/// a `Window`.
pub fn as_window<'b>(&'b sel... | get_cx | identifier_name |
any.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 {
None
}
}
/// Returns some mutable reference to the boxed value if it is of type `T`, or
/// `None` if it isn't.
#[unstable = "naming conventions around acquiring references may change"]
#[inline]
pub fn downcast_mut<'a, T:'static>(&'a mut self) -> Option<&'a mut T> {... | {
unsafe {
// Get the raw representation of the trait object
let to: TraitObject = transmute(self);
// Extract the data pointer
Some(transmute(to.data))
}
} | conditional_block |
any.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... | <'a, T:'static>(&'a mut self) -> Option<&'a mut T> {
if self.is::<T>() {
unsafe {
// Get the raw representation of the trait object
let to: TraitObject = transmute(self);
// Extract the data pointer
Some(transmute(to.data))
... | downcast_mut | identifier_name |
any.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... | /// be used as a trait object to emulate the effects dynamic typing.
#[stable]
pub trait Any:'static {
/// Get the `TypeId` of `self`
#[unstable = "this method will likely be replaced by an associated static"]
fn get_type_id(&self) -> TypeId;
}
impl<T:'static> Any for T {
fn get_type_id(&self) -> TypeI... | /// dynamic typing
///
/// Every type with no non-`'static` references implements `Any`, so `Any` can | random_line_split |
any.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... |
}
| {
if self.is::<T>() {
unsafe {
// Get the raw representation of the trait object
let to: TraitObject = transmute(self);
// Extract the data pointer
Some(transmute(to.data))
}
} else {
None
}
... | identifier_body |
session.rs | use prodbg_api::read_write::{Reader, Writer};
use prodbg_api::backend::{CBackendCallbacks};
use plugins::PluginHandler;
use reader_wrapper::{ReaderWrapper, WriterWrapper};
use backend_plugin::{BackendHandle, BackendPlugins};
use libc::{c_void};
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub struct SessionHandle(pub ... |
}
| {
let mut session = Session::new();
session.writers[0].event_begin(0x44);
session.writers[0].event_end();
ReaderWrapper::init_from_writer(&mut session.reader, &session.writers[0]);
assert_eq!(session.reader.get_event().unwrap(), 0x44);
} | identifier_body |
session.rs | use prodbg_api::read_write::{Reader, Writer};
use prodbg_api::backend::{CBackendCallbacks};
use plugins::PluginHandler;
use reader_wrapper::{ReaderWrapper, WriterWrapper};
use backend_plugin::{BackendHandle, BackendPlugins};
use libc::{c_void};
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub struct SessionHandle(pub ... | }
}
None
}
}
#[cfg(test)]
mod tests {
use core::reader_wrapper::{ReaderWrapper};
use super::*;
#[test]
fn create_session() {
let _session = Session::new();
}
#[test]
fn write_simple_event() {
let mut session = Session::new();
sessi... | return Some(&mut self.instances[i]); | random_line_split |
session.rs | use prodbg_api::read_write::{Reader, Writer};
use prodbg_api::backend::{CBackendCallbacks};
use plugins::PluginHandler;
use reader_wrapper::{ReaderWrapper, WriterWrapper};
use backend_plugin::{BackendHandle, BackendPlugins};
use libc::{c_void};
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub struct SessionHandle(pub ... |
}
}
///
/// Sessions handler
///
pub struct Sessions {
instances: Vec<Session>,
current: usize,
session_counter: SessionHandle,
}
impl Sessions {
pub fn new() -> Sessions {
Sessions {
instances: Vec::new(),
current: 0,
session_counter: SessionHandle(0)... | {
unsafe {
let plugin_funcs = backend.plugin_type.plugin_funcs as *mut CBackendCallbacks;
((*plugin_funcs).update.unwrap())(backend.plugin_data,
0,
self.reader.api as *mut c_vo... | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.