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 |
|---|---|---|---|---|
graphic.rs | use cursive::theme::{BaseColor, Color, ColorStyle};
use cursive::traits::*;
use cursive::vec::Vec2;
use cursive::Printer;
use tutor::{Label, LabeledChord, PrevCharStatus};
pub struct Graphic {
switches: Vec<Switch>,
}
#[derive(Clone, Copy)]
pub enum ChordType {
Next,
Error,
Backspace,
Persistent,... |
fn draw(&self, printer: &Printer) {
let (x, y) = self.position;
let row2_left = format!("│{}", self.label());
let (left, right) = self.styles();
printer.with_color(left, |printer| {
printer.print((x, y), "╭───");
printer.print((x, y + 1), &row2_left);
... | fn default_style() -> ColorStyle {
ColorStyle::title_secondary()
} | random_line_split |
headers.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HeadersBinding;
use dom::bindings::code... | for (index, &byte) in value.iter().enumerate().rev() {
if!is_HTTP_whitespace(byte) {
return Some(index);
}
}
None
}
// http://tools.ietf.org/html/rfc7230#section-3.2
fn is_field_name(name: &ByteString) -> bool {
is_token(&*name)
}
// https://tools.ietf.org/html/rfc7230#sect... |
fn index_of_last_non_whitespace(value: &ByteString) -> Option<usize> { | random_line_split |
headers.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HeadersBinding;
use dom::bindings::code... |
// https://tools.ietf.org/html/rfc7230#section-3.2
fn is_field_vchar(x: u8) -> bool {
is_vchar(x) || is_obs_text(x)
}
// https://tools.ietf.org/html/rfc5234#appendix-B.1
fn is_vchar(x: u8) -> bool {
match x {
0x21...0x7E => true,
_ => false,
}
}
// http://tools.ietf.org/html/rfc7230#sect... | {
x == b'\t'
} | identifier_body |
headers.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HeadersBinding;
use dom::bindings::code... | (&self, name: ByteString, value: ByteString) -> Result<(), Error> {
// Step 1
let value = normalize_value(value);
// Step 2
let (valid_name, valid_value) = try!(validate_name_and_value(name, value));
// Step 3
if self.guard == Guard::Immutable {
return Err(Er... | Append | identifier_name |
promisenativehandler.rs | /* This Source Code Form is subject to the terms of the Mozilla Public | use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::root::DomRoot;
use dom::bindings::trace::JSTraceable;
use dom::globalscope::GlobalScope;
use dom_struct::dom_struct;
use js::jsapi::{JSContext, HandleValue};
use malloc_size_of::MallocSizeOf;
pub trait Callback: JSTraceable + MallocSizeO... | * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::PromiseNativeHandlerBinding; | random_line_split |
promisenativehandler.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::PromiseNativeHandlerBinding;
use dom::bindings::reflector::{Reflector, refle... |
fn callback(callback: &Option<Box<Callback>>, cx: *mut JSContext, v: HandleValue) {
if let Some(ref callback) = *callback {
callback.callback(cx, v)
}
}
pub fn resolved_callback(&self, cx: *mut JSContext, v: HandleValue) {
PromiseNativeHandler::callback(&self.resolve, ... | {
reflect_dom_object(Box::new(PromiseNativeHandler {
reflector: Reflector::new(),
resolve: resolve,
reject: reject,
}), global, PromiseNativeHandlerBinding::Wrap)
} | identifier_body |
promisenativehandler.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::PromiseNativeHandlerBinding;
use dom::bindings::reflector::{Reflector, refle... | {
reflector: Reflector,
resolve: Option<Box<Callback>>,
reject: Option<Box<Callback>>,
}
impl PromiseNativeHandler {
pub fn new(global: &GlobalScope,
resolve: Option<Box<Callback>>,
reject: Option<Box<Callback>>)
-> DomRoot<PromiseNativeHandler> {
r... | PromiseNativeHandler | identifier_name |
promisenativehandler.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::PromiseNativeHandlerBinding;
use dom::bindings::reflector::{Reflector, refle... |
}
pub fn resolved_callback(&self, cx: *mut JSContext, v: HandleValue) {
PromiseNativeHandler::callback(&self.resolve, cx, v)
}
pub fn rejected_callback(&self, cx: *mut JSContext, v: HandleValue) {
PromiseNativeHandler::callback(&self.reject, cx, v)
}
}
| {
callback.callback(cx, v)
} | conditional_block |
grid.rs | use colours::Colours;
use file::File;
use filetype::file_colour;
use term_grid as grid;
#[derive(PartialEq, Debug, Copy, Clone)]
pub struct Grid {
pub across: bool,
pub console_width: usize,
pub colours: Colours,
}
impl Grid {
pub fn view(&self, files: &[File]) {
let direction = if self.acro... |
}
}
| {
// File names too long for a grid - drop down to just listing them!
for file in files.iter() {
println!("{}", file_colour(&self.colours, file).paint(&file.name));
}
} | conditional_block |
grid.rs | use colours::Colours;
use file::File;
use filetype::file_colour;
use term_grid as grid;
#[derive(PartialEq, Debug, Copy, Clone)]
pub struct | {
pub across: bool,
pub console_width: usize,
pub colours: Colours,
}
impl Grid {
pub fn view(&self, files: &[File]) {
let direction = if self.across { grid::Direction::LeftToRight }
else { grid::Direction::TopToBottom };
let mut grid = grid::Grid::ne... | Grid | identifier_name |
grid.rs | use colours::Colours;
use file::File;
use filetype::file_colour;
use term_grid as grid;
#[derive(PartialEq, Debug, Copy, Clone)]
pub struct Grid {
pub across: bool,
pub console_width: usize,
pub colours: Colours,
}
impl Grid {
pub fn view(&self, files: &[File]) {
let direction = if self.acro... |
if let Some(display) = grid.fit_into_width(self.console_width) {
print!("{}", display);
}
else {
// File names too long for a grid - drop down to just listing them!
for file in files.iter() {
println!("{}", file_colour(&self.colours, file).pai... | random_line_split | |
grid.rs | use colours::Colours;
use file::File;
use filetype::file_colour;
use term_grid as grid;
#[derive(PartialEq, Debug, Copy, Clone)]
pub struct Grid {
pub across: bool,
pub console_width: usize,
pub colours: Colours,
}
impl Grid {
pub fn view(&self, files: &[File]) | }
else {
// File names too long for a grid - drop down to just listing them!
for file in files.iter() {
println!("{}", file_colour(&self.colours, file).paint(&file.name));
}
}
}
}
| {
let direction = if self.across { grid::Direction::LeftToRight }
else { grid::Direction::TopToBottom };
let mut grid = grid::Grid::new(grid::GridOptions {
direction: direction,
filling: grid::Filling::Spaces(2),
});
grid.re... | identifier_body |
lib.rs | // =================================================================
//
// * WARNING *
//
// This file is generated!
//
// Changes made to this file will be overwritten. If changes are
// required to the generated code, the service_crategen project
// must be updated to g... | extern crate serde_json;
mod generated;
mod custom;
pub use generated::*;
pub use custom::*; | extern crate serde;
#[macro_use]
extern crate serde_derive; | random_line_split |
reg_status.rs | #[derive(Debug, Clone)]
pub struct RegStatus {
pub carry: bool,
pub zero: bool,
pub interrupt_disable: bool,
pub decimal: bool,
pub break_command: bool,
expansion: bool,
pub overflow: bool,
pub negative: bool,
}
impl From<u8> for RegStatus {
fn from(value: u8) -> Self {
RegS... |
if self.negative {
ret |= 1 << 7;
}
ret
}
}
| {
ret |= 1 << 6;
} | conditional_block |
reg_status.rs | #[derive(Debug, Clone)]
pub struct | {
pub carry: bool,
pub zero: bool,
pub interrupt_disable: bool,
pub decimal: bool,
pub break_command: bool,
expansion: bool,
pub overflow: bool,
pub negative: bool,
}
impl From<u8> for RegStatus {
fn from(value: u8) -> Self {
RegStatus{
carry: (value & 1)!= 0,
... | RegStatus | identifier_name |
reg_status.rs | #[derive(Debug, Clone)]
pub struct RegStatus {
pub carry: bool, | pub decimal: bool,
pub break_command: bool,
expansion: bool,
pub overflow: bool,
pub negative: bool,
}
impl From<u8> for RegStatus {
fn from(value: u8) -> Self {
RegStatus{
carry: (value & 1)!= 0,
zero: (value & (1 << 1))!= 0,
interrupt_disable: (valu... | pub zero: bool,
pub interrupt_disable: bool, | random_line_split |
fs2.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... |
fn name_bytes(&self) -> &[u8] {
extern {
fn rust_list_dir_val(ptr: *mut libc::dirent_t) -> *const c_char;
}
unsafe {
let ptr = rust_list_dir_val(self.dirent);
ffi::c_str_to_bytes(mem::copy_lifetime(self, &ptr))
}
}
}
impl OpenOptions {
p... | {
self.root.join(<OsStr as OsStrExt>::from_bytes(self.name_bytes()))
} | identifier_body |
fs2.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... | use sys_common::FromInner;
use vec::Vec;
pub struct File(FileDesc);
pub struct FileAttr {
stat: libc::stat,
}
pub struct ReadDir {
dirp: *mut libc::DIR,
root: Rc<PathBuf>,
}
pub struct DirEntry {
buf: Vec<u8>,
dirent: *mut libc::dirent_t,
root: Rc<PathBuf>,
}
#[derive(Clone)]
pub struct Ope... | use ptr;
use rc::Rc;
use sys::fd::FileDesc;
use sys::{c, cvt, cvt_r}; | random_line_split |
fs2.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... | { mode: mode_t }
impl FileAttr {
pub fn is_dir(&self) -> bool {
(self.stat.st_mode as mode_t) & libc::S_IFMT == libc::S_IFDIR
}
pub fn is_file(&self) -> bool {
(self.stat.st_mode as mode_t) & libc::S_IFMT == libc::S_IFREG
}
pub fn size(&self) -> u64 { self.stat.st_size as u64 }
... | FilePermissions | identifier_name |
lib.rs | // Copyright 2012-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... | #![feature(no_std)]
#![no_std]
#![feature(core)]
extern crate core;
// regex module
pub use tables::regex;
mod normalize;
mod tables;
mod u_char;
mod u_str;
// re-export char so that std et al see it correctly
/// Character manipulation (`char` type, Unicode Scalar Value)
///
/// This module provides the `CharExt` ... | html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/",
html_playground_url = "http://play.rust-lang.org/")] | random_line_split |
mod.rs | // This file is part of rust-web/twig
//
// For the copyright and license information, please view the LICENSE
// file that was distributed with this source code.
//! Twig Template API.
use engine::TwigError;
use runtime::Runtime; | use api::error::Traced;
pub const _ANY_CALL: &'static str = "any";
pub const _ARRAY_CALL: &'static str = "array";
pub const _METHOD_CALL: &'static str = "method";
pub trait Template {
/// Renders the template with the given context and returns it as string.
fn render(&self, runtime: &Runtime) -> Result<String... | random_line_split | |
basic_search.rs | // # Basic Example
//
// This example covers the basic functionalities of
// tantivy.
//
// We will :
// - define our schema
// - create an index in a directory
// - index a few documents into our index
// - search for the best document matching a basic query
// - retrieve the best document's original content.
// ---
... | // that.
//
// `TEXT` means the field should be tokenized and indexed,
// along with its term frequency and term positions.
//
// `STORED` means that the field will also be saved
// in a compressed, row-oriented key-value store.
// This store is useful for reconstructing the
// docum... | {
// Let's create a temporary directory for the
// sake of this example
let index_path = TempDir::new()?;
// # Defining the schema
//
// The Tantivy index requires a very strict schema.
// The schema declares which fields are in the index,
// and for each field, its type and "the way it... | identifier_body |
basic_search.rs | // # Basic Example
//
// This example covers the basic functionalities of
// tantivy.
//
// We will :
// - define our schema
// - create an index in a directory
// - index a few documents into our index
// - search for the best document matching a basic query
// - retrieve the best document's original content.
// ---
... | () -> tantivy::Result<()> {
// Let's create a temporary directory for the
// sake of this example
let index_path = TempDir::new()?;
// # Defining the schema
//
// The Tantivy index requires a very strict schema.
// The schema declares which fields are in the index,
// and for each field... | main | identifier_name |
basic_search.rs | // # Basic Example
//
// This example covers the basic functionalities of
// tantivy.
//
// We will :
// - define our schema
// - create an index in a directory
// - index a few documents into our index
// - search for the best document matching a basic query
// - retrieve the best document's original content.
// ---
... | //
// Since the body field was not configured as stored,
// the document returned will only contain
// a title.
for (_score, doc_address) in top_docs {
let retrieved_doc = searcher.doc(doc_address)?;
println!("{}", schema.to_json(&retrieved_doc));
}
Ok(())
} | // retrieved from Tantivy's store. | random_line_split |
script.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/. */
#[crate_id = "github.com/mozilla/servo#script:0.1"];
#[crate_type = "lib"];
#[crate_type = "dylib"];
#[crate_type ... | pub mod htmlimageelement;
pub mod htmlinputelement;
pub mod htmllabelelement;
pub mod htmllegendelement;
pub mod htmllielement;
pub mod htmllinkelement;
pub mod htmlmainelement;
pub mod htmlmapelement;
pub mod htmlmediaelement;
pub mod htmlmetaelement;
pub mod htmlmeterelemen... | random_line_split | |
audio_talker.rs | use crate::data::Data;
use crate::talker::{Talker, TalkerBase};
use crate::voice;
pub const MODEL: &str = "AudioTalker";
pub struct AudioTalker {
base: TalkerBase,
}
impl AudioTalker {
pub fn new(def_value: f32, hidden: Option<bool>) -> AudioTalker {
let value = if def_value.is_nan() { 0. } else | ;
let mut base = TalkerBase::new_data("", MODEL, Data::f(value));
let voice = voice::audio(None, value, None);
base.add_voice(voice);
base.set_hidden(hidden.unwrap_or(false));
Self { base }
}
}
impl Talker for AudioTalker {
fn base<'a>(&'a self) -> &'a TalkerBase {
... | { def_value } | conditional_block |
audio_talker.rs | use crate::data::Data;
use crate::talker::{Talker, TalkerBase};
use crate::voice;
pub const MODEL: &str = "AudioTalker";
pub struct AudioTalker {
base: TalkerBase,
}
impl AudioTalker {
pub fn new(def_value: f32, hidden: Option<bool>) -> AudioTalker {
let value = if def_value.is_nan() { 0. } else { de... | None
}
} | return voice.borrow().audio_value(0);
}
} | random_line_split |
audio_talker.rs | use crate::data::Data;
use crate::talker::{Talker, TalkerBase};
use crate::voice;
pub const MODEL: &str = "AudioTalker";
pub struct AudioTalker {
base: TalkerBase,
}
impl AudioTalker {
pub fn new(def_value: f32, hidden: Option<bool>) -> AudioTalker {
let value = if def_value.is_nan() { 0. } else { de... | (&self) -> &str {
MODEL
}
fn talk(&mut self, _port: usize, tick: i64, len: usize) -> usize {
for voice in self.voices() {
let mut vc = voice.borrow_mut();
vc.set_len(len);
vc.set_tick(tick);
}
len
}
fn voice_value(&self, port: usize)... | model | identifier_name |
dtable.rs | //
// SOS: the Stupid Operating System
// by Eliza Weisman (eliza@elizas.website)
//
// Copyright (c) 2015-2017 Eliza Weisman
// Released under the terms of the MIT license. See `LICENSE` in the root
// directory of this repository for more information.
//! `x86` and `x86_64` descriptor tables (IDT, GDT, or LDT)
/... | // If we wanted to be really clever, we could probably also have a
// method to get a pointer to a first entry (or enforce that the
// DTable supports indexing?) and then we could get a pointer only
// to the array segment of the DTable, while still allowing variables
// ... | // to place more variables after the array in the DTable structure.
// | random_line_split |
dtable.rs | //
// SOS: the Stupid Operating System
// by Eliza Weisman (eliza@elizas.website)
//
// Copyright (c) 2015-2017 Eliza Weisman
// Released under the terms of the MIT license. See `LICENSE` in the root
// directory of this repository for more information.
//! `x86` and `x86_64` descriptor tables (IDT, GDT, or LDT)
/... | -> Pointer<Self> {
Pointer {
limit: (size_of::<Self::Entry>() * self.entry_count()) as u16
, base: self as *const _
}
}
/// Returns the number of Entries in the `DTable`.
///
/// This is used for calculating the limit.
fn entry_count(&self) -> usize;
/// L... | (&self) | 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 init() -> (pipe,pipe) {
let m = Arc::new((Mutex::new(Vec::new()), Condvar::new()));
((&m).clone(), m)
}
fn thread_ring(i: uint, count: uint, num_chan: pipe, num_port: pipe) {
let mut num_chan = Some(num_chan);
let mut num_port = Some(num_port);
// Send/Receive lots of messages.
for j in r... | {
let &(ref lock, ref cond) = &**p;
let mut arr = lock.lock();
while arr.is_empty() {
cond.wait(&arr);
}
arr.pop().unwrap()
} | 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 ... | (p: &pipe) -> uint {
let &(ref lock, ref cond) = &**p;
let mut arr = lock.lock();
while arr.is_empty() {
cond.wait(&arr);
}
arr.pop().unwrap()
}
fn init() -> (pipe,pipe) {
let m = Arc::new((Mutex::new(Vec::new()), Condvar::new()));
((&m).clone(), m)
}
fn thread_ring(i: uint, count... | recv | 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 ... | else if args.len() <= 1u {
vec!("".to_string(), "10".to_string(), "100".to_string())
} else {
args.clone().into_iter().collect()
};
let num_tasks = from_str::<uint>(args[1].as_slice()).unwrap();
let msg_per_task = from_str::<uint>(args[2].as_slice()).unwrap();
let (mut num_chan, n... | {
vec!("".to_string(), "100".to_string(), "10000".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 ... |
fn init() -> (pipe,pipe) {
let m = Arc::new((Mutex::new(Vec::new()), Condvar::new()));
((&m).clone(), m)
}
fn thread_ring(i: uint, count: uint, num_chan: pipe, num_port: pipe) {
let mut num_chan = Some(num_chan);
let mut num_port = Some(num_port);
// Send/Receive lots of messages.
for j in ra... | arr.pop().unwrap()
} | random_line_split |
mem.rs | // Copyright 2012-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... | <T>(x: &mut T, y: &mut T) {
unsafe {
// Give ourselves some scratch space to work with
let mut t: T = uninitialized();
// Perform the swap, `&mut` pointers never alias
ptr::copy_nonoverlapping(&*x, &mut t, 1);
ptr::copy_nonoverlapping(&*y, x, 1);
ptr::copy_nonoverlap... | swap | identifier_name |
mem.rs | // Copyright 2012-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... | /// This function is not marked as `unsafe` as Rust does not guarantee that the
/// `Drop` implementation for a value will always run. Note, however, that
/// leaking resources such as memory or I/O objects is likely not desired, so
/// this function is only recommended for specialized use cases.
///
/// The safety of ... | /// value and any resources that it owns.
///
/// # Safety
/// | random_line_split |
mem.rs | // Copyright 2012-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... |
/// Returns the alignment in memory for a type.
///
/// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// assert_eq!(4, mem::align_of::<i32>());
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn a... | {
unsafe { intrinsics::min_align_of_val(val) }
} | identifier_body |
main.rs | fn pe015() -> u64 {
const LIMIT:usize = 20;
let mut numerator = vec![];
let mut denominator = vec![];
for i in 0.. LIMIT {
denominator.push(i+1);
numerator.push(i+LIMIT+1);
}
// walk through lists and cast away multiples to reduce size of numbers from
// factorials - this is incom... | {
println!("{}", pe015())
} | identifier_body | |
main.rs | fn pe015() -> u64 {
const LIMIT:usize = 20;
let mut numerator = vec![];
let mut denominator = vec![];
for i in 0.. LIMIT {
denominator.push(i+1);
numerator.push(i+LIMIT+1);
}
// walk through lists and cast away multiples to reduce size of numbers from
// factorials - this is incom... |
}
}
let mut den64:u64;
let mut num64:u64;
num64 = 1;
den64 = 1;
for i in 0.. LIMIT {
num64 = num64 * numerator[i] as u64;
den64 = den64 * denominator[i] as u64;
}
num64 / den64
}
fn main() {
println!("{}", pe015())
}
| {
numerator[j] = num / den;
denominator[i] = 1;
} | conditional_block |
main.rs | fn pe015() -> u64 {
const LIMIT:usize = 20;
let mut numerator = vec![];
let mut denominator = vec![];
for i in 0.. LIMIT {
denominator.push(i+1);
numerator.push(i+LIMIT+1);
}
// walk through lists and cast away multiples to reduce size of numbers from
// factorials - this is incom... | let mut num:usize;
for i in 0.. LIMIT {
for j in 0.. LIMIT {
den = denominator[i];
num = numerator[j];
if den!= 1 && num % den == 0 {
numerator[j] = num / den;
denominator[i] = 1;
}
}
}
let mut den64:u64;
... | random_line_split | |
main.rs | fn | () -> u64 {
const LIMIT:usize = 20;
let mut numerator = vec![];
let mut denominator = vec![];
for i in 0.. LIMIT {
denominator.push(i+1);
numerator.push(i+LIMIT+1);
}
// walk through lists and cast away multiples to reduce size of numbers from
// factorials - this is incomplete fa... | pe015 | identifier_name |
options.rs | use num_traits::FromPrimitive;
use std::net::Ipv4Addr;
#[derive(PartialEq, Clone)]
pub struct RawDhcpOption {
pub code: u8,
pub data: Vec<u8>,
}
#[derive(PartialEq)]
pub enum DhcpOption {
DhcpMessageType(MessageType),
ServerIdentifier(Ipv4Addr),
ParameterRequestList(Vec<u8>),
RequestedIpAddres... |
pub const TFTP_SERVER_NAME: u8 = 66;
pub const BOOTFILE_NAME: u8 = 67;
pub const USER_CLASS: u8 = 77;
pub const CLIENT_ARCHITECTURE: u8 = 93;
pub const TZ_POSIX_STRING: u8 = 100;
pub const TZ_DATABASE_STRING: u8 = 101;
pub const CLASSLESS_ROUTE_FORMAT: u8 = 121;
/// Returns title of DHCP Option code, if known.
pu... | random_line_split | |
options.rs | use num_traits::FromPrimitive;
use std::net::Ipv4Addr;
#[derive(PartialEq, Clone)]
pub struct RawDhcpOption {
pub code: u8,
pub data: Vec<u8>,
}
#[derive(PartialEq)]
pub enum DhcpOption {
DhcpMessageType(MessageType),
ServerIdentifier(Ipv4Addr),
ParameterRequestList(Vec<u8>),
RequestedIpAddres... | data: name.as_bytes().to_vec(),
},
Self::Router(addrs) => RawDhcpOption {
code: ROUTER,
data: {
let mut v = vec![];
for a in addrs {
v.extend(a.octets().iter());
}
... | {
match self {
Self::DhcpMessageType(mtype) => RawDhcpOption {
code: DHCP_MESSAGE_TYPE,
data: vec![*mtype as u8],
},
Self::ServerIdentifier(addr) => RawDhcpOption {
code: SERVER_IDENTIFIER,
data: addr.octets().to... | identifier_body |
options.rs | use num_traits::FromPrimitive;
use std::net::Ipv4Addr;
#[derive(PartialEq, Clone)]
pub struct RawDhcpOption {
pub code: u8,
pub data: Vec<u8>,
}
#[derive(PartialEq)]
pub enum DhcpOption {
DhcpMessageType(MessageType),
ServerIdentifier(Ipv4Addr),
ParameterRequestList(Vec<u8>),
RequestedIpAddres... | (&self) -> RawDhcpOption {
match self {
Self::DhcpMessageType(mtype) => RawDhcpOption {
code: DHCP_MESSAGE_TYPE,
data: vec![*mtype as u8],
},
Self::ServerIdentifier(addr) => RawDhcpOption {
code: SERVER_IDENTIFIER,
... | to_raw | identifier_name |
progressevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::ProgressEv... | {
event: Event,
length_computable: bool,
loaded: u64,
total: u64
}
impl ProgressEvent {
fn new_inherited(length_computable: bool, loaded: u64, total: u64) -> ProgressEvent {
ProgressEvent {
event: Event::new_inherited(),
length_computable: length_computable,
... | ProgressEvent | identifier_name |
progressevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::ProgressEv... |
pub fn Constructor(global: GlobalRef,
type_: DOMString,
init: &ProgressEventBinding::ProgressEventInit)
-> Fallible<Root<ProgressEvent>> {
let bubbles = if init.parent.bubbles { EventBubbles::Bubbles } else { EventBubbles::DoesNotBubble }... | {
let ev = reflect_dom_object(box ProgressEvent::new_inherited(length_computable, loaded, total),
global,
ProgressEventBinding::Wrap);
{
let event = ev.upcast::<Event>();
event.InitEvent(type_, can_bubble == ... | identifier_body |
progressevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::ProgressEv... | }
} |
// https://xhr.spec.whatwg.org/#dom-progressevent-total
fn Total(&self) -> u64 {
self.total | random_line_split |
progressevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::ProgressEv... |
else { EventCancelable::NotCancelable };
let ev = ProgressEvent::new(global, type_, bubbles, cancelable,
init.lengthComputable, init.loaded, init.total);
Ok(ev)
}
}
impl ProgressEventMethods for ProgressEvent {
// https://xhr.spec.wh... | { EventCancelable::Cancelable } | conditional_block |
crypto.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::CryptoBinding;
use dom::bindings::codegen::Bindings::CryptoBinding::CryptoMe... |
pub fn new(global: GlobalRef) -> Root<Crypto> {
reflect_dom_object(box Crypto::new_inherited(), global, CryptoBinding::Wrap)
}
}
impl<'a> CryptoMethods for &'a Crypto {
#[allow(unsafe_code)]
// https://dvcs.w3.org/hg/webcrypto-api/raw-file/tip/spec/Overview.html#Crypto-method-getRandomValues
... | {
Crypto {
reflector_: Reflector::new(),
rng: DOMRefCell::new(OsRng::new().unwrap()),
}
} | identifier_body |
crypto.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::CryptoBinding;
use dom::bindings::codegen::Bindings::CryptoBinding::CryptoMe... | #[allow(unsafe_code)]
fn is_integer_buffer(input: *mut JSObject) -> bool {
match unsafe { JS_GetArrayBufferViewType(input) } {
Type::Uint8 |
Type::Uint8Clamped |
Type::Int8 |
Type::Uint16 |
Type::Int16 |
Type::Uint32 |
Type::Int32 => true,
_ => false
... |
Ok(input)
}
}
| random_line_split |
crypto.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::CryptoBinding;
use dom::bindings::codegen::Bindings::CryptoBinding::CryptoMe... | () -> Crypto {
Crypto {
reflector_: Reflector::new(),
rng: DOMRefCell::new(OsRng::new().unwrap()),
}
}
pub fn new(global: GlobalRef) -> Root<Crypto> {
reflect_dom_object(box Crypto::new_inherited(), global, CryptoBinding::Wrap)
}
}
impl<'a> CryptoMethods for... | new_inherited | identifier_name |
dirname.rs | #![crate_name = "dirname"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Derek Chiang <derekchiang93@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
use std::path::Path;
static... | () {
std::process::exit(uumain(std::env::args().collect()));
}
| main | identifier_name |
dirname.rs | #![crate_name = "dirname"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Derek Chiang <derekchiang93@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
use std::path::Path;
static... | {
std::process::exit(uumain(std::env::args().collect()));
} | identifier_body | |
dirname.rs | #![crate_name = "dirname"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Derek Chiang <derekchiang93@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
use std::path::Path;
static... | };
if matches.opt_present("help") {
let msg = format!("{0} {1} - strip last component from file name
Usage:
{0} [OPTION] NAME...
Output each NAME with its last non-slash component and trailing slashes
removed; if NAME contains no /'s, output '.' (meaning the current
directory).", NAME, VERSIO... | opts.optflag("", "version", "output version information and exit");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => panic!("Invalid options\n{}", f) | random_line_split |
main.rs | extern crate time;
use std::sync::{Arc, mpsc};
use std::thread;
type Float = f64;
type Integer = u32;
type Callback = Box<Fn(Float) -> Float + Send + Sync +'static>;
type FnThread = Fn() -> Callback + Send + Sync;
#[derive(Clone)]
struct Integrator {
f: Arc<FnThread>,
a: Float,
b: Float,
n: Integer,
}... | println!("result = {:+.16}", pi);
println!(" err = {:+.16}", std::f64::consts::PI - pi);
println!(" time = {} ms\n", duration.num_milliseconds());
}
} | random_line_split | |
main.rs | extern crate time;
use std::sync::{Arc, mpsc};
use std::thread;
type Float = f64;
type Integer = u32;
type Callback = Box<Fn(Float) -> Float + Send + Sync +'static>;
type FnThread = Fn() -> Callback + Send + Sync;
#[derive(Clone)]
struct Integrator {
f: Arc<FnThread>,
a: Float,
b: Float,
n: Integer,
}... | (&self, threads: Integer) -> Float {
let mut thread_list = Vec::new();
let h_step = (self.b - self.a) / self.n as Float;
let t_step = self.n / threads;
let (tx, rx) = mpsc::channel::<Float>();
for i in 0..threads {
let local_tx = tx.clone();
let local_self... | monte_carlo | identifier_name |
main.rs | extern crate time;
use std::sync::{Arc, mpsc};
use std::thread;
type Float = f64;
type Integer = u32;
type Callback = Box<Fn(Float) -> Float + Send + Sync +'static>;
type FnThread = Fn() -> Callback + Send + Sync;
#[derive(Clone)]
struct Integrator {
f: Arc<FnThread>,
a: Float,
b: Float,
n: Integer,
}... | println!(" time = {} ms\n", duration.num_milliseconds());
}
} | {
// [a, b] -- interval
// n -- iteration count
let (a, b, n) = (0.0, 1.0, 10_000_000);
let f_a = Integrator::new(Arc::new(f), a, b, n);
println!("# Iteration count: {:E}", n as Float);
let start = time::get_time();
let pi = monte_carlo_linear(Arc::new(f), a, b, n) * 4.0;
let durati... | identifier_body |
pad_controller.rs | // Copyright 2013-2018, 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 ffi;
use glib::IsA;
use glib::translate::*;
use PadActionEntry;
use PadController;
pub ... | let n_entries = entries.len() as i32;
let entries = entries.as_ptr();
unsafe {
ffi::gtk_pad_controller_set_action_entries(self.as_ref().to_glib_none().0,
mut_override(entries as *const _),
... |
impl<O: IsA<PadController>> PadControllerExtManual for O {
#[cfg(any(feature = "v3_22", feature = "dox"))]
fn set_action_entries(&self, entries: &[PadActionEntry]) { | random_line_split |
pad_controller.rs | // Copyright 2013-2018, 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 ffi;
use glib::IsA;
use glib::translate::*;
use PadActionEntry;
use PadController;
pub ... | (&self, entries: &[PadActionEntry]) {
let n_entries = entries.len() as i32;
let entries = entries.as_ptr();
unsafe {
ffi::gtk_pad_controller_set_action_entries(self.as_ref().to_glib_none().0,
mut_override(entries as *const _),
... | set_action_entries | identifier_name |
pad_controller.rs | // Copyright 2013-2018, 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 ffi;
use glib::IsA;
use glib::translate::*;
use PadActionEntry;
use PadController;
pub ... |
}
| {
let n_entries = entries.len() as i32;
let entries = entries.as_ptr();
unsafe {
ffi::gtk_pad_controller_set_action_entries(self.as_ref().to_glib_none().0,
mut_override(entries as *const _),
... | identifier_body |
server_trait.rs | //
// This file is part of Osmium.
// Osmium 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.
// Osmium is distributed in the hope ... | // Copyright 2017 ThetaSinner | random_line_split | |
test_uio.rs | use nix::sys::uio::*;
use nix::unistd::*;
use rand::{thread_rng, Rng};
use std::{cmp, iter};
use std::fs::{OpenOptions};
use std::os::unix::io::AsRawFd;
use tempdir::TempDir;
use tempfile::tempfile;
#[test]
fn test_writev() {
let mut to_write = Vec::with_capacity(16 * 128);
for _ in 0..16 {
let s: Str... |
#[test]
#[cfg(target_os = "linux")]
fn test_pwritev() {
use std::io::Read;
let to_write: Vec<u8> = (0..128).collect();
let expected: Vec<u8> = [vec![0;100], to_write.clone()].concat();
let iovecs = [
IoVec::from_slice(&to_write[0..17]),
IoVec::from_slice(&to_write[17..64]),
I... | {
use std::io::Write;
let tempdir = TempDir::new("nix-test_pread").unwrap();
let path = tempdir.path().join("pread_test_file");
let mut file = OpenOptions::new().write(true).read(true).create(true)
.truncate(true).open(path).unwrap();
let file_content: Vec<u8> =... | identifier_body |
test_uio.rs | use nix::sys::uio::*;
use nix::unistd::*;
use rand::{thread_rng, Rng};
use std::{cmp, iter};
use std::fs::{OpenOptions};
use std::os::unix::io::AsRawFd;
use tempdir::TempDir;
use tempfile::tempfile;
#[test]
fn test_writev() {
let mut to_write = Vec::with_capacity(16 * 128);
for _ in 0..16 {
let s: Str... | () {
use std::io::Read;
let to_write: Vec<u8> = (0..128).collect();
let expected: Vec<u8> = [vec![0;100], to_write.clone()].concat();
let iovecs = [
IoVec::from_slice(&to_write[0..17]),
IoVec::from_slice(&to_write[17..64]),
IoVec::from_slice(&to_write[64..128]),
];
let... | test_pwritev | identifier_name |
test_uio.rs | use nix::sys::uio::*;
use nix::unistd::*;
use rand::{thread_rng, Rng};
use std::{cmp, iter};
use std::fs::{OpenOptions};
use std::os::unix::io::AsRawFd;
use tempdir::TempDir;
use tempfile::tempfile;
#[test]
fn test_writev() {
let mut to_write = Vec::with_capacity(16 * 128); | let b = s.as_bytes();
to_write.extend(b.iter().map(|x| x.clone()));
}
// Allocate and fill iovecs
let mut iovecs = Vec::new();
let mut consumed = 0;
while consumed < to_write.len() {
let left = to_write.len() - consumed;
let slice_len = if left <= 64 { left } else { t... | for _ in 0..16 {
let s: String = thread_rng().gen_ascii_chars().take(128).collect(); | random_line_split |
test_uio.rs | use nix::sys::uio::*;
use nix::unistd::*;
use rand::{thread_rng, Rng};
use std::{cmp, iter};
use std::fs::{OpenOptions};
use std::os::unix::io::AsRawFd;
use tempdir::TempDir;
use tempfile::tempfile;
#[test]
fn test_writev() {
let mut to_write = Vec::with_capacity(16 * 128);
for _ in 0..16 {
let s: Str... | ;
let v: Vec<u8> = iter::repeat(0u8).take(vec_len).collect();
storage.push(v);
allocated += vec_len;
}
let mut iovecs = Vec::with_capacity(storage.len());
for v in storage.iter_mut() {
iovecs.push(IoVec::from_mut_slice(&mut v[..]));
}
let pipe_res = pipe();
assert... | { thread_rng().gen_range(64, cmp::min(256, left)) } | conditional_block |
trait-default-method-bound-subst.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 ... | <U>(&self, x: T, y: U) -> (T, U) { (x, y) }
}
impl A<i32> for i32 { }
impl<T> A<T> for u32 { }
fn f<T, U, V: A<T>>(i: V, j: T, k: U) -> (T, U) {
i.g(j, k)
}
pub fn main () {
assert_eq!(f(0, 1, 2), (1, 2));
assert_eq!(f(0, 1, 2), (1, 2));
}
| g | identifier_name |
trait-default-method-bound-subst.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_eq!(f(0, 1, 2), (1, 2));
assert_eq!(f(0, 1, 2), (1, 2));
} | identifier_body | |
trait-default-method-bound-subst.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 A<i32> for i32 { }
impl<T> A<T> for u32 { }
fn f<T, U, V: A<T>>(i: V, j: T, k: U) -> (T, U) {
i.g(j, k)
}
pub fn main () {
assert_eq!(f(0, 1, 2), (1, 2));
assert_eq!(f(0, 1, 2), (1, 2));
} | } | random_line_split |
mock.rs | //! BDCS Mock API handling
//!
//! # Overview
//!
//! This module provides a mock API service that reads json files from a static directory and serves up
//! the data from the file as-is.
//!
//! Requests like /route are read from a file named route.json
//! Requests like /route/param are read from route-param.json
//!... |
/// Filter the contents of a static json file based on the action and parameter passed to the API
///
/// # Arguments
///
/// * `route` - The 1st argument on the API path
/// * `action` - The 2nd argument on the API path
/// * `param` - The 3rd argument on the API path
/// * `offset` - Number of results to skip befor... | {
info!("mock request"; "route" => route, "param" => param, "offset" => offset, "limit" => limit);
let mock_path = config::active()
.unwrap()
.get_str("mockfiles_path")
.unwrap_or("/var/tmp/bdcs-mockfiles/");
// TODO Better wa... | identifier_body |
mock.rs | //! BDCS Mock API handling
//!
//! # Overview
//!
//! This module provides a mock API service that reads json files from a static directory and serves up
//! the data from the file as-is.
//!
//! Requests like /route are read from a file named route.json
//! Requests like /route/param are read from route-param.json
//!... |
}
// Nothing to return
CORS(JSON(Value::Object(json_map! { route => Value::Null,
"offset" => serde_json::to_value(offset).unwrap(),
"limit" => serde_json::to_value(limit).unwrap() })))
}
| {
// Not an array, just return it
return CORS(JSON(Value::Object(json_map! { route => api_route.clone(),
"offset" => serde_json::to_value(offset).unwrap(),
"limit" => serde_json::to_value(limit).unwrap() })));
} | conditional_block |
mock.rs | //! BDCS Mock API handling
//!
//! # Overview
//!
//! This module provides a mock API service that reads json files from a static directory and serves up
//! the data from the file as-is.
//!
//! Requests like /route are read from a file named route.json
//! Requests like /route/param are read from route-param.json
//!... | /// # Response
///
/// * JSON response selected from the file.
///
/// The filename to read is constructed by joining the route and the action with a '-' and
/// appending.json to it. eg. `/modules/info/http-server` will read from a file named `modules-info.json`
///
/// The filtering arguments, offset and limit, are i... | /// * `offset` - Number of results to skip before returning results. Default is 0.
/// * `limit` - Maximum number of results to return. It may return less. Default is 20.
/// | random_line_split |
mock.rs | //! BDCS Mock API handling
//!
//! # Overview
//!
//! This module provides a mock API service that reads json files from a static directory and serves up
//! the data from the file as-is.
//!
//! Requests like /route are read from a file named route.json
//! Requests like /route/param are read from route-param.json
//!... | (route: &str, action: &str, param: &str) -> CORS<JSON<Value>> {
filter_json(route, action, param, OFFSET, LIMIT)
}
/// Return a static json file based on the route and parameter passed to the API
///
/// # Arguments
///
/// * `route` - The 1st argument on the API path
/// * `param` - The 2nd argument on the API pa... | static_route_action | identifier_name |
random.rs | use orderings::ORDERINGS;
use random::Seed;
use slices::{random_values_from_slice, RandomValuesFromSlice};
use std::cmp::Ordering;
use std::iter::Cloned;
pub type RandomOrderings = Cloned<RandomValuesFromSlice<'static, Ordering>>;
/// Generates a random `Ordering` that has an equal probability of being `Less`, `Great... | (seed: Seed) -> RandomOrderings {
random_values_from_slice(seed, &ORDERINGS).cloned()
}
| random_orderings | identifier_name |
random.rs | use orderings::ORDERINGS;
use random::Seed;
use slices::{random_values_from_slice, RandomValuesFromSlice};
use std::cmp::Ordering;
use std::iter::Cloned;
pub type RandomOrderings = Cloned<RandomValuesFromSlice<'static, Ordering>>;
/// Generates a random `Ordering` that has an equal probability of being `Less`, `Great... | {
random_values_from_slice(seed, &ORDERINGS).cloned()
} | identifier_body | |
random.rs | use orderings::ORDERINGS;
use random::Seed;
use slices::{random_values_from_slice, RandomValuesFromSlice};
use std::cmp::Ordering;
use std::iter::Cloned;
pub type RandomOrderings = Cloned<RandomValuesFromSlice<'static, Ordering>>;
/// Generates a random `Ordering` that has an equal probability of being `Less`, `Great... | random_values_from_slice(seed, &ORDERINGS).cloned()
} | random_line_split | |
39-2.rs | /* Problem 39: Integer right triangles
*
* If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are
* exactly three solutions for p = 120.
*
* {20,48,52}, {24,45,51}, {30,40,50}
*
* For which value of p ≤ 1000, is the number of solutions maximised? */
const MAX_PERIMETER: f... | b += 1.0;
continue;
}
let perimeter = a + b + c;
if perimeter < MAX_PERIMETER {
counts[(perimeter as usize) - 1] += 1;
}
b += 1.0;
}
a += 1.0;
}
let mut max_count = 0;
let mut max... | random_line_split | |
39-2.rs | /* Problem 39: Integer right triangles
*
* If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are
* exactly three solutions for p = 120.
*
* {20,48,52}, {24,45,51}, {30,40,50}
*
* For which value of p ≤ 1000, is the number of solutions maximised? */
const MAX_PERIMETER: f... | {
let mut counts = [0usize; MAX_PERIMETER as usize];
let max_perimeter_by_3 = MAX_PERIMETER / 3.0;
let two_thirds_of_max = 2.0 * max_perimeter_by_3;
let mut a = 1.0;
while a < max_perimeter_by_3 {
let a_squared = a * a;
let mut b = a + 1.0;
while b < two_thirds_of_max - ... | in() | identifier_name |
39-2.rs | /* Problem 39: Integer right triangles
*
* If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are
* exactly three solutions for p = 120.
*
* {20,48,52}, {24,45,51}, {30,40,50}
*
* For which value of p ≤ 1000, is the number of solutions maximised? */
const MAX_PERIMETER: f... | let perimeter = a + b + c;
if perimeter < MAX_PERIMETER {
counts[(perimeter as usize) - 1] += 1;
}
b += 1.0;
}
a += 1.0;
}
let mut max_count = 0;
let mut max = 0;
for (index, &count) in counts.iter().enumerate() {
... | b += 1.0;
continue;
}
| conditional_block |
39-2.rs | /* Problem 39: Integer right triangles
*
* If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are
* exactly three solutions for p = 120.
*
* {20,48,52}, {24,45,51}, {30,40,50}
*
* For which value of p ≤ 1000, is the number of solutions maximised? */
const MAX_PERIMETER: f... | }
let perimeter = a + b + c;
if perimeter < MAX_PERIMETER {
counts[(perimeter as usize) - 1] += 1;
}
b += 1.0;
}
a += 1.0;
}
let mut max_count = 0;
let mut max = 0;
for (index, &count) in counts.iter().enum... | let mut counts = [0usize; MAX_PERIMETER as usize];
let max_perimeter_by_3 = MAX_PERIMETER / 3.0;
let two_thirds_of_max = 2.0 * max_perimeter_by_3;
let mut a = 1.0;
while a < max_perimeter_by_3 {
let a_squared = a * a;
let mut b = a + 1.0;
while b < two_thirds_of_max - a {... | identifier_body |
issue-22684.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
mod foo {
pub struct Foo;
impl Foo {
fn bar(&self) {}
}
pub trait Baz {
fn bar(&self) -> bool { true }
}
impl Baz for Foo {}
}
fn main() {
use foo::Baz;
// Check that `bar` resolves to the trait method, not the inherent impl method.
let _: () = foo::Foo.bar(); //~... | random_line_split | |
issue-22684.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self) -> bool { true }
}
impl Baz for Foo {}
}
fn main() {
use foo::Baz;
// Check that `bar` resolves to the trait method, not the inherent impl method.
let _: () = foo::Foo.bar(); //~ ERROR mismatched types
}
| bar | identifier_name |
issue-22684.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
use foo::Baz;
// Check that `bar` resolves to the trait method, not the inherent impl method.
let _: () = foo::Foo.bar(); //~ ERROR mismatched types
} | identifier_body | |
server.rs | // Copyright 2017 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | )
.get_matches();
let host = matches.value_of("host").unwrap_or("127.0.0.1");
let port: u16 = matches.value_of("port").unwrap_or("8080").parse().unwrap();
let use_tls: bool = matches
.value_of("use_tls")
.unwrap_or("false")
.parse()
.unwrap();
let env = Arc::n... | {
let matches = App::new("Interoperability Test Server")
.about("ref https://github.com/grpc/grpc/blob/v1.3.x/doc/interop-test-descriptions.md")
.arg(
Arg::with_name("host")
.long("host")
.help("The server host to listen to. For example, \"localhost\" or \... | identifier_body |
server.rs | // Copyright 2017 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | ;
let mut server = builder.build().unwrap();
for &(ref host, port) in server.bind_addrs() {
info!("listening on {}:{}", host, port);
}
server.start();
let _ = future::empty::<(), ()>().wait();
}
| {
builder.bind(host, port)
} | conditional_block |
server.rs | // Copyright 2017 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | .arg(
Arg::with_name("use_tls")
.long("use_tls")
.help("Whether to use a plaintext or encrypted connection")
.takes_value(true),
)
.get_matches();
let host = matches.value_of("host").unwrap_or("127.0.0.1");
let port: u16 = matches.va... | .help("The port to listen on. For example, \"8080\"")
.takes_value(true),
) | random_line_split |
server.rs | // Copyright 2017 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | () {
let matches = App::new("Interoperability Test Server")
.about("ref https://github.com/grpc/grpc/blob/v1.3.x/doc/interop-test-descriptions.md")
.arg(
Arg::with_name("host")
.long("host")
.help("The server host to listen to. For example, \"localhost\" or \"... | main | identifier_name |
issue-3563-3.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 ... | {
test_ascii_art_ctor();
test_add_pt();
test_shapes();
} | identifier_body | |
issue-3563-3.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 ... | (actual: &str, expected: &str) -> bool {
if actual!= expected {
println!("Found:\n{}\nbut expected\n{}", actual, expected);
return false;
}
return true;
}
fn test_ascii_art_ctor() {
let art = AsciiArt(3, 3, '*');
assert!(check_strs(art.to_str().as_slice(), "...\n...\n..."));
}
fn... | check_strs | identifier_name |
issue-3563-3.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 ... |
}
}
// Allows AsciiArt to be converted to a string using the libcore ToStr trait.
// Note that the %s fmt! specifier will not call this automatically.
impl fmt::Show for AsciiArt {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// Convert each line into a string.
let lines = self.lines... | {
if y >= 0 && y < self.height as int {
// Note that numeric types don't implicitly convert to each other.
let v = y as uint;
let h = x as uint;
// Vector subscripting will normally copy the element, but &v[i]
// will return a ... | conditional_block |
issue-3563-3.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 _ in range(0, height) {
lines.push(Vec::from_elem(width, '.'));
}
// Rust code often returns values by omitting the trailing semi-colon
// instead of using an explicit return statement.
AsciiArt {width: width, height: height, fill: fill, lines: lines}
}
// Methods particular to the Asc... | // Other constructor sort of functions are typically named from_foo, from_bar, etc.
fn AsciiArt(width: uint, height: uint, fill: char) -> AsciiArt {
// Use an anonymous function to build a vector of vectors containing
// blank characters for each position in our canvas.
let mut lines = Vec::new(); | random_line_split |
var_int.rs | use bytes::BytesMut;
use criterion::{black_box, criterion_group, criterion_main, Benchmark, Criterion};
use protocol::{Decode, Encode, Var};
fn criterion_benchmark(c: &mut Criterion) {
c.bench(
"benches",
Benchmark::new("write_var_u64", move |b| {
b.iter(|| {
let mut buf... | b.iter(|| {
let mut buf = BytesMut::with_capacity(10);
Var(black_box(3_000_000_000u32)).encode(black_box(&mut buf))
})
}),
);
c.bench(
"benches",
Benchmark::new("read_var_u64", move |b| {
let mut buf = BytesMut::new();
... |
c.bench(
"benches",
Benchmark::new("write_var_u32", move |b| { | random_line_split |
var_int.rs | use bytes::BytesMut;
use criterion::{black_box, criterion_group, criterion_main, Benchmark, Criterion};
use protocol::{Decode, Encode, Var};
fn | (c: &mut Criterion) {
c.bench(
"benches",
Benchmark::new("write_var_u64", move |b| {
b.iter(|| {
let mut buf = BytesMut::with_capacity(10);
Var(black_box(12_456_456_456_465_464u64)).encode(black_box(&mut buf))
})
}),
);
c.bench... | criterion_benchmark | identifier_name |
var_int.rs | use bytes::BytesMut;
use criterion::{black_box, criterion_group, criterion_main, Benchmark, Criterion};
use protocol::{Decode, Encode, Var};
fn criterion_benchmark(c: &mut Criterion) |
c.bench(
"benches",
Benchmark::new("read_var_u64", move |b| {
let mut buf = BytesMut::new();
Var(12_456_456_456_465_464u64).encode(&mut buf);
b.iter(|| Var::<u64>::decode(&mut (black_box(&buf[0..]))).unwrap())
}),
);
c.bench(
"benches",
... | {
c.bench(
"benches",
Benchmark::new("write_var_u64", move |b| {
b.iter(|| {
let mut buf = BytesMut::with_capacity(10);
Var(black_box(12_456_456_456_465_464u64)).encode(black_box(&mut buf))
})
}),
);
c.bench(
"benches",... | identifier_body |
framed.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 n... |
let nwrite = b.len(); // always less than available write buffer capacity
self.buf[self.pos..(self.pos + nwrite)].clone_from_slice(b);
self.pos += nwrite;
Ok(nwrite)
}
fn flush(&mut self) -> io::Result<()> {
let message_size = self.pos;
if let 0 = message_size... | {
return Err(
io::Error::new(
ErrorKind::Other,
format!(
"bytes to be written ({}) exceeds buffer \
capacity ({})",
b.len(),
self.buf... | conditional_block |
framed.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 n... |
}
impl TWriteTransportFactory for TFramedWriteTransportFactory {
/// Create a `TFramedWriteTransport`.
fn create(&self, channel: Box<Write + Send>) -> Box<TWriteTransport + Send> {
Box::new(TFramedWriteTransport::new(channel))
}
}
#[cfg(test)]
mod tests {
// use std::io::{Read, Write};
... | {
TFramedWriteTransportFactory {}
} | identifier_body |
framed.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 n... | <C>
where
C: Write,
{
buf: Box<[u8]>,
pos: usize,
channel: C,
}
impl<C> TFramedWriteTransport<C>
where
C: Write,
{
/// Create a `TFramedTransport` with default-sized internal read and
/// write buffers that wraps the given `TIoChannel`.
pub fn new(channel: C) -> TFramedWriteTransport<C>... | TFramedWriteTransport | identifier_name |
framed.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 n... | /// ```no_run
/// use std::io::Read;
/// use thrift::transport::{TFramedReadTransport, TTcpChannel};
///
/// let mut c = TTcpChannel::new();
/// c.open("localhost:9090").unwrap();
///
/// let mut t = TFramedReadTransport::new(c);
///
/// t.read(&mut vec![0u8; 1]).unwrap();
/// ```
#[derive(Debug)]
pub struct TFramedRea... | ///
/// Create and use a `TFramedReadTransport`.
/// | random_line_split |
json.rs | //! Serialize `Script`s to `json`
/// Serialize the given `Script` into a `json`
///
/// Serialize the given `Script` into the following `json` format and write
/// it to the given `Writer`.
///
/// # Example
///
/// ```json
/// [
/// [
/// {
/// "place": "Snowy Landscape",
/// "typ... | : Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
s.emit_map(3, |s| {
try!(emit_map_key_val(s, 0, "place", |s| self.name.encode(s)));
match self.kind {
LocationType::Undefined => {}
ref kind => {
let kind: &str = kind.clone().into(... | code<S | identifier_name |
json.rs | //! Serialize `Script`s to `json`
/// Serialize the given `Script` into a `json`
///
/// Serialize the given `Script` into the following `json` format and write
/// it to the given `Writer`.
///
/// # Example
///
/// ```json
/// [
/// [
/// {
/// "place": "Snowy Landscape",
/// "typ... | }
}
}
impl Encodable for DialogPart {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
match self {
&DialogPart::Dialog(ref dialog) => {
s.emit_str(dialog)
}
&DialogPart::Direction(ref direction) => {
s.emit_map... | s.emit_map(3, |s| {
try!(emit_map_key_val(s, 0, "page", |s| page.encode(s)));
try!(emit_map_key_val(s, 1, "character", |s| speaker.encode(s)));
try!(emit_map_key_val(s, 2, "dialog", |s| dialog.encode(s)));
Ok(())
... | conditional_block |
json.rs | //! Serialize `Script`s to `json`
/// Serialize the given `Script` into a `json`
///
/// Serialize the given `Script` into the following `json` format and write
/// it to the given `Writer`.
///
/// # Example
///
/// ```json
/// [
/// [
/// {
/// "place": "Snowy Landscape",
/// "typ... |
use ::{DialogPart, Location, LocationType, ScenePart, Script};
use rustc_serialize::Encodable;
use rustc_serialize::{Encoder, json};
use std::io::Write;
use std::fmt;
/// Needed because rustc-serialize uses fmt::Write instead of io::Write.
/// See https://github.com/rust-lang-nursery/rustc-serialize/issues/111
struc... | } | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.