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 |
|---|---|---|---|---|
utf8_chars.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!((!str::is_utf8([0xe0_u8])));
assert!((!str::is_utf8([0xe0_u8, 0x10_u8])));
assert!((!str::is_utf8([0xe0_u8, 0xff_u8, 0x10_u8])));
// invalid 4 byte prefix
assert!((!str::is_utf8([0xf0_u8])));
assert!((!str::is_utf8([0xf0_u8, 0x10_u8])));
assert!((!str::is_utf8([0xf0_u8, 0xff_u8, 0x10... | {
// Chars of 1, 2, 3, and 4 bytes
let chs: ~[char] = ~['e', 'é', '€', '\U00010000'];
let s: ~str = str::from_chars(chs);
let schs: ~[char] = s.chars().collect();
assert!(s.len() == 10u);
assert!(s.char_len() == 4u);
assert!(schs.len() == 4u);
assert!(str::from_chars(schs) == s);
as... | identifier_body |
utf8_chars.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!((str::is_utf8(s.as_bytes())));
// invalid prefix
assert!((!str::is_utf8([0x80_u8])));
// invalid 2 byte prefix
assert!((!str::is_utf8([0xc0_u8])));
assert!((!str::is_utf8([0xc0_u8, 0x10_u8])));
// invalid 3 byte prefix
assert!((!str::is_utf8([0xe0_u8])));
assert!((!str::is_u... | assert!(schs.len() == 4u);
assert!(str::from_chars(schs) == s);
assert!(s.char_at(0u) == 'e');
assert!(s.char_at(1u) == 'é'); | random_line_split |
utf8_chars.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 ... | () {
// Chars of 1, 2, 3, and 4 bytes
let chs: ~[char] = ~['e', 'é', '€', '\U00010000'];
let s: ~str = str::from_chars(chs);
let schs: ~[char] = s.chars().collect();
assert!(s.len() == 10u);
assert!(s.char_len() == 4u);
assert!(schs.len() == 4u);
assert!(str::from_chars(schs) == s);
... | main | identifier_name |
mod.rs | `send*`
//! methods of [`LocalEndpoint`] and [`RemoteEndpoint`]. They define almost every aspect of how
//! a message transaction is handled.
//!
//! Typical usage of this crate does not require writing implementing [`SendDesc`] by hand,
//! although you could certainly do so if needed.
//! Instead, `SyncDesc` instanc... |
let ret = (TP::COAP_ACK_TIMEOUT.as_millis() as u64) << retransmits_sent as u64;
const JDIV: u64 = 512u64;
let rmod: u64 = (JDIV as f32 * (TP::COAP_ACK_RANDOM_FACTOR - 1.0)) as u64;
let jmul = JDIV + rand::random::<u64>() % rmod;
Some(Duration::from_millis(ret * jmul / JDIV))
... | {
return None;
} | conditional_block |
mod.rs | to the `send*`
//! methods of [`LocalEndpoint`] and [`RemoteEndpoint`]. They define almost every aspect of how
//! a message transaction is handled.
//!
//! Typical usage of this crate does not require writing implementing [`SendDesc`] by hand,
//! although you could certainly do so if needed.
//! Instead, `SyncDesc` ... | /// Adds one instance of the option `key` with a value of `value`.
fn add_option<K>(self, key: OptionKey<K>, value: K) -> AddOption<Self, K, Once<K>, IC>
where
K: Send + Clone,
{
self.add_option_iter(key, once(value))
}
/// Adds an Accept option with the given `ContentFormat`.
... | viter,
phantom: PhantomData,
}
}
| random_line_split |
mod.rs | `send*`
//! methods of [`LocalEndpoint`] and [`RemoteEndpoint`]. They define almost every aspect of how
//! a message transaction is handled.
//!
//! Typical usage of this crate does not require writing implementing [`SendDesc`] by hand,
//! although you could certainly do so if needed.
//! Instead, `SyncDesc` instanc... |
/// Adds a handler function to be called when a response message has been received (or when
/// an error has occurred).
fn use_handler<F, FR>(self, handler: F) -> Handler<Self, F>
where
F: FnMut(
Result<&dyn InboundContext<SocketAddr = IC::SocketAddr>, Error>,
) -> ... | {
self.add_option(option::CONTENT_FORMAT, content_format)
} | identifier_body |
mod.rs | `send*`
//! methods of [`LocalEndpoint`] and [`RemoteEndpoint`]. They define almost every aspect of how
//! a message transaction is handled.
//!
//! Typical usage of this crate does not require writing implementing [`SendDesc`] by hand,
//! although you could certainly do so if needed.
//! Instead, `SyncDesc` instanc... | (self) -> IncludeSocketAddr<Self> {
IncludeSocketAddr::new(self)
}
/// Adds an inspection closure that will be called for each received response message.
///
/// The inspector closure will not be called if no responses are received, and it cannot
/// change the behavior of the send descript... | include_socket_addr | identifier_name |
diff.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! A simple binary that computes the diff between two files.
use std::fs;
#[cfg(target_family = "unix")]
use std::os::unix::fs::Permissio... | #[structopt(short, long)]
copy: bool,
/// Treat the <file-b> as a move of the <file-a>
#[structopt(short, long)]
move_: bool,
/// Do not follow symlinks - compare them instead (POSIX-only)
#[structopt(short, long)]
symlink: bool,
/// Number of lines of unified context (default: 3)... | random_line_split | |
diff.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! A simple binary that computes the diff between two files.
use std::fs;
#[cfg(target_family = "unix")]
use std::os::unix::fs::Permissio... |
let copy_info = match (opt.copy, opt.move_) {
(true, false) => CopyInfo::Copy,
(false, true) => CopyInfo::Move,
(false, false) => CopyInfo::None,
(true, true) => panic!("file can't be marked as both copy and move"),
};
let a_path_str = opt.file_a.to_string_lossy();
let... | {
Ok((FileType::Regular, fs::read(path)?))
} | identifier_body |
diff.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! A simple binary that computes the diff between two files.
use std::fs;
#[cfg(target_family = "unix")]
use std::os::unix::fs::Permissio... | {
/// Input file
#[structopt(parse(from_os_str))]
file_a: PathBuf,
/// Output file, stdout if not present
#[structopt(parse(from_os_str))]
file_b: PathBuf,
/// Treat the <file-b> as a copy of the <file-a>
#[structopt(short, long)]
copy: bool,
/// Treat the <file-b> as a move ... | Opt | identifier_name |
unused-attr.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 ... |
#[foo] //~ ERROR unused attribute
struct Foo {
#[foo] //~ ERROR unused attribute
a: isize
}
#[foo] //~ ERROR unused attribute
trait Baz {
#[foo] //~ ERROR unused attribute
fn blah();
#[foo] //~ ERROR unused attribute
fn blah2() {}
}
fn main() {}
| {
match f {
#[foo] //~ ERROR unused attribute
foo::Foo::Bar => {}
}
} | identifier_body |
unused-attr.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 ... | #[foo] //~ ERROR unused attribute
pub enum Foo {
#[foo] //~ ERROR unused attribute
Bar,
}
}
#[foo] //~ ERROR unused attribute
fn bar(f: foo::Foo) {
match f {
#[foo] //~ ERROR unused attribute
foo::Foo::Bar => {}
}
}
#[foo] //~ ERROR unused attribute
struct Foo {
... | random_line_split | |
unused-attr.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 ... | () {}
}
fn main() {}
| blah2 | identifier_name |
move-3-unique.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let x = ~Triple{x: 1, y: 2, z: 3};
for _ in range(0u, 10000u) {
assert_eq!(test(true, x.clone()), 2);
}
assert_eq!(test(false, x), 5);
} | identifier_body | |
move-3-unique.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 ... | (x: bool, foo: ~Triple) -> int {
let bar = foo;
let mut y: ~Triple;
if x { y = bar; } else { y = ~Triple {x: 4, y: 5, z: 6}; }
return y.y;
}
pub fn main() {
let x = ~Triple{x: 1, y: 2, z: 3};
for _ in range(0u, 10000u) {
assert_eq!(test(true, x.clone()), 2);
}
assert_eq!(test(fa... | test | identifier_name |
move-3-unique.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!(test(false, x), 5);
} | random_line_split | |
move-3-unique.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 ... |
return y.y;
}
pub fn main() {
let x = ~Triple{x: 1, y: 2, z: 3};
for _ in range(0u, 10000u) {
assert_eq!(test(true, x.clone()), 2);
}
assert_eq!(test(false, x), 5);
}
| { y = ~Triple {x: 4, y: 5, z: 6}; } | conditional_block |
live.rs | /// Disk scheme replacement when making live disk
use alloc::sync::Arc;
use alloc::collections::BTreeMap;
use core::{slice, str};
use core::sync::atomic::{AtomicUsize, Ordering};
use spin::RwLock;
use syscall::data::Stat;
use syscall::error::*;
use syscall::flag::{MODE_DIR, MODE_FILE};
use syscall::scheme::{calc_seek... | }
impl DiskScheme {
pub fn new() -> Option<DiskScheme> {
let mut phys = 0;
let mut size = 0;
for line in str::from_utf8(unsafe { crate::INIT_ENV }).unwrap_or("").lines() {
let mut parts = line.splitn(2, '=');
let name = parts.next().unwrap_or("");
let va... | pub struct DiskScheme {
next_id: AtomicUsize,
list: Arc<RwLock<&'static mut [u8]>>,
data: Arc<RwLock<&'static mut [u8]>>,
handles: RwLock<BTreeMap<usize, Handle>> | random_line_split |
live.rs | /// Disk scheme replacement when making live disk
use alloc::sync::Arc;
use alloc::collections::BTreeMap;
use core::{slice, str};
use core::sync::atomic::{AtomicUsize, Ordering};
use spin::RwLock;
use syscall::data::Stat;
use syscall::error::*;
use syscall::flag::{MODE_DIR, MODE_FILE};
use syscall::scheme::{calc_seek... | {
path: &'static [u8],
data: Arc<RwLock<&'static mut [u8]>>,
mode: u16,
seek: usize
}
pub struct DiskScheme {
next_id: AtomicUsize,
list: Arc<RwLock<&'static mut [u8]>>,
data: Arc<RwLock<&'static mut [u8]>>,
handles: RwLock<BTreeMap<usize, Handle>>
}
impl DiskScheme {
pub fn new()... | Handle | identifier_name |
live.rs | /// Disk scheme replacement when making live disk
use alloc::sync::Arc;
use alloc::collections::BTreeMap;
use core::{slice, str};
use core::sync::atomic::{AtomicUsize, Ordering};
use spin::RwLock;
use syscall::data::Stat;
use syscall::error::*;
use syscall::flag::{MODE_DIR, MODE_FILE};
use syscall::scheme::{calc_seek... |
}
}
impl Scheme for DiskScheme {
fn open(&self, path: &str, _flags: usize, _uid: u32, _gid: u32) -> Result<usize> {
let path_trimmed = path.trim_matches('/');
match path_trimmed {
"" => {
let id = self.next_id.fetch_add(1, Ordering::SeqCst);
self.han... | {
None
} | conditional_block |
live.rs | /// Disk scheme replacement when making live disk
use alloc::sync::Arc;
use alloc::collections::BTreeMap;
use core::{slice, str};
use core::sync::atomic::{AtomicUsize, Ordering};
use spin::RwLock;
use syscall::data::Stat;
use syscall::error::*;
use syscall::flag::{MODE_DIR, MODE_FILE};
use syscall::scheme::{calc_seek... |
fn fcntl(&self, id: usize, _cmd: usize, _arg: usize) -> Result<usize> {
let handles = self.handles.read();
let _handle = handles.get(&id).ok_or(Error::new(EBADF))?;
Ok(0)
}
fn fpath(&self, id: usize, buf: &mut [u8]) -> Result<usize> {
let handles = self.handles.read();
... | {
let mut handles = self.handles.write();
let handle = handles.get_mut(&id).ok_or(Error::new(EBADF))?;
let data = handle.data.read();
let new_offset = calc_seek_offset_usize(handle.seek, pos, whence, data.len())?;
handle.seek = new_offset as usize;
Ok(new_offset)
} | identifier_body |
windowproxy.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::utils::{CacheableWrapper, WrapperCache, BindingObject};
use script_task::page_from_context;
us... | (@mut self, _cx: *JSContext, _scope: *JSObject) -> *JSObject {
fail!("not yet implemented")
}
}
| wrap_object_shared | identifier_name |
windowproxy.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::utils::{CacheableWrapper, WrapperCache, BindingObject};
use script_task::page_from_context;
us... | } | }
fn wrap_object_shared(@mut self, _cx: *JSContext, _scope: *JSObject) -> *JSObject {
fail!("not yet implemented")
} | random_line_split |
solver014.rs | // COPYRIGHT (C) 2017 barreiro. All Rights Reserved.
// Rust solvers for Project Euler problems
use euler::algorithm::long::is_even;
use euler::Solver;
// The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd)
//
// Using the rule above and starting wit... | }
collatz
}
} | let collatz = if is_even(value) { 1 + self.length(value >> 1) } else { 2 + self.length((value * 3 + 1) >> 1) };
if v < size {
self.cache[v] = collatz; | random_line_split |
solver014.rs | // COPYRIGHT (C) 2017 barreiro. All Rights Reserved.
// Rust solvers for Project Euler problems
use euler::algorithm::long::is_even;
use euler::Solver;
// The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd)
//
// Using the rule above and starting wit... | e>
}
fn collatz_memoize(size: isize) -> CollatzMemoize {
let mut cache = vec![0; size as _];
cache[1] = 1;
CollatzMemoize { cache }
}
impl CollatzMemoize {
fn length(&mut self, value: isize) -> isize {
let (v, size) = (value as usize, self.cache.len());
if v < size && self.cache[v]!= 0... | ache: Vec<isiz | identifier_name |
solver014.rs | // COPYRIGHT (C) 2017 barreiro. All Rights Reserved.
// Rust solvers for Project Euler problems
use euler::algorithm::long::is_even;
use euler::Solver;
// The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd)
//
// Using the rule above and starting wit... |
}
| he[v] = collatz;
}
collatz
} | conditional_block |
lib.rs | use cookie::Cookie as Cookie_M;
use sapper::header::{Cookie, SetCookie};
use sapper::{Key, Request, Response, Result};
pub struct SessionVal;
impl Key for SessionVal {
type Value = String;
}
pub fn session_val(req: &mut Request, ckey: Option<&'static str>) -> Result<()> | }
}
}
}
}
None => {
println!("no cookie in headers");
}
}
session_value.and_then(|val| {
req.ext_mut().insert::<SessionVal>(val);
Some(())
});
Ok(())
}
// library function
pub ... | {
if ckey.is_none() {
return Ok(());
}
let mut session_value: Option<String> = None;
match req.headers().get::<Cookie>() {
Some(cookie_headers) => {
//let mut cookie_jar = CookieJar::new();
for header in cookie_headers.iter() {
let raw_str = match... | identifier_body |
lib.rs | use cookie::Cookie as Cookie_M;
use sapper::header::{Cookie, SetCookie};
use sapper::{Key, Request, Response, Result};
pub struct SessionVal;
impl Key for SessionVal {
type Value = String;
}
pub fn session_val(req: &mut Request, ckey: Option<&'static str>) -> Result<()> {
if ckey.is_none() {
return Ok... |
}
}
}
}
None => {
println!("no cookie in headers");
}
}
session_value.and_then(|val| {
req.ext_mut().insert::<SessionVal>(val);
Some(())
});
Ok(())
}
// library function
pub fn set_cookie(
res: &m... | {
session_value = Some(cookie.value().to_owned());
break;
} | conditional_block |
lib.rs | use cookie::Cookie as Cookie_M;
use sapper::header::{Cookie, SetCookie};
use sapper::{Key, Request, Response, Result};
pub struct SessionVal;
impl Key for SessionVal {
type Value = String;
}
pub fn session_val(req: &mut Request, ckey: Option<&'static str>) -> Result<()> {
if ckey.is_none() {
return Ok... | (
res: &mut Response,
ckey: String,
val: String,
domain: Option<String>,
path: Option<String>,
secure: Option<bool>,
max_age: Option<i64>,
) -> Result<()> {
let mut cookie = Cookie_M::new(ckey, val);
if domain.is_some() {
cookie.set_domain(domain.unwrap());
}
if path.... | set_cookie | identifier_name |
lib.rs | use cookie::Cookie as Cookie_M;
use sapper::header::{Cookie, SetCookie};
use sapper::{Key, Request, Response, Result};
pub struct SessionVal;
impl Key for SessionVal {
type Value = String;
}
pub fn session_val(req: &mut Request, ckey: Option<&'static str>) -> Result<()> {
if ckey.is_none() {
return Ok... | Ok(())
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {}
} | random_line_split | |
mode.rs | // When starting program, start at state "Init"
// Always allow commands "debug" and "isready"
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
pub enum | {
// * `uci`
// send all "id" and "option" messages
// send one "uciok" message
// go to mode "Wait"
Init,
// * `setoption`
// maybe initialize stuff
// set the option
// stay in mode Wait
// * `ucinewgame`
// reset status
// take note that GUI supports the ucinewgame c... | Mode | identifier_name |
mode.rs | // When starting program, start at state "Init"
// Always allow commands "debug" and "isready"
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
pub enum Mode {
// * `uci`
// send all "id" and "option" messages
// send one "uciok" message
// go to mode "Wait"
Init,
// * `setoption`
// maybe init... | NewGame,
// * `go`
// process the arguments
// start searching
// go to mode Search
Ready,
// * `ponderhit`
// Execute the ponder move
// stay in mode Search
// * `stop`
// * OR
// * engine decides on best move
// stop searching
// send all "info" data/messages
... | // go to Ready mode | random_line_split |
mode.rs | // When starting program, start at state "Init"
// Always allow commands "debug" and "isready"
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
pub enum Mode {
// * `uci`
// send all "id" and "option" messages
// send one "uciok" message
// go to mode "Wait"
Init,
// * `setoption`
// maybe init... |
}
| {
Mode::Init
} | identifier_body |
rlperrors.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self, f)
}
}
impl From<FromBytesError> for DecoderError {
fn from(err: FromBytesError) -> DecoderError {
DecoderError::FromBytesError(err)
}
}
| fmt | identifier_name |
rlperrors.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | RlpExpectedToBeList,
/// Expect encoded data, RLP was something else.
RlpExpectedToBeData,
/// Expected a different size list.
RlpIncorrectListLen,
/// Data length number has a prefixed zero byte, invalid for numbers.
RlpDataLenWithZeroPrefix,
/// List length number has a prefixed zero byte, invalid for numbers... | /// Data has too few bytes for valid RLP.
RlpIsTooShort,
/// Expect an encoded list, RLP was something else. | random_line_split |
gaussian.rs | extern crate rand;
use crate::distribs::distribution::*;
use crate::util::math::*;
use std::f64::consts;
#[allow(dead_code)]
pub struct Gaussian {
mu: f64,
sigma: f64,
}
impl Gaussian {
pub fn new(avg: f64, variance: f64) -> Gaussian {
Gaussian {
mu: avg,
sigma: variance.s... | self, x: f64) -> f64 {
phi((x - self.mu) / self.sigma)
}
}
| f(& | identifier_name |
gaussian.rs | extern crate rand;
use crate::distribs::distribution::*;
use crate::util::math::*;
use std::f64::consts;
#[allow(dead_code)]
pub struct Gaussian {
mu: f64,
sigma: f64,
}
impl Gaussian {
pub fn new(avg: f64, variance: f64) -> Gaussian {
Gaussian {
mu: avg,
sigma: variance.s... | fn pdf(&self, x: f64) -> f64 {
let factor = (2.0f64 * self.sigma * self.sigma * consts::PI)
.sqrt()
.recip();
let exp_num = -((x - self.mu).powi(2));
let exp_denom = 2.0f64 * self.sigma * self.sigma;
factor * (exp_num / exp_denom).exp()
}
fn cdf(&self,... | self.sigma
}
| identifier_body |
gaussian.rs | extern crate rand;
use crate::distribs::distribution::*;
use crate::util::math::*;
use std::f64::consts;
#[allow(dead_code)]
pub struct Gaussian {
mu: f64, | pub fn new(avg: f64, variance: f64) -> Gaussian {
Gaussian {
mu: avg,
sigma: variance.sqrt(),
}
}
}
impl Distribution<f64> for Gaussian {
//Using the Box–Muller transform (https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform)
fn sample(&self) -> RandomVaria... | sigma: f64,
}
impl Gaussian { | random_line_split |
select.rs | // Copyright 2015 Colin Sherratt
//
// 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 o... |
}
impl Signals for Select {
fn signal(&self) -> Signal {
let (pulse, t) = Signal::new();
let mut guard = self.inner.lock().unwrap();
if guard.ready.len() == 0 {
guard.trigger = Some(t);
} else {
t.pulse();
}
pulse
}
}
/// `SelectMap` is ... | {
loop {
if self.signals.len() == 0 {
return None;
}
let pulse = {
let mut guard = self.inner.lock().unwrap();
while let Some(x) = guard.ready.pop() {
if let Some(x) = self.signals.remove(&x) {
... | identifier_body |
select.rs | // Copyright 2015 Colin Sherratt
//
// 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 o... | <T> {
select: Select,
items: HashMap<usize, T>,
}
impl<T> SelectMap<T> {
/// Create a new empty `SelectMap`
pub fn new() -> SelectMap<T> {
SelectMap {
select: Select::new(),
items: HashMap::new(),
}
}
/// Add a `Signal` and an associated value into the `... | SelectMap | identifier_name |
select.rs | // Copyright 2015 Colin Sherratt
//
// 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 o... |
}
let (pulse, t) = Signal::new();
guard.trigger = Some(t);
pulse
};
pulse.wait().unwrap();
}
}
}
impl Signals for Select {
fn signal(&self) -> Signal {
let (pulse, t) = Signal::new();
let mut guard ... | {
return Some(x.disarm());
} | conditional_block |
select.rs | // Copyright 2015 Colin Sherratt
//
// 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 o... | use std::collections::HashMap;
use {Signal, ArmedSignal, Pulse, Waiting, Barrier, Signals};
pub struct Inner {
pub ready: Vec<usize>,
pub trigger: Option<Pulse>,
}
pub struct Handle(pub Arc<Mutex<Inner>>);
/// A `Select` listens to 1 or more signals. It will wait until
/// any signal becomes available before... | use std::sync::{Arc, Mutex}; | random_line_split |
slot.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/. */
//! An in-place, dynamically borrowable slot. Useful for "mutable fields". Assuming this works out
//! well, this ... |
let immutable_borrow_count = cast::transmute_mut(&self.immutable_borrow_count);
*immutable_borrow_count += 1;
SlotRef {
ptr: &self.value,
immutable_borrow_count: immutable_borrow_count,
}
}
}
#[inline]
pub fn mutate<'a... | {
self.fail()
} | conditional_block |
slot.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/. */
//! An in-place, dynamically borrowable slot. Useful for "mutable fields". Assuming this works out
//! well, this ... | /// Replaces the slot's value with the given value and returns the old value.
#[inline]
pub fn replace(&self, value: T) -> T {
util::replace(self.mutate().ptr, value)
}
#[inline(never)]
pub fn fail(&self) ->! {
fail!("slot is borrowed")
}
}
impl<T:Clone> Slot<T> {
#[inl... | *self.mutate().ptr = value
}
| random_line_split |
slot.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/. */
//! An in-place, dynamically borrowable slot. Useful for "mutable fields". Assuming this works out
//! well, this ... |
#[inline]
pub fn borrow<'a>(&'a self) -> SlotRef<'a,T> {
unsafe {
if self.immutable_borrow_count == 255 || self.mutably_borrowed {
self.fail()
}
let immutable_borrow_count = cast::transmute_mut(&self.immutable_borrow_count);
*immutable_bo... | {
&self.value
} | identifier_body |
slot.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/. */
//! An in-place, dynamically borrowable slot. Useful for "mutable fields". Assuming this works out
//! well, this ... | (&mut self) {
// Noncopyable.
}
}
pub struct SlotRef<'self,T> {
ptr: &'self T,
priv immutable_borrow_count: *mut u8,
}
#[unsafe_destructor]
impl<'self,T> Drop for SlotRef<'self,T> {
#[inline]
fn drop(&mut self) {
unsafe {
*self.immutable_borrow_count -= 1
}
... | drop | identifier_name |
read_manifest.rs | use std::env;
use std::error::Error;
use cargo::core::{Package, Source};
use cargo::util::{CliResult, CliError, Config};
use cargo::util::important_paths::{find_root_manifest_for_cwd};
use cargo::sources::{PathSource};
#[derive(RustcDecodable)]
struct | {
flag_manifest_path: Option<String>,
flag_color: Option<String>,
}
pub const USAGE: &'static str = "
Usage:
cargo read-manifest [options]
cargo read-manifest -h | --help
Options:
-h, --help Print this message
-v, --verbose Use verbose output
--manifest-path PATH ... | Options | identifier_name |
read_manifest.rs | use std::env;
use std::error::Error;
use cargo::core::{Package, Source};
use cargo::util::{CliResult, CliError, Config};
use cargo::util::important_paths::{find_root_manifest_for_cwd};
use cargo::sources::{PathSource};
#[derive(RustcDecodable)]
struct Options {
flag_manifest_path: Option<String>,
flag_color: ... |
let mut source = try!(PathSource::for_path(root.parent().unwrap(), config).map_err(|e| {
CliError::new(e.description(), 1)
}));
try!(source.update().map_err(|err| CliError::new(err.description(), 1)));
source.root_package()
.map(|pkg| Some(pkg))
.map_err(|err| CliError::from... | env::args().collect::<Vec<_>>());
try!(config.shell().set_color_config(options.flag_color.as_ref().map(|s| &s[..])));
let root = try!(find_root_manifest_for_cwd(options.flag_manifest_path)); | random_line_split |
read_manifest.rs | use std::env;
use std::error::Error;
use cargo::core::{Package, Source};
use cargo::util::{CliResult, CliError, Config};
use cargo::util::important_paths::{find_root_manifest_for_cwd};
use cargo::sources::{PathSource};
#[derive(RustcDecodable)]
struct Options {
flag_manifest_path: Option<String>,
flag_color: ... | {
debug!("executing; cmd=cargo-read-manifest; args={:?}",
env::args().collect::<Vec<_>>());
try!(config.shell().set_color_config(options.flag_color.as_ref().map(|s| &s[..])));
let root = try!(find_root_manifest_for_cwd(options.flag_manifest_path));
let mut source = try!(PathSource::for_path... | identifier_body | |
type-ascription-soundness.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | ref x => {}
}
let _len = (arr: &[u8]).len(); //~ ERROR mismatched types
} | let arr = &[1u8, 2, 3];
let ref x = arr: &[u8]; //~ ERROR mismatched types
let ref mut x = arr: &[u8]; //~ ERROR mismatched types
match arr: &[u8] { //~ ERROR mismatched types | random_line_split |
type-ascription-soundness.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let arr = &[1u8, 2, 3];
let ref x = arr: &[u8]; //~ ERROR mismatched types
let ref mut x = arr: &[u8]; //~ ERROR mismatched types
match arr: &[u8] { //~ ERROR mismatched types
ref x => {}
}
let _len = (arr: &[u8]).len(); //~ ERROR mismatched types
} | identifier_body | |
type-ascription-soundness.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let arr = &[1u8, 2, 3];
let ref x = arr: &[u8]; //~ ERROR mismatched types
let ref mut x = arr: &[u8]; //~ ERROR mismatched types
match arr: &[u8] { //~ ERROR mismatched types
ref x => {}
}
let _len = (arr: &[u8]).len(); //~ ERROR mismatched types
}
| main | identifier_name |
models.rs | use rocket::http::RawStr;
use rocket::request::FromParam;
use diesel::backend::Backend;
use diesel::deserialize::{self, FromSql};
use diesel::serialize::{self, Output, ToSql};
use diesel::sql_types::Integer;
use super::schema::{measurements, sensors};
use super::MeteoError;
use crate::db::models::Node;
use crate::u... |
#[derive(Identifiable, Queryable, Associations, Debug, Clone)]
#[belongs_to(Sensor)]
pub(super) struct Measurement {
pub id: i32,
pub sensor_id: i32,
pub value: f32,
pub measured_at: DateTimeUtc,
}
#[derive(Debug, PartialEq, Eq, Copy, Clone, FromSqlRow, AsExpression)]
#[sql_type = "Integer"]
#[repr(i3... | pub public_id: i32,
pub node_id: i32,
pub sensor_type: SensorTypeEnum,
pub name: String,
} | random_line_split |
models.rs | use rocket::http::RawStr;
use rocket::request::FromParam;
use diesel::backend::Backend;
use diesel::deserialize::{self, FromSql};
use diesel::serialize::{self, Output, ToSql};
use diesel::sql_types::Integer;
use super::schema::{measurements, sensors};
use super::MeteoError;
use crate::db::models::Node;
use crate::u... |
}
impl<DB> FromSql<Integer, DB> for SensorTypeEnum
where
DB: Backend,
i32: FromSql<Integer, DB>,
{
fn from_sql(bytes: Option<&<DB as Backend>::RawValue>) -> deserialize::Result<Self> {
let raw_val = i32::from_sql(bytes)?;
match raw_val {
x if x == SensorTypeEnum::Pressure as i3... | {
match sensor_type_str {
"pressure" => Ok(SensorTypeEnum::Pressure),
"temperature" => Ok(SensorTypeEnum::Temperature),
"humidity" => Ok(SensorTypeEnum::Humidity),
"light_level" => Ok(SensorTypeEnum::LightLevel),
_ => Err(MeteoError),
}
} | identifier_body |
models.rs | use rocket::http::RawStr;
use rocket::request::FromParam;
use diesel::backend::Backend;
use diesel::deserialize::{self, FromSql};
use diesel::serialize::{self, Output, ToSql};
use diesel::sql_types::Integer;
use super::schema::{measurements, sensors};
use super::MeteoError;
use crate::db::models::Node;
use crate::u... | {
pub id: i32,
pub sensor_id: i32,
pub value: f32,
pub measured_at: DateTimeUtc,
}
#[derive(Debug, PartialEq, Eq, Copy, Clone, FromSqlRow, AsExpression)]
#[sql_type = "Integer"]
#[repr(i32)]
pub enum SensorTypeEnum {
Pressure = 0,
Temperature = 1,
Humidity = 2,
LightLevel = 3,
}
impl ... | Measurement | identifier_name |
lib.rs | #![doc(html_favicon_url = "https://www.ruma.io/favicon.ico")]
#![doc(html_logo_url = "https://www.ruma.io/images/logo.png")]
//! (De)serializable types for the [Matrix Client-Server API][client-api].
//! These types can be shared by client and server code.
//!
//! [client-api]: https://spec.matrix.org/v1.2/client-serve... | (Box<str>);
impl fmt::Debug for PrivOwnedStr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
| PrivOwnedStr | identifier_name |
lib.rs | #![doc(html_favicon_url = "https://www.ruma.io/favicon.ico")]
#![doc(html_logo_url = "https://www.ruma.io/images/logo.png")]
//! (De)serializable types for the [Matrix Client-Server API][client-api].
//! These types can be shared by client and server code.
//!
//! [client-api]: https://spec.matrix.org/v1.2/client-serve... | pub mod filter;
pub mod keys;
pub mod knock;
pub mod media;
pub mod membership;
pub mod message;
pub mod presence;
pub mod profile;
pub mod push;
pub mod read_marker;
pub mod receipt;
pub mod redact;
pub mod room;
pub mod search;
pub mod server;
pub mod session;
pub mod space;
pub mod state;
pub mod sync;
pub mod tag;
... | random_line_split | |
download.rs | use chrono::naive::NaiveDateTime;
use chrono::Local;
use database::Database;
use rutracker::RutrackerForum;
use std::collections::HashMap;
use std::collections::HashSet;
type Result<T> = std::result::Result<T, failure::Error>;
pub struct Downloader<'a> {
db: &'a Database,
forum: &'a RutrackerForum,
ignore... | .collect(); */
Ok(HashMap::new())
}
} | .filter(|(_, v)| v.seeders <= download)
.filter(|(_, v)| check_reg_time_and_status(v.tor_status, v.reg_time))
.filter(|(id, _)| !self.ignored_id.contains(id) && !keeper_list.contains(id)) | random_line_split |
download.rs | use chrono::naive::NaiveDateTime;
use chrono::Local;
use database::Database;
use rutracker::RutrackerForum;
use std::collections::HashMap;
use std::collections::HashSet;
type Result<T> = std::result::Result<T, failure::Error>;
pub struct Downloader<'a> {
db: &'a Database,
forum: &'a RutrackerForum,
ignore... |
}
| {
/* let date = Local::now().naive_local();
let num_days = |time: NaiveDateTime| date.signed_duration_since(time).num_days();
let check_reg_time_and_status = |status: i16, time: NaiveDateTime| {
([2, 3, 8].contains(&status) && num_days(time) > 30)
|| ([0, 10].contains... | identifier_body |
download.rs | use chrono::naive::NaiveDateTime;
use chrono::Local;
use database::Database;
use rutracker::RutrackerForum;
use std::collections::HashMap;
use std::collections::HashSet;
type Result<T> = std::result::Result<T, failure::Error>;
pub struct Downloader<'a> {
db: &'a Database,
forum: &'a RutrackerForum,
ignore... | (db: &'a Database, forum: &'a RutrackerForum, ignored_id: Vec<usize>) -> Self {
Self {
db,
forum,
ignored_id,
}
}
pub fn get_list_for_download(
&self,
forum_id: usize,
download: i16,
) -> Result<HashMap<usize, (String, usize)>> {
... | new | identifier_name |
error.rs | use curl::Error as CurlError;
use std::io::Error as IOError;
use std::fmt::{Formatter,Debug,Display,Error as FormatterError};
use std::error::Error as TraitError;
use std::convert::From;
/// Errors during starting download manager or processing request.
pub enum Error<E> {
/// IO Error
IOError { error: IOError },
... |
fn cause(&self) -> Option<&TraitError> {
match self {
&Error::IOError {ref error} => {
Some(error)
},
&Error::Curl {ref error} => {
Some(error)
},
&Error::Initialize {..} => {
None
},
}
}
}
impl <E>From<IOError> for Error<E> {
fn from(error: IOError) -> Self {
Error::I... | {
match self {
&Error::IOError {..} => {
"IOError"
},
&Error::Curl {..} => {
"Curl error"
},
&Error::Initialize {..} => {
"Initialize error"
},
}
} | identifier_body |
error.rs | use curl::Error as CurlError;
use std::io::Error as IOError;
use std::fmt::{Formatter,Debug,Display,Error as FormatterError};
use std::error::Error as TraitError;
use std::convert::From;
/// Errors during starting download manager or processing request.
pub enum Error<E> {
/// IO Error
IOError { error: IOError },
... | (&self) -> &str {
match self {
&Error::IOError {..} => {
"IOError"
},
&Error::Curl {..} => {
"Curl error"
},
&Error::Initialize {..} => {
"Initialize error"
},
}
}
fn cause(&self) -> Option<&TraitError> {
match self {
&Error::IOError {ref error} => {
Some(error)
},... | description | identifier_name |
error.rs | use curl::Error as CurlError;
use std::io::Error as IOError;
use std::fmt::{Formatter,Debug,Display,Error as FormatterError};
use std::error::Error as TraitError;
use std::convert::From;
/// Errors during starting download manager or processing request.
pub enum Error<E> {
/// IO Error
IOError { error: IOError },
... | }
}
}
impl <E>From<IOError> for Error<E> {
fn from(error: IOError) -> Self {
Error::IOError {
error: error
}
}
}
impl <E>From<CurlError> for Error<E> {
fn from(error: CurlError) -> Self {
Error::Curl {
error: error
}
}
}
// impl <E:!CurlError>From<E> for Error<E> where E:!CurlError {
// fn... | },
&Error::Initialize {..} => {
None
}, | random_line_split |
extern-generic.rs | //
// We specify incremental here because we want to test the partitioning for
// incremental compilation
// incremental
// compile-flags:-Zprint-mono-items=eager -Zshare-generics=y
#![allow(dead_code)]
#![crate_type="lib"]
// aux-build:cgu_generic_function.rs
extern crate cgu_generic_function;
//~ MONO_ITEM fn user... | () {
let _ = cgu_generic_function::foo("abc");
}
mod mod1 {
use cgu_generic_function;
//~ MONO_ITEM fn mod1::mod1::user @@ extern_generic-mod1-mod1[Internal]
fn user() {
let _ = cgu_generic_function::foo("abc");
}
}
}
mod mod2 {
use cgu_generic_func... | user | identifier_name |
extern-generic.rs | //
// We specify incremental here because we want to test the partitioning for
// incremental compilation
// incremental
// compile-flags:-Zprint-mono-items=eager -Zshare-generics=y
#![allow(dead_code)]
#![crate_type="lib"]
// aux-build:cgu_generic_function.rs
extern crate cgu_generic_function;
//~ MONO_ITEM fn user... |
}
// Make sure the two generic functions from the extern crate get instantiated
// once for the current crate
//~ MONO_ITEM fn cgu_generic_function::foo::<&str> @@ cgu_generic_function-in-extern_generic.volatile[External]
//~ MONO_ITEM fn cgu_generic_function::bar::<&str> @@ cgu_generic_function-in-extern_generic.vol... | {} | identifier_body |
extern-generic.rs | //
// We specify incremental here because we want to test the partitioning for
// incremental compilation
// incremental
// compile-flags:-Zprint-mono-items=eager -Zshare-generics=y
#![allow(dead_code)]
#![crate_type="lib"]
// aux-build:cgu_generic_function.rs
extern crate cgu_generic_function;
//~ MONO_ITEM fn user... |
mod mod1 {
use cgu_generic_function;
//~ MONO_ITEM fn mod1::user @@ extern_generic-mod1[Internal]
fn user() {
let _ = cgu_generic_function::foo("abc");
}
mod mod1 {
use cgu_generic_function;
//~ MONO_ITEM fn mod1::mod1::user @@ extern_generic-mod1-mod1[Internal]
f... | fn user() {
let _ = cgu_generic_function::foo("abc");
} | random_line_split |
others.rs | use super::prelude::*;
use stencila_schema::*;
replaceable_struct!(Date, value);
patchable_struct!(
Organization,
// All properties except `id` (as at 2021-11-18)
// Commented out properties have types that do not yet have a `impl Patchable`.
//address,
alternate_names,
//brands,
//contac... | ); | name,
telephone_numbers,
url | random_line_split |
foo.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let _a = unsafe { _foo() };
} | identifier_body | |
foo.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 ... | (_main: *const u8, _argc: isize, _argv: *const *const u8) -> isize { 0 }
extern {
fn _foo() -> [u8; 16];
}
fn _main() {
let _a = unsafe { _foo() };
}
| start | identifier_name |
foo.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 ... |
#[lang="sized"]
trait Sized { }
#[lang = "freeze"]
auto trait Freeze {}
#[lang="start"]
fn start(_main: *const u8, _argc: isize, _argv: *const *const u8) -> isize { 0 }
extern {
fn _foo() -> [u8; 16];
}
fn _main() {
let _a = unsafe { _foo() };
} | random_line_split | |
x86.rs | #[repr(C)]
#[derive(Copy)]
pub struct glob_t {
pub gl_pathc: ::size_t,
pub gl_pathv: *mut *mut ::schar_t,
pub gl_offs: ::size_t,
pub gl_flags: ::int_t,
pub gl_closedir: fn(*mut ::void_t, ),
pub gl_readdir: fn(*mut ::void_t, ) -> *mut ::void_t,
pub gl_opendir: fn(*const ::schar_t, ) -> *mut :... | }
new!(glob_t);
pub const GLOB_APPEND: ::int_t = (1 << 5);
pub const GLOB_DOOFFS: ::int_t = (1 << 3);
pub const GLOB_ERR: ::int_t = (1 << 0);
pub const GLOB_MARK: ::int_t = (1 << 1);
pub const GLOB_NOCHECK: ::int_t = (1 << 4);
pub const GLOB_NOESCAPE: ::int_t = (1 << 6);
pub const GLOB_NOSORT: ::int_t = (1 << 2);
pub c... | pub gl_stat: fn(*const ::schar_t, *mut ::void_t, ) -> ::int_t, | random_line_split |
x86.rs | #[repr(C)]
#[derive(Copy)]
pub struct | {
pub gl_pathc: ::size_t,
pub gl_pathv: *mut *mut ::schar_t,
pub gl_offs: ::size_t,
pub gl_flags: ::int_t,
pub gl_closedir: fn(*mut ::void_t, ),
pub gl_readdir: fn(*mut ::void_t, ) -> *mut ::void_t,
pub gl_opendir: fn(*const ::schar_t, ) -> *mut ::void_t,
pub gl_lstat: fn(*const ::schar... | glob_t | identifier_name |
core-uint-to-str.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
vec!(~"", ~"10000000")
} else if args.len() <= 1u {
vec!(~"", ~"100000")
} else {
args.move_iter().collect()
};
let n = from_str::<uint>(*args.get(1)).unwrap();
for i in range(0u, n) {
... | main | identifier_name |
core-uint-to-str.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
vec!(~"", ~"10000000")
} else if args.len() <= 1u {
vec!(~"", ~"100000")
} else {
args.move_iter().collect()
};
let n = from_str::<uint>(*args.get(1)).unwrap();
for i in range(0u, n) {
... | identifier_body | |
core-uint-to-str.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!(~"", ~"100000")
} else {
args.move_iter().collect()
};
let n = from_str::<uint>(*args.get(1)).unwrap();
for i in range(0u, n) {
let x = i.to_str();
println!("{}", x);
}
} | random_line_split | |
core-uint-to-str.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | else {
args.move_iter().collect()
};
let n = from_str::<uint>(*args.get(1)).unwrap();
for i in range(0u, n) {
let x = i.to_str();
println!("{}", x);
}
}
| {
vec!(~"", ~"100000")
} | conditional_block |
parser.rs |
peg_file! ply_rustpeg("ply.rustpeg");
pub fn parse(s: &str) -> Result<PLY, String> {
let (f, v, mut counted_elems, data) = try!(ply_rustpeg::parse(s));
let mut counter = 0us;
for &mut (count, ref mut elem) in counted_elems.iter_mut() {
//let (count, ref mut elem) = counted_elems.get_mut(i).unwrap();
if data.l... |
elem.data.push_all(&data[counter.. counter + count]);
counter += count;
}
Ok(PLY {format: f, version: v, elements: counted_elems.into_iter().map(|(_,e)|e).collect()})
}
#[derive(Debug, Copy)]
pub enum Format { Ascii }
#[derive(Debug, Copy)]
pub struct Version (u32, u32);
#[derive(Debug)]
pub struct ElementSp... | {
return Err(format!("Data section too short."));
} | conditional_block |
parser.rs |
peg_file! ply_rustpeg("ply.rustpeg");
pub fn parse(s: &str) -> Result<PLY, String> {
let (f, v, mut counted_elems, data) = try!(ply_rustpeg::parse(s));
let mut counter = 0us;
for &mut (count, ref mut elem) in counted_elems.iter_mut() {
//let (count, ref mut elem) = counted_elems.get_mut(i).unwrap();
if data.l... | {
pub format: Format,
pub version: Version,
pub elements: Vec<ElementSpec>,
}
impl PLY {
pub fn get_elem(&self, name: String) -> Option<&ElementSpec> {
self.elements.iter().filter(|&e| e.name == name).next()
}
}
| PLY | identifier_name |
parser.rs | peg_file! ply_rustpeg("ply.rustpeg");
pub fn parse(s: &str) -> Result<PLY, String> {
let (f, v, mut counted_elems, data) = try!(ply_rustpeg::parse(s));
let mut counter = 0us;
for &mut (count, ref mut elem) in counted_elems.iter_mut() {
//let (count, ref mut elem) = counted_elems.get_mut(i).unwrap();
if data.le... |
impl PLY {
pub fn get_elem(&self, name: String) -> Option<&ElementSpec> {
self.elements.iter().filter(|&e| e.name == name).next()
}
} | } | random_line_split |
macros.rs | macro_rules! non_null {
( $obj:expr, $ctx:expr ) => {
if $obj.is_null() {
return Err($crate::errors::ErrorKind::NullPtr($ctx).into());
} else {
$obj
}
}
}
macro_rules! deref {
( $obj:expr, $ctx:expr ) => {
if $obj.is_null() {
return Err($c... | trace!("exception found, returning error");
return Err($crate::errors::Error::from(
$crate::errors::ErrorKind::JavaException).into());
}
trace!("no exception found");
}
}
macro_rules! jni_unchecked {
( $jnienv:expr, $name:tt $(, $args:expr )* ) => ({
... | if check { | random_line_split |
token.rs | ),
NtExpr(@ast::Expr),
NtTy( P<ast::Ty>),
NtIdent(Box<ast::Ident>, bool),
NtMeta(@ast::MetaItem), // stuff inside brackets for attributes
NtPath(Box<ast::Path>),
NtTT( @ast::TokenTree), // needs @ed to break a circularity
NtMatchers(Vec<ast::Matcher> )
}
impl fmt::Show for Nonterminal {
... | $(init_vec.push($sk_str);)*
$(init_vec.push($rk_str);)*
interner::StrInterner::prefill(init_vec.as_slice())
}
}}
// If the special idents get renumbered, remember to modify these two as appropriate
static SELF_KEYWORD_NAME: Name = 1;
static STATIC_KEYWORD_NAME: Name = 2;
declare_special_id... | let mut init_vec = Vec::new();
$(init_vec.push($si_str);)* | random_line_split |
token.rs |
NtExpr(@ast::Expr),
NtTy( P<ast::Ty>),
NtIdent(Box<ast::Ident>, bool),
NtMeta(@ast::MetaItem), // stuff inside brackets for attributes
NtPath(Box<ast::Path>),
NtTT( @ast::TokenTree), // needs @ed to break a circularity
NtMatchers(Vec<ast::Matcher> )
}
impl fmt::Show for Nonterminal {
... | (t: &Token) -> Option<Token> {
match *t {
LPAREN => Some(RPAREN),
LBRACE => Some(RBRACE),
LBRACKET => Some(RBRACKET),
_ => None
}
}
pub fn is_lit(t: &Token) -> bool {
match *t {
LIT_CHAR(_) => true,
LIT_INT(_, _) => true,
LIT_UINT(_, _) => true,
... | close_delimiter_for | identifier_name |
token.rs |
NtExpr(@ast::Expr),
NtTy( P<ast::Ty>),
NtIdent(Box<ast::Ident>, bool),
NtMeta(@ast::MetaItem), // stuff inside brackets for attributes
NtPath(Box<ast::Path>),
NtTT( @ast::TokenTree), // needs @ed to break a circularity
NtMatchers(Vec<ast::Matcher> )
}
impl fmt::Show for Nonterminal {
... |
LIT_INT(i, t) => ast_util::int_ty_to_str(t, Some(i)),
LIT_UINT(u, t) => ast_util::uint_ty_to_str(t, Some(u)),
LIT_INT_UNSUFFIXED(i) => { i.to_str().to_strbuf() }
LIT_FLOAT(s, t) => {
let mut body = StrBuf::from_str(get_ident(s).get());
if body.as_slice().ends_with(".") {
... | {
let mut res = StrBuf::from_str("'");
c.escape_default(|c| {
res.push_char(c);
});
res.push_char('\'');
res
} | conditional_block |
token.rs |
NtExpr(@ast::Expr),
NtTy( P<ast::Ty>),
NtIdent(Box<ast::Ident>, bool),
NtMeta(@ast::MetaItem), // stuff inside brackets for attributes
NtPath(Box<ast::Path>),
NtTT( @ast::TokenTree), // needs @ed to break a circularity
NtMatchers(Vec<ast::Matcher> )
}
impl fmt::Show for Nonterminal {
... |
pub fn to_str(t: &Token) -> StrBuf {
match *t {
EQ => "=".to_strbuf(),
LT => "<".to_strbuf(),
LE => "<=".to_strbuf(),
EQEQ => "==".to_strbuf(),
NE => "!=".to_strbuf(),
GE => ">=".to_strbuf(),
GT => ">".to_strbuf(),
NOT => "!".to_strbuf(),
TILDE => "~".to_strbu... | {
match o {
PLUS => "+".to_strbuf(),
MINUS => "-".to_strbuf(),
STAR => "*".to_strbuf(),
SLASH => "/".to_strbuf(),
PERCENT => "%".to_strbuf(),
CARET => "^".to_strbuf(),
AND => "&".to_strbuf(),
OR => "|".to_strbuf(),
SHL => "<<".to_strbuf(),
SHR => ">>".to_s... | identifier_body |
tuple-struct.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... | () {
let no_padding16 = NoPadding16(10000, -10001);
let no_padding32 = NoPadding32(-10002, -10003.5, 10004);
let no_padding64 = NoPadding64(-10005.5, 10006, 10007);
let no_padding163264 = NoPadding163264(-10008, 10009, 10010, 10011);
let internal_padding = InternalPadding(10012, -10013);
let pa... | main | identifier_name |
tuple-struct.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 zzz() {()}
| {
let no_padding16 = NoPadding16(10000, -10001);
let no_padding32 = NoPadding32(-10002, -10003.5, 10004);
let no_padding64 = NoPadding64(-10005.5, 10006, 10007);
let no_padding163264 = NoPadding163264(-10008, 10009, 10010, 10011);
let internal_padding = InternalPadding(10012, -10013);
let paddi... | identifier_body |
tuple-struct.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... | // gdb-check:$5 = {10012, -10013}
// gdb-command:print padding_at_end
// gdb-check:$6 = {-10014, 10015}
// === LLDB TESTS ==================================================================================
// lldb-command:run
// lldb-command:print no_padding16
// lldb-check:[...]$0 = NoPadding16(10000, -10001)
// ... | // gdb-check:$4 = {-10008, 10009, 10010, 10011}
// gdb-command:print internal_padding | random_line_split |
smallest-hello-world.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... | #[no_split_stack]
fn main(_: int, _: *const *const u8) -> int {
unsafe {
let (ptr, _): (*const u8, uint) = transmute("Hello!\0");
puts(ptr);
}
return 0;
} | #[lang = "sized"] pub trait Sized {}
#[start] | random_line_split |
smallest-hello-world.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... | (_: int, _: *const *const u8) -> int {
unsafe {
let (ptr, _): (*const u8, uint) = transmute("Hello!\0");
puts(ptr);
}
return 0;
}
| main | identifier_name |
smallest-hello-world.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... | {
unsafe {
let (ptr, _): (*const u8, uint) = transmute("Hello!\0");
puts(ptr);
}
return 0;
} | identifier_body | |
lib.rs | use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::io::Write;
use std::path::PathBuf;
use chrono::prelude::*;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use anyhow::Result;
use regex::Regex;
#[macro_use]
extern crate lazy_static;
use thiserror::Error;
pub struct... | #[derive(Debug, Error)]
pub enum WsfError {
#[error("Terminal not found: {0}")]
TerminalNotFound(String),
} | random_line_split | |
lib.rs | use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::io::Write;
use std::path::PathBuf;
use chrono::prelude::*;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use anyhow::Result;
use regex::Regex;
#[macro_use]
extern crate lazy_static;
use thiserror::Error;
pub struct... |
let now = Local::now();
let path = format!(
"/schedule/{}-{}-{}/{}/{}",
now.year(),
now.month(),
now.day(),
from,
to
);
let schedule: Schedule = self.get(path).await?;
self.cache
.sailings
... | {
self.cache.sailings.clear();
} | conditional_block |
lib.rs | use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::io::Write;
use std::path::PathBuf;
use chrono::prelude::*;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use anyhow::Result;
use regex::Regex;
#[macro_use]
extern crate lazy_static;
use thiserror::Error;
pub struct... | {
pub DepartingTime: String,
pub ArrivingTime: Option<String>,
pub VesselName: String,
}
impl SailingTime {
// parse date strings of form "/Date(1436318400000-0700)/"
pub fn depart_time(&self) -> Result<DateTime<Local>> {
lazy_static! {
static ref RE: regex::Regex =
... | SailingTime | identifier_name |
advent2.rs | // advent2.rs
// bathroom keypad decoding
use std::io;
use std::io::prelude::*;
fn main() {
let mut pos1 = (1, 1);
let mut code1 = String::new();
let mut pos2 = (0, 2);
let mut code2 = String::new();
let stdin = io::stdin();
for line in stdin.lock().lines().map(|l| l.expect("Failed to read ... | () {
assert_eq!(1, digit_from_pos((0, 0)));
assert_eq!(2, digit_from_pos((1, 0)));
assert_eq!(3, digit_from_pos((2, 0)));
assert_eq!(4, digit_from_pos((0, 1)));
assert_eq!(5, digit_from_pos((1, 1)));
assert_eq!(6, digit_from_pos((2, 1)));
assert_eq!(7, digit_from_pos((0, 2)));
assert_eq!... | test_digit_from_pos | identifier_name |
advent2.rs | // advent2.rs
// bathroom keypad decoding
use std::io;
use std::io::prelude::*;
fn main() {
let mut pos1 = (1, 1);
let mut code1 = String::new();
let mut pos2 = (0, 2);
let mut code2 = String::new();
let stdin = io::stdin();
for line in stdin.lock().lines().map(|l| l.expect("Failed to read ... |
// ////////
// Part 2
// Same as part 1, except the conditions are less obvious
#[cfg_attr(rustfmt, rustfmt_skip)]
fn parse_move2(pos: (i32, i32), s: &str) -> (i32, i32) {
let (mut x, mut y) = pos;
for c in s.trim().chars() {
match c {
'U' => if y - (x - 2).abs() > 0 {y -= 1;},
... | {
let (mut x, mut y) = pos;
for c in s.trim().chars() {
match c {
'U' => if y > 0 {y -= 1;},
'D' => if y < 2 {y += 1;},
'L' => if x > 0 {x -= 1;},
'R' => if x < 2 {x += 1;},
_ => panic!("unexpected char in input")
}
}
(x, y)
} | identifier_body |
advent2.rs | // advent2.rs
// bathroom keypad decoding
use std::io;
use std::io::prelude::*;
fn main() {
let mut pos1 = (1, 1);
let mut code1 = String::new();
let mut pos2 = (0, 2);
let mut code2 = String::new();
let stdin = io::stdin();
for line in stdin.lock().lines().map(|l| l.expect("Failed to read ... | ,
'L' => if x > 0 {x -= 1;},
'R' => if x < 2 {x += 1;},
_ => panic!("unexpected char in input")
}
}
(x, y)
}
// ////////
// Part 2
// Same as part 1, except the conditions are less obvious
#[cfg_attr(rustfmt, rustfmt_skip)]
fn parse_move2(pos: (i32, i32), s: &str) ... | {y += 1;} | conditional_block |
advent2.rs | // advent2.rs
// bathroom keypad decoding
use std::io;
use std::io::prelude::*;
fn main() {
let mut pos1 = (1, 1);
let mut code1 = String::new();
let mut pos2 = (0, 2);
let mut code2 = String::new();
let stdin = io::stdin();
for line in stdin.lock().lines().map(|l| l.expect("Failed to read ... | ['5', '6', '7', '8', '9'],
['*', 'A', 'B', 'C', '*'],
['*', '*', 'D', '*', '*']];
fn char_from_pos2(pos: (i32, i32)) -> char {
KEYPAD2_TABLE[pos.1 as usize][pos.0 as usize]
}
// //////
// Tests
#[t... | ['*', '2', '3', '4', '*'], | random_line_split |
main.rs |
#[macro_use]
extern crate lazy_static;
extern crate md5;
use md5::compute;
fn next_pair(input: &[u8], pepper: &mut u64) -> Option<(u8, u8)> {
let mut preimage = Vec::new();
// Ignore edge case where maximum pepper yields the digit.
while *pepper!= u64::max_value() {
preimage.clear();
pr... |
}
}
None
}
fn next_digit(input: &[u8], pepper: &mut u64) -> Option<u8> {
next_pair(input, pepper).map(|(x, _)| x)
}
fn solve_one(input: &[u8]) -> Option<String> {
let mut password = Vec::new();
let mut pepper = 0u64;
for _ in 0..8 {
match next_digit(input, &mut pepper) {
... | {
let d6 = digest[2] & 0xf;
let d7 = (digest[3] >> 4) & 0xf;
return Some((d6, d7));
} | conditional_block |
main.rs |
#[macro_use]
extern crate lazy_static;
extern crate md5;
use md5::compute;
fn next_pair(input: &[u8], pepper: &mut u64) -> Option<(u8, u8)> {
let mut preimage = Vec::new();
// Ignore edge case where maximum pepper yields the digit.
while *pepper!= u64::max_value() {
preimage.clear();
pr... | (input: &[u8]) -> Option<String> {
let mut password = Vec::new();
let mut pepper = 0u64;
for _ in 0..8 {
match next_digit(input, &mut pepper) {
Some(digit) => password.push(format!("{:x}", digit)),
_ => return None,
}
}
Some(password.join(""))
}
fn solve_tw... | solve_one | identifier_name |
main.rs | #[macro_use]
extern crate lazy_static;
extern crate md5;
use md5::compute;
fn next_pair(input: &[u8], pepper: &mut u64) -> Option<(u8, u8)> {
let mut preimage = Vec::new();
// Ignore edge case where maximum pepper yields the digit.
while *pepper!= u64::max_value() {
preimage.clear();
pre... | match next_digit(input, &mut pepper) {
Some(digit) => password.push(format!("{:x}", digit)),
_ => return None,
}
}
Some(password.join(""))
}
fn solve_two(input: &[u8]) -> Option<String> {
let (mut free, mut pepper) = (8, 0u64);
let mut password = [!0u8; 8];
... | let mut pepper = 0u64;
for _ in 0..8 { | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.