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 |
|---|---|---|---|---|
skin.rs | // Copyright 2015 Birunthan Mohanathas
//
// Licensed under the MIT license <http://opensource.org/licenses/MIT>. This
// file may not be copied, modified, or distributed except according to those
// terms.
use measure::Measureable;
pub struct Skin<'a> {
name: String,
measures: Vec<Box<Measureable<'a> + 'a>>,... |
#[test]
fn test_add_measure() {
use time_measure::TimeMeasure;
let mut skin = Skin::new("skin");
skin.add_measure(Box::new(TimeMeasure::new("foo")));
assert_eq!(1, skin.measures().len());
}
| {
let skin = Skin::new("skin");
assert_eq!("skin", skin.name());
} | identifier_body |
skin.rs | // Copyright 2015 Birunthan Mohanathas
//
// Licensed under the MIT license <http://opensource.org/licenses/MIT>. This
// file may not be copied, modified, or distributed except according to those
// terms.
use measure::Measureable;
pub struct Skin<'a> {
name: String,
measures: Vec<Box<Measureable<'a> + 'a>>,... | pub fn name(&self) -> &str {
self.name.as_slice()
}
pub fn add_measure(&mut self, measure: Box<Measureable<'a> + 'a>) {
self.measures.push(measure);
}
pub fn measures(&self) -> &Vec<Box<Measureable<'a> + 'a>> {
&self.measures
}
}
#[test]
fn test_name() {
let skin =... | random_line_split | |
mod.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 ... | }
/// A trait for viewing representations from std types
#[doc(hidden)]
pub trait AsInnerMut<Inner:?Sized> {
fn as_inner_mut(&mut self) -> &mut Inner;
}
/// A trait for extracting representations from std types
#[doc(hidden)]
pub trait IntoInner<Inner> {
fn into_inner(self) -> Inner;
}
/// A trait for creati... |
/// A trait for viewing representations from std types
#[doc(hidden)]
pub trait AsInner<Inner: ?Sized> {
fn as_inner(&self) -> &Inner; | random_line_split |
demo.rs | #!/usr/bin/env run-cargo-script
//! ```cargo
//! [dependencies]
//! unixbar = "0"
//! systemstat = "0"
//! ```
#[macro_use]
extern crate unixbar;
extern crate systemstat;
use systemstat::{Platform, System};
use unixbar::*;
fn main() {
UnixBar::new(I3BarFormatter::new())
.add(Volume::new(default_volume(),
... | else {
bfmt![click[MouseButton::Left => sh "rhythmbox"]
fg["#bbbbbb"] text["[start music]"]]
}
}
))
.add(Text::new(bfmt![click[MouseButton::Left => sh "notify-send hi"]
click[MouseButton::Right => sh ... | {
bfmt![
fg["#bbbbbb"]
multi[
(click[MouseButton::Left => fn "prev"] no_sep text["[|<]"]),
(click[MouseButton::Left => fn "play_pause"]
no_sep text[if playing { "[||]"... | conditional_block |
demo.rs | #!/usr/bin/env run-cargo-script
//! ```cargo
//! [dependencies]
//! unixbar = "0"
//! systemstat = "0"
//! ```
#[macro_use]
extern crate unixbar;
extern crate systemstat;
use systemstat::{Platform, System};
use unixbar::*;
fn main() | (click[MouseButton::Left => fn "prev"] no_sep text["[|<]"]),
(click[MouseButton::Left => fn "play_pause"]
no_sep text[if playing { "[||]" } else { "[>]" }]),
(click[MouseButton::Left => sh format!("firefox '... | {
UnixBar::new(I3BarFormatter::new())
.add(Volume::new(default_volume(),
|volume|
match volume.muted {
false => bfmt![fmt["Volume {}", (volume.volume * 100.0) as i32]],
true => bfmt![fmt["(muted) {}", (volume.volume * 100.0) as i32]]
... | identifier_body |
demo.rs | #!/usr/bin/env run-cargo-script
//! ```cargo
//! [dependencies]
//! unixbar = "0"
//! systemstat = "0"
//! ```
#[macro_use]
extern crate unixbar;
extern crate systemstat;
use systemstat::{Platform, System};
use unixbar::*;
fn | () {
UnixBar::new(I3BarFormatter::new())
.add(Volume::new(default_volume(),
|volume|
match volume.muted {
false => bfmt![fmt["Volume {}", (volume.volume * 100.0) as i32]],
true => bfmt![fmt["(muted) {}", (volume.volume * 100.0) as i32]]
... | main | identifier_name |
demo.rs | #!/usr/bin/env run-cargo-script
//! ```cargo
//! [dependencies]
//! unixbar = "0"
//! systemstat = "0"
//! ```
#[macro_use]
extern crate unixbar;
extern crate systemstat;
use systemstat::{Platform, System};
use unixbar::*;
fn main() {
UnixBar::new(I3BarFormatter::new())
.add(Volume::new(default_volume(),
... | .register_fn("play_pause", move || { MPRISMusic::new().play_pause(); })
.register_fn("next", move || { MPRISMusic::new().next(); })
.add(Music::new(MPRISMusic::new(),
|song| {
if let Some(playing) = song.playback.map(|playback| playback.playing) {
bfm... | random_line_split | |
pattern-tyvar-2.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 ... | () { }
| main | identifier_name |
pattern-tyvar-2.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 ... | //~ ERROR binary operation * cannot be applied to
fn main() { }
| { match t { t1(_, Some(x)) => { return x * 3; } _ => { fail!(); } } } | identifier_body |
pattern-tyvar-2.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 ... | enum bar { t1((), Option<~[int]>), t2, }
// n.b. my change changes this error message, but I think it's right -- tjc
fn foo(t: bar) -> int { match t { t1(_, Some(x)) => { return x * 3; } _ => { fail!(); } } } //~ ERROR binary operation * cannot be applied to
fn main() { } | random_line_split | |
htmlpreelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLPreElementBinding;
use dom::bindings::js::Root;
use dom::document::Docum... |
}
| {
Node::reflect_node(box HTMLPreElement::new_inherited(local_name, prefix, document),
document,
HTMLPreElementBinding::Wrap)
} | identifier_body |
htmlpreelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLPreElementBinding;
use dom::bindings::js::Root;
use dom::document::Docum... | }
}
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalName,
prefix: Option<Prefix>,
document: &Document) -> Root<HTMLPreElement> {
Node::reflect_node(box HTMLPreElement::new_inherited(local_name, prefix, document),
document,
... | htmlelement:
HTMLElement::new_inherited(local_name, prefix, document) | random_line_split |
htmlpreelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLPreElementBinding;
use dom::bindings::js::Root;
use dom::document::Docum... | (local_name: LocalName,
prefix: Option<Prefix>,
document: &Document) -> Root<HTMLPreElement> {
Node::reflect_node(box HTMLPreElement::new_inherited(local_name, prefix, document),
document,
HTMLPreElementBinding::Wrap)
}
}
| new | identifier_name |
simple.rs | // SPDX-License-Identifier: MIT
use orbclient::{Color, EventOption, GraphicsPath, Mode, Renderer, Window};
fn main() | 0,
0,
(win_w / 3) as i32,
(win_h / 2) as i32,
Color::rgb(128, 128, 128),
Color::rgb(255, 255, 255),
);
// horizontal gradient
window.linear_gradient(
(win_w / 3) as i32,
0,
win_w / 3,
win_h,
(win_w / 3) as i32,
0... | {
let (width, height) = orbclient::get_display_size().unwrap();
let mut window = Window::new(
(width as i32) / 4,
(height as i32) / 4,
width / 2,
height / 2,
"TITLE",
)
.unwrap();
let (win_w, win_h) = (width / 2, height / 2);
// top left -> bottom rigth... | identifier_body |
simple.rs | // SPDX-License-Identifier: MIT
use orbclient::{Color, EventOption, GraphicsPath, Mode, Renderer, Window};
fn | () {
let (width, height) = orbclient::get_display_size().unwrap();
let mut window = Window::new(
(width as i32) / 4,
(height as i32) / 4,
width / 2,
height / 2,
"TITLE",
)
.unwrap();
let (win_w, win_h) = (width / 2, height / 2);
// top left -> bottom rig... | main | identifier_name |
simple.rs | // SPDX-License-Identifier: MIT
use orbclient::{Color, EventOption, GraphicsPath, Mode, Renderer, Window};
fn main() {
let (width, height) = orbclient::get_display_size().unwrap();
let mut window = Window::new(
(width as i32) / 4,
(height as i32) / 4,
width / 2,
height / 2,
... | window.sync();
'events: loop {
for event in window.events() {
match event.to_option() {
EventOption::Quit(_quit_event) => break 'events,
EventOption::Mouse(evt) => println!(
"At position {:?} pixel color is : {:?}",
(ev... | window.box_blur(170, 100, 150, 150, 10);
//Draw a shadow around a box
window.box_shadow(170, 100, 150, 150, 0, 0, 20, Color::rgba(0, 0, 0, 255));
| random_line_split |
lib.rs | #![warn(missing_docs, missing_debug_implementations)]
//! EGL utilities
//!
//! This module contains bindings to the `libwayland-egl.so` library.
//!
//! This library is used to interface with the OpenGL stack, and creating
//! EGL surfaces from a wayland surface. |
use std::os::raw::c_void;
use wayland_backend::{client::InvalidId, sys::client::ObjectId};
use wayland_sys::{client::wl_proxy, egl::*, ffi_dispatch};
/// Checks if the wayland-egl lib is available and can be used
///
/// Trying to create an `WlEglSurface` while this function returns
/// `false` will result in a pani... | //!
//! See WlEglSurface documentation for details. | random_line_split |
lib.rs | #![warn(missing_docs, missing_debug_implementations)]
//! EGL utilities
//!
//! This module contains bindings to the `libwayland-egl.so` library.
//!
//! This library is used to interface with the OpenGL stack, and creating
//! EGL surfaces from a wayland surface.
//!
//! See WlEglSurface documentation for details.
u... |
/// Create an EGL surface from a raw pointer to a wayland surface
///
/// # Safety
///
/// The provided pointer must be a valid `wl_surface` pointer from `libwayland-client`.
pub unsafe fn new_from_raw(surface: *mut wl_proxy, width: i32, height: i32) -> WlEglSurface {
let ptr = ffi_dis... | {
if surface.interface().name != "wl_surface" {
return Err(InvalidId);
}
let ptr = surface.as_ptr();
if ptr.is_null() {
Err(InvalidId)
} else {
Ok(unsafe { WlEglSurface::new_from_raw(ptr, width, height) })
}
} | identifier_body |
lib.rs | #![warn(missing_docs, missing_debug_implementations)]
//! EGL utilities
//!
//! This module contains bindings to the `libwayland-egl.so` library.
//!
//! This library is used to interface with the OpenGL stack, and creating
//! EGL surfaces from a wayland surface.
//!
//! See WlEglSurface documentation for details.
u... | (&self) -> *const c_void {
self.ptr as *const c_void
}
}
impl Drop for WlEglSurface {
fn drop(&mut self) {
unsafe {
ffi_dispatch!(WAYLAND_EGL_HANDLE, wl_egl_window_destroy, self.ptr);
}
}
}
| ptr | identifier_name |
lib.rs | #![warn(missing_docs, missing_debug_implementations)]
//! EGL utilities
//!
//! This module contains bindings to the `libwayland-egl.so` library.
//!
//! This library is used to interface with the OpenGL stack, and creating
//! EGL surfaces from a wayland surface.
//!
//! See WlEglSurface documentation for details.
u... |
}
/// Create an EGL surface from a raw pointer to a wayland surface
///
/// # Safety
///
/// The provided pointer must be a valid `wl_surface` pointer from `libwayland-client`.
pub unsafe fn new_from_raw(surface: *mut wl_proxy, width: i32, height: i32) -> WlEglSurface {
let ptr = f... | {
Ok(unsafe { WlEglSurface::new_from_raw(ptr, width, height) })
} | conditional_block |
home.rs | ///Tässä tiedostossa luodaan routeri "/" polulle. Jos käyttäjä on kirjautuneena, näytetään omat
///tapahtumat, suosituimmat tapahtumat, lippukunnan tapahtumat ja hallinoimat tapahtumat. Jos ei ole, kerrotaan mikä on Silmukka ja ohjataan
///rekisteröitymään
use nickel::{Nickel, HttpRouter};
use nickel::router::router::... | erverData>{
let mut home: Router<ServerData> = Nickel::router();
home.get("/", middleware!{|req, mut vastaus|
let mut palautetaan = HashMap::new();
let logged = match *CookieSession::get_mut(req, &mut vastaus){
Some(_) => true,
_ => false
};
if logged =... | ter<S | identifier_name |
home.rs | ///Tässä tiedostossa luodaan routeri "/" polulle. Jos käyttäjä on kirjautuneena, näytetään omat
///tapahtumat, suosituimmat tapahtumat, lippukunnan tapahtumat ja hallinoimat tapahtumat. Jos ei ole, kerrotaan mikä on Silmukka ja ohjataan
///rekisteröitymään
use nickel::{Nickel, HttpRouter};
use nickel::router::router::... | let mut user = "/user/".to_string();
// otetaan käyttäjänimi
{let ref a: Option<String> = *CookieSession::get_mut(req, &mut vastaus);
user.push_str(&(a.clone().unwrap()));}
palautetaan.insert("kirjaudu".to_string(), "Kirjaudu ulos".to_string());
... | if logged == false{
palautetaan.insert("kirjaudu".to_string(), "Kirjaudu sisään".to_string());
return vastaus.render("assets/out_index.html", &palautetaan);
}
else{ | random_line_split |
home.rs | ///Tässä tiedostossa luodaan routeri "/" polulle. Jos käyttäjä on kirjautuneena, näytetään omat
///tapahtumat, suosituimmat tapahtumat, lippukunnan tapahtumat ja hallinoimat tapahtumat. Jos ei ole, kerrotaan mikä on Silmukka ja ohjataan
///rekisteröitymään
use nickel::{Nickel, HttpRouter};
use nickel::router::router::... | });
return home;
}
| t home: Router<ServerData> = Nickel::router();
home.get("/", middleware!{|req, mut vastaus|
let mut palautetaan = HashMap::new();
let logged = match *CookieSession::get_mut(req, &mut vastaus){
Some(_) => true,
_ => false
};
if logged == false{
p... | identifier_body |
mod.rs | // Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co
//
// This file is part of cancer.
//
// cancer 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
// (a... | pub mod cursor;
pub use self::cursor::Cursor;
pub mod grid;
pub use self::grid::Grid;
mod tabs;
pub use self::tabs::Tabs;
mod input;
pub use self::input::Input;
mod sixel;
pub use self::sixel::Sixel;
mod terminal;
pub use self::terminal::Terminal; | pub mod mode;
pub use self::mode::Mode;
| random_line_split |
io.rs | // This file is part of zinc64.
// Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved.
// Licensed under the GPLv3. See LICENSE file in the project root for full license text.
#[cfg(not(feature = "std"))]
use alloc::prelude::*;
use byteorder::ByteOrder;
use core::result;
pub type Result<T> = result::R... |
}
impl<R: Reader +?Sized> ReadBytesExt for R {}
| {
let mut buf = [0; 4];
self.read_exact(&mut buf)?;
Ok(T::read_u32(&buf))
} | identifier_body |
io.rs | // This file is part of zinc64. | // Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved.
// Licensed under the GPLv3. See LICENSE file in the project root for full license text.
#[cfg(not(feature = "std"))]
use alloc::prelude::*;
use byteorder::ByteOrder;
use core::result;
pub type Result<T> = result::Result<T, String>;
pub trait Rea... | random_line_split | |
io.rs | // This file is part of zinc64.
// Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved.
// Licensed under the GPLv3. See LICENSE file in the project root for full license text.
#[cfg(not(feature = "std"))]
use alloc::prelude::*;
use byteorder::ByteOrder;
use core::result;
pub type Result<T> = result::R... | (&mut self) -> Result<u8> {
let mut buf = [0; 1];
self.read_exact(&mut buf)?;
Ok(buf[0])
}
#[inline]
fn read_u16<T: ByteOrder>(&mut self) -> Result<u16> {
let mut buf = [0; 2];
self.read_exact(&mut buf)?;
Ok(T::read_u16(&buf))
}
#[inline]
fn read... | read_u8 | identifier_name |
colors.rs | //! Color definitions.
//!
//! This module should contain all colors used in the game. Later on, we could
//! replace it with a customizeable version, where people could write themes
//! (e.g. in TOML or YAML format).
//!
//! Make sure to contain only semantic names (e.g. "primary" or "background",
//! not "red" or "gr... | {
pub primary: [f32; 4],
pub secondary: [f32; 4],
}
pub const PLAYERS: [Player; 3] = [
Player {
primary: ORANGE,
secondary: YELLOW,
},
Player {
primary: RED,
secondary: ORANGE,
},
Player {
primary: BLUE,
secondary: LIGHT_BLUE,
},
];
| Player | identifier_name |
colors.rs | //! Color definitions.
//!
//! This module should contain all colors used in the game. Later on, we could
//! replace it with a customizeable version, where people could write themes
//! (e.g. in TOML or YAML format).
//!
//! Make sure to contain only semantic names (e.g. "primary" or "background",
//! not "red" or "gr... | pub const LIGHT_BLUE: [f32; 4] = [0.22, 0.22, 1.0, 1.0];
pub const BLUE: [f32; 4] = [0.0, 0.0, 1.0, 1.0];
pub struct Player {
pub primary: [f32; 4],
pub secondary: [f32; 4],
}
pub const PLAYERS: [Player; 3] = [
Player {
primary: ORANGE,
secondary: YELLOW,
},
Player {
primar... | pub const TRANSPARENT_WHITE: [f32; 4] = [1.0, 1.0, 1.0, 0.2];
pub const YELLOW: [f32; 4] = [1.0, 1.0, 0.22, 1.0];
pub const ORANGE: [f32; 4] = [1.0, 0.61, 0.22, 1.0];
pub const RED: [f32; 4] = [1.0, 0.22, 0.22, 1.0]; | random_line_split |
simple_packet.rs | use crate::errors::PcapError;
use byteorder::{ByteOrder, ReadBytesExt};
use std::borrow::Cow;
use derive_into_owned::IntoOwned;
/// The Simple Packet Block (SPB) is a lightweight container for storing the packets coming from the network.
/// Its presence is optional.
#[derive(Clone, Debug, IntoOwned)]
pub struct Simp... | if slice.len() < 4 {
return Err(PcapError::InvalidField("SimplePacketBlock: block length < 4"));
}
let original_len = slice.read_u32::<B>()?;
let packet = SimplePacketBlock {
original_len,
data: Cow::Borrowed(slice)
};
Ok((&[], packet... | random_line_split | |
simple_packet.rs | use crate::errors::PcapError;
use byteorder::{ByteOrder, ReadBytesExt};
use std::borrow::Cow;
use derive_into_owned::IntoOwned;
/// The Simple Packet Block (SPB) is a lightweight container for storing the packets coming from the network.
/// Its presence is optional.
#[derive(Clone, Debug, IntoOwned)]
pub struct Simp... | <B: ByteOrder>(mut slice: &'a [u8]) -> Result<(&'a [u8], Self), PcapError> {
if slice.len() < 4 {
return Err(PcapError::InvalidField("SimplePacketBlock: block length < 4"));
}
let original_len = slice.read_u32::<B>()?;
let packet = SimplePacketBlock {
original_l... | from_slice | identifier_name |
simple_packet.rs | use crate::errors::PcapError;
use byteorder::{ByteOrder, ReadBytesExt};
use std::borrow::Cow;
use derive_into_owned::IntoOwned;
/// The Simple Packet Block (SPB) is a lightweight container for storing the packets coming from the network.
/// Its presence is optional.
#[derive(Clone, Debug, IntoOwned)]
pub struct Simp... |
let original_len = slice.read_u32::<B>()?;
let packet = SimplePacketBlock {
original_len,
data: Cow::Borrowed(slice)
};
Ok((&[], packet))
}
}
| {
return Err(PcapError::InvalidField("SimplePacketBlock: block length < 4"));
} | conditional_block |
reader.rs | //! Represents a way to read a record-based file by mapping each read line to a record. The mapping between
//! the data from the file and the record name is made by the `mapper` function.
//!
//! # Examples
//! ```rust
//! use rbf::record::{AsciiMode, UTF8Mode};
//! use rbf::layout::Layout;
//! use rbf::reade... | line: String::new(),
lazyness: ReaderLazyness::Lazy,
file_size: metadata.len(),
chars_read: 0,
nblines_read: 0,
}
}
/// Returns a muta
ble reference on the record corresponding to the line read. **next()** returns **None**
/// if EOF.
... | or reading
let bufreader = match File::open(&rbf_file) {
// if ok, create a new BufReader to read the file line by line
Ok(f) => match layout.rec_length {
0 => BufReader::new(f),
_ => BufReader::with_capacity(layout.rec_length+1, f),
},
... | identifier_body |
reader.rs | //! Represents a way to read a record-based file by mapping each read line to a record. The mapping between
//! the data from the file and the record name is made by the `mapper` function.
//!
//! # Examples
//! ```rust
//! use rbf::record::{AsciiMode, UTF8Mode};
//! use rbf::layout::Layout;
//! use rbf::reade... | //! for (i, l) in greek.chars().enumerate() {
//! let fname = format!("G{}", i+1);
//! assert_eq!(rec.get_value(&fname), l.to_string().repeat(i+1));
//! }
//! },
//! "DP" => {
//! assert_e... | random_line_split | |
reader.rs | //! Represents a way to read a record-based file by mapping each read line to a record. The mapping between
//! the data from the file and the record name is made by the `mapper` function.
//!
//! # Examples
//! ```rust
//! use rbf::record::{AsciiMode, UTF8Mode};
//! use rbf::layout::Layout;
//! use rbf::reade... | aderLazyness) {
self.lazyness = lazyness;
}
}
| lazyness: Re | identifier_name |
reader.rs | //! Represents a way to read a record-based file by mapping each read line to a record. The mapping between
//! the data from the file and the record name is made by the `mapper` function.
//!
//! # Examples
//! ```rust
//! use rbf::record::{AsciiMode, UTF8Mode};
//! use rbf::layout::Layout;
//! use rbf::reade... | self.chars_read = chars_read;
self.nblines_read += 1;
},
// error reading bytes
Err(why) => panic!("error {} when reading file {}", why.description(), self.rbf_file),
};
// get the record ID using mapper
... | return None;
} else {
| conditional_block |
factor.rs | #![crate_name = "uu_factor"]
/*
* This file is part of the uutils coreutils package.
*
* (c) T. Jameson Little <t.jameson.little@gmail.com>
* (c) Wiktor Kuropatwa <wiktor.kuropatwa@gmail.com>
* 20150223 added Pollard rho method implementation
* (c) kwantam <kwantam@gmail.com>
* 20150429 sped up trial division ... |
}
}
fn rho_pollard_factor(num: u64, factors: &mut Vec<u64>) {
if is_prime(num) {
factors.push(num);
return;
}
let divisor = rho_pollard_find_divisor(num);
rho_pollard_factor(divisor, factors);
rho_pollard_factor(num / divisor, factors);
}
fn table_division(mut num: u64, factor... | {
return d;
} | conditional_block |
factor.rs | #![crate_name = "uu_factor"]
/*
* This file is part of the uutils coreutils package.
*
* (c) T. Jameson Little <t.jameson.little@gmail.com>
* (c) Wiktor Kuropatwa <wiktor.kuropatwa@gmail.com>
* 20150223 added Pollard rho method implementation
* (c) kwantam <kwantam@gmail.com>
* 20150429 sped up trial division ... | let matches = new_coreopts!(SYNTAX, SUMMARY, LONG_HELP)
.parse(args);
if matches.free.is_empty() {
for line in BufReader::new(stdin()).lines() {
for number in line.unwrap().split_whitespace() {
print_factors_str(number);
}
}
} else {
fo... | pub fn uumain(args: Vec<String>) -> i32 { | random_line_split |
factor.rs | #![crate_name = "uu_factor"]
/*
* This file is part of the uutils coreutils package.
*
* (c) T. Jameson Little <t.jameson.little@gmail.com>
* (c) Wiktor Kuropatwa <wiktor.kuropatwa@gmail.com>
* 20150223 added Pollard rho method implementation
* (c) kwantam <kwantam@gmail.com>
* 20150429 sped up trial division ... | (mut a: u64, mut b: u64) -> u64 {
while b > 0 {
a %= b;
swap(&mut a, &mut b);
}
a
}
fn rho_pollard_find_divisor(num: u64) -> u64 {
let range = Range::new(1, num);
let mut rng = rand::weak_rng();
let mut x = range.ind_sample(&mut rng);
let mut y = x;
let mut a = range.ind... | gcd | identifier_name |
factor.rs | #![crate_name = "uu_factor"]
/*
* This file is part of the uutils coreutils package.
*
* (c) T. Jameson Little <t.jameson.little@gmail.com>
* (c) Wiktor Kuropatwa <wiktor.kuropatwa@gmail.com>
* 20150223 added Pollard rho method implementation
* (c) kwantam <kwantam@gmail.com>
* 20150429 sped up trial division ... |
pub fn uumain(args: Vec<String>) -> i32 {
let matches = new_coreopts!(SYNTAX, SUMMARY, LONG_HELP)
.parse(args);
if matches.free.is_empty() {
for line in BufReader::new(stdin()).lines() {
for number in line.unwrap().split_whitespace() {
print_factors_str(number);
... | {
if let Err(e) = num_str.parse::<u64>().and_then(|x| Ok(print_factors(x))) {
show_warning!("{}: {}", num_str, e);
}
} | identifier_body |
intrinsicck.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | if def.variants[data_idx].fields.len() == 1 {
return def.variants[data_idx].fields[0].ty(tcx, substs);
}
}
ty
}
impl<'a, 'tcx> ExprVisitor<'a, 'tcx> {
fn def_id_is_transmute(&self, def_id: DefId) -> bool {
self.tcx.fn_sig(def_id).abi() == RustIntrinsic &&
self.... | {
let (def, substs) = match ty.sty {
ty::Adt(def, substs) => (def, substs),
_ => return ty
};
if def.variants.len() == 2 && !def.repr.c() && def.repr.int.is_none() {
let data_idx;
let one = VariantIdx::new(1);
let zero = VariantIdx::new(0);
if def.variants[... | identifier_body |
intrinsicck.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | <'a, 'tcx: 'a> {
tcx: TyCtxt<'a, 'tcx, 'tcx>
}
struct ExprVisitor<'a, 'tcx: 'a> {
tcx: TyCtxt<'a, 'tcx, 'tcx>,
tables: &'tcx ty::TypeckTables<'tcx>,
param_env: ty::ParamEnv<'tcx>,
}
/// If the type is `Option<T>`, it will return `T`, otherwise
/// the type itself. Works on most `Option`-like types.
fn... | ItemVisitor | identifier_name |
intrinsicck.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | if sk_from.same_size(sk_to) {
return;
}
// Special-case transmutting from `typeof(function)` and
// `Option<typeof(function)>` to present a clearer error.
let from = unpack_option_like(self.tcx.global_tcx(), from);
if let (&ty::FnD... | random_line_split | |
file.rs | use std::path::Path;
use std::fs::File;
use std::io::{Read, Write};
use encoding::{Encoding, DecoderTrap, EncoderTrap};
use encoding::all::WINDOWS_1252;
pub fn | <P: AsRef<Path>>(path: P) -> String {
let mut file = File::open(path).unwrap();
let mut data = String::new();
file.read_to_string(&mut data).unwrap();
data
}
pub fn write_all_text<P: AsRef<Path>>(path: P, text: &str) {
let mut file = File::create(path).unwrap();
file.write_all(text.as_bytes()... | read_all_text | identifier_name |
file.rs | use std::path::Path;
use std::fs::File;
use std::io::{Read, Write};
use encoding::{Encoding, DecoderTrap, EncoderTrap};
use encoding::all::WINDOWS_1252;
pub fn read_all_text<P: AsRef<Path>>(path: P) -> String {
let mut file = File::open(path).unwrap();
let mut data = String::new();
file.read_to_string(&mu... |
pub fn write_all_win_1252<P: AsRef<Path>>(path: P, text: &str) {
let mut file = File::create(path).unwrap();
let data = WINDOWS_1252.encode(&text, EncoderTrap::Strict).unwrap();
file.write_all(&data).unwrap();
}
| {
let mut file = File::open(path).unwrap();
let mut data = Vec::new();
file.read_to_end(&mut data).unwrap();
WINDOWS_1252.decode(&data, DecoderTrap::Strict).unwrap()
} | identifier_body |
file.rs | use std::path::Path;
use std::fs::File;
use std::io::{Read, Write};
use encoding::{Encoding, DecoderTrap, EncoderTrap};
use encoding::all::WINDOWS_1252; | let mut data = String::new();
file.read_to_string(&mut data).unwrap();
data
}
pub fn write_all_text<P: AsRef<Path>>(path: P, text: &str) {
let mut file = File::create(path).unwrap();
file.write_all(text.as_bytes()).unwrap();
}
pub fn read_all_win_1252<P: AsRef<Path>>(path: P) -> String {
let ... |
pub fn read_all_text<P: AsRef<Path>>(path: P) -> String {
let mut file = File::open(path).unwrap();
| random_line_split |
page.rs | /*
* Copyright 2019 Jeehoon Kang
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed t... |
Ok(Self::from_raw(
new_begin as *mut RawPage,
(new_end - new_begin) / PAGE_SIZE,
))
}
pub fn into_raw(self) -> *mut RawPage {
let ptr = self.ptr;
mem::forget(self);
ptr as *mut _
}
pub fn clear(&mut self) {
for page in self.iter... | {
return Err(());
} | conditional_block |
page.rs | /*
* Copyright 2019 Jeehoon Kang
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed t... | if new_begin >= new_end || new_end - new_begin < PAGE_SIZE {
return Err(());
}
Ok(Self::from_raw(
new_begin as *mut RawPage,
(new_end - new_begin) / PAGE_SIZE,
))
}
pub fn into_raw(self) -> *mut RawPage {
let ptr = self.ptr;
m... | // Round begin address up, and end address down.
let new_begin = round_up(ptr as usize, PAGE_SIZE);
let new_end = round_down(ptr as usize + size, PAGE_SIZE);
// No pages if there isn't enough room for an entry. | random_line_split |
page.rs | /*
* Copyright 2019 Jeehoon Kang
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed t... | () -> Self {
Self {
inner: [0; PAGE_SIZE],
}
}
pub fn clear(&mut self) {
for byte in self.inner.iter_mut() {
*byte = 0;
}
}
}
impl Deref for RawPage {
type Target = [u8; PAGE_SIZE];
fn deref(&self) -> &Self::Target {
&self.inner
... | new | identifier_name |
pipe-pingpong-bounded.rs | // xfail-fast
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <... | () {
let (client_, server_) = ::pingpong::init();
let client_ = Cell(client_);
let server_ = Cell(server_);
do task::spawn {
let client__ = client_.take();
test::client(client__);
};
do task::spawn {
let server__ = server_.take();
test::server(server__);
};
}
| main | identifier_name |
pipe-pingpong-bounded.rs | // xfail-fast
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <... | let server__ = server_.take();
test::server(server__);
};
} | let client__ = client_.take();
test::client(client__);
};
do task::spawn { | random_line_split |
parser.rs | use std::io;
use std::path::PathBuf;
use super::read_config;
use crate::modules::{ModuleResolutionError, ModuleResolutionErrorKind};
use crate::{ErrorKind, Input, Session};
#[test]
fn parser_errors_in_submods_are_surfaced() {
// See also https://github.com/rust-lang/rustfmt/issues/4126
let filename = "tests/... | (filename: &str) {
let file = PathBuf::from(filename);
let config = read_config(&file);
let mut session = Session::<io::Stdout>::new(config, None);
let _ = session.format(Input::File(filename.into())).unwrap();
assert!(session.has_parsing_errors());
}
#[test]
fn parser_creation_errors_on_entry_new_... | assert_parser_error | identifier_name |
parser.rs | use std::io;
use std::path::PathBuf;
use super::read_config;
use crate::modules::{ModuleResolutionError, ModuleResolutionErrorKind};
use crate::{ErrorKind, Input, Session};
#[test]
fn parser_errors_in_submods_are_surfaced() | panic!("Expected parser error");
}
} else {
panic!("Expected ModuleResolution operation error");
}
}
fn assert_parser_error(filename: &str) {
let file = PathBuf::from(filename);
let config = read_config(&file);
let mut session = Session::<io::Stdout>::new(config, None);... | {
// See also https://github.com/rust-lang/rustfmt/issues/4126
let filename = "tests/parser/issue-4126/lib.rs";
let input_file = PathBuf::from(filename);
let exp_mod_name = "invalid";
let config = read_config(&input_file);
let mut session = Session::<io::Stdout>::new(config, None);
if let Er... | identifier_body |
parser.rs | use std::io;
use std::path::PathBuf;
use super::read_config;
use crate::modules::{ModuleResolutionError, ModuleResolutionErrorKind};
use crate::{ErrorKind, Input, Session};
#[test]
fn parser_errors_in_submods_are_surfaced() {
// See also https://github.com/rust-lang/rustfmt/issues/4126
let filename = "tests/... | #[test]
fn crate_parsing_errors_on_unclosed_delims() {
// See also https://github.com/rust-lang/rustfmt/issues/4466
let filename = "tests/parser/unclosed-delims/issue_4466.rs";
assert_parser_error(filename);
} | }
| random_line_split |
parser.rs | use std::io;
use std::path::PathBuf;
use super::read_config;
use crate::modules::{ModuleResolutionError, ModuleResolutionErrorKind};
use crate::{ErrorKind, Input, Session};
#[test]
fn parser_errors_in_submods_are_surfaced() {
// See also https://github.com/rust-lang/rustfmt/issues/4126
let filename = "tests/... |
}
fn assert_parser_error(filename: &str) {
let file = PathBuf::from(filename);
let config = read_config(&file);
let mut session = Session::<io::Stdout>::new(config, None);
let _ = session.format(Input::File(filename.into())).unwrap();
assert!(session.has_parsing_errors());
}
#[test]
fn parser_cre... | {
panic!("Expected ModuleResolution operation error");
} | conditional_block |
interact.rs | //! Functions for an interactive mode command line (REPL)
use crate::command::Run;
use eyre::{bail, eyre, Result};
use rustyline::error::ReadlineError;
use std::path::Path;
use structopt::StructOpt;
fn help() -> String {
use ansi_term::{
Colour::{Green, Yellow},
Style,
};
let mut help = S... | fn highlight_char(&self, line: &str, pos: usize) -> bool {
self.highlighter.highlight_char(line, pos)
}
}
}
| Owned(Yellow.dimmed().paint(candidate).to_string())
}
| identifier_body |
interact.rs | //! Functions for an interactive mode command line (REPL)
use crate::command::Run;
use eyre::{bail, eyre, Result};
use rustyline::error::ReadlineError;
use std::path::Path;
use structopt::StructOpt;
fn help() -> String {
use ansi_term::{
Colour::{Green, Yellow},
Style,
};
let mut help = S... | 's: 'b, 'p: 'b>(
&'s self,
prompt: &'p str,
_default: bool,
) -> Cow<'b, str> {
Owned(Blue.paint(prompt).to_string())
}
fn highlight_hint<'h>(&self, hint: &'h str) -> Cow<'h, str> {
Owned(White.dimmed().paint(hint).to_string())
... | light_prompt<'b, | identifier_name |
interact.rs | //! Functions for an interactive mode command line (REPL)
use crate::command::Run;
use eyre::{bail, eyre, Result};
use rustyline::error::ReadlineError;
use std::path::Path;
use structopt::StructOpt;
fn help() -> String {
use ansi_term::{
Colour::{Green, Yellow},
Style,
};
let mut help = S... | ("Ctrl+C", "Cancel the current task (if any)"),
("Ctrl+D", "Exit interactive session"),
] {
help += &format!(" {} {}\n", Green.paint(*keys), desc)
}
help
}
/// Run the interactive REPL
#[tracing::instrument]
pub async fn run<T>(mut prefix: Vec<String>, formats: &[String], histor... | ("<< ", "Clear the command prefix"),
("$ ", "Ignore the command prefix for this command"),
("↑ ", "Go back through command history"),
("↓ ", "Go forward through command history"),
("? ", "Print this message"), | random_line_split |
mod.rs | //! Kafka producers.
//!
//! ## The C librdkafka producer
//!
//! Rust-rdkafka relies on the C librdkafka producer to communicate with Kafka,
//! so in order to understand how the Rust producers work it is important to
//! understand the basics of the C one as well.
//!
//! ### Async
//!
//! The librdkafka producer is ... | ;
impl ClientContext for DefaultProducerContext {}
impl ProducerContext for DefaultProducerContext {
type DeliveryOpaque = ();
fn delivery(&self, _: &DeliveryResult<'_>, _: Self::DeliveryOpaque) {}
}
/// Common trait for all producers.
pub trait Producer<C = DefaultProducerContext>
where
C: ProducerConte... | DefaultProducerContext | identifier_name |
mod.rs | //! Kafka producers.
//!
//! ## The C librdkafka producer
//!
//! Rust-rdkafka relies on the C librdkafka producer to communicate with Kafka,
//! so in order to understand how the Rust producers work it is important to
//! understand the basics of the C one as well.
//!
//! ### Async
//!
//! The librdkafka producer is ... | /// failed to). The `DeliveryOpaque` will be the one provided by the user
/// when calling send.
fn delivery(&self, delivery_result: &DeliveryResult<'_>, delivery_opaque: Self::DeliveryOpaque);
}
/// An inert producer context that can be used when customizations are not
/// required.
#[derive(Clone)]
pub s... | /// the producer when producing a message, and returned to the `delivery`
/// method once the message has been delivered, or failed to.
type DeliveryOpaque: IntoOpaque;
/// This method will be called once the message has been delivered (or | random_line_split |
armv7s_apple_ios.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 ... | () -> TargetResult {
let base = opts(Arch::Armv7s)?;
Ok(Target {
llvm_target: "armv7s-apple-ios".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:o-p:32:32-f64:32:64-v64:32:64... | target | identifier_name |
armv7s_apple_ios.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 ... | options: TargetOptions {
features: "+v7,+vfp4,+neon".to_string(),
max_atomic_width: Some(64),
abi_blacklist: super::arm_base::abi_blacklist(),
.. base
}
})
} | target_env: String::new(),
target_vendor: "apple".to_string(),
linker_flavor: LinkerFlavor::Gcc, | random_line_split |
armv7s_apple_ios.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 base = opts(Arch::Armv7s)?;
Ok(Target {
llvm_target: "armv7s-apple-ios".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:o-p:32:32-f64:32:64-v64:32:64-v128:32:128-a:0:32... | identifier_body |
unboxed-closures-drop.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&mut self) {
unsafe {
DROP_COUNT += 1
}
}
}
fn a<F:Fn(isize, isize) -> isize>(f: F) -> isize {
f(1, 2)
}
fn b<F:FnMut(isize, isize) -> isize>(mut f: F) -> isize {
f(3, 4)
}
fn c<F:FnOnce(isize, isize) -> isize>(f: F) -> isize {
f(5, 6)
}
fn test_fn() {
{
a(mo... | drop | identifier_name |
unboxed-closures-drop.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 ... | {
test_fn();
test_fn_mut();
test_fn_once();
} | identifier_body | |
unboxed-closures-drop.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 zz = Droppable::new();
c(move |a: isize, b| { z; zz; a + b });
assert_eq!(drop_count(), 9);
}
assert_eq!(drop_count(), 9);
}
fn main() {
test_fn();
test_fn_mut();
test_fn_once();
} | assert_eq!(drop_count(), 7);
{
let z = Droppable::new(); | random_line_split |
flock.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 ... |
Lock { handle: handle }
}
}
impl Drop for Lock {
fn drop(&mut self) {
let mut overlapped: libc::OVERLAPPED = unsafe { mem::init() };
unsafe {
UnlockFileEx(self.handle, 0, 100, 0, &mut overlapped);
libc::CloseHandle(self.handle... | {
unsafe { libc::CloseHandle(handle); }
fail!("could not lock `{}`: {}", p.display(),
os::last_os_error())
} | conditional_block |
flock.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 fd = p.with_c_str(|s| unsafe {
libc::open(s, libc::O_RDWR | libc::O_CREAT, libc::S_IRWXU)
});
assert!(fd > 0);
let flock = os::flock {
l_start: 0,
l_len: 0,
l_pid: 0,
l_whence: libc::SEEK_... |
impl Lock {
pub fn new(p: &Path) -> Lock { | random_line_split |
flock.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 ... | {
l_type: libc::c_short,
l_whence: libc::c_short,
l_start: libc::off_t,
l_len: libc::off_t,
l_pid: libc::pid_t,
// not actually here, but brings in line with freebsd
l_sysid: libc::c_int,
}
pub static F_WRLCK: libc::c... | flock | identifier_name |
03-literals-and-operators.rs | fn main() | println!("One million is written as {}", 1_000_000u);
}
| {
// Integer addition
println!("1 + 2 = {}", 1u + 2);
// Integer subtraction
println!("1 - 2 = {}", 1i - 2);
// Short-circuiting boolean logic
println!("true AND false is {}", true && false);
println!("true OR false is {}", true || false);
println!("NOT true is {}", !true);
// Bit... | identifier_body |
03-literals-and-operators.rs | fn | () {
// Integer addition
println!("1 + 2 = {}", 1u + 2);
// Integer subtraction
println!("1 - 2 = {}", 1i - 2);
// Short-circuiting boolean logic
println!("true AND false is {}", true && false);
println!("true OR false is {}", true || false);
println!("NOT true is {}",!true);
// B... | main | identifier_name |
03-literals-and-operators.rs | fn main() {
// Integer addition
println!("1 + 2 = {}", 1u + 2);
// Integer subtraction
println!("1 - 2 = {}", 1i - 2); |
// Bitwise operations
println!("0011 AND 0101 is {:04t}", 0b0011u & 0b0101);
println!("0011 OR 0101 is {:04t}", 0b0011u | 0b0101);
println!("0011 XOR 0101 is {:04t}", 0b0011u ^ 0b0101);
println!("1 << 5 is {}", 1u << 5);
println!("0x80 >> 2 is 0x{:x}", 0x80u >> 2);
// Use underscores to im... |
// Short-circuiting boolean logic
println!("true AND false is {}", true && false);
println!("true OR false is {}", true || false);
println!("NOT true is {}", !true); | random_line_split |
mimetype.rs | use std::path;
use std::io;
use std::io::{Error, ErrorKind};
use std::io::BufRead;
use std::io::BufReader;
use std::fs::File;
use server_side::utils;
#[derive(Debug)]
pub struct Mimetype {
mimetype_vec: Vec<MimetypeData>,
pub default_mimetype: String
}
#[derive(Debug)]
pub struct MimetypeData {
extension: String... | }
pub fn get_mimetype(&self) -> String {
self.mimetype.to_owned()
}
pub fn set_mimetype(&mut self, e: String) {
self.mimetype = e;
}
pub fn delete(self) {}
} | MimetypeData{extension: e, mimetype: m}
}
pub fn get_extension(&self) -> String {
self.extension.to_owned() | random_line_split |
mimetype.rs |
use std::path;
use std::io;
use std::io::{Error, ErrorKind};
use std::io::BufRead;
use std::io::BufReader;
use std::fs::File;
use server_side::utils;
#[derive(Debug)]
pub struct Mimetype {
mimetype_vec: Vec<MimetypeData>,
pub default_mimetype: String
}
#[derive(Debug)]
pub struct MimetypeData {
extension: Strin... | (&self) -> String {
self.mimetype.to_owned()
}
pub fn set_mimetype(&mut self, e: String) {
self.mimetype = e;
}
pub fn delete(self) {}
}
| get_mimetype | identifier_name |
exercise.rs | use regex::Regex;
use serde::Deserialize;
use std::fmt::{self, Display, Formatter};
use std::fs::{self, remove_file, File};
use std::io::Read;
use std::path::PathBuf;
use std::process::{self, Command};
const RUSTC_COLOR_ARGS: &[&str] = &["--color", "always"];
const I_AM_DONE_REGEX: &str = r"(?m)^\s*///?\s*I\s+AM\s+NOT... | {
// The source code that is still pending completion
pub line: String,
// The line number of the source code still pending completion
pub number: usize,
// Whether or not this is important
pub important: bool,
}
// The result of compiling an exercise
pub struct CompiledExercise<'a> {
exer... | ContextLine | identifier_name |
exercise.rs | use regex::Regex;
use serde::Deserialize;
use std::fmt::{self, Display, Formatter};
use std::fs::{self, remove_file, File};
use std::io::Read;
use std::path::PathBuf;
use std::process::{self, Command};
const RUSTC_COLOR_ARGS: &[&str] = &["--color", "always"];
const I_AM_DONE_REGEX: &str = r"(?m)^\s*///?\s*I\s+AM\s+NOT... | .expect("Failed to compile!");
// Due to an issue with Clippy, a cargo clean is required to catch all lints.
// See https://github.com/rust-lang/rust-clippy/issues/2604
// This is already fixed on master branch. See this issue to track merging into Carg... | Command::new("rustc")
.args(&[self.path.to_str().unwrap(), "-o", &temp_file()])
.args(RUSTC_COLOR_ARGS)
.output() | random_line_split |
exercise.rs | use regex::Regex;
use serde::Deserialize;
use std::fmt::{self, Display, Formatter};
use std::fs::{self, remove_file, File};
use std::io::Read;
use std::path::PathBuf;
use std::process::{self, Command};
const RUSTC_COLOR_ARGS: &[&str] = &["--color", "always"];
const I_AM_DONE_REGEX: &str = r"(?m)^\s*///?\s*I\s+AM\s+NOT... |
}
impl Exercise {
pub fn compile(&self) -> Result<CompiledExercise, ExerciseOutput> {
let cmd = match self.mode {
Mode::Compile => Command::new("rustc")
.args(&[self.path.to_str().unwrap(), "-o", &temp_file()])
.args(RUSTC_COLOR_ARGS)
.output(),
... | {
clean();
} | identifier_body |
exercise.rs | use regex::Regex;
use serde::Deserialize;
use std::fmt::{self, Display, Formatter};
use std::fs::{self, remove_file, File};
use std::io::Read;
use std::path::PathBuf;
use std::process::{self, Command};
const RUSTC_COLOR_ARGS: &[&str] = &["--color", "always"];
const I_AM_DONE_REGEX: &str = r"(?m)^\s*///?\s*I\s+AM\s+NOT... | let matched_line_index = source
.lines()
.enumerate()
.filter_map(|(i, line)| if re.is_match(line) { Some(i) } else { None })
.next()
.expect("This should not happen at all");
let min_line = ((matched_line_index as i32) - (CONTEXT as i32)).max(0) as us... | return State::Done;
}
| conditional_block |
clipboard.rs | use std::string;
use SdlResult;
use get_error;
#[allow(non_camel_case_types)]
pub mod ll {
use libc::{c_int, c_char};
pub type SDL_bool = c_int;
extern "C" {
pub fn SDL_SetClipboardText(text: *const c_char) -> c_int;
pub fn SDL_GetClipboardText() -> *const c_char;
pub fn SDL_HasCl... | () -> SdlResult<String> {
let result = unsafe {
let cstr = ll::SDL_GetClipboardText() as *const u8;
string::raw::from_buf(cstr)
};
if result.len() == 0 {
Err(get_error())
} else {
Ok(result)
}
}
pub fn has_clipboard_text() -> bool {
unsafe { ll::SDL_HasClipboard... | get_clipboard_text | identifier_name |
clipboard.rs | use std::string;
use SdlResult;
use get_error;
#[allow(non_camel_case_types)]
pub mod ll {
use libc::{c_int, c_char};
pub type SDL_bool = c_int;
extern "C" {
pub fn SDL_SetClipboardText(text: *const c_char) -> c_int;
pub fn SDL_GetClipboardText() -> *const c_char;
pub fn SDL_HasCl... | else {
Ok(())
}
}
}
pub fn get_clipboard_text() -> SdlResult<String> {
let result = unsafe {
let cstr = ll::SDL_GetClipboardText() as *const u8;
string::raw::from_buf(cstr)
};
if result.len() == 0 {
Err(get_error())
} else {
Ok(result)
}
}
... | {
Err(get_error())
} | conditional_block |
clipboard.rs | use std::string;
use SdlResult;
use get_error;
#[allow(non_camel_case_types)]
pub mod ll {
use libc::{c_int, c_char};
pub type SDL_bool = c_int;
extern "C" {
pub fn SDL_SetClipboardText(text: *const c_char) -> c_int;
pub fn SDL_GetClipboardText() -> *const c_char;
pub fn SDL_HasCl... |
pub fn has_clipboard_text() -> bool {
unsafe { ll::SDL_HasClipboardText() == 1 }
}
| {
let result = unsafe {
let cstr = ll::SDL_GetClipboardText() as *const u8;
string::raw::from_buf(cstr)
};
if result.len() == 0 {
Err(get_error())
} else {
Ok(result)
}
} | identifier_body |
clipboard.rs | use std::string;
use SdlResult;
use get_error; | #[allow(non_camel_case_types)]
pub mod ll {
use libc::{c_int, c_char};
pub type SDL_bool = c_int;
extern "C" {
pub fn SDL_SetClipboardText(text: *const c_char) -> c_int;
pub fn SDL_GetClipboardText() -> *const c_char;
pub fn SDL_HasClipboardText() -> SDL_bool;
}
}
pub fn set_c... | random_line_split | |
communication.rs | // Copyright Cryptape Technologies LLC.
//
// 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 ... | #[derive(Debug)]
pub enum Error {
BadStatus,
Timeout,
Parse,
}
type RpcSender =
Mutex<mpsc::Sender<(hyper::Request, oneshot::Sender<Result<hyper::Chunk, Error>>)>>;
pub struct RpcClient {
sender: RpcSender,
uri: RwLock<hyper::Uri>,
}
impl RpcClient {
pub fn create(upstream: &UpStream) -> ... | use jsonrpc_types::{rpc_request, rpc_types};
use libproto::blockchain::UnverifiedTransaction;
| random_line_split |
communication.rs | // Copyright Cryptape Technologies LLC.
//
// 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 ... | else {
Err(Error::BadStatus)
}
}
| {
Ok(result.hash)
} | conditional_block |
communication.rs | // Copyright Cryptape Technologies LLC.
//
// 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 ... | (upstream: &UpStream) -> Result<rpc_types::MetaData, Error> {
let height = rpc_types::BlockNumber::latest();
let req = rpc_request::GetMetaDataParams::new(height).into_request(1);
let result = rpc_send_and_get_result_from_reply!(upstream, req, rpc_types::MetaData);
Ok(result)
}
pub fn cita_send_transac... | cita_get_metadata | identifier_name |
communication.rs | // Copyright Cryptape Technologies LLC.
//
// 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 ... |
}
// Pack the result type into a reply type, and parse result from the reply, and return the result.
// The user of this macro do NOT have to care about the inner reply type.
macro_rules! rpc_send_and_get_result_from_reply {
($upstream:ident, $request:ident, $result_type:path) => {{
define_reply_type!(Rep... | {
let uri = { self.uri.read().clone() };
trace!("Send body {:?} to {:?}.", body, uri);
let mut req = hyper::Request::new(hyper::Method::Post, uri);
req.headers_mut().set(hyper::header::ContentType::json());
req.set_body(body.to_owned());
let (tx, rx) = oneshot::channel();... | identifier_body |
functional-struct-update-noncopyable.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
}
fn main() {
let a = A { y: Arc::new(1), x: Arc::new(2) };
let _b = A { y: Arc::new(3),..a }; //~ ERROR cannot move out of type `A`
let _c = a;
}
| { println!("x={}", *self.x); } | identifier_body |
functional-struct-update-noncopyable.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | { y: Arc<isize>, x: Arc<isize> }
impl Drop for A {
fn drop(&mut self) { println!("x={}", *self.x); }
}
fn main() {
let a = A { y: Arc::new(1), x: Arc::new(2) };
let _b = A { y: Arc::new(3),..a }; //~ ERROR cannot move out of type `A`
let _c = a;
}
| A | identifier_name |
functional-struct-update-noncopyable.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
// | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// issue 7327
use std::sync::Arc;
struct A { y: Arc<isize>, x: Arc<isize> }
impl Drop for A {
fn drop(&mut self) { println!("x={}", *self.x); }
}
f... | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license | random_line_split |
admin_geofinder.rs | // Copyright © 2016, Canal TP and/or its affiliates. All rights reserved.
//
// This file is part of Navitia,
// the software to build cool stuff with public transport.
//
// Hope you'll enjoy and contribute to this project,
// powered by Canal TP (www.canaltp.fr).
// Help us simplify mobility and open public t... | Some("bob_country"),
));
finder.insert(make_complex_admin(
"bob_country",
40.,
Some(ZoneType::Country),
3.,
None,
));
// not_typed zone is outside the hierarchy, but since it contains the point and it has no type it... | 40.,
Some(ZoneType::StateDistrict),
2., | random_line_split |
admin_geofinder.rs | // Copyright © 2016, Canal TP and/or its affiliates. All rights reserved.
//
// This file is part of Navitia,
// the software to build cool stuff with public transport.
//
// Hope you'll enjoy and contribute to this project,
// powered by Canal TP (www.canaltp.fr).
// Help us simplify mobility and open public t... | &mut self, admin: Admin) {
use ordered_float::OrderedFloat;
fn min(a: OrderedFloat<f32>, b: f64) -> f32 {
a.0.min(down(b as f32))
}
fn max(a: OrderedFloat<f32>, b: f64) -> f32 {
a.0.max(up(b as f32))
}
let rect = {
let mut coords = mat... | nsert( | identifier_name |
admin_geofinder.rs | // Copyright © 2016, Canal TP and/or its affiliates. All rights reserved.
//
// This file is part of Navitia,
// the software to build cool stuff with public transport.
//
// Hope you'll enjoy and contribute to this project,
// powered by Canal TP (www.canaltp.fr).
// Help us simplify mobility and open public t... | }
// the goal is that f in [down(f as f32) as f64, up(f as f32) as f64]
fn down(f: f32) -> f32 {
f - (f * ::std::f32::EPSILON).abs()
}
fn up(f: f32) -> f32 {
f + (f * ::std::f32::EPSILON).abs()
}
#[test]
fn test_up_down() {
for &f in [1.0f64, 0., -0., -1., 0.1, -0.1, 0.9, -0.9, 42., -42.].iter() {
... |
let mut geofinder = AdminGeoFinder::default();
for admin in admins {
geofinder.insert(admin);
}
geofinder
}
| identifier_body |
log.rs | /* Copyright (C) 2017 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... | line,
to_safe_cstring(function).as_ptr(),
code,
to_safe_cstring(message).as_ptr());
}
}
// Fall back if the Suricata C context is not registered which is
// the case when Rust unit tests are running.
//
// We don't log the time... | to_safe_cstring(filename).as_ptr(), | random_line_split |
log.rs | /* Copyright (C) 2017 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... | () -> i32 {
unsafe {
LEVEL
}
}
pub fn log_set_level(level: i32) {
unsafe {
LEVEL = level;
}
}
#[no_mangle]
pub extern "C" fn rs_log_set_level(level: i32) {
log_set_level(level);
}
fn basename(filename: &str) -> &str {
let path = Path::new(filename);
for os_str in path.file... | get_log_level | identifier_name |
log.rs | /* Copyright (C) 2017 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... |
// This macro returns the function name.
//
// This macro has been borrowed from https://github.com/popzxc/stdext-rs, which
// is released under the MIT license as there is currently no macro in Rust
// to provide the function name.
#[cfg(feature = "function-macro")]
#[macro_export(local_inner_macros)]
macro_rules!fu... | {
let filename = basename(file);
sc_log_message(level,
filename,
line,
function,
code,
message);
} | identifier_body |
lib.rs | use std::f64::consts::PI;
/// Calculates the volume of the n-sphere.
pub fn sphere_volume(radius: f64, dim: u64) -> f64 |
#[test]
fn volume_of_1_sphere_works() {
for radius in (0..5000000).map(|n| n as f64 / 7000.) {
let expected = PI * radius.powi(2);
let actual = sphere_volume(radius, 2);
assert!(equals(expected, actual, 0.0001, 5), "Expected: {}, Actual: {}", expected, actual);
}
}
#[test]
fn volume_o... | {
let gamma = if dim % 2 == 0 {
// This works because dim / 2 is a whole number.
fact(dim / 2) as f64
} else {
// This works because the function is gamma(1/2 + n) where n = dim / 2 + 1
let n = dim / 2 + 1;
(fact(2 * n) as f64 / (4u64.pow(n as u32) * fact(n)) as f64) * PI... | identifier_body |
lib.rs | use std::f64::consts::PI;
/// Calculates the volume of the n-sphere.
pub fn sphere_volume(radius: f64, dim: u64) -> f64 {
let gamma = if dim % 2 == 0 {
// This works because dim / 2 is a whole number.
fact(dim / 2) as f64
} else {
// This works because the function is gamma(1/2 + n) whe... |
let a_i64 = unsafe{::std::mem::transmute::<_, i64>(a)};
let b_i64 = unsafe{::std::mem::transmute::<_, i64>(b)};
let ulps_diff = i64::abs(a_i64 - b_i64);
return ulps_diff <= max_ulps_diff;
}
#[inline]
fn fact(n: u64) -> u64 {
//TODO: This could be made faster with better algorithm, but it's called ... | {
return false;
} | conditional_block |
lib.rs | use std::f64::consts::PI;
/// Calculates the volume of the n-sphere.
pub fn sphere_volume(radius: f64, dim: u64) -> f64 {
let gamma = if dim % 2 == 0 { | // This works because dim / 2 is a whole number.
fact(dim / 2) as f64
} else {
// This works because the function is gamma(1/2 + n) where n = dim / 2 + 1
let n = dim / 2 + 1;
(fact(2 * n) as f64 / (4u64.pow(n as u32) * fact(n)) as f64) * PI.sqrt()
};
(PI.powf(0.5 * di... | random_line_split | |
lib.rs | use std::f64::consts::PI;
/// Calculates the volume of the n-sphere.
pub fn sphere_volume(radius: f64, dim: u64) -> f64 {
let gamma = if dim % 2 == 0 {
// This works because dim / 2 is a whole number.
fact(dim / 2) as f64
} else {
// This works because the function is gamma(1/2 + n) whe... | (a: f64, b: f64, max_diff: f64, max_ulps_diff: i64) -> bool {
let diff = f64::abs(a - b);
if diff <= max_diff {
return true;
}
if a.is_sign_positive() &&!b.is_sign_positive() {
return false;
}
let a_i64 = unsafe{::std::mem::transmute::<_, i64>(a)};
let b_i64 = unsafe{::std::m... | equals | identifier_name |
def.rs | #[test]
fn parse_macro_def_no_params() {
super::test_parser(
r#"
<marker type="NODE_MACRO_DEF">macro test<marker type="NODE_MACRO_PARAM_LIST">()</marker> {
}</marker>
"#,
)
}
#[test]
fn parse_macro_def() {
super::test_parser(
r#"
<marker type="NODE_MACRO_DEF">mac... |
#[test]
fn parse_var_with_initializer() {
super::test_parser(
r#"
<marker type="NODE_VARIABLE_DEF">type_attribute a = <marker type="NODE_BINARY_EXPR">a | b</marker>;</marker>
"#,
)
}
| {
super::test_parser(
r#"
<marker type="NODE_VARIABLE_DEF">type a;</marker>
"#,
)
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.