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 |
|---|---|---|---|---|
computations.rs | // Lumol, an extensible molecular simulation engine
// Copyright (C) 2015-2016 Lumol's contributors — BSD license
use energy::{Potential, PairPotential};
/// Alternative energy and forces computation.
///
/// The `Computation` trait represent an alternative way to compute a given
/// potential. For example using inte... |
assert_eq!(table.compute_energy(2.5), 6.25);
assert_eq!(table.compute_force(2.5), -25.0);
// Check that the table is defined up to the cutoff value
let delta = 4.0 / 1000.0;
assert_eq!(table.compute_energy(4.0 - 2.0 * delta), 99.2016);
assert_eq!(table.compute_force(4.0... | let table = TableComputation::new(
Box::new(Harmonic{k: 50.0, x0: 2.0}), 1000, 4.0
); | random_line_split |
computations.rs | // Lumol, an extensible molecular simulation engine
// Copyright (C) 2015-2016 Lumol's contributors — BSD license
use energy::{Potential, PairPotential};
/// Alternative energy and forces computation.
///
/// The `Computation` trait represent an alternative way to compute a given
/// potential. For example using inte... | }
fn compute_force(&self, r: f64) -> f64 {
debug_assert_eq!(self.energy_table.len(), self.force_table.len());
let bin = f64::floor(r / self.delta) as usize;
if bin < self.force_table.len() - 1 {
let dx = r - (bin as f64) * self.delta;
let slope = (self.force_table... | return 0.0;
}
| conditional_block |
packed-struct-generic-layout.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
use std::cast;
#[packed]
struct S<T, S> {
a: T,
b: u8,
c: S
}
fn main() {
unsafe {
let s = S { a: 0xff_ff_ff_ffu32, b: 1, c: 0xaa_aa_aa_aa as i32 };
let transd : [u8,.. 9] = cast::transmute(s);
// Don't worry about endianness, the numbers are palindromic.
assert_eq!(tr... | random_line_split | |
packed-struct-generic-layout.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <T, S> {
a: T,
b: u8,
c: S
}
fn main() {
unsafe {
let s = S { a: 0xff_ff_ff_ffu32, b: 1, c: 0xaa_aa_aa_aa as i32 };
let transd : [u8,.. 9] = cast::transmute(s);
// Don't worry about endianness, the numbers are palindromic.
assert_eq!(transd,
[0xff, 0xf... | S | identifier_name |
packed-struct-generic-layout.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
unsafe {
let s = S { a: 0xff_ff_ff_ffu32, b: 1, c: 0xaa_aa_aa_aa as i32 };
let transd : [u8, .. 9] = cast::transmute(s);
// Don't worry about endianness, the numbers are palindromic.
assert_eq!(transd,
[0xff, 0xff, 0xff, 0xff,
1,
... | identifier_body | |
stores.rs | // Copyright 2015, 2016 Parity Technologies (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 la... | /// Disk-serializable HashMap
#[derive(Debug)]
struct DiskMap<K: hash::Hash + Eq, V> {
path: PathBuf,
cache: HashMap<K, V>,
transient: bool,
}
impl<K: hash::Hash + Eq, V> ops::Deref for DiskMap<K, V> {
type Target = HashMap<K, V>;
fn deref(&self) -> &Self::Target {
&self.cache
}
}
impl<K: hash::Hash + Eq, V> ... | }
| random_line_split |
stores.rs | // Copyright 2015, 2016 Parity Technologies (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 la... | (&self) {
self.cache.save(AccountMeta::write_address_map)
}
/// Sets new name for given address.
pub fn set_name(&mut self, a: Address, name: String) {
{
let mut x = self.cache.entry(a)
.or_insert_with(|| AccountMeta {name: Default::default(), meta: "{}".to_owned(), uuid: None});
x.name = name;
}
... | save | identifier_name |
stores.rs | // Copyright 2015, 2016 Parity Technologies (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 la... |
trace!(target: "diskmap", "revert {:?}", self.path);
let _ = fs::File::open(self.path.clone())
.map_err(|e| trace!(target: "diskmap", "Couldn't open disk map: {}", e))
.and_then(|f| read(f).map_err(|e| warn!(target: "diskmap", "Couldn't read disk map: {}", e)))
.and_then(|m| {
self.cache = m;
Ok((... | { return; } | conditional_block |
stores.rs | // Copyright 2015, 2016 Parity Technologies (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 la... |
}
| {
let temp = RandomTempPath::create_dir();
let path = temp.as_str().to_owned();
let mut b = AddressBook::new(path.clone());
b.set_name(1.into(), "One".to_owned());
b.set_name(2.into(), "Two".to_owned());
b.set_name(3.into(), "Three".to_owned());
b.remove(2.into());
let b = AddressBook::new(path);
as... | identifier_body |
dct.rs | use rustdct::{DCTplanner, TransformType2And3};
use transpose::transpose;
use std::sync::Arc;
pub const SIZE_MULTIPLIER: u32 = 2;
pub const SIZE_MULTIPLIER_U: usize = SIZE_MULTIPLIER as usize;
pub struct DctCtxt {
row_dct: Arc<dyn TransformType2And3<f32>>,
col_dct: Arc<dyn TransformType2And3<f32>>,
width:... |
pub fn width(&self) -> u32 {
self.width as u32
}
pub fn height(&self) -> u32 {
self.height as u32
}
/// Perform a 2D DCT on a 1D-packed vector with a given `width x height`.
///
/// Assumes `packed_2d` is double-length for scratch space. Returns the vector truncated to
... | {
let mut planner = DCTplanner::new();
let width = width as usize * SIZE_MULTIPLIER_U;
let height = height as usize * SIZE_MULTIPLIER_U;
DctCtxt {
row_dct: planner.plan_dct2(width),
col_dct: planner.plan_dct2(height),
width,
height,
... | identifier_body |
dct.rs | use rustdct::{DCTplanner, TransformType2And3};
use transpose::transpose;
use std::sync::Arc;
pub const SIZE_MULTIPLIER: u32 = 2;
pub const SIZE_MULTIPLIER_U: usize = SIZE_MULTIPLIER as usize;
pub struct DctCtxt {
row_dct: Arc<dyn TransformType2And3<f32>>,
col_dct: Arc<dyn TransformType2And3<f32>>,
width:... |
/// Crop the values off a 1D-packed 2D DCT.
///
/// Returns `packed` truncated to the premultiplied size, as determined by `rowstride`
///
/// Generic for easier testing
fn crop_2d_dct<T: Copy>(mut packed: Vec<T>, rowstride: usize) -> Vec<T> {
// assert that the rowstride was previously multiplied by SIZE_MULTIPLI... |
pub fn crop_2d(&self, packed: Vec<f32>) -> Vec<f32> {
crop_2d_dct(packed, self.width)
}
} | random_line_split |
dct.rs | use rustdct::{DCTplanner, TransformType2And3};
use transpose::transpose;
use std::sync::Arc;
pub const SIZE_MULTIPLIER: u32 = 2;
pub const SIZE_MULTIPLIER_U: usize = SIZE_MULTIPLIER as usize;
pub struct | {
row_dct: Arc<dyn TransformType2And3<f32>>,
col_dct: Arc<dyn TransformType2And3<f32>>,
width: usize,
height: usize,
}
impl DctCtxt {
pub fn new(width: u32, height: u32) -> Self {
let mut planner = DCTplanner::new();
let width = width as usize * SIZE_MULTIPLIER_U;
let heigh... | DctCtxt | identifier_name |
util.rs |
use ::Disruption;
use rustc_serialize::{Encodable};
use rustc_serialize::json::{self};
use std::sync::Arc;
use std::sync::atomic::Ordering;
use time::PreciseTime;
use hyper::Client;
pub fn disruption_to_usize(d: &Option<&(Disruption, usize)>) -> usize |
pub fn send_bulk<T: Encodable>(url: &str, client: &Arc<Client>, bulk: Vec<T>) {
::ACTIVE_THREADS.fetch_add(1, Ordering::SeqCst);
debug!("......");
let mut s = String::new();
let size = bulk.len();
for b in bulk {
s.push_str("{\"index\":{}}\n");
s.push_str(&json::encode(&b).unwrap(... | {
match *d {
None => 0,
Some(&(Disruption::Node(_), _)) => 1,
Some(&(Disruption::Query(_), _)) => 2,
Some(&(Disruption::Metric(_), _)) => 3
}
} | identifier_body |
util.rs |
use ::Disruption;
use rustc_serialize::{Encodable};
use rustc_serialize::json::{self};
use std::sync::Arc;
use std::sync::atomic::Ordering;
use time::PreciseTime;
use hyper::Client;
pub fn disruption_to_usize(d: &Option<&(Disruption, usize)>) -> usize {
match *d {
None => 0,
Some(&(Disruption::Nod... | <T: Encodable>(url: &str, client: &Arc<Client>, bulk: Vec<T>) {
::ACTIVE_THREADS.fetch_add(1, Ordering::SeqCst);
debug!("......");
let mut s = String::new();
let size = bulk.len();
for b in bulk {
s.push_str("{\"index\":{}}\n");
s.push_str(&json::encode(&b).unwrap());
s.push... | send_bulk | identifier_name |
util.rs | use ::Disruption;
use rustc_serialize::{Encodable};
use rustc_serialize::json::{self};
use std::sync::Arc;
use std::sync::atomic::Ordering;
use time::PreciseTime;
use hyper::Client; | pub fn disruption_to_usize(d: &Option<&(Disruption, usize)>) -> usize {
match *d {
None => 0,
Some(&(Disruption::Node(_), _)) => 1,
Some(&(Disruption::Query(_), _)) => 2,
Some(&(Disruption::Metric(_), _)) => 3
}
}
pub fn send_bulk<T: Encodable>(url: &str, client: &Arc<Client>, b... | random_line_split | |
errors.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::ast::{SyntaxError, SourceLocation};
pub struct ErrorLoggerIterator<I>(pub I);
impl<T, I: Iterat... |
}
/// Defaults to a no-op.
/// Set a `RUST_LOG=style::errors` environment variable
/// to log CSS parse errors to stderr.
pub fn log_css_error(location: SourceLocation, message: &str) {
// Check this first as it’s cheaper than local_data.
if log_enabled!(::log::INFO) {
if silence_errors.get().is_none... | {
let ErrorLoggerIterator(ref mut this) = *self;
loop {
match this.next() {
Some(Ok(v)) => return Some(v),
Some(Err(error)) => log_css_error(error.location,
format!("{:?}", error.reason).as_slice()),
... | identifier_body |
errors.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::ast::{SyntaxError, SourceLocation};
pub struct ErrorLoggerIterator<I>(pub I);
impl<T, I: Iterat... | >(f: || -> T) -> T {
silence_errors.replace(Some(()));
let result = f();
silence_errors.replace(None);
result
}
| th_errors_silenced<T | identifier_name |
errors.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::ast::{SyntaxError, SourceLocation};
pub struct ErrorLoggerIterator<I>(pub I);
impl<T, I: Iterat... |
local_data_key!(silence_errors: ())
pub fn with_errors_silenced<T>(f: || -> T) -> T {
silence_errors.replace(Some(()));
let result = f();
silence_errors.replace(None);
result
} | }
}
}
| random_line_split |
timeout.rs | extern crate futures;
use futures::{Future, Poll};
use std::io;
use std::marker::PhantomData;
use std::time::{Duration, Instant};
pub struct Timeout<T,E> {
timestamp: Instant,
duration: Duration,
error: E,
phantom: PhantomData<T>,
}
impl<T,E> Timeout<T,E>
where E: Fn() -> io::Error
{
pub fn n... | (&mut self) -> Poll<Self::Item, Self::Error> {
use futures::{Async, task};
if self.is_elapsed() {
Err((self.error)())
} else {
task::park().unpark(); // this tells the task driving the future to recheck this again
// in the future. Otherwise poll will only be... | poll | identifier_name |
timeout.rs | extern crate futures;
use futures::{Future, Poll};
use std::io;
use std::marker::PhantomData;
use std::time::{Duration, Instant};
pub struct Timeout<T,E> {
timestamp: Instant,
duration: Duration,
error: E,
phantom: PhantomData<T>,
}
impl<T,E> Timeout<T,E>
where E: Fn() -> io::Error
{
pub fn n... | else {
task::park().unpark(); // this tells the task driving the future to recheck this again
// in the future. Otherwise poll will only be run once.
Ok(Async::NotReady)
}
}
}
| {
Err((self.error)())
} | conditional_block |
timeout.rs | extern crate futures;
use futures::{Future, Poll};
use std::io;
use std::marker::PhantomData;
use std::time::{Duration, Instant};
pub struct Timeout<T,E> {
timestamp: Instant,
duration: Duration,
error: E,
phantom: PhantomData<T>,
}
impl<T,E> Timeout<T,E>
where E: Fn() -> io::Error
{
pub fn n... |
}
| {
use futures::{Async, task};
if self.is_elapsed() {
Err((self.error)())
} else {
task::park().unpark(); // this tells the task driving the future to recheck this again
// in the future. Otherwise poll will only be run once.
Ok(Async::NotReady)
... | identifier_body |
timeout.rs | extern crate futures;
use futures::{Future, Poll};
use std::io;
use std::marker::PhantomData;
use std::time::{Duration, Instant};
pub struct Timeout<T,E> {
timestamp: Instant,
duration: Duration,
error: E,
phantom: PhantomData<T>,
}
impl<T,E> Timeout<T,E>
where E: Fn() -> io::Error
{
pub fn n... | impl<T,E> Future for Timeout<T,E>
where E: Fn() -> io::Error
{
type Item = T;
type Error = io::Error;
// Return type of the Future::poll method, indicates whether a future's value is ready or not.
//
// Ok(Async::Ready(t)) means that a future has successfully resolved
// Ok(Async::NotReady... | random_line_split | |
log.rs | use std::cmp;
use game::*;
#[derive(Debug, Serialize, Deserialize)]
pub struct MessageLogEntry {
pub message: MessageType,
pub repeated: usize,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct MessageLog {
messages: Vec<MessageLogEntry>,
last_temporary: bool,
}
impl MessageLog {
pub fn new(... |
self.last_temporary = true;
self.messages.push(MessageLogEntry {
message: message,
repeated: 1,
});
}
}
| {
self.messages.pop();
} | conditional_block |
log.rs | use std::cmp;
use game::*;
#[derive(Debug, Serialize, Deserialize)]
pub struct MessageLogEntry {
pub message: MessageType,
pub repeated: usize,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct MessageLog {
messages: Vec<MessageLogEntry>,
last_temporary: bool,
}
impl MessageLog {
pub fn new(... |
pub fn tail_with_offset(&self, count: usize, offset: usize) -> &[MessageLogEntry] {
let end = cmp::max(0, (self.len() as isize) - (offset as isize)) as usize;
let start = cmp::max(0, (end as isize) - (count as isize)) as usize;
&self.messages[start..end]
}
pub fn add(&mut self, me... | {
let mid = cmp::max(0, (self.len() as isize) - (count as isize)) as usize;
&self.messages[mid..]
} | identifier_body |
log.rs | use std::cmp;
use game::*;
#[derive(Debug, Serialize, Deserialize)]
pub struct MessageLogEntry {
pub message: MessageType,
pub repeated: usize,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct MessageLog {
messages: Vec<MessageLogEntry>,
last_temporary: bool,
}
impl MessageLog {
pub fn new(... | }
} | repeated: 1,
}); | random_line_split |
log.rs | use std::cmp;
use game::*;
#[derive(Debug, Serialize, Deserialize)]
pub struct MessageLogEntry {
pub message: MessageType,
pub repeated: usize,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct MessageLog {
messages: Vec<MessageLogEntry>,
last_temporary: bool,
}
impl MessageLog {
pub fn new(... | (&mut self, message: MessageType) {
if self.last_temporary {
self.messages.pop();
}
self.last_temporary = true;
self.messages.push(MessageLogEntry {
message: message,
repeated: 1,
});
}
}
| add_temporary | identifier_name |
screen.rs | use crate::portal::PortalRef;
use alloc::sync::Weak;
use cairo::bindings::{CAIRO_FORMAT_A8, CAIRO_FORMAT_ARGB32, CAIRO_FORMAT_RGB24};
use cairo::{Cairo, Surface};
use core::mem;
use graphics_base::frame_buffer::{AsSurface, AsSurfaceMut, FrameBuffer};
use graphics_base::types::{EventInput, MouseButton, MouseInputInfo, R... | const CURSOR_HOTSPOT_Y: f64 = 8.0;
pub struct ScreenBuffer {
pub pos: Rect,
pub frame_buffer_size: (u16, u16),
pub frame_buffer: Weak<FrameBuffer>,
pub portal_ref: PortalRef,
}
pub struct InputCapture {
button: MouseButton,
pub pos: Rect,
pub portal_ref: PortalRef,
}
fn to_sprite(hotspot:... | use jpeg_decoder::{Decoder, ImageInfo, PixelFormat};
const CURSOR_WIDTH: f64 = 32.0;
const CURSOR_HEIGHT: f64 = 32.0;
const CURSOR_HOTSPOT_X: f64 = 12.0; | random_line_split |
screen.rs | use crate::portal::PortalRef;
use alloc::sync::Weak;
use cairo::bindings::{CAIRO_FORMAT_A8, CAIRO_FORMAT_ARGB32, CAIRO_FORMAT_RGB24};
use cairo::{Cairo, Surface};
use core::mem;
use graphics_base::frame_buffer::{AsSurface, AsSurfaceMut, FrameBuffer};
use graphics_base::types::{EventInput, MouseButton, MouseInputInfo, R... | (&mut self, x: u16, y: u16, _dw: i8, buttons: [bool; 3]) -> Result<()> {
let prev_cursor_hotspot = self.cursor_hotspot;
let prev_cursor_sprite = self.cursor_sprite;
let prev_buttons = self.buttons;
self.cursor_hotspot = (x, y);
self.cursor_sprite = to_sprite(self.cursor_hotspot)... | update_mouse_state | identifier_name |
screen.rs | use crate::portal::PortalRef;
use alloc::sync::Weak;
use cairo::bindings::{CAIRO_FORMAT_A8, CAIRO_FORMAT_ARGB32, CAIRO_FORMAT_RGB24};
use cairo::{Cairo, Surface};
use core::mem;
use graphics_base::frame_buffer::{AsSurface, AsSurfaceMut, FrameBuffer};
use graphics_base::types::{EventInput, MouseButton, MouseInputInfo, R... |
}
}
}
for input in inputs {
portal_ref.send_input(input)?;
}
}
let cr = self
.lfb
.as_surface_mut(CAIRO_FORMAT_ARGB32, self.screen_size)
.into_cairo();
cr.rectangle(prev_c... | {
self.input_capture = None;
} | conditional_block |
normalization.rs | // Copyright (c) 2016, ilammy
//
// Licensed under MIT license (see LICENSE file in the root directory).
// This file may be copied, distributed, and modified only in accordance
// with the terms specified by this license.
//! Unicode normalization algorithms.
//!
//! This module implements _Unicode Normalization Form... |
/// Check for a Primary Composite (D114) equivalent to the given pair of characters.
/// This is the second part of step R2 of the Canonical Composition Algorithm (D117).
fn primary_composite(c1: char, c2: char) -> Option<charcc> {
compose_hangul(c1, c2).or_else(|| composition_mappings::primary(c1, c2))
}
| {
assert!(ai < ci);
let ccc_a = slice[ai].ccc();
let ccc_c = slice[ci].ccc();
if ccc_a == 0 {
for bi in (ai + 1)..ci {
let ccc_b = slice[bi].ccc();
if (ccc_b == 0) || (ccc_b >= ccc_c) {
return true;
}
}
}
return false;
} | identifier_body |
normalization.rs | // Copyright (c) 2016, ilammy
//
// Licensed under MIT license (see LICENSE file in the root directory).
// This file may be copied, distributed, and modified only in accordance
// with the terms specified by this license.
//! Unicode normalization algorithms.
//!
//! This module implements _Unicode Normalization Form... | (slice: &[charcc], ci: usize) -> Option<usize> {
for li in (0..ci).rev() {
if slice[li].ccc() == 0 {
return Some(li);
}
}
return None;
}
/// Verify that A is not blocked (D115) from C in a character slice.
/// This is the first part of step R2 of the Canonical Composition Algori... | find_starter | identifier_name |
normalization.rs | // Copyright (c) 2016, ilammy
//
// Licensed under MIT license (see LICENSE file in the root directory).
// This file may be copied, distributed, and modified only in accordance
// with the terms specified by this license.
//! Unicode normalization algorithms.
//!
//! This module implements _Unicode Normalization Form... |
last_ccc = this_ccc;
}
return true;
}
//
// Decomposition
//
/// Produce a Compatibility decomposition (D65) of a character sequence.
fn compatibility_decomposition<I>(chars: I) -> Vec<charcc>
where I: IntoIterator<Item=char>
{
let mut buffer = Vec::new();
for c in chars {
push... | {
return false;
} | conditional_block |
normalization.rs | // Copyright (c) 2016, ilammy
//
// Licensed under MIT license (see LICENSE file in the root directory).
// This file may be copied, distributed, and modified only in accordance
// with the terms specified by this license. | //! This module implements _Unicode Normalization Forms_ as defined by [Unicode Standard
//! Annex #15][UAX-15]. Unicode normalization is used to ensure that visually equivalent
//! strings have equivalent binary representations.
//!
//! [UAX-15]: http://www.unicode.org/reports/tr15/
use std::iter::{FromIterator, Into... |
//! Unicode normalization algorithms.
//! | random_line_split |
generate_lockfile.rs | use std::env;
use cargo::ops;
use cargo::util::{CliResult, CliError, Config};
use cargo::util::important_paths::find_root_manifest_for_wd;
#[derive(RustcDecodable)]
struct | {
flag_manifest_path: Option<String>,
flag_verbose: bool,
flag_quiet: bool,
flag_color: Option<String>,
}
pub const USAGE: &'static str = "
Generate the lockfile for a project
Usage:
cargo generate-lockfile [options]
Options:
-h, --help Print this message
--manifest-path PA... | Options | identifier_name |
generate_lockfile.rs | use std::env;
use cargo::ops;
use cargo::util::{CliResult, CliError, Config};
use cargo::util::important_paths::find_root_manifest_for_wd;
#[derive(RustcDecodable)]
struct Options {
flag_manifest_path: Option<String>,
flag_verbose: bool,
flag_quiet: bool,
flag_color: Option<String>,
}
pub const USAGE... | debug!("executing; cmd=cargo-generate-lockfile; args={:?}", env::args().collect::<Vec<_>>());
try!(config.shell().set_verbosity(options.flag_verbose, options.flag_quiet));
try!(config.shell().set_color_config(options.flag_color.as_ref().map(|s| &s[..])));
let root = try!(find_root_manifest_for_wd(option... | pub fn execute(options: Options, config: &Config) -> CliResult<Option<()>> { | random_line_split |
generate_lockfile.rs | use std::env;
use cargo::ops;
use cargo::util::{CliResult, CliError, Config};
use cargo::util::important_paths::find_root_manifest_for_wd;
#[derive(RustcDecodable)]
struct Options {
flag_manifest_path: Option<String>,
flag_verbose: bool,
flag_quiet: bool,
flag_color: Option<String>,
}
pub const USAGE... | {
debug!("executing; cmd=cargo-generate-lockfile; args={:?}", env::args().collect::<Vec<_>>());
try!(config.shell().set_verbosity(options.flag_verbose, options.flag_quiet));
try!(config.shell().set_color_config(options.flag_color.as_ref().map(|s| &s[..])));
let root = try!(find_root_manifest_for_wd(opti... | identifier_body | |
access_control_max_age.rs | header! {
/// `Access-Control-Max-Age` header, part of
/// [CORS](http://www.w3.org/TR/cors/#access-control-max-age-response-header)
///
/// The `Access-Control-Max-Age` header indicates how long the results of a
/// preflight request can be cached in a preflight result cache.
///
/// # ABNF... | /// Access-Control-Max-Age = \"Access-Control-Max-Age\" \":\" delta-seconds
/// ```
///
/// # Example values
/// * `531`
///
/// # Examples
/// ```
/// use hyper::header::{Headers, AccessControlMaxAge};
///
/// let mut headers = Headers::new();
/// headers.set(AccessContr... | random_line_split | |
visible-private-types-generics.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 ... | > {
x: T
}
pub struct S2<T> where
T
: Foo //~ ERROR private trait in exported type parameter bound
{
x: T
}
pub enum E1<
T
: Foo //~ ERROR private trait in exported type parameter bound
> {
V1(T)
}
pub enum E2<T> where
T
: Foo //~ ERROR private trait in exported type parameter bou... | T
: Foo //~ ERROR private trait in exported type parameter bound | random_line_split |
visible-private-types-generics.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 ... | <
T
: Foo //~ ERROR private trait in exported type parameter bound
> {
x: T
}
pub struct S2<T> where
T
: Foo //~ ERROR private trait in exported type parameter bound
{
x: T
}
pub enum E1<
T
: Foo //~ ERROR private trait in exported type parameter bound
> {
V1(T)
}
pub enum E2<T> w... | S1 | identifier_name |
main.rs | // main.rs
// Main entry point for a dining philosophers,
// a concurrency problem.
//
// taken from the rust-lang tutorial:
// https://doc.rust-lang.org/stable/book/dining-philosophers.html
//
// vim: ft=rust sw=4 ts=4
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
// a philosopher struct
str... | (&self, table: &Table, pause: u32, repeat: u32) {
for x in 0..repeat {
thread::sleep(Duration::from_millis(u64::from(pause)));
println!("{} went to table for {}. time.", self.name, (x + 1));
self.eat(table);
}
}
}
struct Table {
forks: Vec<Mutex<()>>,
}
fn m... | mult_eat | identifier_name |
main.rs | // main.rs
// Main entry point for a dining philosophers,
// a concurrency problem.
//
// taken from the rust-lang tutorial:
// https://doc.rust-lang.org/stable/book/dining-philosophers.html
//
// vim: ft=rust sw=4 ts=4
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
// a philosopher struct
str... | let _right = table.forks[self.right].lock().unwrap();
println!("{} has started eating.", self.name);
thread::sleep(Duration::from_millis(1000));
println!("{} has finished eating.", self.name);
}
fn mult_eat(&self, table: &Table, pause: u32, repeat: u32) {
for x in 0..... | }
fn eat(&self, table: &Table) {
let _left = table.forks[self.left].lock().unwrap(); | random_line_split |
main.rs | // main.rs
// Main entry point for a dining philosophers,
// a concurrency problem.
//
// taken from the rust-lang tutorial:
// https://doc.rust-lang.org/stable/book/dining-philosophers.html
//
// vim: ft=rust sw=4 ts=4
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
// a philosopher struct
str... |
fn eat(&self, table: &Table) {
let _left = table.forks[self.left].lock().unwrap();
let _right = table.forks[self.right].lock().unwrap();
println!("{} has started eating.", self.name);
thread::sleep(Duration::from_millis(1000));
println!("{} has finished eating.", self.na... | {
Philosopher {
name: name.to_string(),
left,
right,
}
} | identifier_body |
font_template.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 style::computed_values::font_weight;
use platform::font_context::FontContextHandle;
use platform::font::FontHa... | },
None => {
let data = self.get_data();
let handle = FontHandleMethods::new_from_template(fctx, data.clone(), None);
let handle: FontHandle = match handle {
Ok(handle) => handle,
Err(()) => fail!("TODO - Han... | random_line_split | |
font_template.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 style::computed_values::font_weight;
use platform::font_context::FontContextHandle;
use platform::font::FontHa... | {
pub weight: font_weight::T,
pub italic: bool,
}
impl FontTemplateDescriptor {
pub fn new(weight: font_weight::T, italic: bool) -> FontTemplateDescriptor {
FontTemplateDescriptor {
weight: weight,
italic: italic,
}
}
}
impl PartialEq for FontTemplateDescriptor... | FontTemplateDescriptor | identifier_name |
advent16.rs | // advent16.rs
// find Aunt Sue
extern crate pcre;
use std::io;
fn main() {
loop {
let mut input = String::new();
let result = io::stdin().read_line(&mut input);
match result {
Ok(byte_count) => if byte_count == 0 { break; },
Err(_) => {
println!("e... |
fn check_match_equal(s: &str, property: &str, value: u32) -> bool {
check_match(s, property, value, |x,y| x == y)
}
// returns false if it has the property and it doesn't match the value
// returns true if the property doesn't exist or it exists but doesn't match
fn check_match<F>(s: &str, property: &str, value:... | {
check_match_equal(s, "children", 3)
&& check_match_equal(s, "cats", 7)
&& check_match_equal(s, "samoyeds", 2)
&& check_match_equal(s, "pomeranians", 3)
&& check_match_equal(s, "akitas", 0)
&& check_match_equal(s, "vizslas", 0)
&& check_match_equal(s, "goldfish", 5... | identifier_body |
advent16.rs | // advent16.rs
// find Aunt Sue
extern crate pcre;
use std::io;
fn main() {
loop {
let mut input = String::new();
let result = io::stdin().read_line(&mut input);
match result {
Ok(byte_count) => if byte_count == 0 { break; },
Err(_) => {
println!("e... | () {
let s = "junk, foo: 4, bar: 5";
assert!(check_match_equal(s, "foo", 4));
assert!(check_match_equal(s, "bar", 5));
assert!(!check_match_equal(s, "foo", 3));
assert!(check_match_equal(s, "string that isn't even there", 5));
}
// part 2
fn check_match_less(s: &str, property: &str, value: u32) -> ... | test_check_match_equal | identifier_name |
advent16.rs | // advent16.rs
// find Aunt Sue
extern crate pcre;
use std::io;
fn main() {
loop {
let mut input = String::new();
let result = io::stdin().read_line(&mut input);
match result {
Ok(byte_count) => if byte_count == 0 { break; },
Err(_) => {
println!("e... | else {
// property doesn't exist
true
}
}
#[test]
fn test_check_match_equal() {
let s = "junk, foo: 4, bar: 5";
assert!(check_match_equal(s, "foo", 4));
assert!(check_match_equal(s, "bar", 5));
assert!(!check_match_equal(s, "foo", 3));
assert!(check_match_equal(s, "string that ... | {
assert!(m.string_count() > 1);
f(m.group(1).parse::<u32>().unwrap(), value)
} | conditional_block |
advent16.rs | // advent16.rs
// find Aunt Sue
extern crate pcre;
use std::io;
fn main() {
loop {
let mut input = String::new();
let result = io::stdin().read_line(&mut input);
match result {
Ok(byte_count) => if byte_count == 0 { break; },
Err(_) => {
println!("e... | && check_match_equal(s, "perfumes", 1)
} | && check_match_equal(s, "akitas", 0)
&& check_match_equal(s, "vizslas", 0)
&& check_match_less(s, "goldfish", 5)
&& check_match_greater(s, "trees", 3)
&& check_match_equal(s, "cars", 2) | random_line_split |
mempty.rs | /*
* Copyright 2017 Sreejith Krishnan R
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed... |
} | {
self
} | identifier_body |
mempty.rs | /*
* Copyright 2017 Sreejith Krishnan R
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed... | () -> MemptyLayout {
MemptyLayout {}
}
}
impl Layout for MemptyLayout {
fn layout<'a>(&'a self, _: &Context) -> Box<Drawable + 'a> {
Box::new(Empty::new())
}
fn as_any(&self) -> &Any {
self
}
fn as_any_mut(&mut self) -> &mut Any {
self
}
} | new | identifier_name |
mempty.rs | /*
* Copyright 2017 Sreejith Krishnan R
*
* Licensed under the Apache License, Version 2.0 (the "License"); | * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under 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
* | random_line_split |
users.rs | #![crate_name = "users"]
#![feature(collections, core, old_io, rustc_private, std_misc)]
/*
* This file is part of the uutils coreutils package.
*
* (c) KokaKiwi <kokakiwi@kokakiwi.net>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
... | }
}
endutxent();
}
if users.len() > 0 {
users.sort();
println!("{}", users.connect(" "));
}
}
| {
unsafe {
utmpxname(CString::new(filename).unwrap().as_ptr());
}
let mut users = vec!();
unsafe {
setutxent();
loop {
let line = getutxent();
if line == ptr::null() {
break;
}
if (*line).ut_type == USER_PROCESS... | identifier_body |
users.rs | #![crate_name = "users"]
#![feature(collections, core, old_io, rustc_private, std_misc)]
/*
* This file is part of the uutils coreutils package.
*
* (c) KokaKiwi <kokakiwi@kokakiwi.net>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
... | (args: Vec<String>) -> i32 {
let program = args[0].as_slice();
let opts = [
getopts::optflag("h", "help", "display this help and exit"),
getopts::optflag("V", "version", "output version information and exit"),
];
let matches = match getopts::getopts(args.tail(), &opts) {
Ok(m) =... | uumain | identifier_name |
users.rs | #![crate_name = "users"]
#![feature(collections, core, old_io, rustc_private, std_misc)]
/*
* This file is part of the uutils coreutils package.
*
* (c) KokaKiwi <kokakiwi@kokakiwi.net>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
... | unsafe extern fn utmpxname(_file: *const libc::c_char) -> libc::c_int {
0
}
static NAME: &'static str = "users";
pub fn uumain(args: Vec<String>) -> i32 {
let program = args[0].as_slice();
let opts = [
getopts::optflag("h", "help", "display this help and exit"),
getopts::optflag("V", "vers... | }
#[cfg(target_os = "freebsd")] | random_line_split |
content_location.rs | header! {
/// `Content-Location` header, defined in
/// [RFC7231](https://tools.ietf.org/html/rfc7231#section-3.1.4.2)
///
/// The header can be used by both the client in requests and the server
/// in resposes with different semantics. Client sets `Content-Location`
/// to refer to the URI whe... | /// ```
/// use hyper::header::{Headers, ContentLocation};
///
/// let mut headers = Headers::new();
/// headers.set(ContentLocation("/hypertext/Overview.html".to_owned()));
/// ```
/// ```
/// use hyper::header::{Headers, ContentLocation};
///
/// let mut headers = Headers::new(... | /// * `http://www.example.org/hypertext/Overview.html`
///
/// # Examples
/// | random_line_split |
horiz.rs | use ascii_canvas::AsciiView;
use itertools::Itertools;
use super::*;
#[derive(Debug)]
pub struct Horiz {
items: Vec<Box<Content>>,
separate: usize, // 0 => overlapping, 1 => each on its own line, 2 => paragraphs
}
impl Horiz {
pub fn new(items: Vec<Box<Content>>, separate: usize) -> Self {
Horiz {... |
fn into_wrap_items(self: Box<Self>, wrap_items: &mut Vec<Box<Content>>) {
wrap_items.push(self);
}
}
pub fn emit_horiz(view: &mut AsciiView,
items: &[Box<Content>],
separate: usize)
{
let mut column = 0;
for item in items {
let (_, end_column) = ite... | {
emit_horiz(view, &self.items, self.separate);
} | identifier_body |
horiz.rs | use ascii_canvas::AsciiView; | use itertools::Itertools;
use super::*;
#[derive(Debug)]
pub struct Horiz {
items: Vec<Box<Content>>,
separate: usize, // 0 => overlapping, 1 => each on its own line, 2 => paragraphs
}
impl Horiz {
pub fn new(items: Vec<Box<Content>>, separate: usize) -> Self {
Horiz {
items: items,
... | random_line_split | |
horiz.rs | use ascii_canvas::AsciiView;
use itertools::Itertools;
use super::*;
#[derive(Debug)]
pub struct Horiz {
items: Vec<Box<Content>>,
separate: usize, // 0 => overlapping, 1 => each on its own line, 2 => paragraphs
}
impl Horiz {
pub fn new(items: Vec<Box<Content>>, separate: usize) -> Self {
Horiz {... | (self: Box<Self>, wrap_items: &mut Vec<Box<Content>>) {
wrap_items.push(self);
}
}
pub fn emit_horiz(view: &mut AsciiView,
items: &[Box<Content>],
separate: usize)
{
let mut column = 0;
for item in items {
let (_, end_column) = item.emit_at(view, 0, colum... | into_wrap_items | identifier_name |
htmlhrelement.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::RGBA;
use dom::bindings::codegen::Bindings::HTMLHRElementBinding::{self, HTMLHRElementMethods};
use... |
}
| {
match name {
&atom!("align") => AttrValue::from_dimension(value.into()),
&atom!("color") => AttrValue::from_legacy_color(value.into()),
&atom!("width") => AttrValue::from_dimension(value.into()),
_ => self.super_type().unwrap().parse_plain_attribute(name, value)... | identifier_body |
htmlhrelement.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::RGBA;
use dom::bindings::codegen::Bindings::HTMLHRElementBinding::{self, HTMLHRElementMethods};
use... | (localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLHRElement> {
Node::reflect_node(box HTMLHRElement::new_inherited(localName, prefix, document),
document,
HTMLHRElementBinding::Wrap)
}
}
impl HTM... | new | identifier_name |
htmlhrelement.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::RGBA;
use dom::bindings::codegen::Bindings::HTMLHRElementBinding::{self, HTMLHRElementMethods};
use... | }
impl HTMLHRElement {
fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLHRElement {
HTMLHRElement {
htmlelement: HTMLElement::new_inherited(localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: Atom,
... | random_line_split | |
mod.rs | //! Platform-specific extensions to `std` for Unix platforms.
//!
//! Provides access to platform-level information on Unix platforms, and
//! exposes Unix-specific functions that would otherwise be inappropriate as
//! part of the core `std` library.
//!
//! It exposes more ways to deal with platform-specific strings ... | #[doc(no_inline)]
#[stable(feature = "rust1", since = "1.0.0")]
pub use super::ffi::{OsStrExt, OsStringExt};
#[doc(no_inline)]
#[stable(feature = "rust1", since = "1.0.0")]
pub use super::fs::DirEntryExt;
#[doc(no_inline)]
#[stable(feature = "file_offset", since = "1.15.0")]
pub use ... | /// A prelude for conveniently writing platform-specific code.
///
/// Includes all extension traits, and some important type definitions.
#[stable(feature = "rust1", since = "1.0.0")]
pub mod prelude { | random_line_split |
shadowroot.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::Shado... | owner,
s,
StylesheetSetRef::Author(&mut self.author_styles.borrow_mut().stylesheets),
)
}
pub fn invalidate_stylesheets(&self) {
self.document.invalidate_shadow_roots_stylesheets();
self.author_styles.borrow_mut().stylesheets.force_dirty();
//... | /// Remove a stylesheet owned by `owner` from the list of shadow root sheets.
#[allow(unrooted_must_root)] // Owner needs to be rooted already necessarily.
pub fn remove_stylesheet(&self, owner: &Element, s: &Arc<Stylesheet>) {
DocumentOrShadowRoot::remove_stylesheet( | random_line_split |
shadowroot.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::Shado... |
}
elements
}
/// https://dom.spec.whatwg.org/#dom-shadowroot-mode
fn Mode(&self) -> ShadowRootMode {
ShadowRootMode::Closed
}
/// https://dom.spec.whatwg.org/#dom-shadowroot-host
fn Host(&self) -> DomRoot<Element> {
DomRoot::from_ref(&self.host)
}
// h... | {
elements.push(element);
} | conditional_block |
shadowroot.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::Shado... | (&self) {
self.document.invalidate_shadow_roots_stylesheets();
self.author_styles.borrow_mut().stylesheets.force_dirty();
// Mark the host element dirty so a reflow will be performed.
self.host
.upcast::<Node>()
.dirty(NodeDamage::NodeStyleDamaged);
}
/// R... | invalidate_stylesheets | identifier_name |
shadowroot.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::Shado... |
/// https://dom.spec.whatwg.org/#dom-shadowroot-host
fn Host(&self) -> DomRoot<Element> {
DomRoot::from_ref(&self.host)
}
// https://drafts.csswg.org/cssom/#dom-document-stylesheets
fn StyleSheets(&self) -> DomRoot<StyleSheetList> {
self.stylesheet_list.or_init(|| {
St... | {
ShadowRootMode::Closed
} | identifier_body |
connected.rs | use super::*;
use std::mem::forget;
use std::ops::Deref;
use std::ptr;
use std::thread::panicking;
use std::marker::PhantomData;
/// State used by `Connected`. Means that autocommit is enabled
#[derive(Debug)]
#[allow(missing_copy_implementations)]
pub enum AutocommitOn {}
/// State used by `Connected`. Means that au... | ,
}
}
}
impl<'env, AC: AutocommitMode> Connected<'env, AC> {
/// Releases inner Connection Handle without calling disconnect.
pub fn into_hdbc(self) -> HDbc<'env> {
unsafe {
let hdbc = ptr::read(&self.0);
forget(self); // do not call drop
hdbc
}
... | {
panic!("SQLDisconnect returned error")
} | conditional_block |
connected.rs | use super::*;
use std::mem::forget;
use std::ops::Deref;
use std::ptr;
use std::thread::panicking;
use std::marker::PhantomData;
/// State used by `Connected`. Means that autocommit is enabled
#[derive(Debug)]
#[allow(missing_copy_implementations)]
pub enum AutocommitOn {}
/// State used by `Connected`. Means that au... | }
impl<'env, AC: AutocommitMode> Connected<'env, AC> {
/// Releases inner Connection Handle without calling disconnect.
pub fn into_hdbc(self) -> HDbc<'env> {
unsafe {
let hdbc = ptr::read(&self.0);
forget(self); // do not call drop
hdbc
}
}
}
impl<'env,... | panic!("SQLDisconnect returned error")
},
}
} | random_line_split |
connected.rs | use super::*;
use std::mem::forget;
use std::ops::Deref;
use std::ptr;
use std::thread::panicking;
use std::marker::PhantomData;
/// State used by `Connected`. Means that autocommit is enabled
#[derive(Debug)]
#[allow(missing_copy_implementations)]
pub enum AutocommitOn {}
/// State used by `Connected`. Means that au... |
}
impl<'env, AC: AutocommitMode> DerefMut for Connected<'env, AC> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<'env, AC: AutocommitMode> HDbcWrapper<'env> for Connected<'env, AC> {
type Handle = Connected<'env, AC>;
fn into_hdbc(self) -> HDbc<'env> {
self.int... | {
&self.0
} | identifier_body |
connected.rs | use super::*;
use std::mem::forget;
use std::ops::Deref;
use std::ptr;
use std::thread::panicking;
use std::marker::PhantomData;
/// State used by `Connected`. Means that autocommit is enabled
#[derive(Debug)]
#[allow(missing_copy_implementations)]
pub enum | {}
/// State used by `Connected`. Means that autocommit is disabled
#[derive(Debug)]
#[allow(missing_copy_implementations)]
pub enum AutocommitOff {}
/// Marker trait for autocommit mode state types
pub trait AutocommitMode {}
impl AutocommitMode for AutocommitOn {}
impl AutocommitMode for AutocommitOff {}
/// An ... | AutocommitOn | identifier_name |
normal.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <R: Rng>(&self, rng: &mut R) -> f64 {
self.norm.ind_sample(rng).exp()
}
}
#[cfg(test)]
mod tests {
use distributions::{Sample, IndependentSample};
use super::{Normal, LogNormal};
#[test]
fn test_normal() {
let mut norm = Normal::new(10.0, 10.0);
let mut rng = ::test::rng();... | ind_sample | identifier_name |
normal.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | else { ziggurat_tables::ZIG_NORM_R - x }
}
StandardNormal(ziggurat(
rng,
true, // this is symmetric
&ziggurat_tables::ZIG_NORM_X,
&ziggurat_tables::ZIG_NORM_F,
pdf, zero_case))
}
}
/// The normal distribution `N(mean, std_dev**2)`.
///
/... | { x - ziggurat_tables::ZIG_NORM_R } | conditional_block |
normal.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
/// The log-normal distribution `ln N(mean, std_dev**2)`.
///
/// If `X` is log-normal distributed, then `ln(X)` is `N(mean,
/// std_dev**2)` distributed.
///
/// # Example
///
/// ```rust
/// use rand::distributions::{LogNormal, IndependentSample};
///
/// // mean 2, standard deviation 3
/// let log_normal = LogNo... | fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 {
let StandardNormal(n) = rng.gen::<StandardNormal>();
self.mean + self.std_dev * n
} | random_line_split |
normal.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
impl Sample<f64> for Normal {
fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) }
}
impl IndependentSample<f64> for Normal {
fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 {
let StandardNormal(n) = rng.gen::<StandardNormal>();
self.mean + self.std_dev * n
}
}
///... | {
assert!(std_dev >= 0.0, "Normal::new called with `std_dev` < 0");
Normal {
mean: mean,
std_dev: std_dev
}
} | identifier_body |
coerce-match.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 _: Box<[int]> = if true { box [1i, 2, 3] } else { box [1i] };
let _: Box<[int]> = match true { true => box [1i, 2, 3], false => box [1i] };
// Check we don't get over-keen at propagating coercions in the case of casts.
let x = if true { 42 } else { 42u8 } as u16;
let x = match true { true... | main | identifier_name |
coerce-match.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 _: Box<[int]> = if true { box [1i, 2, 3] } else { box [1i] };
let _: Box<[int]> = match true { true => box [1i, 2, 3], false => box [1i] };
// Check we don't get over-keen at propagating coercions in the case of casts.
let x = if true { 42 } else { 42u8 } as u16;
let x = match true { true =>... | identifier_body | |
coerce-match.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 | // except according to those terms.
// Check that coercions are propagated through match and if expressions.
#![allow(unknown_features)]
#![feature(box_syntax)]
pub fn main() {
let _: Box<[int]> = if true { box [1i, 2, 3] } else { box [1i] };
let _: Box<[int]> = match true { true => box [1i, 2, 3], false =>... | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed | random_line_split |
coerce-match.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 ... | else { box [1i] };
let _: Box<[int]> = match true { true => box [1i, 2, 3], false => box [1i] };
// Check we don't get over-keen at propagating coercions in the case of casts.
let x = if true { 42 } else { 42u8 } as u16;
let x = match true { true => 42, false => 42u8 } as u16;
}
| { box [1i, 2, 3] } | conditional_block |
lib.rs | //! An entity component system based on changesets.
//!
//! # Definition
//!
//! An entity component system is a game architecture pattern where you separate data
//! from logic.
//!
//! In this design, an **entity** is a unique id, **components** are any data | //! they directly act on entitie's components to make the world alive.
//!
//! # Design
//!
//! At its heart, Glue is based on immutable **components** and **changesets**.
//! This mean that when you want to modify a component
//! you don't modify the current component.
//! Instead, you push modifications that build up... | //! that you want to attach to an entity like a position in the game world.
//! Processes (glue's **systems**), are the logic of the game | random_line_split |
token.rs | ), string=s.as_slice().to_ascii().as_str_ascii())
}
/* Name components */
IDENT(s, _) => get_ident(s).get().to_string(),
LIFETIME(s) => {
format!("{}", get_ident(s))
}
UNDERSCORE => "_".to_string(),
/* Other */
DOC_COMMENT(s) => get_ident(s).get().to_string(),... | {
match *tok {
token::IDENT(sid, false) => match sid.name {
SELF_KEYWORD_NAME | STATIC_KEYWORD_NAME |
STRICT_KEYWORD_START .. RESERVED_KEYWORD_FINAL => true,
_ => false,
},
_ => false
}
} | identifier_body | |
token.rs | Box<ast::Path>),
NtTT( Gc<ast::TokenTree>), // needs @ed to break a circularity
NtMatchers(Vec<ast::Matcher> )
}
impl fmt::Show for Nonterminal {
fn | (&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
NtItem(..) => f.pad("NtItem(..)"),
NtBlock(..) => f.pad("NtBlock(..)"),
NtStmt(..) => f.pad("NtStmt(..)"),
NtPat(..) => f.pad("NtPat(..)"),
NtExpr(..) => f.pad("NtExpr(..)"),
Nt... | fmt | identifier_name |
token.rs | // except according to those terms.
use ast;
use ast::{P, Ident, Name, Mrk};
use ast_util;
use ext::mtwt;
use parse::token;
use util::interner::{RcStr, StrInterner};
use util::interner;
use serialize::{Decodable, Decoder, Encodable, Encoder};
use std::fmt;
use std::gc::Gc;
use std::mem;
use std::path::BytesContainer;... | //
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed | random_line_split | |
grafana_chart.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use seed::{attrs, iframe, prelude::*};
use std::collections::BTreeMap;
pub static IML_METRICS_DASHBOARD_ID: &str = "8Klek6wZz";
pub static IML_METRICS_DASHBOARD_NAME:... | (
panel_id: u16,
refresh: &str,
vars: impl IntoIterator<Item = (impl ToString, impl ToString)>,
) -> GrafanaChartData {
let hm: BTreeMap<String, String> = vars
.into_iter()
.map(|(x, y)| {
let var = x.to_string();
let key = match var.as_str() {
"to" ... | create_chart_params | identifier_name |
grafana_chart.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use seed::{attrs, iframe, prelude::*};
use std::collections::BTreeMap;
pub static IML_METRICS_DASHBOARD_ID: &str = "8Klek6wZz";
pub static IML_METRICS_DASHBOARD_NAME:... | height: &str,
) -> Node<T> {
iframe![attrs! {
At::Src => format!("/grafana/d-solo/{}/{}?kiosk&{}", dashboard_id, dashboard_name, serde_urlencoded::to_string(chart_data).unwrap()),
At::Width => "100%",
At::Height => height,
"frameborder" => 0
}]
} | dashboard_name: &str,
chart_data: GrafanaChartData<'a>, | random_line_split |
panic-runtime-unwind2.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 ... |
#[no_mangle]
pub extern fn rust_eh_personality() {}
| {} | identifier_body |
panic-runtime-unwind2.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 ... | () {}
| rust_eh_personality | identifier_name |
panic-runtime-unwind2.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 ... | // option. This file may not be copied, modified, or distributed
// except according to those terms.
// compile-flags:-C panic=unwind
// no-prefer-dynamic
#![feature(panic_runtime)]
#![crate_type = "rlib"]
#![no_std]
#![panic_runtime]
#[no_mangle]
pub extern fn __rust_maybe_catch_panic() {}
#[no_mangle]
pub extern... | random_line_split | |
indexing.rs | use numeric::Tensor;
macro_rules! add_impl {
($t:ty, $m:ident) => (
mod $m {
use numeric::Tensor;
type T = Tensor<$t>;
/*
#[test]
fn indexing() {
let t = T::range(6);
let v = t[2];
assert_eq!(v, 2.0... | () {
let t: Tensor<f64> = Tensor::zeros(&[3, 4, 5, 6]);
assert_eq!(t.ravel_index(&[0, 1, 0, 3]), 33);
assert_eq!(t.ravel_index(&[0, 1, 4, 3]), 57);
assert_eq!(t.ravel_index(&[1, 1, 4, 1]), 175);
assert_eq!(t.ravel_index(&[2, 2, 0, 0]), 300);
}
#[test]
fn unravel_index() {
let t: Tensor<f64> = T... | ravel_index | identifier_name |
indexing.rs | use numeric::Tensor;
macro_rules! add_impl {
($t:ty, $m:ident) => (
mod $m {
use numeric::Tensor;
type T = Tensor<$t>;
/*
#[test]
fn indexing() {
let t = T::range(6);
let v = t[2];
assert_eq!(v, 2.0... |
#[test]
fn unravel_index() {
let t: Tensor<f64> = Tensor::zeros(&[3, 4, 5, 6]);
assert_eq!(t.unravel_index(33), vec![0, 1, 0, 3]);
assert_eq!(t.unravel_index(57), vec![0, 1, 4, 3]);
assert_eq!(t.unravel_index(175), vec![1, 1, 4, 1]);
assert_eq!(t.unravel_index(300), vec![2, 2, 0, 0]);
}
| {
let t: Tensor<f64> = Tensor::zeros(&[3, 4, 5, 6]);
assert_eq!(t.ravel_index(&[0, 1, 0, 3]), 33);
assert_eq!(t.ravel_index(&[0, 1, 4, 3]), 57);
assert_eq!(t.ravel_index(&[1, 1, 4, 1]), 175);
assert_eq!(t.ravel_index(&[2, 2, 0, 0]), 300);
} | identifier_body |
indexing.rs | use numeric::Tensor;
macro_rules! add_impl {
($t:ty, $m:ident) => (
mod $m {
use numeric::Tensor;
type T = Tensor<$t>;
/*
#[test]
fn indexing() {
let t = T::range(6);
let v = t[2];
assert_eq!(v, 2.0... | #[test]
fn ravel_index() {
let t: Tensor<f64> = Tensor::zeros(&[3, 4, 5, 6]);
assert_eq!(t.ravel_index(&[0, 1, 0, 3]), 33);
assert_eq!(t.ravel_index(&[0, 1, 4, 3]), 57);
assert_eq!(t.ravel_index(&[1, 1, 4, 1]), 175);
assert_eq!(t.ravel_index(&[2, 2, 0, 0]), 300);
}
#[test]
fn unravel_index() {
... | // Ravelling and unravelling indices
| random_line_split |
namednodemap.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::attr::Attr;
use dom::bindings::codegen::Bindings::NamedNodeMapBinding;
use dom::bindings::codegen::Bindin... | (self, name: DOMString) -> Option<Temporary<Attr>> {
let owner = self.owner.root();
// FIXME(https://github.com/rust-lang/rust/issues/23338)
let owner = owner.r();
owner.get_attribute_by_name(name)
}
// https://dom.spec.whatwg.org/#dom-namednodemap-getnameditemns
fn GetNamed... | GetNamedItem | identifier_name |
namednodemap.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::attr::Attr;
use dom::bindings::codegen::Bindings::NamedNodeMapBinding;
use dom::bindings::codegen::Bindin... |
}
| {
let item = self.GetNamedItem(name);
*found = item.is_some();
item
} | identifier_body |
namednodemap.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::attr::Attr;
use dom::bindings::codegen::Bindings::NamedNodeMapBinding;
use dom::bindings::codegen::Bindin... | use dom::window::Window;
use util::namespace;
use util::str::DOMString;
use string_cache::Atom;
#[dom_struct]
pub struct NamedNodeMap {
reflector_: Reflector,
owner: JS<Element>,
}
impl NamedNodeMap {
fn new_inherited(elem: JSRef<Element>) -> NamedNodeMap {
NamedNodeMap {
reflector_: ... | use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, JSRef, Temporary};
use dom::bindings::utils::{Reflector, reflect_dom_object};
use dom::element::{AttributeHandlers, Element, ElementHelpers}; | random_line_split |
lib.rs | //! Crate which contain the virtual machine which executes gluon programs
#![doc(html_root_url = "https://docs.rs/gluon_vm/0.18.0")] // # GLUON
#![recursion_limit = "1024"]
#[macro_use]
extern crate collect_mac;
#[doc(hidden)]
pub extern crate frunk_core;
#[macro_use]
extern crate log;
#[macro_use]
extern crate quick_... | }
}
/// Internal types and functions exposed to the main `gluon` crate
pub mod internal {
pub use crate::interner::InternedStr;
pub use crate::value::{Cloner, ClosureData, Value, ValuePrinter};
pub use crate::vm::Global;
} | random_line_split | |
lib.rs | //! Crate which contain the virtual machine which executes gluon programs
#![doc(html_root_url = "https://docs.rs/gluon_vm/0.18.0")] // # GLUON
#![recursion_limit = "1024"]
#[macro_use]
extern crate collect_mac;
#[doc(hidden)]
pub extern crate frunk_core;
#[macro_use]
extern crate log;
#[macro_use]
extern crate quick_... |
}
/// Type returned from vm functions which may fail
pub type Result<T> = ::std::result::Result<T, Error>;
quick_error! {
/// Representation of all possible errors that can occur when interacting with the `vm` crate
#[derive(Debug, Eq, PartialEq, Hash, Clone)]
pub enum Error {
Dead {
... | {
unsafe { ValueRef::rooted_new(&self.0) }
} | identifier_body |
lib.rs | //! Crate which contain the virtual machine which executes gluon programs
#![doc(html_root_url = "https://docs.rs/gluon_vm/0.18.0")] // # GLUON
#![recursion_limit = "1024"]
#[macro_use]
extern crate collect_mac;
#[doc(hidden)]
pub extern crate frunk_core;
#[macro_use]
extern crate log;
#[macro_use]
extern crate quick_... | (&self, _map: &base::source::CodeMap) -> Diagnostic<FileId> {
Diagnostic::error().with_message(self.to_string())
}
}
struct Panic<'a> {
err: &'a String,
stacktrace: &'a Option<Stacktrace>,
}
impl<'a> fmt::Display for Panic<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
le... | as_diagnostic | identifier_name |
lib.rs | //! Crate which contain the virtual machine which executes gluon programs
#![doc(html_root_url = "https://docs.rs/gluon_vm/0.18.0")] // # GLUON
#![recursion_limit = "1024"]
#[macro_use]
extern crate collect_mac;
#[doc(hidden)]
pub extern crate frunk_core;
#[macro_use]
extern crate log;
#[macro_use]
extern crate quick_... |
Ok(())
}
}
impl fmt::Debug for ExternLoader {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("ExternLoader")
.field("dependencies", &self.dependencies)
.finish()
}
}
pub struct ExternLoader {
pub load_fn: Box<dyn Fn(&Thread) -> Result<Exter... | {
write!(f, "\n\n{}", stacktrace)?;
} | conditional_block |
associated-types-struct-field-numbered.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 node: Node<i32> = Node(1, Some(22));
assert_eq!(foo(&node), Some(22_u32));
let node: Node<u32> = Node(1, Some(22));
assert_eq!(foo(&node), Some(22_i32));
} | identifier_body | |
associated-types-struct-field-numbered.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 ... | <K : UnifyKey<Value=Option<V>>,V : Clone>(node: &Node<K>) -> Option<V> {
node.1.clone()
}
impl UnifyKey for i32 {
type Value = Option<u32>;
}
impl UnifyKey for u32 {
type Value = Option<i32>;
}
pub fn main() {
let node: Node<i32> = Node(1, Some(22));
assert_eq!(foo(&node), Some(22_u32));
let... | foo | identifier_name |
associated-types-struct-field-numbered.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 node: Node<u32> = Node(1, Some(22));
assert_eq!(foo(&node), Some(22_i32));
} | pub fn main() {
let node: Node<i32> = Node(1, Some(22));
assert_eq!(foo(&node), Some(22_u32)); | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.