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 |
|---|---|---|---|---|
loader.rs | One of the immediate problems with linking the same library together twice
//! in the same problem is dealing with duplicate symbols. The primary way to
//! deal with this in rustc is to add hashes to the end of each symbol.
//!
//! In order to force hashes to change between versions of a library, if
//! desired, the ... | (&mut self) -> Option<Library> {
// If an SVH is specified, then this is a transitive dependency that
// must be loaded via -L plus some filtering.
if self.hash.is_none() {
self.should_match_name = false;
match self.find_commandline_library() {
Some(l) => ... | find_library_crate | identifier_name |
loader.rs | triple for crate `{}`", self.ident)
} else {
format!("can't find crate for `{}`", self.ident)
};
let message = match self.root {
&None => message,
&Some(ref r) => format!("{} which `{}` depends on",
message, r.ident)
... | { unsafe { &*self.data } } | identifier_body | |
loader.rs | //! One of the immediate problems with linking the same library together twice
//! in the same problem is dealing with duplicate symbols. The primary way to
//! deal with this in rustc is to add hashes to the end of each symbol.
//!
//! In order to force hashes to change between versions of a library, if
//! desired, t... | pub rlib: Option<Path>,
pub metadata: MetadataBlob,
}
pub struct ArchiveMetadata {
_archive: ArchiveRO,
// points into self._archive
data: *const [u8],
}
pub struct CratePaths {
pub ident: String,
pub dylib: Option<Path>,
pub rlib: Option<Path>
}
impl CratePaths {
fn paths(&self) ... | }
pub struct Library {
pub dylib: Option<Path>, | random_line_split |
lib.rs | use std::env;
use std::error::Error;
use std::fs;
pub struct Config {
pub query: String,
pub filename: String,
pub case_sensitive: bool,
}
// ANCHOR: here
impl Config {
pub fn new(mut args: env::Args) -> Result<Config, &'static str> {
// --snip--
// ANCHOR_END: here
if args.len... | ;
for line in results {
println!("{}", line);
}
Ok(())
}
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
let mut results = Vec::new();
for line in contents.lines() {
if line.contains(query) {
results.push(line);
}
}
results
}
pub ... | {
search_case_insensitive(&config.query, &contents)
} | conditional_block |
lib.rs | use std::env;
use std::error::Error;
use std::fs;
pub struct Config {
pub query: String,
pub filename: String,
pub case_sensitive: bool,
}
// ANCHOR: here
impl Config {
pub fn new(mut args: env::Args) -> Result<Config, &'static str> {
// --snip--
// ANCHOR_END: here
if args.len... | };
for line in results {
println!("{}", line);
}
Ok(())
}
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
let mut results = Vec::new();
for line in contents.lines() {
if line.contains(query) {
results.push(line);
}
}
results
}
... | } else {
search_case_insensitive(&config.query, &contents) | random_line_split |
lib.rs | use std::env;
use std::error::Error;
use std::fs;
pub struct Config {
pub query: String,
pub filename: String,
pub case_sensitive: bool,
}
// ANCHOR: here
impl Config {
pub fn new(mut args: env::Args) -> Result<Config, &'static str> |
}
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(config.filename)?;
let results = if config.case_sensitive {
search(&config.query, &contents)
} else {
search_case_insensitive(&config.query, &contents)
};
for line in results {
... | {
// --snip--
// ANCHOR_END: here
if args.len() < 3 {
return Err("not enough arguments");
}
let query = args[1].clone();
let filename = args[2].clone();
let case_sensitive = env::var("CASE_INSENSITIVE").is_err();
Ok(Config {
quer... | identifier_body |
lib.rs | use std::env;
use std::error::Error;
use std::fs;
pub struct Config {
pub query: String,
pub filename: String,
pub case_sensitive: bool,
}
// ANCHOR: here
impl Config {
pub fn new(mut args: env::Args) -> Result<Config, &'static str> {
// --snip--
// ANCHOR_END: here
if args.len... | () {
let query = "rUsT";
let contents = "\
Rust:
safe, fast, productive.
Pick three.
Trust me.";
assert_eq!(
vec!["Rust:", "Trust me."],
search_case_insensitive(query, contents)
);
}
}
| case_insensitive | identifier_name |
glue.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/. */
#![allow(unsafe_code)]
use app_units::Au;
use data::{NUM_THREADS, PerDocumentStyleData};
use env_logger;
use eucl... |
pub struct GeckoDeclarationBlock {
pub declarations: Option<Arc<PropertyDeclarationBlock>>,
// XXX The following two fields are made atomic to work around the
// ownership system so that they can be changed inside a shared
// instance. It wouldn't provide safety as Rust usually promises,
// but it... | {
let _ = data.into_box::<PerDocumentStyleData>();
} | identifier_body |
glue.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/. */
#![allow(unsafe_code)]
use app_units::Au;
use data::{NUM_THREADS, PerDocumentStyleData};
use env_logger;
use eucl... | (ptr: ServoComputedValuesBorrowed) -> () {
unsafe { ComputedValues::addref(ptr) };
}
#[no_mangle]
pub extern "C" fn Servo_ComputedValues_Release(ptr: ServoComputedValuesBorrowed) -> () {
unsafe { ComputedValues::release(ptr) };
}
#[no_mangle]
pub extern "C" fn Servo_StyleSet_Init() -> RawServoStyleSetOwned {
... | Servo_ComputedValues_AddRef | identifier_name |
glue.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/. */
#![allow(unsafe_code)]
use app_units::Au;
use data::{NUM_THREADS, PerDocumentStyleData};
use env_logger;
use eucl... | let per_doc_data = PerDocumentStyleData::from_ffi(raw_data);
let snapshot = unsafe { GeckoElementSnapshot::from_raw(snapshot) };
let element = GeckoElement(element);
// NB: This involves an FFI call, we can get rid of it easily if needed.
let current_state = element.get_state();
let hint = per... | pub extern "C" fn Servo_ComputeRestyleHint(element: RawGeckoElementBorrowed,
snapshot: *mut ServoElementSnapshot,
raw_data: RawServoStyleSetBorrowed) -> nsRestyleHint { | random_line_split |
lib.rs | //! Provides an interface for reading input from a *Nintendo GameCube Controller Adapter for Wii U*
//! USB device.
//!
//! Third party clones such as the 4-port Mayflash adapter in "Wii U mode" are also supported.
//!
//! This library depends on `libusb`, which is available as a dynamic library on many platforms
//! i... | right: data[1] & (1 << 5)!= 0,
down: data[1] & (1 << 6)!= 0,
up: data[1] & (1 << 7)!= 0,
start: data[2] & (1 << 0)!= 0,
z: data[2] & (1 << 1)!= 0,
r: data[2] & (1 << 2)!= 0,
l: data[2] & (1 << 3)!= 0,
stick_x: data[3],
... | a: data[1] & (1 << 0) != 0,
b: data[1] & (1 << 1) != 0,
x: data[1] & (1 << 2) != 0,
y: data[1] & (1 << 3) != 0,
left: data[1] & (1 << 4) != 0, | random_line_split |
lib.rs | //! Provides an interface for reading input from a *Nintendo GameCube Controller Adapter for Wii U*
//! USB device.
//!
//! Third party clones such as the 4-port Mayflash adapter in "Wii U mode" are also supported.
//!
//! This library depends on `libusb`, which is available as a dynamic library on many platforms
//! i... | <'a> {
handle: DeviceHandle<'a>,
buffer: [u8; 37],
has_kernel_driver: bool,
interface: u8,
endpoint_in: u8,
}
impl<'a> Listener<'a> {
/// Reads a data packet and returns the states for each of the four possibly connected
/// controllers.
///
/// If reading a single packet takes over... | Listener | identifier_name |
lib.rs | //! Provides an interface for reading input from a *Nintendo GameCube Controller Adapter for Wii U*
//! USB device.
//!
//! Third party clones such as the 4-port Mayflash adapter in "Wii U mode" are also supported.
//!
//! This library depends on `libusb`, which is available as a dynamic library on many platforms
//! i... |
/// Returns the first adapter found, or `None` if no adapter was found.
pub fn find_adapter<'a>(&'a mut self) -> Result<Option<Adapter<'a>>, Error> {
for mut device in try!(self.context.devices()).iter() {
let desc = try!(device.device_descriptor());
if desc.vendor_id() == VEN... | {
Ok(Scanner { context: try!(Context::new()) })
} | identifier_body |
extern-generic.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 mod1 {
use cgu_generic_function;
//~ MONO_ITEM fn extern_generic::mod1[0]::user[0] @@ extern_generic-mod1[Internal]
fn user() {
let _ = cgu_generic_function::foo("abc");
}
mod mod1 {
use cgu_generic_function;
//~ MONO_ITEM fn extern_generic::mod1[0]::mod1[0]::user[0]... | {
let _ = cgu_generic_function::foo("abc");
} | identifier_body |
extern-generic.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 mod1 {
use cgu_generic_function;
//~ MONO_ITEM fn extern_generic::mod1[0]::mod1[0]::user[0] @@ extern_generic-mod1-mod1[Internal]
fn user() {
let _ = cgu_generic_function::foo("abc");
}
}
}
mod mod2 {
use cgu_generic_function;
//~ MONO_ITEM fn extern_g... | random_line_split | |
extern-generic.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 ... | () {
let _ = cgu_generic_function::foo("abc");
}
}
mod mod3 {
//~ MONO_ITEM fn extern_generic::mod3[0]::non_user[0] @@ extern_generic-mod3[Internal]
fn non_user() {}
}
// Make sure the two generic functions from the extern crate get instantiated
// once for the current crate
//~ MONO_ITEM fn cgu_g... | user | identifier_name |
htmlstyleelement.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 cssparser::Parser as CssParser;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HTM... |
pub fn parse_own_css(&self) {
let node = self.upcast::<Node>();
let element = self.upcast::<Element>();
assert!(node.is_in_doc());
let win = window_from_node(node);
let url = win.get_url();
let mq_attribute = element.get_attribute(&ns!(), &atom!("media"));
... | {
Node::reflect_node(box HTMLStyleElement::new_inherited(local_name, prefix, document),
document,
HTMLStyleElementBinding::Wrap)
} | identifier_body |
htmlstyleelement.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 cssparser::Parser as CssParser;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HTM... |
}
}
| {
self.parse_own_css();
} | conditional_block |
htmlstyleelement.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 cssparser::Parser as CssParser;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HTM... | if let Some(ref s) = self.super_type() {
s.children_changed(mutation);
}
if self.upcast::<Node>().is_in_doc() {
self.parse_own_css();
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.bind_to_tr... | Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn children_changed(&self, mutation: &ChildrenMutation) { | random_line_split |
htmlstyleelement.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 cssparser::Parser as CssParser;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HTM... | (local_name: Atom,
prefix: Option<DOMString>,
document: &Document) -> HTMLStyleElement {
HTMLStyleElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
stylesheet: DOMRefCell::new(None),
}
}
#[allow(unr... | new_inherited | identifier_name |
constref.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
assert!(const_ref());
assert!(associated_const_ref());
} | identifier_body | |
constref.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
assert!(const_ref());
assert!(associated_const_ref());
}
| main | identifier_name |
constref.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | pub fn main() {
assert!(const_ref());
assert!(associated_const_ref());
} | random_line_split | |
query16.rs | use timely::dataflow::*;
// use timely::dataflow::operators::*;
use timely::dataflow::operators::probe::Handle as ProbeHandle;
// use differential_dataflow::AsCollection;
use differential_dataflow::operators::*;
use differential_dataflow::lattice::Lattice;
use ::Collections;
// -- $ID$
// -- TPC-H/TPC-R Parts/Suppli... |
)
.semijoin_u(&parts)
.count()
.probe()
} | { None } | conditional_block |
query16.rs | use timely::dataflow::*;
// use timely::dataflow::operators::*;
use timely::dataflow::operators::probe::Handle as ProbeHandle;
// use differential_dataflow::AsCollection;
use differential_dataflow::operators::*; | use differential_dataflow::lattice::Lattice;
use ::Collections;
// -- $ID$
// -- TPC-H/TPC-R Parts/Supplier Relationship Query (Q16)
// -- Functional Query Definition
// -- Approved February 1998
// :x
// :o
// select
// p_brand,
// p_type,
// p_size,
// count(distinct ps_suppkey) as supplier_cnt
// f... | random_line_split | |
query16.rs | use timely::dataflow::*;
// use timely::dataflow::operators::*;
use timely::dataflow::operators::probe::Handle as ProbeHandle;
// use differential_dataflow::AsCollection;
use differential_dataflow::operators::*;
use differential_dataflow::lattice::Lattice;
use ::Collections;
// -- $ID$
// -- TPC-H/TPC-R Parts/Suppli... |
collections
.parts()
.flat_map(|p|
if!starts_with(&p.brand, b"Brand45") &&!starts_with(&p.typ.as_bytes(), b"MEDIUM POLISHED") && [49, 14, 23, 45, 19, 3, 36, 9].contains(&p.size) {
Some((p.part_key, (p.brand, p.typ.to_string(), p.size)))
}
else { No... | {
println!("TODO: query 16 could use a count_u if it joins after to re-collect its attributes");
let suppliers =
collections
.suppliers()
.flat_map(|s|
if substring2(s.comment.as_bytes(), b"Customer", b"Complaints") {
Some((s.supp_key))
}
... | identifier_body |
query16.rs | use timely::dataflow::*;
// use timely::dataflow::operators::*;
use timely::dataflow::operators::probe::Handle as ProbeHandle;
// use differential_dataflow::AsCollection;
use differential_dataflow::operators::*;
use differential_dataflow::lattice::Lattice;
use ::Collections;
// -- $ID$
// -- TPC-H/TPC-R Parts/Suppli... | <G: Scope>(collections: &mut Collections<G>) -> ProbeHandle<G::Timestamp>
where G::Timestamp: Lattice+Ord {
println!("TODO: query 16 could use a count_u if it joins after to re-collect its attributes");
let suppliers =
collections
.suppliers()
.flat_map(|s|
if substring2(s.comm... | query | identifier_name |
capstone.rs | use alloc::string::{String, ToString};
use core::convert::From;
use core::marker::PhantomData;
use libc::{c_int, c_uint, c_void};
use capstone_sys::cs_opt_value::*;
use capstone_sys::*;
use crate::arch::CapstoneBuilder;
use crate::constants::{Arch, Endian, ExtraMode, Mode, OptValue, Syntax};
use crate::error::*;
use... | <T: Iterator<Item = ExtraMode>>(&mut self, extra_mode: T) -> CsResult<()> {
let old_val = self.extra_mode;
self.extra_mode = Self::extra_mode_value(extra_mode);
let old_mode = self.raw_mode;
let new_mode = self.update_raw_mode();
let result = self._set_cs_option(cs_opt_type::CS... | set_extra_mode | identifier_name |
capstone.rs | use alloc::string::{String, ToString};
use core::convert::From;
use core::marker::PhantomData;
use libc::{c_int, c_uint, c_void};
use capstone_sys::cs_opt_value::*;
use capstone_sys::*;
use crate::arch::CapstoneBuilder;
use crate::constants::{Arch, Endian, ExtraMode, Mode, OptValue, Syntax};
use crate::error::*;
use... |
/// Controls whether to capstone will generate extra details about disassembled instructions.
///
/// Pass `true` to enable detail or `false` to disable detail.
pub fn set_detail(&mut self, enable_detail: bool) -> CsResult<()> {
let option_value: usize = OptValue::from(enable_detail).0 as usiz... | {
let err = unsafe { cs_option(self.csh(), option_type, option_value) };
if cs_err::CS_ERR_OK == err {
Ok(())
} else {
Err(err.into())
}
} | identifier_body |
capstone.rs | use alloc::string::{String, ToString};
use core::convert::From;
use core::marker::PhantomData;
use libc::{c_int, c_uint, c_void};
use capstone_sys::cs_opt_value::*;
use capstone_sys::*;
use crate::arch::CapstoneBuilder;
use crate::constants::{Arch, Endian, ExtraMode, Mode, OptValue, Syntax};
use crate::error::*;
use... | /// assert!(cs.is_ok());
/// ```
pub fn new_raw<T: Iterator<Item = ExtraMode>>(
arch: Arch,
mode: Mode,
extra_mode: T,
endian: Option<Endian>,
) -> CsResult<Capstone> {
let mut handle: csh = 0;
let csarch: cs_arch = arch.into();
let csmode: cs_mode... | /// ```
/// use capstone::{Arch, Capstone, NO_EXTRA_MODE, Mode};
/// let cs = Capstone::new_raw(Arch::X86, Mode::Mode64, NO_EXTRA_MODE, None); | random_line_split |
main.rs | mod sqrl_s4;
mod sqrl_crypto;
use sqrl_s4::SqrlS4Identity;
use sqrl_crypto::en_scrypt;
fn main() | {
//let identity = SqrlS4Identity{type1_length: 34, ..Default::default()};
//let mut identity = SqrlS4Identity::default();
let sqrlbinary = b"sqrldata}\x00\x01\x00-\x00\"wQ\x122\x0e\xb5\x891\xfep\x97\xef\xf2e]\xf6\x0fg\x07\x8c_\xda\xd4\xe0Z\xe0\xb8\t\x96\x00\x00\x00\xf3\x01\x04\x05\x0f\x00\x023\x88\xcd\xa0\... | identifier_body | |
main.rs | mod sqrl_s4;
mod sqrl_crypto;
use sqrl_s4::SqrlS4Identity;
use sqrl_crypto::en_scrypt;
fn main() {
//let identity = SqrlS4Identity{type1_length: 34,..Default::default()};
//let mut identity = SqrlS4Identity::default();
let sqrlbinary = b"sqrldata}\x00\x01\x00-\x00\"wQ\x122\x0e\xb5\x891\xfep\x97\xef\xf2e]\... | println!("identity debug\n{:?}", identity);
println!("identity print\n{}", identity);
identity.type1_length = 125;
println!("identity.type1_length {}", identity.type1_length);
println!("{:?}", en_scrypt(b"", b"", 64, 1));
} | let mut identity = SqrlS4Identity::from_binary(sqrlbinary); | random_line_split |
main.rs | mod sqrl_s4;
mod sqrl_crypto;
use sqrl_s4::SqrlS4Identity;
use sqrl_crypto::en_scrypt;
fn | () {
//let identity = SqrlS4Identity{type1_length: 34,..Default::default()};
//let mut identity = SqrlS4Identity::default();
let sqrlbinary = b"sqrldata}\x00\x01\x00-\x00\"wQ\x122\x0e\xb5\x891\xfep\x97\xef\xf2e]\xf6\x0fg\x07\x8c_\xda\xd4\xe0Z\xe0\xb8\t\x96\x00\x00\x00\xf3\x01\x04\x05\x0f\x00\x023\x88\xcd\xa... | main | identifier_name |
error.rs | use std::error::Error;
use std::fmt;
use hyper::client::Response;
use hyper::error::HttpError;
use rustc_serialize::json::Json;
/// An error returned by `Client` when an API call fails.
pub struct FleetError {
/// An HTTP status code returned by the fleet API.
pub code: Option<u16>,
/// A message describi... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{}: {}",
self.code.unwrap_or(0),
self.message.clone().unwrap_or("Unknown error".to_string()),
)
}
}
fn extract_message(response: &mut Response) -> Option<String> {
match Json::from_reader(... | fmt | identifier_name |
error.rs | use std::error::Error;
use std::fmt;
use hyper::client::Response;
use hyper::error::HttpError;
use rustc_serialize::json::Json;
/// An error returned by `Client` when an API call fails.
pub struct FleetError {
/// An HTTP status code returned by the fleet API.
pub code: Option<u16>,
/// A message describi... |
}
fn extract_message(response: &mut Response) -> Option<String> {
match Json::from_reader(response) {
Ok(json) => {
match json.find_path(&["error", "message"]) {
Some(message_json) => match message_json.as_string() {
Some(message) => {
if m... | {
write!(
f,
"{}: {}",
self.code.unwrap_or(0),
self.message.clone().unwrap_or("Unknown error".to_string()),
)
} | identifier_body |
error.rs | use std::error::Error;
use std::fmt;
use hyper::client::Response;
use hyper::error::HttpError;
use rustc_serialize::json::Json;
/// An error returned by `Client` when an API call fails.
pub struct FleetError {
/// An HTTP status code returned by the fleet API.
pub code: Option<u16>,
/// A message describi... | }
/// Constructs a new `FleetError` from a `hyper::client::Response`. Not intended for public
/// use.
pub fn from_hyper_response(response: &mut Response) -> FleetError {
FleetError {
code: Some(response.status.to_u16()),
message: extract_message(response),
}
... | code: None,
message: Some(error.description().to_string()),
} | random_line_split |
middleware.rs | use std::default::Default;
use std::sync::Arc;
use mysql::conn::MyOpts;
use mysql::conn::pool::MyPool;
use mysql::value::from_value;
use nickel::{Request, Response, Middleware, Continue, MiddlewareResult};
use typemap::Key;
use plugin::{Pluggable, Extensible};
pub struct MysqlMiddleware {
pub pool: Arc<MyPool>,
}... | }
impl Key for MysqlMiddleware { type Value = Arc<MyPool>; }
impl Middleware for MysqlMiddleware {
fn invoke<'res>(&self, request: &mut Request, response: Response<'res>) -> MiddlewareResult<'res> {
request.extensions_mut().insert::<MysqlMiddleware>(self.pool.clone());
Ok(Continue(response))
}... | random_line_split | |
middleware.rs | use std::default::Default;
use std::sync::Arc;
use mysql::conn::MyOpts;
use mysql::conn::pool::MyPool;
use mysql::value::from_value;
use nickel::{Request, Response, Middleware, Continue, MiddlewareResult};
use typemap::Key;
use plugin::{Pluggable, Extensible};
pub struct MysqlMiddleware {
pub pool: Arc<MyPool>,
}... | <'res>(&self, request: &mut Request, response: Response<'res>) -> MiddlewareResult<'res> {
request.extensions_mut().insert::<MysqlMiddleware>(self.pool.clone());
Ok(Continue(response))
}
}
pub trait MysqlRequestExtensions {
fn db_connection(&self) -> Arc<MyPool>;
}
impl<'a, 'b, 'c> Mys... | invoke | identifier_name |
relais_controller.rs | use errors::*;
use gtk;
use gtk::prelude::*;
use shift_register::*;
use std::sync::{Arc, Mutex};
pub fn all(button: >k::ToggleButton, relais: &Arc<Mutex<ShiftRegister>>) -> Result<()> {
let mut relais = relais.lock().unwrap();
match button.get_active() {
true => relais.all()?,
false => relai... |
pub fn set(button: >k::ToggleButton, relais: &Arc<Mutex<ShiftRegister>>, num: u64) -> Result<()> {
let mut relais = relais.lock().unwrap();
match button.get_active() {
true => relais.set(num)?,
false => relais.clear(num)?,
}
Ok(())
}
| {
let mut relais = relais.lock().unwrap();
match button.get_active() {
true => {
for i in 1..10 {
relais.set(i);
::std::thread::sleep(::std::time::Duration::from_millis(100));
}
},
false => relais.reset()?,
}
Ok(())
} | identifier_body |
relais_controller.rs | use errors::*;
use gtk;
use gtk::prelude::*;
use shift_register::*;
use std::sync::{Arc, Mutex};
pub fn all(button: >k::ToggleButton, relais: &Arc<Mutex<ShiftRegister>>) -> Result<()> {
let mut relais = relais.lock().unwrap();
match button.get_active() {
true => relais.all()?,
false => relai... | (button: >k::ToggleButton, relais: &Arc<Mutex<ShiftRegister>>) -> Result<()> {
let mut relais = relais.lock().unwrap();
match button.get_active() {
true => relais.test_random()?,
false => relais.reset()?,
}
Ok(())}
pub fn one_after_one(button: >k::ToggleButton, relais: &Arc<Mutex<S... | random | identifier_name |
relais_controller.rs | use errors::*;
use gtk;
use gtk::prelude::*;
use shift_register::*;
use std::sync::{Arc, Mutex};
pub fn all(button: >k::ToggleButton, relais: &Arc<Mutex<ShiftRegister>>) -> Result<()> {
let mut relais = relais.lock().unwrap();
match button.get_active() {
true => relais.all()?,
false => relai... | let mut relais = relais.lock().unwrap();
match button.get_active() {
true => {
for i in 1..10 {
relais.set(i);
::std::thread::sleep(::std::time::Duration::from_millis(100));
}
},
false => relais.reset()?,
}
Ok(())
}
pub f... | pub fn one_after_one(button: >k::ToggleButton, relais: &Arc<Mutex<ShiftRegister>>) -> Result<()> { | random_line_split |
acoustic_wave.rs | extern crate arrayfire as af;
use af::*;
use std::f64::consts::*;
fn main() {
set_device(0);
info();
acoustic_wave_simulation();
}
fn normalise(a: &Array) -> Array |
fn acoustic_wave_simulation() {
// Speed of sound
let c = 0.1;
// Distance step
let dx = 0.5;
// Time step
let dt = 1.0;
// Grid size.
let nx = 1500;
let ny = 1500;
// Grid dimensions.
let dims = Dim4::new(&[nx, ny, 1, 1]);
// Pressure field
let mut p = constant::... | {
(a/(max_all(&abs(a)).0 as f32 * 2.0f32)) + 0.5f32
} | identifier_body |
acoustic_wave.rs | extern crate arrayfire as af;
use af::*;
use std::f64::consts::*;
fn main() {
set_device(0);
info();
acoustic_wave_simulation();
}
fn | (a: &Array) -> Array {
(a/(max_all(&abs(a)).0 as f32 * 2.0f32)) + 0.5f32
}
fn acoustic_wave_simulation() {
// Speed of sound
let c = 0.1;
// Distance step
let dx = 0.5;
// Time step
let dt = 1.0;
// Grid size.
let nx = 1500;
let ny = 1500;
// Grid dimensions.
let dims =... | normalise | identifier_name |
acoustic_wave.rs | extern crate arrayfire as af;
use af::*;
use std::f64::consts::*;
fn main() {
set_device(0);
info();
acoustic_wave_simulation();
}
fn normalise(a: &Array) -> Array {
(a/(max_all(&abs(a)).0 as f32 * 2.0f32)) + 0.5f32
}
fn acoustic_wave_simulation() {
// Speed of sound
let c = 0.1;
// Dist... |
// Draw the image.
win.set_colormap(af::ColorMap::BLUE);
win.draw_image(&normalise(&p), None);
it += 1;
}
}
| {
// Location of the source.
let seqs = &[Seq::new(700.0, 800.0, 1.0), Seq::new(800.0, 800.0, 1.0)];
// Set the pressure there.
p = assign_seq(&p, seqs, &index(&pulse, &[Seq::new(it as f64, it as f64, 1.0)]));
} | conditional_block |
acoustic_wave.rs | extern crate arrayfire as af;
use af::*;
use std::f64::consts::*;
fn main() {
set_device(0);
info(); |
fn normalise(a: &Array) -> Array {
(a/(max_all(&abs(a)).0 as f32 * 2.0f32)) + 0.5f32
}
fn acoustic_wave_simulation() {
// Speed of sound
let c = 0.1;
// Distance step
let dx = 0.5;
// Time step
let dt = 1.0;
// Grid size.
let nx = 1500;
let ny = 1500;
// Grid dimensions.
... |
acoustic_wave_simulation();
} | random_line_split |
htmltablecaptionelement.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::HTMLTableCaptionElementBinding;
use dom::bindings::js::Root;
use dom::bindin... |
#[allow(unrooted_must_root)]
pub fn new(local_name: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLTableCaptionElement> {
Node::reflect_node(box HTMLTableCaptionElement::new_inherited(local_name, prefix, document),
document,
... | {
HTMLTableCaptionElement {
htmlelement:
HTMLElement::new_inherited(local_name, prefix, document)
}
} | identifier_body |
htmltablecaptionelement.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::HTMLTableCaptionElementBinding;
use dom::bindings::js::Root;
use dom::bindin... | (local_name: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLTableCaptionElement> {
Node::reflect_node(box HTMLTableCaptionElement::new_inherited(local_name, prefix, document),
document,
HTMLTableCaptionElement... | new | identifier_name |
htmltablecaptionelement.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::HTMLTableCaptionElementBinding;
use dom::bindings::js::Root;
use dom::bindin... | document,
HTMLTableCaptionElementBinding::Wrap)
}
} | pub fn new(local_name: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLTableCaptionElement> {
Node::reflect_node(box HTMLTableCaptionElement::new_inherited(local_name, prefix, document), | random_line_split |
color.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("Color", inherited=True) %>
<% fr... | let s = match *self {
% for color in system_colors + extra_colors:
LookAndFeel_ColorID::eColorID_${to_rust_ident(color)} => "${color}",
% endfor
LookAndFeel_ColorID::eColorID_LAST_COLOR => unreachable!(),
};
dest.wri... | fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{ | random_line_split |
cache.rs | use crate::error::CkError;
use serde_json::Value;
use std::collections::HashMap;
use std::io;
use std::path::{Path, PathBuf};
use fs_err as fs;
#[derive(Debug)]
pub struct Cache {
root: PathBuf,
files: HashMap<PathBuf, String>,
values: HashMap<PathBuf, Value>,
pub variables: HashMap<String, Value>,
... |
}
fn read_file(&mut self, path: PathBuf) -> Result<String, io::Error> {
if let Some(f) = self.files.get(&path) {
return Ok(f.clone());
}
let file = fs::read_to_string(&path)?;
self.files.insert(path, file.clone());
Ok(file)
}
/// Get the text fro... | {
self.last_path
.as_ref()
// FIXME: Point to a line number
.expect("No last path set. Make sure to specify a full path before using `-`")
.clone()
} | conditional_block |
cache.rs | use crate::error::CkError;
use serde_json::Value;
use std::collections::HashMap;
use std::io;
use std::path::{Path, PathBuf};
use fs_err as fs;
#[derive(Debug)]
pub struct Cache {
root: PathBuf,
files: HashMap<PathBuf, String>,
values: HashMap<PathBuf, Value>,
pub variables: HashMap<String, Value>,
... |
/// Parse the JSON from a file. If called multiple times, the file will only be read once.
pub fn get_value(&mut self, path: &String) -> Result<Value, CkError> {
let path = self.resolve_path(path);
if let Some(v) = self.values.get(&path) {
return Ok(v.clone());
}
... | {
let path = self.resolve_path(path);
self.read_file(path)
} | identifier_body |
cache.rs | use crate::error::CkError;
use serde_json::Value;
use std::collections::HashMap;
use std::io;
use std::path::{Path, PathBuf};
use fs_err as fs;
#[derive(Debug)]
pub struct Cache {
root: PathBuf,
files: HashMap<PathBuf, String>,
values: HashMap<PathBuf, Value>,
pub variables: HashMap<String, Value>,
... | .clone()
}
}
fn read_file(&mut self, path: PathBuf) -> Result<String, io::Error> {
if let Some(f) = self.files.get(&path) {
return Ok(f.clone());
}
let file = fs::read_to_string(&path)?;
self.files.insert(path, file.clone());
Ok(file... | .as_ref()
// FIXME: Point to a line number
.expect("No last path set. Make sure to specify a full path before using `-`") | random_line_split |
cache.rs | use crate::error::CkError;
use serde_json::Value;
use std::collections::HashMap;
use std::io;
use std::path::{Path, PathBuf};
use fs_err as fs;
#[derive(Debug)]
pub struct Cache {
root: PathBuf,
files: HashMap<PathBuf, String>,
values: HashMap<PathBuf, Value>,
pub variables: HashMap<String, Value>,
... | (&mut self, path: PathBuf) -> Result<String, io::Error> {
if let Some(f) = self.files.get(&path) {
return Ok(f.clone());
}
let file = fs::read_to_string(&path)?;
self.files.insert(path, file.clone());
Ok(file)
}
/// Get the text from a file. If called mult... | read_file | identifier_name |
trie_node.rs | use {TrieNode, KeyValue, NibbleVec, BRANCH_FACTOR};
use keys::*;
macro_rules! no_children {
() => ([
None, None, None, None,
None, None, None, None,
None, None, None, None,
None, None, None, None
])
}
impl<K, V> TrieNode<K, V>
where K: TrieKey
{
/// Create a value-less,... |
}
(true, sub_tree_size)
}
}
| {
match child.check_integrity_recursive(&trie_key) {
(false, _) => return (false, sub_tree_size),
(true, child_size) => sub_tree_size += child_size,
}
} | conditional_block |
trie_node.rs | use {TrieNode, KeyValue, NibbleVec, BRANCH_FACTOR};
use keys::*;
macro_rules! no_children {
() => ([
None, None, None, None,
None, None, None, None,
None, None, None, None,
None, None, None, None
])
}
impl<K, V> TrieNode<K, V>
where K: TrieKey
{
/// Create a value-less,... | () -> TrieNode<K, V> {
TrieNode {
key: NibbleVec::new(),
key_value: None,
children: no_children![],
child_count: 0,
}
}
/// Create a TrieNode with no children.
pub fn with_key_value(key_fragments: NibbleVec, key: K, value: V) -> TrieNode<K, V>... | new | identifier_name |
trie_node.rs | use {TrieNode, KeyValue, NibbleVec, BRANCH_FACTOR};
use keys::*;
macro_rules! no_children {
() => ([
None, None, None, None,
None, None, None, None,
None, None, None, None,
None, None, None, None
])
}
impl<K, V> TrieNode<K, V>
where K: TrieKey
{
/// Create a value-less,... |
/// Compute the number of keys and values in this node's subtrie.
pub fn compute_size(&self) -> usize {
let mut size = if self.key_value.is_some() { 1 } else { 0 };
for child in &self.children {
if let &Some(ref child) = child {
// TODO: could unroll this recursion
... | })
} | random_line_split |
trie_node.rs | use {TrieNode, KeyValue, NibbleVec, BRANCH_FACTOR};
use keys::*;
macro_rules! no_children {
() => ([
None, None, None, None,
None, None, None, None,
None, None, None, None,
None, None, None, None
])
}
impl<K, V> TrieNode<K, V>
where K: TrieKey
{
/// Create a value-less,... |
/// Get a mutable value whilst checking a key match.
pub fn value_checked_mut(&mut self, key: &K) -> Option<&mut V> {
self.key_value.as_mut().map(|kv| {
check_keys(&kv.key, key);
&mut kv.value
})
}
/// Compute the number of keys and values in this node's subtri... | {
self.key_value.as_ref().map(|kv| {
check_keys(&kv.key, key);
&kv.value
})
} | identifier_body |
table.rs | use crate::rmeta::*;
use rustc_index::vec::Idx;
use rustc_serialize::opaque::Encoder;
use rustc_serialize::Encoder as _;
use std::convert::TryInto;
use std::marker::PhantomData;
use std::num::NonZeroUsize;
use tracing::debug;
/// Helper trait, for encoding to, and decoding from, a fixed number of bytes.
/// Used main... |
fn write_to_bytes(self, b: &mut [u8]) {
self.map(|lazy| Lazy::<T>::from_position(lazy.position)).write_to_bytes(b);
let len = self.map_or(0, |lazy| lazy.meta);
let len: u32 = len.try_into().unwrap();
len.write_to_bytes(&mut b[u32::BYTE_LEN..]);
}
}
/// Random-access table (i... | {
Some(Lazy::from_position_and_meta(
<Option<Lazy<T>>>::from_bytes(b)?.position,
u32::from_bytes(&b[u32::BYTE_LEN..]) as usize,
))
} | identifier_body |
table.rs | use crate::rmeta::*;
use rustc_index::vec::Idx;
use rustc_serialize::opaque::Encoder;
use rustc_serialize::Encoder as _;
use std::convert::TryInto;
use std::marker::PhantomData;
use std::num::NonZeroUsize;
use tracing::debug;
/// Helper trait, for encoding to, and decoding from, a fixed number of bytes.
/// Used main... | (b: &[u8]) -> Self {
Some(Lazy::from_position(NonZeroUsize::new(u32::from_bytes(b) as usize)?))
}
fn write_to_bytes(self, b: &mut [u8]) {
let position = self.map_or(0, |lazy| lazy.position.get());
let position: u32 = position.try_into().unwrap();
position.write_to_bytes(b)
... | from_bytes | identifier_name |
table.rs | use crate::rmeta::*;
use rustc_index::vec::Idx;
use rustc_serialize::opaque::Encoder;
use rustc_serialize::Encoder as _;
use std::convert::TryInto;
use std::marker::PhantomData;
use std::num::NonZeroUsize;
use tracing::debug;
/// Helper trait, for encoding to, and decoding from, a fixed number of bytes.
/// Used main... |
Some(value).write_to_bytes_at(&mut self.bytes, i);
}
pub(crate) fn encode(&self, buf: &mut Encoder) -> Lazy<Table<I, T>> {
let pos = buf.position();
buf.emit_raw_bytes(&self.bytes).unwrap();
Lazy::from_position_and_meta(NonZeroUsize::new(pos as usize).unwrap(), self.bytes.len(... | {
self.bytes.resize(needed, 0);
} | conditional_block |
table.rs | use crate::rmeta::*;
use rustc_index::vec::Idx;
use rustc_serialize::opaque::Encoder;
use rustc_serialize::Encoder as _;
use std::convert::TryInto;
use std::marker::PhantomData;
use std::num::NonZeroUsize;
use tracing::debug;
/// Helper trait, for encoding to, and decoding from, a fixed number of bytes.
/// Used main... |
// HACK(eddyb) this shouldn't be needed (see comments on the methods above).
macro_rules! fixed_size_encoding_byte_len_and_defaults {
($byte_len:expr) => {
const BYTE_LEN: usize = $byte_len;
fn maybe_read_from_bytes_at(b: &[u8], i: usize) -> Option<Self> {
const BYTE_LEN: usize = $byte_... | /// at `&mut b[i * Self::BYTE_LEN..]`, using `Self::write_to_bytes`.
fn write_to_bytes_at(self, b: &mut [u8], i: usize);
} | random_line_split |
zhttpto.rs | //
// zhttpto.rs
//
// Starting code for PS1
// Running on Rust 0.9
//
// Note that this code has serious security risks! You should not run it
// on any system with access to sensitive files.
//
// University of Virginia - cs4414 Spring 2014
// Weilin Xu and David Evans
// Version 0.3
#[feature(globs)];
use std::i... | () {
let addr = from_str::<SocketAddr>(format!("{:s}:{:d}", IP, PORT)).unwrap();
let mut acceptor = net::tcp::TcpListener::bind(addr).listen();
println(format!("Listening on [{:s}]...", addr.to_str()));
for stream in acceptor.incoming() {
// Spawn a task to handle the connection
... | main | identifier_name |
zhttpto.rs | //
// zhttpto.rs
//
// Starting code for PS1
// Running on Rust 0.9
//
// Note that this code has serious security risks! You should not run it
// on any system with access to sensitive files.
//
// University of Virginia - cs4414 Spring 2014
// Weilin Xu and David Evans
// Version 0.3
#[feature(globs)];
use std::i... |
else {
println!("Error reading file. Recieved request :\n{:s}", request_str);
let fr = ~"HTTP/1.1 418 I'M A TEAPOT\r\nContent-Type: text/html; charset=UTF-8\r\n\r\nI'm a teapot";
stream.write(fr.as_bytes());
println!("End o... | {
println!("File requested: {:s}", path_str);
let mut file = buffered::BufferedReader::new(File::open(&cwdpath));
let fl_arr: ~[~str] = file.lines().collect();
let mut fr = ~"HTTP/1.1 200 OK\r\nContent-Type: text/html; ... | conditional_block |
zhttpto.rs | //
// zhttpto.rs
//
// Starting code for PS1
// Running on Rust 0.9
//
// Note that this code has serious security risks! You should not run it
// on any system with access to sensitive files.
//
// University of Virginia - cs4414 Spring 2014
// Weilin Xu and David Evans
// Version 0.3
#[feature(globs)];
use std::i... | let mut buf = [0,..500];
stream.read(buf);
let request_str = str::from_utf8(buf);
let split_str: ~[&str] = request_str.split(' ').collect();
let path = os::getcwd();
let mut path_str: ~str;
if split_str[0] == "GET" && split... | {
let addr = from_str::<SocketAddr>(format!("{:s}:{:d}", IP, PORT)).unwrap();
let mut acceptor = net::tcp::TcpListener::bind(addr).listen();
println(format!("Listening on [{:s}] ...", addr.to_str()));
for stream in acceptor.incoming() {
// Spawn a task to handle the connection
... | identifier_body |
zhttpto.rs | //
// zhttpto.rs
//
// Starting code for PS1
// Running on Rust 0.9
//
// Note that this code has serious security risks! You should not run it
// on any system with access to sensitive files.
//
// University of Virginia - cs4414 Spring 2014
// Weilin Xu and David Evans
// Version 0.3
#[feature(globs)];
use std::i... | }
},
None => ()
}
let mut buf = [0,..500];
stream.read(buf);
let request_str = str::from_utf8(buf);
let split_str: ~[&str] = request_str.split(' ').collect();
... | match s.peer_name() {
Some(pn) => {println(format!("Received connection from: [{:s}]", pn.to_str()));},
None => () | random_line_split |
snippet_parser.rs | use std::error::Error;
use structs::*;
use filesystem::read_file_to_json;
use std::fs::read_dir;
use filesystem::read_file_to_string;
use std::fs::DirEntry;
pub fn get_all_snippets() -> Result<Vec<Snippet>, Box<Error>> {
let mut all_snippets = Vec::new();
let snippets_path = "./snippets/";
let snippets_dir... | .map(|x| x.as_str().expect("failed to parse crates").to_string())
.collect(),
tags: info["tags"]
.as_array()
.expect("failed to parse tags")
.into_iter()
.map(|x| x.as_str().expect("failed to parse tags").to_string())
.collect(),
... | {
let uw = snippet_folder;
let folder_relative_path = uw.path().display().to_string();
let folder_name = uw.file_name()
.to_str()
.expect("failed to get snippet folder name")
.to_string();
let info_path = format!("{}/info.json", folder_relative_path);
let content_path = forma... | identifier_body |
snippet_parser.rs | use std::error::Error;
use structs::*;
use filesystem::read_file_to_json;
use std::fs::read_dir;
use filesystem::read_file_to_string;
use std::fs::DirEntry;
pub fn | () -> Result<Vec<Snippet>, Box<Error>> {
let mut all_snippets = Vec::new();
let snippets_path = "./snippets/";
let snippets_dirs = read_dir(snippets_path).unwrap();
for snippet_folder in snippets_dirs {
let uw = snippet_folder?;
if uw.file_type().expect("failed to get folder type").is_di... | get_all_snippets | identifier_name |
snippet_parser.rs | use std::error::Error;
use structs::*;
use filesystem::read_file_to_json;
use std::fs::read_dir;
use filesystem::read_file_to_string;
use std::fs::DirEntry;
pub fn get_all_snippets() -> Result<Vec<Snippet>, Box<Error>> {
let mut all_snippets = Vec::new();
let snippets_path = "./snippets/";
let snippets_dir... | .to_str()
.expect("failed to get snippet folder name")
.to_string();
let info_path = format!("{}/info.json", folder_relative_path);
let content_path = format!("{}/content.md", folder_relative_path);
let info = read_file_to_json(&info_path);
let content = read_file_to_string(&content... | let folder_relative_path = uw.path().display().to_string();
let folder_name = uw.file_name() | random_line_split |
snippet_parser.rs | use std::error::Error;
use structs::*;
use filesystem::read_file_to_json;
use std::fs::read_dir;
use filesystem::read_file_to_string;
use std::fs::DirEntry;
pub fn get_all_snippets() -> Result<Vec<Snippet>, Box<Error>> {
let mut all_snippets = Vec::new();
let snippets_path = "./snippets/";
let snippets_dir... |
}
Ok(all_snippets)
}
fn parse_snippet(snippet_folder: &DirEntry) -> Snippet {
let uw = snippet_folder;
let folder_relative_path = uw.path().display().to_string();
let folder_name = uw.file_name()
.to_str()
.expect("failed to get snippet folder name")
.to_string();
let info... | {
let snippet = parse_snippet(&uw);
all_snippets.push(snippet);
} | conditional_block |
hidden-line.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 ... | ///
/// ```rust
/// mod to_make_deriving_work { // FIXME #4913
///
/// # #[derive(PartialEq)] // invisible
/// # struct Foo; // invisible
///
/// #[derive(PartialEq)] // Bar
/// struct Bar(Foo);
///
/// fn test() {
/// let x = Bar(Foo);
/// assert_eq!(x, x); // check that the derivings worked
/// }
///
/// }
//... | /// The '# ' lines should be removed from the output, but the #[derive] should be
/// retained. | random_line_split |
hidden-line.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 ... | () {}
// @!has hidden_line/fn.foo.html invisible
// @matches - //pre "#\[derive\(PartialEq\)\] // Bar"
| foo | identifier_name |
hidden-line.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 ... |
// @!has hidden_line/fn.foo.html invisible
// @matches - //pre "#\[derive\(PartialEq\)\] // Bar"
| {} | identifier_body |
filehandler.rs | /*
* The module filehandler consists of funtions to write
* a string to a file and to read a file into a string
*/
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::fs;
/*
* Reads a file with name @filename into
* the referenced mutable String @content
*/
pub fn read_f... | (filename:String, content:String) {
let path = Path::new(&filename);
let parent = path.parent().unwrap();
match fs::create_dir_all(parent) {
Ok(m) => m,
Err(e) => panic!(e), // Parent-Folder could not be created
};
let f = File::create(&filename);
let mut file = match f {
Ok(file) => file,
... | write_file | identifier_name |
filehandler.rs | /*
* The module filehandler consists of funtions to write
* a string to a file and to read a file into a string
*/
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::fs;
/*
* Reads a file with name @filename into
* the referenced mutable String @content
*/
pub fn read_f... | {
let path = Path::new(&filename);
let parent = path.parent().unwrap();
match fs::create_dir_all(parent) {
Ok(m) => m,
Err(e) => panic!(e), // Parent-Folder could not be created
};
let f = File::create(&filename);
let mut file = match f {
Ok(file) => file,
Err(m) => panic!("Datei kann nic... | identifier_body | |
filehandler.rs | /*
* The module filehandler consists of funtions to write
* a string to a file and to read a file into a string
*/
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::fs;
/*
* Reads a file with name @filename into
* the referenced mutable String @content
*/
pub fn read_f... | /*
* Writes the String @content into a file
* with the name @filename. It overwrites its
* former content.
*/
pub fn write_file(filename:String, content:String) {
let path = Path::new(&filename);
let parent = path.parent().unwrap();
match fs::create_dir_all(parent) {
Ok(m) => m,
Err(e) => panic!(e), // ... | }
content.push_str(&tmpcontent);
}
| random_line_split |
viewport.rs | use lsp_types::Range;
use serde::{Deserialize, Serialize};
/// Visible lines of editor.
///
/// Inclusive at start, exclusive at end. Both start and end are 0-based.
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Copy, Clone)]
pub struct Viewport {
pub start: u64,
pub end: u64,
}
impl Viewport {
#... |
#[test]
fn test_overlaps() {
use lsp_types::*;
let viewport = Viewport::new(2, 7);
assert_eq!(
viewport.overlaps(Range::new(Position::new(0, 0), Position::new(1, 10))),
false
);
assert_eq!(
viewport.overlaps(Range::new(Position::new(... | {
let viewport = Viewport::new(0, 7);
assert_eq!(viewport.start, 0);
assert_eq!(viewport.end, 7);
} | identifier_body |
viewport.rs | use lsp_types::Range;
use serde::{Deserialize, Serialize};
/// Visible lines of editor.
///
/// Inclusive at start, exclusive at end. Both start and end are 0-based.
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Copy, Clone)]
pub struct Viewport {
pub start: u64,
pub end: u64,
}
impl Viewport {
#... | }
#[test]
fn test_overlaps() {
use lsp_types::*;
let viewport = Viewport::new(2, 7);
assert_eq!(
viewport.overlaps(Range::new(Position::new(0, 0), Position::new(1, 10))),
false
);
assert_eq!(
viewport.overlaps(Range::new(Position:... | assert_eq!(viewport.end, 7); | random_line_split |
viewport.rs | use lsp_types::Range;
use serde::{Deserialize, Serialize};
/// Visible lines of editor.
///
/// Inclusive at start, exclusive at end. Both start and end are 0-based.
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Copy, Clone)]
pub struct Viewport {
pub start: u64,
pub end: u64,
}
impl Viewport {
#... | (start: u64, end: u64) -> Self {
Self { start, end }
}
fn contains(&self, line: u64) -> bool {
line >= self.start && line < self.end
}
pub fn overlaps(&self, range: Range) -> bool {
self.contains(range.start.line) || self.contains(range.end.line)
}
}
#[cfg(test)]
mod test ... | new | identifier_name |
mkart.rs | extern crate jiyunet_core as core;
extern crate jiyunet_dag as dag;
#[macro_use] extern crate clap;
use std::fs;
use std::io::Read;
use core::io::BinaryComponent;
use core::sig::Signed;
use dag::artifact;
use dag::segment;
mod util;
fn | () {
let matches = clap_app!(jiyu_mkart =>
(version: "0.1.0")
(author: "treyzania <treyzania@gmail.com>")
(about: "Packages an file into a signed Jiyunet segment. Note that the segment is not likely to be valid on the blockchain due to noncing, etc.")
(@arg src: +required "Source f... | main | identifier_name |
mkart.rs | extern crate jiyunet_core as core;
extern crate jiyunet_dag as dag;
#[macro_use] extern crate clap;
use std::fs;
use std::io::Read;
use core::io::BinaryComponent;
use core::sig::Signed;
use dag::artifact;
use dag::segment;
mod util;
fn main() | let data = {
let mut f: fs::File = fs::File::open(src).unwrap();
let mut v = Vec::new();
f.read_to_end(&mut v).expect("error reading provided artifact contents");
v
};
let art = artifact::ArtifactData::new(atype, data);
let seg = segment::Segment::new_artifact_seg(art, u... | {
let matches = clap_app!(jiyu_mkart =>
(version: "0.1.0")
(author: "treyzania <treyzania@gmail.com>")
(about: "Packages an file into a signed Jiyunet segment. Note that the segment is not likely to be valid on the blockchain due to noncing, etc.")
(@arg src: +required "Source file... | identifier_body |
mkart.rs | extern crate jiyunet_core as core;
extern crate jiyunet_dag as dag;
#[macro_use] extern crate clap;
use std::fs;
use std::io::Read;
use core::io::BinaryComponent;
use core::sig::Signed;
use dag::artifact;
use dag::segment;
mod util; |
fn main() {
let matches = clap_app!(jiyu_mkart =>
(version: "0.1.0")
(author: "treyzania <treyzania@gmail.com>")
(about: "Packages an file into a signed Jiyunet segment. Note that the segment is not likely to be valid on the blockchain due to noncing, etc.")
(@arg src: +required "... | random_line_split | |
syncer.rs | use postgres;
use serde_json;
use std;
use std::fmt::Debug;
use std::iter::Iterator;
use std::collections::BTreeMap;
use serde::{Serialize,Deserialize};
use errors::*;
pub struct Comm<I: std::iter::Iterator<Item=T>, J: std::iter::Iterator<Item=T>, T: Clone + Eq + Ord> { l: std::iter::Peekable<I>, r: std::iter::Peekabl... | <T>(conn: &postgres::Connection, k: &str, new: Vec<T>, old: &Vec<T>, heed_deletions: bool) -> Result<(Vec<T>, Vec<T>, Vec<T>)> where T: Clone + for<'de> Deserialize<'de> + Serialize + Eq + Ord + Debug {
let (all, additions, deletions) = comm_list(new, old, heed_deletions);
if!(additions.is_empty() && deletions.... | update_list | identifier_name |
syncer.rs | use postgres;
use serde_json;
use std;
use std::fmt::Debug;
use std::iter::Iterator;
use std::collections::BTreeMap;
use serde::{Serialize,Deserialize};
use errors::*;
pub struct Comm<I: std::iter::Iterator<Item=T>, J: std::iter::Iterator<Item=T>, T: Clone + Eq + Ord> { l: std::iter::Peekable<I>, r: std::iter::Peekabl... | // match x.cmp(y) {
// o @ std::cmp::Ordering::Equal => { ret.push((o, l.next().and(r.next()).unwrap().clone())); },
// o @ std::cmp::Ordering::Less => { ret.push((o, l.next() .unwrap().clone())); },
// o @ std::cmp::Ordering::Greater => { ret.push((o, r.next() ... | // let mut ret: Vec<(std::cmp::Ordering, T)> = Vec::with_capacity(left.capacity()+right.capacity());
// let (mut l, mut r) = (left.iter().peekable(), right.iter().peekable());
// while l.peek().is_some() && r.peek().is_some() {
// let x = l.peek().unwrap().clone();
// let y = r.peek().unwrap().cl... | random_line_split |
syncer.rs | use postgres;
use serde_json;
use std;
use std::fmt::Debug;
use std::iter::Iterator;
use std::collections::BTreeMap;
use serde::{Serialize,Deserialize};
use errors::*;
pub struct Comm<I: std::iter::Iterator<Item=T>, J: std::iter::Iterator<Item=T>, T: Clone + Eq + Ord> { l: std::iter::Peekable<I>, r: std::iter::Peekabl... |
fn comm_map<'a, K, T>(mut new: BTreeMap<K, Vec<T>>, old: &'a mut BTreeMap<K, Vec<T>>, heed_deletions: bool) -> (BTreeMap<K, Vec<T>>, BTreeMap<K, Vec<T>>, BTreeMap<K, Vec<T>>) where T: Debug + Clone + for<'de> Deserialize<'de> + Serialize + Eq + Ord, K: Debug + Ord + Clone + for<'de> Deserialize<'de> + Serialize {
... | {
let (mut all, mut additions, mut deletions) : (Vec<T>, Vec<T>, Vec<T>) = (Vec::with_capacity(new.len()), vec![], vec![]);
for (o, x) in Comm::new(new.into_iter(), old.iter().cloned()) {
match o {
std::cmp::Ordering::Equal => all.push(x),
std::cmp::Ordering::Less => { additions.... | identifier_body |
main.rs | use std::io;
use std::io::Read;
use std::collections::HashMap;
use std::str::FromStr;
type DynamicInfo<'a> = HashMap<&'a str, u8>;
#[derive(Debug)]
struct Aunt<'a> {
number: u16,
info: DynamicInfo<'a>
}
fn parse_aunt(line: &str) -> Aunt {
let tokens: Vec<_> = line
.split(|c: char|!c.is_alphanumeri... | .into_iter()
.all(|(attribute, value)| {
match specification.get(attribute) {
Some(x) if x == value => true,
_ => false
}
})
}
fn matches_adjusted(aunt: &Aunt, specification: &DynamicInfo) -> bool {
let ref info = aunt.info;
info
... | }
fn matches(aunt: &Aunt, specification: &DynamicInfo) -> bool {
let ref info = aunt.info;
info | random_line_split |
main.rs | use std::io;
use std::io::Read;
use std::collections::HashMap;
use std::str::FromStr;
type DynamicInfo<'a> = HashMap<&'a str, u8>;
#[derive(Debug)]
struct Aunt<'a> {
number: u16,
info: DynamicInfo<'a>
}
fn parse_aunt(line: &str) -> Aunt {
let tokens: Vec<_> = line
.split(|c: char|!c.is_alphanumeri... | (aunt: &Aunt, specification: &DynamicInfo) -> bool {
let ref info = aunt.info;
info
.into_iter()
.all(|(attribute, value)| {
match (*attribute, specification.get(attribute)) {
("cats", Some(x)) | ("trees", Some(x)) => x < value,
("pomeranians", Some(x)) ... | matches_adjusted | identifier_name |
main.rs | #[macro_use]
extern crate error_chain;
extern crate calamine;
mod errors;
use std::path::{PathBuf, Path};
use std::fs;
use std::io::{BufWriter, Write};
use errors::Result;
use calamine::{Sheets, Range, CellType};
fn main() {
let mut args = ::std::env::args();
let file = args.by_ref()
.skip(1)
.... | <P, T>(path: P, range: Range<T>) -> Result<()>
where P: AsRef<Path>,
T: CellType + ::std::fmt::Display
{
if range.is_empty() {
return Ok(());
}
let mut f = BufWriter::new(fs::File::create(path.as_ref())?);
let ((srow, scol), (_, ecol)) = (range.start(), range.end());
write!(f... | write_range | identifier_name |
main.rs | #[macro_use]
extern crate error_chain;
extern crate calamine;
mod errors;
use std::path::{PathBuf, Path};
use std::fs;
use std::io::{BufWriter, Write};
use errors::Result;
use calamine::{Sheets, Range, CellType};
fn main() {
let mut args = ::std::env::args();
let file = args.by_ref()
.skip(1)
.... |
let vba = root.join("vba");
if!vba.exists() {
fs::create_dir(&vba)?;
}
let formula = root.join("formula");
if!formula.exists() {
fs::create_dir(&formula)?;
}
Ok(XlPaths {
orig: orig,
data: data,
... | {
fs::create_dir(&data)?;
} | conditional_block |
main.rs | #[macro_use]
extern crate error_chain;
extern crate calamine;
mod errors;
use std::path::{PathBuf, Path};
use std::fs;
use std::io::{BufWriter, Write};
use errors::Result;
use calamine::{Sheets, Range, CellType};
fn main() {
let mut args = ::std::env::args();
let file = args.by_ref()
.skip(1)
.... | buf.extend(rev.chars().rev());
}
buf
} | let c = col % 26;
rev.push((b'A' + c as u8) as char);
col -= c;
col /= 26;
} | random_line_split |
lib.rs | The interrupt controller is initialized with the provided mapping.
pub fn new(intc_config: &IntcConfig) -> Result<Pruss<'a>> {
// Enforce singleton instantiation.
if PRUSS_IS_INSTANTIATED.swap(true, Ordering::Acquire) {
return Err(Error::AlreadyInstantiated);
}
// Handy... |
}
unsafe impl<'a> Send for MemSegment<'a> {}
unsafe impl<'a> Sync for MemSegment<'a> {}
/// PRU interrupt controller configuration.
///
/// A call to the `new_populated` method automatically initializes the data with the same defaults
/// as the PRUSS_INTC_INITDATA macro of the C prussdrv library. Alternatively, ... | {
assert!(position >= self.from && position <= self.to);
(MemSegment {
base: self.base,
from: self.from,
to: position,
_memory_marker: PhantomData,
},
MemSegment {
base: self.base,
from: position,
to: se... | identifier_body |
lib.rs | /// The interrupt controller is initialized with the provided mapping.
pub fn new(intc_config: &IntcConfig) -> Result<Pruss<'a>> {
// Enforce singleton instantiation.
if PRUSS_IS_INSTANTIATED.swap(true, Ordering::Acquire) {
return Err(Error::AlreadyInstantiated);
}
// H... |
/// Clears a system event.
pub fn clear_sysevt(&self, sysevt: Sysevt) {
unsafe {
ptr::write_volatile(self.intc_reg.offset(SICR_REG), sysevt as u32);
}
}
/// Enables a system event.
pub fn enable_sysevt(&self, sysevt: Sysevt) {
unsafe {
ptr::write_vol... | } | random_line_split |
lib.rs | 1_SIZE);
// Create memory views.
let dram0 = MemSegment::new(prumap.base, DRAM0_OFFSET, DRAM0_OFFSET + DRAM0_SIZE);
let dram1 = MemSegment::new(prumap.base, DRAM1_OFFSET, DRAM1_OFFSET + DRAM1_SIZE);
let dram2 = MemSegment::new(prumap.base, DRAM2_OFFSET, DRAM2_OFFSET + DRAM2_SIZE);
... | EvtoutIrq | identifier_name | |
nf.rs | use e2d2::headers::*;
use e2d2::operators::*;
#[inline]
fn lat() {
unsafe {
asm!("nop"
:
:
:
: "volatile");
}
}
#[inline]
fn delay_loop(delay: u64) {
let mut d = 0;
while d < delay {
lat();
d += 1;
} | pub fn delay<T:'static + Batch<Header = NullHeader>>(
parent: T,
delay: u64,
) -> MapBatch<NullHeader, ResetParsingBatch<TransformBatch<MacHeader, ParsedBatch<MacHeader, T>>>> {
parent
.parse::<MacHeader>()
.transform(box move |pkt| {
assert!(pkt.refcnt() == 1);
let hdr... | }
| random_line_split |
nf.rs | use e2d2::headers::*;
use e2d2::operators::*;
#[inline]
fn | () {
unsafe {
asm!("nop"
:
:
:
: "volatile");
}
}
#[inline]
fn delay_loop(delay: u64) {
let mut d = 0;
while d < delay {
lat();
d += 1;
}
}
pub fn delay<T:'static + Batch<Header = NullHeader>>(
parent: T,
delay: u6... | lat | identifier_name |
nf.rs | use e2d2::headers::*;
use e2d2::operators::*;
#[inline]
fn lat() |
#[inline]
fn delay_loop(delay: u64) {
let mut d = 0;
while d < delay {
lat();
d += 1;
}
}
pub fn delay<T:'static + Batch<Header = NullHeader>>(
parent: T,
delay: u64,
) -> MapBatch<NullHeader, ResetParsingBatch<TransformBatch<MacHeader, ParsedBatch<MacHeader, T>>>> {
parent
... | {
unsafe {
asm!("nop"
:
:
:
: "volatile");
}
} | identifier_body |
delete.rs | use nom::character::complete::multispace1;
use std::{fmt, str};
use common::{statement_terminator, schema_table_reference};
use condition::ConditionExpression;
use keywords::escape_if_keyword;
use nom::bytes::complete::tag_no_case;
use nom::combinator::opt;
use nom::sequence::{delimited, tuple};
use nom::IResult;
use ... | (i: &[u8]) -> IResult<&[u8], DeleteStatement> {
let (remaining_input, (_, _, table, where_clause, _)) = tuple((
tag_no_case("delete"),
delimited(multispace1, tag_no_case("from"), multispace1),
schema_table_reference,
opt(where_clause),
statement_terminator,
))(i)?;
O... | deletion | identifier_name |
delete.rs | use nom::character::complete::multispace1;
use std::{fmt, str};
use common::{statement_terminator, schema_table_reference};
use condition::ConditionExpression;
use keywords::escape_if_keyword;
use nom::bytes::complete::tag_no_case;
use nom::combinator::opt;
use nom::sequence::{delimited, tuple};
use nom::IResult;
use ... |
Ok(())
}
}
pub fn deletion(i: &[u8]) -> IResult<&[u8], DeleteStatement> {
let (remaining_input, (_, _, table, where_clause, _)) = tuple((
tag_no_case("delete"),
delimited(multispace1, tag_no_case("from"), multispace1),
schema_table_reference,
opt(where_clause),
... | {
write!(f, " WHERE ")?;
write!(f, "{}", where_clause)?;
} | conditional_block |
delete.rs | use nom::character::complete::multispace1;
use std::{fmt, str};
use common::{statement_terminator, schema_table_reference};
use condition::ConditionExpression;
use keywords::escape_if_keyword;
use nom::bytes::complete::tag_no_case;
use nom::combinator::opt;
use nom::sequence::{delimited, tuple};
use nom::IResult;
use ... | operator: Operator::Equal,
}));
assert_eq!(
res.unwrap().1,
DeleteStatement {
table: Table::from("users"),
where_clause: expected_where_cond,
..Default::default()
}
);
}
#[test]
fn format_... | let expected_left = Base(Field(Column::from("id")));
let expected_where_cond = Some(ComparisonOp(ConditionTree {
left: Box::new(expected_left),
right: Box::new(Base(Literal(Literal::Integer(1)))), | random_line_split |
delete.rs | use nom::character::complete::multispace1;
use std::{fmt, str};
use common::{statement_terminator, schema_table_reference};
use condition::ConditionExpression;
use keywords::escape_if_keyword;
use nom::bytes::complete::tag_no_case;
use nom::combinator::opt;
use nom::sequence::{delimited, tuple};
use nom::IResult;
use ... |
}
pub fn deletion(i: &[u8]) -> IResult<&[u8], DeleteStatement> {
let (remaining_input, (_, _, table, where_clause, _)) = tuple((
tag_no_case("delete"),
delimited(multispace1, tag_no_case("from"), multispace1),
schema_table_reference,
opt(where_clause),
statement_terminator,... | {
write!(f, "DELETE FROM ")?;
write!(f, "{}", escape_if_keyword(&self.table.name))?;
if let Some(ref where_clause) = self.where_clause {
write!(f, " WHERE ")?;
write!(f, "{}", where_clause)?;
}
Ok(())
} | identifier_body |
job.rs | use std::collections::HashSet;
use std::net::SocketAddr;
use std::time;
use crate::control::cio;
use crate::torrent::Torrent;
use crate::util::UHashMap;
pub trait Job<T: cio::CIO> {
fn update(&mut self, torrents: &mut UHashMap<Torrent<T>>);
}
pub struct TrackerUpdate;
impl<T: cio::CIO> Job<T> for TrackerUpdate ... |
}
if!torrent.complete() {
torrent.rank_peers();
}
if!self.active.contains_key(id) {
self.active.insert(*id, active);
}
let prev = self.active.get_mut(id).unwrap();
if *prev!= active {
*p... | {
torrent.rpc_update_pieces();
self.piece_update = time::Instant::now();
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.